text
stringlengths
54
60.6k
<commit_before>#pragma once //=====================================================================// /*! @file @brief ST7565(R) LCD ドライバー @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "common/delay.hpp" namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief ST7565 テンプレートクラス @param[in] CSI_IO CSI(SPI) 制御クラス @param[in] CS デバイス選択、レジスター選択、制御クラス @param[in] A0 制御切り替え、レジスター選択、制御クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CSI_IO, class CS, class A0> class ST7565 { CSI_IO& csi_; enum class CMD : uint8_t { DISPLAY_OFF = 0xAE, DISPLAY_ON = 0xAF, SET_DISP_START_LINE = 0x40, SET_PAGE = 0xB0, SET_COLUMN_UPPER = 0x10, SET_COLUMN_LOWER = 0x00, SET_ADC_NORMAL = 0xA0, SET_ADC_REVERSE = 0xA1, SET_DISP_NORMAL = 0xA6, SET_DISP_REVERSE = 0xA7, SET_ALLPTS_NORMAL = 0xA4, SET_ALLPTS_ON = 0xA5, SET_BIAS_9 = 0xA2, SET_BIAS_7 = 0xA3, RMW = 0xE0, RMW_CLEAR = 0xEE, INTERNAL_RESET = 0xE2, SET_COM_NORMAL = 0xC0, SET_COM_REVERSE = 0xC8, SET_POWER_CONTROL = 0x28, SET_RESISTOR_RATIO = 0x20, SET_VOLUME_FIRST = 0x81, SET_VOLUME_SECOND = 0x00, SET_STATIC_OFF = 0xAC, SET_STATIC_ON = 0xAD, SET_STATIC_REG = 0x00, SET_BOOSTER_FIRST = 0xF8, SET_BOOSTER_234 = 0, SET_BOOSTER_5 = 1, SET_BOOSTER_6 = 3, NOP = 0xE3, TEST = 0xF0, }; inline void write_(CMD cmd) { csi_.xchg(static_cast<uint8_t>(cmd)); } inline void write_(CMD cmd, uint8_t ord) { csi_.xchg(static_cast<uint8_t>(cmd) | ord); } inline void chip_enable_(bool f = true) const { CS::P = !f; } inline void reg_select_(bool f) const { A0::P = f; } void init_(bool comrvs) { reg_select_(0); chip_enable_(); // toggle RST low to reset; CS low so it'll listen to us // if (cs > 0) // digitalWrite(cs, LOW); // digitalWrite(rst, LOW); // _delay_ms(500); // digitalWrite(rst, HIGH); write_(CMD::DISPLAY_OFF); // LCD bias select write_(CMD::SET_BIAS_7); // ADC select write_(CMD::SET_ADC_NORMAL); // SHL select if(comrvs) { write_(CMD::SET_COM_REVERSE); } else { write_(CMD::SET_COM_NORMAL); } // Initial display line write_(CMD::SET_DISP_START_LINE); // turn on voltage converter (VC=1, VR=0, VF=0) write_(CMD::SET_POWER_CONTROL, 0x4); // wait for 50% rising utils::delay::milli_second(50); // turn on voltage regulator (VC=1, VR=1, VF=0) write_(CMD::SET_POWER_CONTROL, 0x6); // wait >=50ms utils::delay::milli_second(50); // turn on voltage follower (VC=1, VR=1, VF=1) write_(CMD::SET_POWER_CONTROL, 0x7); // wait 10ms utils::delay::milli_second(10); // set lcd operating voltage (regulator resistor, ref voltage resistor) write_(CMD::SET_RESISTOR_RATIO, 0x6); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// ST7565(CSI_IO& csi) : csi_(csi) { } //-----------------------------------------------------------------// /*! @brief ブライトネス設定 @param[in] val ブライトネス値 */ //-----------------------------------------------------------------// void set_brightness(uint8_t val) { write_(CMD::SET_VOLUME_FIRST); write_(CMD::SET_VOLUME_SECOND, (val & 0x3f)); } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] contrast コントラスト @param[in] comrvs コモンライン・リバースの場合:true */ //-----------------------------------------------------------------// void start(uint8_t contrast, bool comrvs = false) { CS::DIR = 1; // (/CS) output A0::DIR = 1; // (A0) output reg_select_(0); chip_enable_(false); utils::delay::milli_second(100); init_(comrvs); write_(CMD::DISPLAY_ON); write_(CMD::SET_ALLPTS_NORMAL); set_brightness(contrast); chip_enable_(false); } //-----------------------------------------------------------------// /*! @brief コピー @param[in] src フレームバッファソース @param[in] num 転送ページ数 @param[in] ofs 転送オフセット */ //-----------------------------------------------------------------// void copy(const uint8_t* src, uint8_t num, uint8_t ofs = 0) { chip_enable_(); uint8_t o = 0x00; for(uint8_t page = ofs; page < (ofs + num); ++page) { reg_select_(0); write_(CMD::SET_PAGE, page); write_(CMD::SET_COLUMN_LOWER, o & 0x0f); write_(CMD::SET_COLUMN_UPPER, o >> 4); /// write_(CMD::RMW); reg_select_(1); csi_.send(src, 128); src += 128; } reg_select_(0); chip_enable_(false); } }; } <commit_msg>update BIAS9<commit_after>#pragma once //=====================================================================// /*! @file @brief ST7565(R) LCD ドライバー @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "common/delay.hpp" namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief ST7565 テンプレートクラス @param[in] CSI_IO CSI(SPI) 制御クラス @param[in] CS デバイス選択、レジスター選択、制御クラス @param[in] A0 制御切り替え、レジスター選択、制御クラス @param[in] RES リセット、制御クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class CSI_IO, class CS, class A0, class RES> class ST7565 { CSI_IO& csi_; enum class CMD : uint8_t { DISPLAY_OFF = 0xAE, DISPLAY_ON = 0xAF, SET_DISP_START_LINE = 0x40, SET_PAGE = 0xB0, SET_COLUMN_UPPER = 0x10, SET_COLUMN_LOWER = 0x00, SET_ADC_NORMAL = 0xA0, SET_ADC_REVERSE = 0xA1, SET_DISP_NORMAL = 0xA6, SET_DISP_REVERSE = 0xA7, SET_ALLPTS_NORMAL = 0xA4, SET_ALLPTS_ON = 0xA5, SET_BIAS_9 = 0xA2, SET_BIAS_7 = 0xA3, RMW = 0xE0, RMW_CLEAR = 0xEE, INTERNAL_RESET = 0xE2, SET_COM_NORMAL = 0xC0, SET_COM_REVERSE = 0xC8, SET_POWER_CONTROL = 0x28, SET_RESISTOR_RATIO = 0x20, SET_VOLUME_FIRST = 0x81, SET_VOLUME_SECOND = 0x00, SET_STATIC_OFF = 0xAC, SET_STATIC_ON = 0xAD, SET_STATIC_REG = 0x00, SET_BOOSTER_FIRST = 0xF8, SET_BOOSTER_234 = 0, SET_BOOSTER_5 = 1, SET_BOOSTER_6 = 3, NOP = 0xE3, TEST = 0xF0, }; inline void write_(CMD cmd) { csi_.xchg(static_cast<uint8_t>(cmd)); } inline void write_(CMD cmd, uint8_t ord) { csi_.xchg(static_cast<uint8_t>(cmd) | ord); } inline void chip_enable_(bool f = true) const { CS::P = !f; } inline void reg_select_(bool f) const { A0::P = f; } void init_(bool comrvs, bool bias9) { reg_select_(0); chip_enable_(); // toggle RST low to reset; CS low so it'll listen to us // if (cs > 0) // digitalWrite(cs, LOW); // digitalWrite(rst, LOW); // _delay_ms(500); // digitalWrite(rst, HIGH); write_(CMD::DISPLAY_OFF); // LCD bias select if(bias9) { write_(CMD::SET_BIAS_9); } else { write_(CMD::SET_BIAS_7); } // ADC select write_(CMD::SET_ADC_NORMAL); // SHL select if(comrvs) { write_(CMD::SET_COM_REVERSE); } else { write_(CMD::SET_COM_NORMAL); } // Initial display line write_(CMD::SET_DISP_START_LINE); // turn on voltage converter (VC=1, VR=0, VF=0) write_(CMD::SET_POWER_CONTROL, 0x4); // wait for 50% rising utils::delay::milli_second(50); // turn on voltage regulator (VC=1, VR=1, VF=0) write_(CMD::SET_POWER_CONTROL, 0x6); // wait >=50ms utils::delay::milli_second(50); // turn on voltage follower (VC=1, VR=1, VF=1) write_(CMD::SET_POWER_CONTROL, 0x7); // wait 10ms utils::delay::milli_second(10); // set lcd operating voltage (regulator resistor, ref voltage resistor) write_(CMD::SET_RESISTOR_RATIO, 0x6); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// ST7565(CSI_IO& csi) : csi_(csi) { } //-----------------------------------------------------------------// /*! @brief ブライトネス設定 @param[in] val ブライトネス値 */ //-----------------------------------------------------------------// void set_brightness(uint8_t val) { write_(CMD::SET_VOLUME_FIRST); write_(CMD::SET_VOLUME_SECOND, (val & 0x3f)); } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] contrast コントラスト @param[in] comrvs コモンライン・リバースの場合:true @param[in] bias9 BIAS9 選択の場合「true」 */ //-----------------------------------------------------------------// void start(uint8_t contrast, bool comrvs = false, bool bias9 = false) { CS::DIR = 1; // (/CS) output A0::DIR = 1; // (A0) output RES::DIR = 1; // (/RES) output RES::P = 0; // assert /RES signal reg_select_(0); chip_enable_(false); utils::delay::milli_second(100); RES::P = 1; // negate /RES signal utils::delay::milli_second(10); init_(comrvs, bias9); write_(CMD::DISPLAY_ON); write_(CMD::SET_ALLPTS_NORMAL); set_brightness(contrast); chip_enable_(false); } //-----------------------------------------------------------------// /*! @brief コピー @param[in] src フレームバッファソース @param[in] num 転送ページ数 @param[in] ofs 転送オフセット */ //-----------------------------------------------------------------// void copy(const uint8_t* src, uint8_t num, uint8_t ofs = 0) { chip_enable_(); uint8_t o = 0x00; for(uint8_t page = ofs; page < (ofs + num); ++page) { reg_select_(0); write_(CMD::SET_PAGE, page); write_(CMD::SET_COLUMN_LOWER, o & 0x0f); write_(CMD::SET_COLUMN_UPPER, o >> 4); reg_select_(1); csi_.send(src, 128); src += 128; } reg_select_(0); chip_enable_(false); } }; } <|endoftext|>
<commit_before>#include "list.h" #include <core/db.h> #include <text/text.h> #include <algorithm> #include <sstream> #include <stdio.h> #define FIELDS "tracks.id, tracks.title, tracks.user_id, users.name, tracks.date, tracks.visible" #define TABLES "users, tracks" #define JOIN "tracks.user_id = users.id" #define JOIN_VISIBLE JOIN " AND tracks.visible='t'" TrackList::TrackList(const std::string &query_fmt, bool all){ char *query = (char*) malloc(query_fmt.size() + strlen(FIELDS) + strlen(TABLES) + strlen(JOIN_VISIBLE)); sprintf(query, query_fmt.c_str(), FIELDS, TABLES, all?JOIN:JOIN_VISIBLE); extract(DB::query(query)); free(query); } void TrackList::extract(const DB::Result &r){ resize(r.size()); for(unsigned i=0; i<r.size(); i++){ at(i).id = number(r[i][0]); at(i).title = r[i][1]; at(i).artist = User(number(r[i][2]), r[i][3]); at(i).date = r[i][4]; at(i).visible = r[i][5] == "t"; } } Dict* TrackList::fill(Dict *d, std::string section, bool buttons){ Dict *list_d = d->AddIncludeDictionary(section); list_d->SetFilename("html/tracklist.tpl"); if(empty()){ list_d->ShowSection("EMPTY"); return list_d; } std::transform(section.begin(), section.end(), section.begin(), ::tolower); for(unsigned i=0; i<size(); i++){ Dict *track_d = list_d->AddSectionDictionary("TRACK"); if(buttons){ track_d->ShowSection("BUTTONS"); track_d->SetIntValue("POSITION", i); track_d->ShowSection(i == 0 ? "IS_FIRST" : "NOT_FIRST"); track_d->ShowSection(i == size()-1 ? "IS_LAST" : "NOT_LAST"); } at(i).fill(track_d); Dict *player_d = at(i).player(track_d); player_d->SetValue("LIST", section); player_d->SetIntValue("COUNT", i+1); } return list_d; } Dict* TrackList::fillJson(Dict *d, bool showArtist){ Dict *item, *data; for(TrackList::const_iterator i=begin(); i!=end(); i++){ item = d->AddSectionDictionary("TRACK"); data = item->AddIncludeDictionary("TRACK"); data->SetFilename("json/track.tpl"); if(showArtist) data->ShowSection("ARTIST"); i->fill(data); } return d; } // Prepared queries TrackList TrackList::search(const std::string &q){ TrackList list; if(q.empty()) return list; std::vector<std::string> p; std::istringstream in(q); std::string buf; std::string sql; while(in){ in >> buf; p.push_back("%"+buf+"%"); sql += " AND (tracks.title ILIKE $" + number(p.size()) + " OR users.name ILIKE $" + number(p.size()) + ")"; } list.extract(DB::query("SELECT "FIELDS" FROM "TABLES" WHERE "JOIN_VISIBLE + sql, p)); return list; } TrackList TrackList::exactSearch(const std::string &artist, const std::string &title){ TrackList list; if(artist.empty() || title.empty()) return list; list.extract(DB::query( "SELECT "FIELDS" FROM "TABLES" WHERE "JOIN_VISIBLE" AND users.name = $1 AND tracks.title = $2", artist, title)); return list; } TrackList TrackList::tag(const std::string &t){ TrackList list; list.extract(DB::query( "SELECT "FIELDS" FROM "TABLES" WHERE "JOIN_VISIBLE" AND $1 = ANY(tracks.tags) ORDER BY tracks.date DESC", t)); return list; } TrackList Tracks::latest(int n, int offset){ return TrackList( "SELECT %s FROM %s WHERE %s ORDER BY date DESC " "LIMIT " + number(n) + " OFFSET " + number(offset)); } TrackList Tracks::featured(int n){ return TrackList( "SELECT %s FROM %s, featured_tracks " "WHERE %s AND featured_tracks.track_id = tracks.id " "ORDER BY featured_tracks.date DESC LIMIT " + number(n)); } TrackList Tracks::random(int n){ return TrackList( "SELECT %s FROM %s WHERE %s ORDER BY random() LIMIT " + number(n)); } TrackList Tracks::byUser(int uid, bool all){ return TrackList( "SELECT %s FROM %s WHERE %s AND users.id = " + number(uid) + " ORDER BY date DESC", all); } <commit_msg>fix json tracklists<commit_after>#include "list.h" #include <core/db.h> #include <text/text.h> #include <algorithm> #include <sstream> #include <stdio.h> #define FIELDS "tracks.id, tracks.title, tracks.user_id, users.name, tracks.date, tracks.visible" #define TABLES "users, tracks" #define JOIN "tracks.user_id = users.id" #define JOIN_VISIBLE JOIN " AND tracks.visible='t'" TrackList::TrackList(const std::string &query_fmt, bool all){ char *query = (char*) malloc(query_fmt.size() + strlen(FIELDS) + strlen(TABLES) + strlen(JOIN_VISIBLE)); sprintf(query, query_fmt.c_str(), FIELDS, TABLES, all?JOIN:JOIN_VISIBLE); extract(DB::query(query)); free(query); } void TrackList::extract(const DB::Result &r){ resize(r.size()); for(unsigned i=0; i<r.size(); i++){ at(i).id = number(r[i][0]); at(i).title = r[i][1]; at(i).artist = User(number(r[i][2]), r[i][3]); at(i).date = r[i][4]; at(i).visible = r[i][5] == "t"; } } Dict* TrackList::fill(Dict *d, std::string section, bool buttons){ Dict *list_d = d->AddIncludeDictionary(section); list_d->SetFilename("html/tracklist.tpl"); if(empty()){ list_d->ShowSection("EMPTY"); return list_d; } std::transform(section.begin(), section.end(), section.begin(), ::tolower); for(unsigned i=0; i<size(); i++){ Dict *track_d = list_d->AddSectionDictionary("TRACK"); if(buttons){ track_d->ShowSection("BUTTONS"); track_d->SetIntValue("POSITION", i); track_d->ShowSection(i == 0 ? "IS_FIRST" : "NOT_FIRST"); track_d->ShowSection(i == size()-1 ? "IS_LAST" : "NOT_LAST"); } at(i).fill(track_d); Dict *player_d = at(i).player(track_d); player_d->SetValue("LIST", section); player_d->SetIntValue("COUNT", i+1); } return list_d; } Dict* TrackList::fillJson(Dict *d, bool showArtist){ Dict *item, *data; for(TrackList::const_iterator i=begin(); i!=end(); i++){ item = d->AddSectionDictionary("ITEM"); data = item->AddIncludeDictionary("DATA"); data->SetFilename("json/track.tpl"); if(showArtist) data->ShowSection("ARTIST"); i->fill(data); } return d; } // Prepared queries TrackList TrackList::search(const std::string &q){ TrackList list; if(q.empty()) return list; std::vector<std::string> p; std::istringstream in(q); std::string buf; std::string sql; while(in){ in >> buf; p.push_back("%"+buf+"%"); sql += " AND (tracks.title ILIKE $" + number(p.size()) + " OR users.name ILIKE $" + number(p.size()) + ")"; } list.extract(DB::query("SELECT "FIELDS" FROM "TABLES" WHERE "JOIN_VISIBLE + sql, p)); return list; } TrackList TrackList::exactSearch(const std::string &artist, const std::string &title){ TrackList list; if(artist.empty() || title.empty()) return list; list.extract(DB::query( "SELECT "FIELDS" FROM "TABLES" WHERE "JOIN_VISIBLE" AND users.name = $1 AND tracks.title = $2", artist, title)); return list; } TrackList TrackList::tag(const std::string &t){ TrackList list; list.extract(DB::query( "SELECT "FIELDS" FROM "TABLES" WHERE "JOIN_VISIBLE" AND $1 = ANY(tracks.tags) ORDER BY tracks.date DESC", t)); return list; } TrackList Tracks::latest(int n, int offset){ return TrackList( "SELECT %s FROM %s WHERE %s ORDER BY date DESC " "LIMIT " + number(n) + " OFFSET " + number(offset)); } TrackList Tracks::featured(int n){ return TrackList( "SELECT %s FROM %s, featured_tracks " "WHERE %s AND featured_tracks.track_id = tracks.id " "ORDER BY featured_tracks.date DESC LIMIT " + number(n)); } TrackList Tracks::random(int n){ return TrackList( "SELECT %s FROM %s WHERE %s ORDER BY random() LIMIT " + number(n)); } TrackList Tracks::byUser(int uid, bool all){ return TrackList( "SELECT %s FROM %s WHERE %s AND users.id = " + number(uid) + " ORDER BY date DESC", all); } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include <sstream> #include <set> #include <string> #include <memory> #include <cstdlib> #ifndef _WINDOWS // Support for pid #include<unistd.h> #endif #include "util/debug.h" namespace lean { static volatile bool g_has_violations = false; static volatile bool g_enable_assertions = true; static std::set<std::string> * g_enabled_debug_tags = nullptr; void initialize_debug() { // lazy initialization } void finalize_debug() { delete g_enabled_debug_tags; } bool has_violations() { return g_has_violations; } // LCOV_EXCL_START void enable_assertions(bool f) { g_enable_assertions = f; } bool assertions_enabled() { return g_enable_assertions; } void notify_assertion_violation(const char * fileName, int line, const char * condition) { std::cerr << "LEAN ASSERTION VIOLATION\n"; std::cerr << "File: " << fileName << "\n"; std::cerr << "Line: " << line << "\n"; std::cerr << condition << "\n"; std::cerr.flush(); } void enable_debug(char const * tag) { if (!g_enabled_debug_tags) g_enabled_debug_tags = new std::set<std::string>(); g_enabled_debug_tags->insert(tag); } void disable_debug(char const * tag) { if (g_enabled_debug_tags) g_enabled_debug_tags->erase(tag); } bool is_debug_enabled(const char * tag) { return g_enabled_debug_tags && g_enabled_debug_tags->find(tag) != g_enabled_debug_tags->end(); } static bool g_debug_dialog = true; void enable_debug_dialog(bool flag) { g_debug_dialog = flag; } void invoke_debugger() { g_has_violations = true; if (!g_debug_dialog) exit(1); int * x = 0; for (;;) { if (std::cin.eof()) exit(1); #ifdef _WINDOWS std::cerr << "(C)ontinue, (A)bort, (S)top\n"; #else std::cerr << "(C)ontinue, (A)bort, (S)top, Invoke (G)DB\n"; #endif char result; std::cin >> result; switch (result) { case 'C': case 'c': return; case 'A': case 'a': case EOF: exit(1); case 'S': case 's': // force seg fault... *x = 0; return; #ifndef _WINDOWS case 'G': case 'g': { std::cerr << "INVOKING GDB...\n"; std::ostringstream buffer; buffer << "gdb -nw /proc/" << getpid() << "/exe " << getpid(); if (system(buffer.str().c_str()) == 0) { std::cerr << "continuing the execution...\n"; } else { std::cerr << "ERROR STARTING GDB...\n"; // forcing seg fault. *x = 0; } return; } #endif default: std::cerr << "INVALID COMMAND\n"; } } } // LCOV_EXCL_STOP } <commit_msg>feat(util/debug): emscripten support<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include <sstream> #include <set> #include <string> #include <memory> #include <cstdlib> #if defined(LEAN_EMSCRIPTEN) #include <emscripten.h> #endif #ifndef _WINDOWS // Support for pid #include<unistd.h> #endif #include "util/debug.h" namespace lean { static volatile bool g_has_violations = false; static volatile bool g_enable_assertions = true; static std::set<std::string> * g_enabled_debug_tags = nullptr; void initialize_debug() { // lazy initialization } void finalize_debug() { delete g_enabled_debug_tags; } bool has_violations() { return g_has_violations; } // LCOV_EXCL_START void enable_assertions(bool f) { g_enable_assertions = f; } bool assertions_enabled() { return g_enable_assertions; } void notify_assertion_violation(const char * fileName, int line, const char * condition) { std::cerr << "LEAN ASSERTION VIOLATION\n"; std::cerr << "File: " << fileName << "\n"; std::cerr << "Line: " << line << "\n"; std::cerr << condition << "\n"; std::cerr.flush(); } void enable_debug(char const * tag) { if (!g_enabled_debug_tags) g_enabled_debug_tags = new std::set<std::string>(); g_enabled_debug_tags->insert(tag); } void disable_debug(char const * tag) { if (g_enabled_debug_tags) g_enabled_debug_tags->erase(tag); } bool is_debug_enabled(const char * tag) { return g_enabled_debug_tags && g_enabled_debug_tags->find(tag) != g_enabled_debug_tags->end(); } static bool g_debug_dialog = true; void enable_debug_dialog(bool flag) { g_debug_dialog = flag; } void invoke_debugger() { #if defined(LEAN_EMSCRIPTEN) EM_ASM(debugger;); exit(1); #else g_has_violations = true; if (!g_debug_dialog) exit(1); int * x = 0; for (;;) { if (std::cin.eof()) exit(1); #ifdef _WINDOWS std::cerr << "(C)ontinue, (A)bort, (S)top\n"; #else std::cerr << "(C)ontinue, (A)bort, (S)top, Invoke (G)DB\n"; #endif char result; std::cin >> result; switch (result) { case 'C': case 'c': return; case 'A': case 'a': case EOF: exit(1); case 'S': case 's': // force seg fault... *x = 0; return; #ifndef _WINDOWS case 'G': case 'g': { std::cerr << "INVOKING GDB...\n"; std::ostringstream buffer; buffer << "gdb -nw /proc/" << getpid() << "/exe " << getpid(); if (system(buffer.str().c_str()) == 0) { std::cerr << "continuing the execution...\n"; } else { std::cerr << "ERROR STARTING GDB...\n"; // forcing seg fault. *x = 0; } return; } #endif default: std::cerr << "INVALID COMMAND\n"; } } #endif } // LCOV_EXCL_STOP } <|endoftext|>
<commit_before> /*************************/ /* Edition des Pastilles */ /*************************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "pcbnew.h" #include "autorout.h" #include "trigo.h" #include "drag.h" #include "protos.h" /* Routines Locales */ /* Variables locales */ static D_PAD* s_CurrentSelectedPad; /* pointeur sur le pad selecte pour edition */ static wxPoint Pad_OldPos; /************************************************************/ static void Exit_Move_Pad(WinEDA_DrawPanel * Panel, wxDC * DC) /************************************************************/ /* Routine de sortie du menu EDIT PADS. Sortie simple si pad de pad en mouvement Remise en etat des conditions initiales avant move si move en cours */ { D_PAD * pad = s_CurrentSelectedPad; Panel->ManageCurseur = NULL; Panel->ForceCloseManageCurseur = NULL; if (pad == NULL) return; pad->Draw(Panel,DC, wxPoint(0,0), GR_XOR); pad->m_Flags = 0; pad->m_Pos = Pad_OldPos; pad->Draw(Panel, DC, wxPoint(0,0), GR_XOR); /* Pad Move en cours : remise a l'etat d'origine */ if( g_Drag_Pistes_On ) { /* Effacement des segments dragges */ DRAG_SEGM * pt_drag = g_DragSegmentList; for( ; pt_drag != NULL; pt_drag = pt_drag->Pnext) { TRACK * Track = pt_drag->m_Segm; Track->Draw(Panel, DC, GR_XOR); Track->SetState(EDIT,OFF); pt_drag->SetInitialValues(); Track->Draw(Panel, DC, GR_OR); } } EraseDragListe(); s_CurrentSelectedPad = NULL; g_Drag_Pistes_On = FALSE; } /*************************************************************************/ static void Show_Pad_Move(WinEDA_DrawPanel * panel, wxDC * DC, bool erase) /*************************************************************************/ /* Affiche le pad et les pistes en mode drag lors des deplacements du pad */ { TRACK * Track; DRAG_SEGM * pt_drag; BASE_SCREEN * screen = panel->GetScreen(); D_PAD * pad = s_CurrentSelectedPad; if ( erase ) pad->Draw(panel, DC, wxPoint(0,0), GR_XOR); pad->m_Pos = screen->m_Curseur; pad->Draw(panel, DC, wxPoint(0,0), GR_XOR); if( ! g_Drag_Pistes_On ) return; /* Tracage des segments dragges */ pt_drag = g_DragSegmentList; for( ; pt_drag != NULL; pt_drag = pt_drag->Pnext) { Track = pt_drag->m_Segm; if ( erase ) Track->Draw(panel, DC, GR_XOR); if( pt_drag->m_Pad_Start) { Track->m_Start = pad->m_Pos; } if( pt_drag->m_Pad_End) { Track->m_End = pad->m_Pos; } Track->Draw(panel, DC, GR_XOR); } } /*************************************************************/ void WinEDA_BasePcbFrame::Export_Pad_Settings( D_PAD * pt_pad) /*************************************************************/ /* Charge en liste des caracteristiques par defaut celles du pad selecte */ { MODULE * Module; if ( pt_pad == NULL ) return; Module = (MODULE*) pt_pad->m_Parent; pt_pad->Display_Infos(this); g_Pad_Master.m_PadShape = pt_pad->m_PadShape; g_Pad_Master.m_Attribut = pt_pad->m_Attribut; g_Pad_Master.m_Masque_Layer = pt_pad->m_Masque_Layer; g_Pad_Master.m_Orient = pt_pad->m_Orient - ((MODULE*)pt_pad->m_Parent)->m_Orient; g_Pad_Master.m_Size = pt_pad->m_Size; g_Pad_Master.m_DeltaSize = pt_pad->m_DeltaSize; pt_pad->ComputeRayon(); g_Pad_Master.m_Offset = pt_pad->m_Offset; g_Pad_Master.m_Drill = pt_pad->m_Drill; g_Pad_Master.m_DrillShape = pt_pad->m_DrillShape; } /***********************************************************************/ void WinEDA_BasePcbFrame::Import_Pad_Settings(D_PAD * pt_pad, wxDC * DC) /***********************************************************************/ /* Met a jour les nouvelles valeurs de dimensions du pad pointe par pt_pad - Source : valeurs choisies des caracteristiques generales - les dimensions sont modifiees - la position et les noms ne sont pas touches */ { if ( DC ) pt_pad->Draw(DrawPanel, DC, wxPoint(0,0), GR_XOR); pt_pad->m_PadShape = g_Pad_Master.m_PadShape ; pt_pad->m_Masque_Layer = g_Pad_Master.m_Masque_Layer ; pt_pad->m_Attribut = g_Pad_Master.m_Attribut ; pt_pad->m_Orient = g_Pad_Master.m_Orient + ((MODULE*)pt_pad->m_Parent)->m_Orient; pt_pad->m_Size = g_Pad_Master.m_Size; pt_pad->m_DeltaSize = wxSize(0,0); pt_pad->m_Offset = g_Pad_Master.m_Offset; pt_pad->m_Drill = g_Pad_Master.m_Drill ; pt_pad->m_DrillShape = g_Pad_Master.m_DrillShape ; /* Traitement des cas particuliers : */ switch ( g_Pad_Master.m_PadShape) { case PAD_TRAPEZOID : pt_pad->m_DeltaSize = g_Pad_Master.m_DeltaSize; break; case PAD_CIRCLE : pt_pad->m_Size.y = pt_pad->m_Size.x; break; } switch( g_Pad_Master.m_Attribut & 0x7F) { case PAD_SMD: case PAD_CONN : pt_pad->m_Drill = wxSize(0,0); pt_pad->m_Offset.x = 0; pt_pad->m_Offset.y = 0; } pt_pad->ComputeRayon(); if ( DC ) pt_pad->Draw(DrawPanel, DC, wxPoint(0,0), GR_XOR); ((MODULE*)pt_pad->m_Parent)->m_LastEdit_Time = time(NULL); } /***********************************************************/ void WinEDA_BasePcbFrame::AddPad(MODULE * Module, wxDC * DC) /***********************************************************/ /* Routine d'ajout d'un pad sur l'module selectionnee */ { D_PAD * Pad, *ptliste; int rX, rY; m_Pcb->m_Status_Pcb = 0 ; Module->m_LastEdit_Time = time(NULL); Pad = new D_PAD( Module ); /* Chainage de la structure en fin de liste des pads : */ ptliste = Module->m_Pads; if( ptliste == NULL ) /* 1er pad */ { Module->m_Pads = Pad; Pad->Pback = (EDA_BaseStruct*) Module; } else { while( ptliste ) { if( ptliste->Pnext == NULL ) break; ptliste = (D_PAD *) ptliste->Pnext; } Pad->Pback = (EDA_BaseStruct*)ptliste; ptliste->Pnext = (EDA_BaseStruct*)Pad; } /* Mise a jour des caract de la pastille : */ Import_Pad_Settings(Pad, NULL); Pad->m_Netname.Empty(); Pad->m_Pos = GetScreen()->m_Curseur; rX = Pad->m_Pos.x - Module->m_Pos.x; rY = Pad->m_Pos.y - Module->m_Pos.y; RotatePoint( &rX, &rY, - Module->m_Orient); Pad->m_Pos0.x = rX; Pad->m_Pos0.y = rY; /* Increment automatique de la reference courante Current_PadName */ long num = 0; int ponder = 1; while ( g_Current_PadName.Last() >= '0' && g_Current_PadName.Last() <= '9') { num += (g_Current_PadName.Last() - '0') * ponder; g_Current_PadName.RemoveLast(); ponder *= 10; } num++; g_Current_PadName << num; Pad->SetPadName(g_Current_PadName); /* Redessin du module */ Module->Set_Rectangle_Encadrement(); Pad->Display_Infos(this); Module->Draw(DrawPanel, DC, wxPoint(0,0),GR_OR); } /*********************************************************/ void WinEDA_BasePcbFrame::DeletePad(D_PAD* Pad, wxDC * DC) /*********************************************************/ /* Function to delete the pad "pad" */ { MODULE * Module; wxString line; if ( Pad == NULL ) return; Module = (MODULE*) Pad->m_Parent; Module->m_LastEdit_Time = time(NULL); line.Printf( _("Delete Pad (module %s %s) "), Module->m_Reference->m_Text.GetData(),Module->m_Value->m_Text.GetData() ); if( ! IsOK(this, line) ) return ; m_Pcb->m_Status_Pcb = 0 ; if ( DC ) Pad->Draw(DrawPanel, DC, wxPoint(0,0),GR_XOR); Pad->DeleteStructure(); /* Redessin du module */ if ( DC ) Module->Draw(DrawPanel, DC, wxPoint(0,0),GR_OR); Module->Set_Rectangle_Encadrement(); GetScreen()->SetModify(); return ; } /*************************************************************/ void WinEDA_BasePcbFrame::StartMovePad(D_PAD * Pad, wxDC * DC) /*************************************************************/ /* Function to initialise the "move pad" command */ { MODULE * Module; if(Pad == NULL ) return; Module = (MODULE*) Pad->m_Parent; s_CurrentSelectedPad = Pad ; Pad_OldPos = Pad->m_Pos; Pad->Display_Infos(this); DrawPanel->ManageCurseur = Show_Pad_Move; DrawPanel->ForceCloseManageCurseur = Exit_Move_Pad; /* Draw the pad (SKETCH mode) */ Pad->Draw(DrawPanel, DC, wxPoint(0,0),GR_XOR); Pad->m_Flags |= IS_MOVED; Pad->Draw(DrawPanel, DC, wxPoint(0,0),GR_XOR); /* Build the list of track segments to drag if the command is a drag pad*/ if ( g_Drag_Pistes_On ) Build_1_Pad_SegmentsToDrag(DrawPanel, DC, Pad); else EraseDragListe(); } /*********************************************************/ void WinEDA_BasePcbFrame::PlacePad(D_PAD * Pad, wxDC * DC) /*********************************************************/ /* Routine to Place a moved pad */ { int dX, dY; TRACK * Track; DRAG_SEGM *pt_drag; MODULE * Module; if(Pad == NULL ) return; Module = (MODULE*) Pad->m_Parent; /* Placement du pad */ Pad->Draw(DrawPanel, DC, wxPoint(0,0),GR_XOR); /* Save old module */ Pad->m_Pos = Pad_OldPos; SaveCopyInUndoList(m_Pcb->m_Modules); Pad->m_Pos = GetScreen()->m_Curseur; /* Compute local coordinates (i.e refer to Module position and for Module orient = 0)*/ dX = Pad->m_Pos.x - Pad_OldPos.x; dY = Pad->m_Pos.y - Pad_OldPos.y; RotatePoint(&dX, &dY, - Module->m_Orient ); Pad->m_Pos0.x += dX; s_CurrentSelectedPad->m_Pos0.y += dY; Pad->m_Flags = 0; Pad->Draw(DrawPanel, DC, wxPoint(0,0),GR_OR); Module->Set_Rectangle_Encadrement(); Module->m_LastEdit_Time = time(NULL); /* Tracage des segments dragges */ pt_drag = g_DragSegmentList; for( ; pt_drag; pt_drag = pt_drag->Pnext) { Track = pt_drag->m_Segm; Track->SetState(EDIT,OFF); Track->Draw(DrawPanel, DC, GR_OR); } EraseDragListe(); GetScreen()->SetModify(); DrawPanel->ManageCurseur = NULL; DrawPanel->ForceCloseManageCurseur = NULL; m_Pcb->m_Status_Pcb &= ~( LISTE_CHEVELU_OK | CONNEXION_OK); } /**********************************************************/ void WinEDA_BasePcbFrame::RotatePad(D_PAD * Pad, wxDC * DC) /**********************************************************/ /* Tourne de 90 degres le pad selectionne : c.a.d intervertit dim X et Y et offsets */ { MODULE * Module; if ( Pad == NULL ) return; Module = (MODULE*) Pad->m_Parent; Module->m_LastEdit_Time = time(NULL); GetScreen()->SetModify(); Module->Draw(DrawPanel, DC, wxPoint(0,0),GR_XOR); EXCHG(Pad->m_Size.x, Pad->m_Size.y); EXCHG(Pad->m_Drill.x, Pad->m_Drill.y); EXCHG(Pad->m_Offset.x, Pad->m_Offset.y); Pad->m_Offset.y = -Pad->m_Offset.y; EXCHG(Pad->m_DeltaSize.x,Pad->m_DeltaSize.y) ; Pad->m_DeltaSize.x = -Pad->m_DeltaSize.x; /* ceci est la variation de la dim Y sur l'axe X */ Module->Set_Rectangle_Encadrement(); Pad->Display_Infos(this); Module->Draw(DrawPanel, DC, wxPoint(0,0), GR_OR); } <commit_msg>beautify<commit_after>/*************************/ /* Edition des Pastilles */ /*************************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "pcbnew.h" #include "autorout.h" #include "trigo.h" #include "drag.h" #include "protos.h" /* Routines Locales */ /* Variables locales */ static D_PAD* s_CurrentSelectedPad; /* pointeur sur le pad selecte pour edition */ static wxPoint Pad_OldPos; /************************************************************/ static void Exit_Move_Pad( WinEDA_DrawPanel* Panel, wxDC* DC ) /************************************************************/ /* Routine de sortie du menu EDIT PADS. * Sortie simple si pad de pad en mouvement * Remise en etat des conditions initiales avant move si move en cours */ { D_PAD* pad = s_CurrentSelectedPad; Panel->ManageCurseur = NULL; Panel->ForceCloseManageCurseur = NULL;. if( pad == NULL ) return; pad->Draw( Panel, DC, wxPoint( 0, 0 ), GR_XOR ); pad->m_Flags = 0; pad->m_Pos = Pad_OldPos; pad->Draw( Panel, DC, wxPoint( 0, 0 ), GR_XOR ); /* Pad Move en cours : remise a l'etat d'origine */ if( g_Drag_Pistes_On ) { /* Effacement des segments dragges */ DRAG_SEGM* pt_drag = g_DragSegmentList; for( ; pt_drag != NULL; pt_drag = pt_drag->Pnext ) { TRACK* Track = pt_drag->m_Segm; Track->Draw( Panel, DC, GR_XOR ); Track->SetState( EDIT, OFF ); pt_drag->SetInitialValues(); Track->Draw( Panel, DC, GR_OR ); } } EraseDragListe(); s_CurrentSelectedPad = NULL; g_Drag_Pistes_On = FALSE; } /*************************************************************************/ static void Show_Pad_Move( WinEDA_DrawPanel* panel, wxDC* DC, bool erase ) /*************************************************************************/ /* Affiche le pad et les pistes en mode drag lors des deplacements du pad */ { TRACK* Track; DRAG_SEGM* pt_drag; BASE_SCREEN* screen = panel->GetScreen(); D_PAD* pad = s_CurrentSelectedPad; if( erase ) pad->Draw( panel, DC, wxPoint( 0, 0 ), GR_XOR ); pad->m_Pos = screen->m_Curseur; pad->Draw( panel, DC, wxPoint( 0, 0 ), GR_XOR ); if( !g_Drag_Pistes_On ) return; /* Tracage des segments dragges */ pt_drag = g_DragSegmentList; for( ; pt_drag != NULL; pt_drag = pt_drag->Pnext ) { Track = pt_drag->m_Segm; if( erase ) Track->Draw( panel, DC, GR_XOR ); if( pt_drag->m_Pad_Start ) { Track->m_Start = pad->m_Pos; } if( pt_drag->m_Pad_End ) { Track->m_End = pad->m_Pos; } Track->Draw( panel, DC, GR_XOR ); } } /*************************************************************/ void WinEDA_BasePcbFrame::Export_Pad_Settings( D_PAD* pt_pad ) /*************************************************************/ /* Charge en liste des caracteristiques par defaut celles du pad selecte */ { MODULE* Module; if( pt_pad == NULL ) return; Module = (MODULE*) pt_pad->m_Parent; pt_pad->Display_Infos( this ); g_Pad_Master.m_PadShape = pt_pad->m_PadShape; g_Pad_Master.m_Attribut = pt_pad->m_Attribut; g_Pad_Master.m_Masque_Layer = pt_pad->m_Masque_Layer; g_Pad_Master.m_Orient = pt_pad->m_Orient - ( (MODULE*) pt_pad->m_Parent )->m_Orient; g_Pad_Master.m_Size = pt_pad->m_Size; g_Pad_Master.m_DeltaSize = pt_pad->m_DeltaSize; pt_pad->ComputeRayon(); g_Pad_Master.m_Offset = pt_pad->m_Offset; g_Pad_Master.m_Drill = pt_pad->m_Drill; g_Pad_Master.m_DrillShape = pt_pad->m_DrillShape; } /***********************************************************************/ void WinEDA_BasePcbFrame::Import_Pad_Settings( D_PAD* pt_pad, wxDC* DC ) /***********************************************************************/ /* Met a jour les nouvelles valeurs de dimensions du pad pointe par pt_pad * - Source : valeurs choisies des caracteristiques generales * - les dimensions sont modifiees * - la position et les noms ne sont pas touches */ { if( DC ) pt_pad->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_XOR ); pt_pad->m_PadShape = g_Pad_Master.m_PadShape; pt_pad->m_Masque_Layer = g_Pad_Master.m_Masque_Layer; pt_pad->m_Attribut = g_Pad_Master.m_Attribut; pt_pad->m_Orient = g_Pad_Master.m_Orient + ( (MODULE*) pt_pad->m_Parent )->m_Orient; pt_pad->m_Size = g_Pad_Master.m_Size; pt_pad->m_DeltaSize = wxSize( 0, 0 ); pt_pad->m_Offset = g_Pad_Master.m_Offset; pt_pad->m_Drill = g_Pad_Master.m_Drill; pt_pad->m_DrillShape = g_Pad_Master.m_DrillShape; /* Traitement des cas particuliers : */ switch( g_Pad_Master.m_PadShape ) { case PAD_TRAPEZOID: pt_pad->m_DeltaSize = g_Pad_Master.m_DeltaSize; break; case PAD_CIRCLE: pt_pad->m_Size.y = pt_pad->m_Size.x; break; } switch( g_Pad_Master.m_Attribut & 0x7F ) { case PAD_SMD: case PAD_CONN: pt_pad->m_Drill = wxSize( 0, 0 ); pt_pad->m_Offset.x = 0; pt_pad->m_Offset.y = 0; } pt_pad->ComputeRayon(); if( DC ) pt_pad->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_XOR ); ( (MODULE*) pt_pad->m_Parent )->m_LastEdit_Time = time( NULL ); } /***********************************************************/ void WinEDA_BasePcbFrame::AddPad( MODULE* Module, wxDC* DC ) /***********************************************************/ /* Routine d'ajout d'un pad sur l'module selectionnee */ { D_PAD* Pad, * ptliste; int rX, rY; m_Pcb->m_Status_Pcb = 0; Module->m_LastEdit_Time = time( NULL ); Pad = new D_PAD( Module ); /* Chainage de la structure en fin de liste des pads : */ ptliste = Module->m_Pads; if( ptliste == NULL ) /* 1er pad */ { Module->m_Pads = Pad; Pad->Pback = (EDA_BaseStruct*) Module; } else { while( ptliste ) { if( ptliste->Pnext == NULL ) break; ptliste = (D_PAD*) ptliste->Pnext; } Pad->Pback = (EDA_BaseStruct*) ptliste; ptliste->Pnext = (EDA_BaseStruct*) Pad; } /* Mise a jour des caract de la pastille : */ Import_Pad_Settings( Pad, NULL ); Pad->m_Netname.Empty(); Pad->m_Pos = GetScreen()->m_Curseur; rX = Pad->m_Pos.x - Module->m_Pos.x; rY = Pad->m_Pos.y - Module->m_Pos.y; RotatePoint( &rX, &rY, -Module->m_Orient ); Pad->m_Pos0.x = rX; Pad->m_Pos0.y = rY; /* Increment automatique de la reference courante Current_PadName */ long num = 0; int ponder = 1; while( g_Current_PadName.Len() && g_Current_PadName.Last() >= '0' && g_Current_PadName.Last() <= '9' ) { num += (g_Current_PadName.Last() - '0') * ponder; g_Current_PadName.RemoveLast(); ponder *= 10; } num++; g_Current_PadName << num; Pad->SetPadName( g_Current_PadName ); /* Redessin du module */ Module->Set_Rectangle_Encadrement(); Pad->Display_Infos( this ); Module->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_OR ); } /*********************************************************/ void WinEDA_BasePcbFrame::DeletePad( D_PAD* Pad, wxDC* DC ) /*********************************************************/ /* Function to delete the pad "pad" */ { MODULE* Module; wxString line; if( Pad == NULL ) return; Module = (MODULE*) Pad->m_Parent; Module->m_LastEdit_Time = time( NULL ); line.Printf( _( "Delete Pad (module %s %s) " ), Module->m_Reference->m_Text.GetData(), Module->m_Value->m_Text.GetData() ); if( !IsOK( this, line ) ) return; m_Pcb->m_Status_Pcb = 0; if( DC ) Pad->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_XOR ); Pad->DeleteStructure(); /* Redessin du module */ if( DC ) Module->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_OR ); Module->Set_Rectangle_Encadrement(); GetScreen()->SetModify(); return; } /*************************************************************/ void WinEDA_BasePcbFrame::StartMovePad( D_PAD* Pad, wxDC* DC ) /*************************************************************/ /* Function to initialise the "move pad" command */ { MODULE* Module; if( Pad == NULL ) return; Module = (MODULE*) Pad->m_Parent; s_CurrentSelectedPad = Pad; Pad_OldPos = Pad->m_Pos; Pad->Display_Infos( this ); DrawPanel->ManageCurseur = Show_Pad_Move; DrawPanel->ForceCloseManageCurseur = Exit_Move_Pad; /* Draw the pad (SKETCH mode) */ Pad->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_XOR ); Pad->m_Flags |= IS_MOVED; Pad->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_XOR ); /* Build the list of track segments to drag if the command is a drag pad*/ if( g_Drag_Pistes_On ) Build_1_Pad_SegmentsToDrag( DrawPanel, DC, Pad ); else EraseDragListe(); } /*********************************************************/ void WinEDA_BasePcbFrame::PlacePad( D_PAD* Pad, wxDC* DC ) /*********************************************************/ /* Routine to Place a moved pad */ { int dX, dY; TRACK* Track; DRAG_SEGM* pt_drag; MODULE* Module; if( Pad == NULL ) return; Module = (MODULE*) Pad->m_Parent; /* Placement du pad */ Pad->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_XOR ); /* Save old module */ Pad->m_Pos = Pad_OldPos; SaveCopyInUndoList( m_Pcb->m_Modules ); Pad->m_Pos = GetScreen()->m_Curseur; /* Compute local coordinates (i.e refer to Module position and for Module orient = 0)*/ dX = Pad->m_Pos.x - Pad_OldPos.x; dY = Pad->m_Pos.y - Pad_OldPos.y; RotatePoint( &dX, &dY, -Module->m_Orient ); Pad->m_Pos0.x += dX; s_CurrentSelectedPad->m_Pos0.y += dY; Pad->m_Flags = 0; Pad->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_OR ); Module->Set_Rectangle_Encadrement(); Module->m_LastEdit_Time = time( NULL ); /* Tracage des segments dragges */ pt_drag = g_DragSegmentList; for( ; pt_drag; pt_drag = pt_drag->Pnext ) { Track = pt_drag->m_Segm; Track->SetState( EDIT, OFF ); Track->Draw( DrawPanel, DC, GR_OR ); } EraseDragListe(); GetScreen()->SetModify(); DrawPanel->ManageCurseur = NULL; DrawPanel->ForceCloseManageCurseur = NULL; m_Pcb->m_Status_Pcb &= ~( LISTE_CHEVELU_OK | CONNEXION_OK); } /**********************************************************/ void WinEDA_BasePcbFrame::RotatePad( D_PAD* Pad, wxDC* DC ) /**********************************************************/ /* Tourne de 90 degres le pad selectionne : * c.a.d intervertit dim X et Y et offsets */ { MODULE* Module; if( Pad == NULL ) return; Module = (MODULE*) Pad->m_Parent; Module->m_LastEdit_Time = time( NULL ); GetScreen()->SetModify(); Module->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_XOR ); EXCHG( Pad->m_Size.x, Pad->m_Size.y ); EXCHG( Pad->m_Drill.x, Pad->m_Drill.y ); EXCHG( Pad->m_Offset.x, Pad->m_Offset.y ); Pad->m_Offset.y = -Pad->m_Offset.y; EXCHG( Pad->m_DeltaSize.x, Pad->m_DeltaSize.y ); Pad->m_DeltaSize.x = -Pad->m_DeltaSize.x; /* ceci est la variation * de la dim Y sur l'axe X */ Module->Set_Rectangle_Encadrement(); Pad->Display_Infos( this ); Module->Draw( DrawPanel, DC, wxPoint( 0, 0 ), GR_OR ); } <|endoftext|>
<commit_before>#include "rename_buffer.h" #include <iostream> #include <memory> #include <set> #include <string> #include <sys/stat.h> #include <utility> #include <vector> #include "../../log.h" #include "batch_handler.h" #include "recent_file_cache.h" using std::endl; using std::move; using std::ostream; using std::set; using std::shared_ptr; using std::static_pointer_cast; using std::string; using std::vector; RenameBufferEntry::RenameBufferEntry(RenameBufferEntry &&original) noexcept : entry(move(original.entry)), current{original.current}, age{original.age} {} RenameBufferEntry::RenameBufferEntry(std::shared_ptr<PresentEntry> entry, bool current) : entry{std::move(entry)}, current{current}, age{0} {} bool RenameBuffer::observe_event(Event &event, RecentFileCache &cache) { const shared_ptr<StatResult> &former = event.get_former(); const shared_ptr<StatResult> &current = event.get_current(); bool handled = false; if (current->could_be_rename_of(*former)) { // inode and entry kind are still the same. Stale ItemRenamed bit, most likely. return false; } if (current->is_present()) { shared_ptr<PresentEntry> current_present = static_pointer_cast<PresentEntry>(current); if (observe_present_entry(event, cache, current_present, true)) handled = true; } if (former->is_present()) { shared_ptr<PresentEntry> former_present = static_pointer_cast<PresentEntry>(former); if (observe_present_entry(event, cache, former_present, false)) handled = true; } if (former->is_absent() && current->is_absent()) { shared_ptr<AbsentEntry> current_absent = static_pointer_cast<AbsentEntry>(current); if (observe_absent(event, cache, current_absent)) handled = true; } return handled; } bool RenameBuffer::observe_present_entry(Event &event, RecentFileCache &cache, const shared_ptr<PresentEntry> &present, bool current) { ostream &logline = LOGGER << "Rename "; auto maybe_entry = observed_by_inode.find(present->get_inode()); if (maybe_entry == observed_by_inode.end()) { // The first-seen half of this rename event. Buffer a new entry to be paired with the second half when or if it's // observed. RenameBufferEntry entry(present, current); observed_by_inode.emplace(present->get_inode(), move(entry)); logline << "first half " << *present << ": Remembering for later." << endl; return true; } RenameBufferEntry &existing = maybe_entry->second; if (present->could_be_rename_of(*(existing.entry))) { // The inodes and entry kinds match, so with high probability, we've found the other half of the rename. // Huzzah! Huzzah forever! bool handled = false; if (!existing.current && current) { // The former end is the "from" end and the current end is the "to" end. logline << "completed pair " << *existing.entry << " => " << *present << ": Emitting rename event." << endl; cache.evict(existing.entry); event.message_buffer().renamed( string(existing.entry->get_path()), string(present->get_path()), present->get_entry_kind()); handled = true; } else if (existing.current && !current) { // The former end is the "to" end and the current end is the "from" end. logline << "completed pair " << *present << " => " << *existing.entry << ": Emitting rename event." << endl; cache.evict(present); event.message_buffer().renamed( string(present->get_path()), string(existing.entry->get_path()), existing.entry->get_entry_kind()); handled = true; } else { // Either both entries are still present (hardlink, re-used inode?) or both are missing (rapidly renamed and // deleted?) This could happen if the entry is renamed again between the lstat() calls, possibly. string existing_desc = existing.current ? " (current) " : " (former) "; string incoming_desc = current ? " (current) " : " (former) "; logline << "conflicting pair " << *present << incoming_desc << " =/= " << *(existing.entry) << existing_desc << "are both present." << endl; handled = false; } observed_by_inode.erase(maybe_entry); return handled; } string existing_desc = existing.current ? " (current) " : " (former) "; string incoming_desc = current ? " (current) " : " (former) "; logline << "conflicting pair " << *present << incoming_desc << " =/= " << *(existing.entry) << existing_desc << "have conflicting entry kinds." << endl; return false; } bool RenameBuffer::observe_absent(Event &event, RecentFileCache & /*cache*/, const std::shared_ptr<AbsentEntry> &absent) { LOGGER << "Unable to correlate rename from " << absent->get_path() << " without an inode." << endl; if (event.flag_created()) { event.message_buffer().created(string(absent->get_path()), absent->get_entry_kind()); } event.message_buffer().deleted(string(absent->get_path()), absent->get_entry_kind()); return true; } shared_ptr<set<RenameBuffer::Key>> RenameBuffer::flush_unmatched(ChannelMessageBuffer &message_buffer) { shared_ptr<set<Key>> all(new set<Key>); for (auto &it : observed_by_inode) { all->insert(it.first); } return flush_unmatched(message_buffer, all); } shared_ptr<set<RenameBuffer::Key>> RenameBuffer::flush_unmatched(ChannelMessageBuffer &message_buffer, const shared_ptr<set<Key>> &keys) { shared_ptr<set<Key>> aged(new set<Key>); vector<Key> to_erase; for (auto &it : observed_by_inode) { const Key &key = it.first; if (keys->count(key) == 0) continue; RenameBufferEntry &existing = it.second; shared_ptr<PresentEntry> entry = existing.entry; if (existing.age == 0u) { existing.age++; aged->insert(key); continue; } if (existing.current) { message_buffer.created(string(entry->get_path()), entry->get_entry_kind()); } else { message_buffer.deleted(string(entry->get_path()), entry->get_entry_kind()); } to_erase.push_back(key); } for (Key &key : to_erase) { observed_by_inode.erase(key); } return aged; } <commit_msg>Use event flags to determine events for absent->absent renames<commit_after>#include "rename_buffer.h" #include <iostream> #include <memory> #include <set> #include <string> #include <sys/stat.h> #include <utility> #include <vector> #include "../../log.h" #include "batch_handler.h" #include "recent_file_cache.h" using std::endl; using std::move; using std::ostream; using std::set; using std::shared_ptr; using std::static_pointer_cast; using std::string; using std::vector; RenameBufferEntry::RenameBufferEntry(RenameBufferEntry &&original) noexcept : entry(move(original.entry)), current{original.current}, age{original.age} {} RenameBufferEntry::RenameBufferEntry(std::shared_ptr<PresentEntry> entry, bool current) : entry{std::move(entry)}, current{current}, age{0} {} bool RenameBuffer::observe_event(Event &event, RecentFileCache &cache) { const shared_ptr<StatResult> &former = event.get_former(); const shared_ptr<StatResult> &current = event.get_current(); bool handled = false; if (current->could_be_rename_of(*former)) { // inode and entry kind are still the same. Stale ItemRenamed bit, most likely. return false; } if (current->is_present()) { shared_ptr<PresentEntry> current_present = static_pointer_cast<PresentEntry>(current); if (observe_present_entry(event, cache, current_present, true)) handled = true; } if (former->is_present()) { shared_ptr<PresentEntry> former_present = static_pointer_cast<PresentEntry>(former); if (observe_present_entry(event, cache, former_present, false)) handled = true; } if (former->is_absent() && current->is_absent()) { shared_ptr<AbsentEntry> current_absent = static_pointer_cast<AbsentEntry>(current); if (observe_absent(event, cache, current_absent)) handled = true; } return handled; } bool RenameBuffer::observe_present_entry(Event &event, RecentFileCache &cache, const shared_ptr<PresentEntry> &present, bool current) { ostream &logline = LOGGER << "Rename "; auto maybe_entry = observed_by_inode.find(present->get_inode()); if (maybe_entry == observed_by_inode.end()) { // The first-seen half of this rename event. Buffer a new entry to be paired with the second half when or if it's // observed. RenameBufferEntry entry(present, current); observed_by_inode.emplace(present->get_inode(), move(entry)); logline << "first half " << *present << ": Remembering for later." << endl; return true; } RenameBufferEntry &existing = maybe_entry->second; if (present->could_be_rename_of(*(existing.entry))) { // The inodes and entry kinds match, so with high probability, we've found the other half of the rename. // Huzzah! Huzzah forever! bool handled = false; if (!existing.current && current) { // The former end is the "from" end and the current end is the "to" end. logline << "completed pair " << *existing.entry << " => " << *present << ": Emitting rename event." << endl; cache.evict(existing.entry); event.message_buffer().renamed( string(existing.entry->get_path()), string(present->get_path()), present->get_entry_kind()); handled = true; } else if (existing.current && !current) { // The former end is the "to" end and the current end is the "from" end. logline << "completed pair " << *present << " => " << *existing.entry << ": Emitting rename event." << endl; cache.evict(present); event.message_buffer().renamed( string(present->get_path()), string(existing.entry->get_path()), existing.entry->get_entry_kind()); handled = true; } else { // Either both entries are still present (hardlink, re-used inode?) or both are missing (rapidly renamed and // deleted?) This could happen if the entry is renamed again between the lstat() calls, possibly. string existing_desc = existing.current ? " (current) " : " (former) "; string incoming_desc = current ? " (current) " : " (former) "; logline << "conflicting pair " << *present << incoming_desc << " =/= " << *(existing.entry) << existing_desc << "are both present." << endl; handled = false; } observed_by_inode.erase(maybe_entry); return handled; } string existing_desc = existing.current ? " (current) " : " (former) "; string incoming_desc = current ? " (current) " : " (former) "; logline << "conflicting pair " << *present << incoming_desc << " =/= " << *(existing.entry) << existing_desc << "have conflicting entry kinds." << endl; return false; } bool RenameBuffer::observe_absent(Event &event, RecentFileCache & /*cache*/, const std::shared_ptr<AbsentEntry> &absent) { LOGGER << "Unable to correlate rename from " << absent->get_path() << " without an inode." << endl; if (event.flag_created() ^ event.flag_deleted()) { // this entry was created just before being renamed or deleted just after being renamed. event.message_buffer().created(string(absent->get_path()), absent->get_entry_kind()); event.message_buffer().deleted(string(absent->get_path()), absent->get_entry_kind()); } else if (!event.flag_created() && !event.flag_deleted()) { // former must have been evicted from the cache. event.message_buffer().deleted(string(absent->get_path()), absent->get_entry_kind()); } return true; } shared_ptr<set<RenameBuffer::Key>> RenameBuffer::flush_unmatched(ChannelMessageBuffer &message_buffer) { shared_ptr<set<Key>> all(new set<Key>); for (auto &it : observed_by_inode) { all->insert(it.first); } return flush_unmatched(message_buffer, all); } shared_ptr<set<RenameBuffer::Key>> RenameBuffer::flush_unmatched(ChannelMessageBuffer &message_buffer, const shared_ptr<set<Key>> &keys) { shared_ptr<set<Key>> aged(new set<Key>); vector<Key> to_erase; for (auto &it : observed_by_inode) { const Key &key = it.first; if (keys->count(key) == 0) continue; RenameBufferEntry &existing = it.second; shared_ptr<PresentEntry> entry = existing.entry; if (existing.age == 0u) { existing.age++; aged->insert(key); continue; } if (existing.current) { message_buffer.created(string(entry->get_path()), entry->get_entry_kind()); } else { message_buffer.deleted(string(entry->get_path()), entry->get_entry_kind()); } to_erase.push_back(key); } for (Key &key : to_erase) { observed_by_inode.erase(key); } return aged; } <|endoftext|>
<commit_before>#include "precomp.hpp" #include "internal.hpp" using namespace std; using namespace kfusion; using namespace kfusion::cuda; static inline float deg2rad (float alpha) { return alpha * 0.017453293f; } kfusion::KinFuParams kfusion::KinFuParams::default_params() { const int iters[] = {10, 5, 4, 0}; const int levels = sizeof(iters)/sizeof(iters[0]); KinFuParams p; p.cols = 640; //pixels p.rows = 480; //pixels p.intr = Intr(525.f, 525.f, p.cols/2 - 0.5f, p.rows/2 - 0.5f); p.volume_dims = Vec3i::all(512); //number of voxels p.volume_size = Vec3f::all(3.f); //meters p.volume_pose = Affine3f().translate(Vec3f(-p.volume_size[0]/2, -p.volume_size[1]/2, 0.5f)); p.bilateral_sigma_depth = 0.04f; //meter p.bilateral_sigma_spatial = 4.5; //pixels p.bilateral_kernel_size = 7; //pixels p.icp_truncate_depth_dist = 0.f; //meters, disabled p.icp_dist_thres = 0.1f; //meters p.icp_angle_thres = deg2rad(30.f); //radians p.icp_iter_num.assign(iters, iters + levels); p.tsdf_min_camera_movement = 0.f; //meters, disabled p.tsdf_trunc_dist = 0.04f; //meters; p.tsdf_max_weight = 64; //frames p.raycast_step_factor = 0.75f; //in voxel sizes p.gradient_delta_factor = 0.5f; //in voxel sizes //p.light_pose = p.volume_pose.translation()/4; //meters p.light_pose = Vec3f::all(0.f); //meters return p; } kfusion::KinFu::KinFu(const KinFuParams& params) : frame_counter_(0), params_(params) { CV_Assert(params.volume_dims[0] % 32 == 0); volume_ = cv::Ptr<cuda::TsdfVolume>(new cuda::TsdfVolume(params_.volume_dims)); volume_->setTruncDist(params_.tsdf_trunc_dist); volume_->setMaxWeight(params_.tsdf_max_weight); volume_->setSize(params_.volume_size); volume_->setPose(params_.volume_pose); volume_->setRaycastStepFactor(params_.raycast_step_factor); volume_->setGradientDeltaFactor(params_.gradient_delta_factor); icp_ = cv::Ptr<cuda::ProjectiveICP>(new cuda::ProjectiveICP()); icp_->setDistThreshold(params_.icp_dist_thres); icp_->setAngleThreshold(params_.icp_angle_thres); icp_->setIterationsNum(params_.icp_iter_num); allocate_buffers(); reset(); } const kfusion::KinFuParams& kfusion::KinFu::params() const { return params_; } kfusion::KinFuParams& kfusion::KinFu::params() { return params_; } const kfusion::cuda::TsdfVolume& kfusion::KinFu::tsdf() const { return *volume_; } kfusion::cuda::TsdfVolume& kfusion::KinFu::tsdf() { return *volume_; } const kfusion::cuda::ProjectiveICP& kfusion::KinFu::icp() const { return *icp_; } kfusion::cuda::ProjectiveICP& kfusion::KinFu::icp() { return *icp_; } void kfusion::KinFu::allocate_buffers() { const int LEVELS = cuda::ProjectiveICP::MAX_PYRAMID_LEVELS; int cols = params_.cols; int rows = params_.rows; dists_.create(rows, cols); curr_.depth_pyr.resize(LEVELS); curr_.normals_pyr.resize(LEVELS); prev_.depth_pyr.resize(LEVELS); prev_.normals_pyr.resize(LEVELS); curr_.points_pyr.resize(LEVELS); prev_.points_pyr.resize(LEVELS); for(int i = 0; i < LEVELS; ++i) { curr_.depth_pyr[i].create(rows, cols); curr_.normals_pyr[i].create(rows, cols); prev_.depth_pyr[i].create(rows, cols); prev_.normals_pyr[i].create(rows, cols); curr_.points_pyr[i].create(rows, cols); prev_.points_pyr[i].create(rows, cols); cols /= 2; rows /= 2; } depths_.create(params_.rows, params_.cols); normals_.create(params_.rows, params_.cols); points_.create(params_.rows, params_.cols); } void kfusion::KinFu::reset() { if (frame_counter_) cout << "Reset" << endl; frame_counter_ = 0; poses_.clear(); poses_.reserve(30000); poses_.push_back(Affine3f::Identity()); volume_->clear(); } kfusion::Affine3f kfusion::KinFu::getCameraPose (int time) const { if (time > (int)poses_.size () || time < 0) time = (int)poses_.size () - 1; return poses_[time]; } bool kfusion::KinFu::operator()(const kfusion::cuda::Depth& depth, const kfusion::cuda::Image& /*image*/) { const KinFuParams& p = params_; const int LEVELS = icp_->getUsedLevelsNum(); cuda::computeDists(depth, dists_, p.intr); cuda::depthBilateralFilter(depth, curr_.depth_pyr[0], p.bilateral_kernel_size, p.bilateral_sigma_spatial, p.bilateral_sigma_depth); if (p.icp_truncate_depth_dist > 0) kfusion::cuda::depthTruncation(curr_.depth_pyr[0], p.icp_truncate_depth_dist); for (int i = 1; i < LEVELS; ++i) cuda::depthBuildPyramid(curr_.depth_pyr[i-1], curr_.depth_pyr[i], p.bilateral_sigma_depth); for (int i = 0; i < LEVELS; ++i) #if defined USE_DEPTH cuda::computeNormalsAndMaskDepth(p.intr, curr_.depth_pyr[i], curr_.normals_pyr[i]); #else cuda::computePointNormals(p.intr(i), curr_.depth_pyr[i], curr_.points_pyr[i], curr_.normals_pyr[i]); #endif cuda::waitAllDefaultStream(); //can't perform more on first frame if (frame_counter_ == 0) { volume_->integrate(dists_, poses_.back(), p.intr); #if defined USE_DEPTH curr_.depth_pyr.swap(prev_.depth_pyr); #else curr_.points_pyr.swap(prev_.points_pyr); #endif curr_.normals_pyr.swap(prev_.normals_pyr); return ++frame_counter_, false; } /////////////////////////////////////////////////////////////////////////////////////////// // ICP Affine3f affine; // cuur -> prev { //ScopeTime time("icp"); #if defined USE_DEPTH bool ok = icp_->estimateTransform(affine, p.intr, curr_.depth_pyr, curr_.normals_pyr, prev_.depth_pyr, prev_.normals_pyr); #else bool ok = icp_->estimateTransform(affine, p.intr, curr_.points_pyr, curr_.normals_pyr, prev_.points_pyr, prev_.normals_pyr); #endif if (!ok) return reset(), false; } poses_.push_back(poses_.back() * affine); // curr -> global /////////////////////////////////////////////////////////////////////////////////////////// // Volume integration // We do not integrate volume if camera does not move. float rnorm = (float)cv::norm(affine.rvec()); float tnorm = (float)cv::norm(affine.translation()); bool integrate = (rnorm + tnorm)/2 >= p.tsdf_min_camera_movement; if (integrate) { //ScopeTime time("tsdf"); volume_->integrate(dists_, poses_.back(), p.intr); } /////////////////////////////////////////////////////////////////////////////////////////// // Ray casting { //ScopeTime time("ray-cast-all"); #if defined USE_DEPTH volume_->raycast(poses_.back(), p.intr, prev_.depth_pyr[0], prev_.normals_pyr[0]); for (int i = 1; i < LEVELS; ++i) resizeDepthNormals(prev_.depth_pyr[i-1], prev_.normals_pyr[i-1], prev_.depth_pyr[i], prev_.normals_pyr[i]); #else volume_->raycast(poses_.back(), p.intr, prev_.points_pyr[0], prev_.normals_pyr[0]); for (int i = 1; i < LEVELS; ++i) resizePointsNormals(prev_.points_pyr[i-1], prev_.normals_pyr[i-1], prev_.points_pyr[i], prev_.normals_pyr[i]); #endif cuda::waitAllDefaultStream(); } return ++frame_counter_, true; } void kfusion::KinFu::renderImage(cuda::Image& image, int flag) { const KinFuParams& p = params_; image.create(p.rows, flag != 3 ? p.cols : p.cols * 2); #if defined USE_DEPTH #define PASS1 prev_.depth_pyr #else #define PASS1 prev_.points_pyr #endif if (flag < 1 || flag > 3) cuda::renderImage(PASS1[0], prev_.normals_pyr[0], params_.intr, params_.light_pose, image); else if (flag == 2) cuda::renderTangentColors(prev_.normals_pyr[0], image); else /* if (flag == 3) */ { DeviceArray2D<RGB> i1(p.rows, p.cols, image.ptr(), image.step()); DeviceArray2D<RGB> i2(p.rows, p.cols, image.ptr() + p.cols, image.step()); cuda::renderImage(PASS1[0], prev_.normals_pyr[0], params_.intr, params_.light_pose, i1); cuda::renderTangentColors(prev_.normals_pyr[0], i2); } #undef PASS1 } void kfusion::KinFu::renderImage(cuda::Image& image, const Affine3f& pose, int flag) { const KinFuParams& p = params_; image.create(p.rows, flag != 3 ? p.cols : p.cols * 2); depths_.create(p.rows, p.cols); normals_.create(p.rows, p.cols); points_.create(p.rows, p.cols); #if defined USE_DEPTH #define PASS1 depths_ #else #define PASS1 points_ #endif volume_->raycast(pose, p.intr, PASS1, normals_); if (flag < 1 || flag > 3) cuda::renderImage(PASS1, normals_, params_.intr, params_.light_pose, image); else if (flag == 2) cuda::renderTangentColors(normals_, image); else /* if (flag == 3) */ { DeviceArray2D<RGB> i1(p.rows, p.cols, image.ptr(), image.step()); DeviceArray2D<RGB> i2(p.rows, p.cols, image.ptr() + p.cols, image.step()); cuda::renderImage(PASS1, normals_, params_.intr, params_.light_pose, i1); cuda::renderTangentColors(normals_, i2); } #undef PASS1 } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //namespace pcl //{ // Eigen::Vector3f rodrigues2(const Eigen::Matrix3f& matrix) // { // Eigen::JacobiSVD<Eigen::Matrix3f> svd(matrix, Eigen::ComputeFullV | Eigen::ComputeFullU); // Eigen::Matrix3f R = svd.matrixU() * svd.matrixV().transpose(); // double rx = R(2, 1) - R(1, 2); // double ry = R(0, 2) - R(2, 0); // double rz = R(1, 0) - R(0, 1); // double s = sqrt((rx*rx + ry*ry + rz*rz)*0.25); // double c = (R.trace() - 1) * 0.5; // c = c > 1. ? 1. : c < -1. ? -1. : c; // double theta = acos(c); // if( s < 1e-5 ) // { // double t; // if( c > 0 ) // rx = ry = rz = 0; // else // { // t = (R(0, 0) + 1)*0.5; // rx = sqrt( std::max(t, 0.0) ); // t = (R(1, 1) + 1)*0.5; // ry = sqrt( std::max(t, 0.0) ) * (R(0, 1) < 0 ? -1.0 : 1.0); // t = (R(2, 2) + 1)*0.5; // rz = sqrt( std::max(t, 0.0) ) * (R(0, 2) < 0 ? -1.0 : 1.0); // if( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R(1, 2) > 0) != (ry*rz > 0) ) // rz = -rz; // theta /= sqrt(rx*rx + ry*ry + rz*rz); // rx *= theta; // ry *= theta; // rz *= theta; // } // } // else // { // double vth = 1/(2*s); // vth *= theta; // rx *= vth; ry *= vth; rz *= vth; // } // return Eigen::Vector3d(rx, ry, rz).cast<float>(); // } //} <commit_msg>bugfix (typo)<commit_after>#include "precomp.hpp" #include "internal.hpp" using namespace std; using namespace kfusion; using namespace kfusion::cuda; static inline float deg2rad (float alpha) { return alpha * 0.017453293f; } kfusion::KinFuParams kfusion::KinFuParams::default_params() { const int iters[] = {10, 5, 4, 0}; const int levels = sizeof(iters)/sizeof(iters[0]); KinFuParams p; p.cols = 640; //pixels p.rows = 480; //pixels p.intr = Intr(525.f, 525.f, p.cols/2 - 0.5f, p.rows/2 - 0.5f); p.volume_dims = Vec3i::all(512); //number of voxels p.volume_size = Vec3f::all(3.f); //meters p.volume_pose = Affine3f().translate(Vec3f(-p.volume_size[0]/2, -p.volume_size[1]/2, 0.5f)); p.bilateral_sigma_depth = 0.04f; //meter p.bilateral_sigma_spatial = 4.5; //pixels p.bilateral_kernel_size = 7; //pixels p.icp_truncate_depth_dist = 0.f; //meters, disabled p.icp_dist_thres = 0.1f; //meters p.icp_angle_thres = deg2rad(30.f); //radians p.icp_iter_num.assign(iters, iters + levels); p.tsdf_min_camera_movement = 0.f; //meters, disabled p.tsdf_trunc_dist = 0.04f; //meters; p.tsdf_max_weight = 64; //frames p.raycast_step_factor = 0.75f; //in voxel sizes p.gradient_delta_factor = 0.5f; //in voxel sizes //p.light_pose = p.volume_pose.translation()/4; //meters p.light_pose = Vec3f::all(0.f); //meters return p; } kfusion::KinFu::KinFu(const KinFuParams& params) : frame_counter_(0), params_(params) { CV_Assert(params.volume_dims[0] % 32 == 0); volume_ = cv::Ptr<cuda::TsdfVolume>(new cuda::TsdfVolume(params_.volume_dims)); volume_->setTruncDist(params_.tsdf_trunc_dist); volume_->setMaxWeight(params_.tsdf_max_weight); volume_->setSize(params_.volume_size); volume_->setPose(params_.volume_pose); volume_->setRaycastStepFactor(params_.raycast_step_factor); volume_->setGradientDeltaFactor(params_.gradient_delta_factor); icp_ = cv::Ptr<cuda::ProjectiveICP>(new cuda::ProjectiveICP()); icp_->setDistThreshold(params_.icp_dist_thres); icp_->setAngleThreshold(params_.icp_angle_thres); icp_->setIterationsNum(params_.icp_iter_num); allocate_buffers(); reset(); } const kfusion::KinFuParams& kfusion::KinFu::params() const { return params_; } kfusion::KinFuParams& kfusion::KinFu::params() { return params_; } const kfusion::cuda::TsdfVolume& kfusion::KinFu::tsdf() const { return *volume_; } kfusion::cuda::TsdfVolume& kfusion::KinFu::tsdf() { return *volume_; } const kfusion::cuda::ProjectiveICP& kfusion::KinFu::icp() const { return *icp_; } kfusion::cuda::ProjectiveICP& kfusion::KinFu::icp() { return *icp_; } void kfusion::KinFu::allocate_buffers() { const int LEVELS = cuda::ProjectiveICP::MAX_PYRAMID_LEVELS; int cols = params_.cols; int rows = params_.rows; dists_.create(rows, cols); curr_.depth_pyr.resize(LEVELS); curr_.normals_pyr.resize(LEVELS); prev_.depth_pyr.resize(LEVELS); prev_.normals_pyr.resize(LEVELS); curr_.points_pyr.resize(LEVELS); prev_.points_pyr.resize(LEVELS); for(int i = 0; i < LEVELS; ++i) { curr_.depth_pyr[i].create(rows, cols); curr_.normals_pyr[i].create(rows, cols); prev_.depth_pyr[i].create(rows, cols); prev_.normals_pyr[i].create(rows, cols); curr_.points_pyr[i].create(rows, cols); prev_.points_pyr[i].create(rows, cols); cols /= 2; rows /= 2; } depths_.create(params_.rows, params_.cols); normals_.create(params_.rows, params_.cols); points_.create(params_.rows, params_.cols); } void kfusion::KinFu::reset() { if (frame_counter_) cout << "Reset" << endl; frame_counter_ = 0; poses_.clear(); poses_.reserve(30000); poses_.push_back(Affine3f::Identity()); volume_->clear(); } kfusion::Affine3f kfusion::KinFu::getCameraPose (int time) const { if (time > (int)poses_.size () || time < 0) time = (int)poses_.size () - 1; return poses_[time]; } bool kfusion::KinFu::operator()(const kfusion::cuda::Depth& depth, const kfusion::cuda::Image& /*image*/) { const KinFuParams& p = params_; const int LEVELS = icp_->getUsedLevelsNum(); cuda::computeDists(depth, dists_, p.intr); cuda::depthBilateralFilter(depth, curr_.depth_pyr[0], p.bilateral_kernel_size, p.bilateral_sigma_spatial, p.bilateral_sigma_depth); if (p.icp_truncate_depth_dist > 0) kfusion::cuda::depthTruncation(curr_.depth_pyr[0], p.icp_truncate_depth_dist); for (int i = 1; i < LEVELS; ++i) cuda::depthBuildPyramid(curr_.depth_pyr[i-1], curr_.depth_pyr[i], p.bilateral_sigma_depth); for (int i = 0; i < LEVELS; ++i) #if defined USE_DEPTH cuda::computeNormalsAndMaskDepth(p.intr(i), curr_.depth_pyr[i], curr_.normals_pyr[i]); #else cuda::computePointNormals(p.intr(i), curr_.depth_pyr[i], curr_.points_pyr[i], curr_.normals_pyr[i]); #endif cuda::waitAllDefaultStream(); //can't perform more on first frame if (frame_counter_ == 0) { volume_->integrate(dists_, poses_.back(), p.intr); #if defined USE_DEPTH curr_.depth_pyr.swap(prev_.depth_pyr); #else curr_.points_pyr.swap(prev_.points_pyr); #endif curr_.normals_pyr.swap(prev_.normals_pyr); return ++frame_counter_, false; } /////////////////////////////////////////////////////////////////////////////////////////// // ICP Affine3f affine; // cuur -> prev { //ScopeTime time("icp"); #if defined USE_DEPTH bool ok = icp_->estimateTransform(affine, p.intr, curr_.depth_pyr, curr_.normals_pyr, prev_.depth_pyr, prev_.normals_pyr); #else bool ok = icp_->estimateTransform(affine, p.intr, curr_.points_pyr, curr_.normals_pyr, prev_.points_pyr, prev_.normals_pyr); #endif if (!ok) return reset(), false; } poses_.push_back(poses_.back() * affine); // curr -> global /////////////////////////////////////////////////////////////////////////////////////////// // Volume integration // We do not integrate volume if camera does not move. float rnorm = (float)cv::norm(affine.rvec()); float tnorm = (float)cv::norm(affine.translation()); bool integrate = (rnorm + tnorm)/2 >= p.tsdf_min_camera_movement; if (integrate) { //ScopeTime time("tsdf"); volume_->integrate(dists_, poses_.back(), p.intr); } /////////////////////////////////////////////////////////////////////////////////////////// // Ray casting { //ScopeTime time("ray-cast-all"); #if defined USE_DEPTH volume_->raycast(poses_.back(), p.intr, prev_.depth_pyr[0], prev_.normals_pyr[0]); for (int i = 1; i < LEVELS; ++i) resizeDepthNormals(prev_.depth_pyr[i-1], prev_.normals_pyr[i-1], prev_.depth_pyr[i], prev_.normals_pyr[i]); #else volume_->raycast(poses_.back(), p.intr, prev_.points_pyr[0], prev_.normals_pyr[0]); for (int i = 1; i < LEVELS; ++i) resizePointsNormals(prev_.points_pyr[i-1], prev_.normals_pyr[i-1], prev_.points_pyr[i], prev_.normals_pyr[i]); #endif cuda::waitAllDefaultStream(); } return ++frame_counter_, true; } void kfusion::KinFu::renderImage(cuda::Image& image, int flag) { const KinFuParams& p = params_; image.create(p.rows, flag != 3 ? p.cols : p.cols * 2); #if defined USE_DEPTH #define PASS1 prev_.depth_pyr #else #define PASS1 prev_.points_pyr #endif if (flag < 1 || flag > 3) cuda::renderImage(PASS1[0], prev_.normals_pyr[0], params_.intr, params_.light_pose, image); else if (flag == 2) cuda::renderTangentColors(prev_.normals_pyr[0], image); else /* if (flag == 3) */ { DeviceArray2D<RGB> i1(p.rows, p.cols, image.ptr(), image.step()); DeviceArray2D<RGB> i2(p.rows, p.cols, image.ptr() + p.cols, image.step()); cuda::renderImage(PASS1[0], prev_.normals_pyr[0], params_.intr, params_.light_pose, i1); cuda::renderTangentColors(prev_.normals_pyr[0], i2); } #undef PASS1 } void kfusion::KinFu::renderImage(cuda::Image& image, const Affine3f& pose, int flag) { const KinFuParams& p = params_; image.create(p.rows, flag != 3 ? p.cols : p.cols * 2); depths_.create(p.rows, p.cols); normals_.create(p.rows, p.cols); points_.create(p.rows, p.cols); #if defined USE_DEPTH #define PASS1 depths_ #else #define PASS1 points_ #endif volume_->raycast(pose, p.intr, PASS1, normals_); if (flag < 1 || flag > 3) cuda::renderImage(PASS1, normals_, params_.intr, params_.light_pose, image); else if (flag == 2) cuda::renderTangentColors(normals_, image); else /* if (flag == 3) */ { DeviceArray2D<RGB> i1(p.rows, p.cols, image.ptr(), image.step()); DeviceArray2D<RGB> i2(p.rows, p.cols, image.ptr() + p.cols, image.step()); cuda::renderImage(PASS1, normals_, params_.intr, params_.light_pose, i1); cuda::renderTangentColors(normals_, i2); } #undef PASS1 } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //namespace pcl //{ // Eigen::Vector3f rodrigues2(const Eigen::Matrix3f& matrix) // { // Eigen::JacobiSVD<Eigen::Matrix3f> svd(matrix, Eigen::ComputeFullV | Eigen::ComputeFullU); // Eigen::Matrix3f R = svd.matrixU() * svd.matrixV().transpose(); // double rx = R(2, 1) - R(1, 2); // double ry = R(0, 2) - R(2, 0); // double rz = R(1, 0) - R(0, 1); // double s = sqrt((rx*rx + ry*ry + rz*rz)*0.25); // double c = (R.trace() - 1) * 0.5; // c = c > 1. ? 1. : c < -1. ? -1. : c; // double theta = acos(c); // if( s < 1e-5 ) // { // double t; // if( c > 0 ) // rx = ry = rz = 0; // else // { // t = (R(0, 0) + 1)*0.5; // rx = sqrt( std::max(t, 0.0) ); // t = (R(1, 1) + 1)*0.5; // ry = sqrt( std::max(t, 0.0) ) * (R(0, 1) < 0 ? -1.0 : 1.0); // t = (R(2, 2) + 1)*0.5; // rz = sqrt( std::max(t, 0.0) ) * (R(0, 2) < 0 ? -1.0 : 1.0); // if( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R(1, 2) > 0) != (ry*rz > 0) ) // rz = -rz; // theta /= sqrt(rx*rx + ry*ry + rz*rz); // rx *= theta; // ry *= theta; // rz *= theta; // } // } // else // { // double vth = 1/(2*s); // vth *= theta; // rx *= vth; ry *= vth; rz *= vth; // } // return Eigen::Vector3d(rx, ry, rz).cast<float>(); // } //} <|endoftext|>
<commit_before>// This file is part of the "x0" project, http://github.com/christianparpart/x0> // (c) 2009-2016 Christian Parpart <trapni@gmail.com> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/http/http1/Connection.h> #include <xzero/http/http1/Channel.h> #include <xzero/http/HttpDateGenerator.h> #include <xzero/http/HttpResponseInfo.h> #include <xzero/http/HttpResponse.h> #include <xzero/http/HttpRequest.h> #include <xzero/http/BadMessage.h> #include <xzero/net/Connection.h> #include <xzero/net/EndPoint.h> #include <xzero/net/EndPointWriter.h> #include <xzero/executor/Executor.h> #include <xzero/logging.h> #include <xzero/RuntimeError.h> #include <xzero/StringUtil.h> #include <xzero/sysconfig.h> #include <cassert> #include <cstdlib> namespace xzero { namespace http { namespace http1 { #define ERROR(msg...) logError("http.http1.Connection", msg) #if !defined(NDEBUG) #define TRACE(msg...) logTrace("http.http1.Connection", msg) #else #define TRACE(msg...) do {} while (0) #endif Connection::Connection(EndPoint* endpoint, Executor* executor, const HttpHandler& handler, HttpDateGenerator* dateGenerator, HttpOutputCompressor* outputCompressor, size_t maxRequestUriLength, size_t maxRequestBodyLength, size_t maxRequestCount, Duration maxKeepAlive, bool corkStream) : ::xzero::Connection(endpoint, executor), channel_(new Channel( this, executor, handler, maxRequestUriLength, maxRequestBodyLength, dateGenerator, outputCompressor)), parser_(Parser::REQUEST, channel_.get()), inputBuffer_(), inputOffset_(0), writer_(), onComplete_(), generator_(&writer_), maxKeepAlive_(maxKeepAlive), requestCount_(0), requestMax_(maxRequestCount), corkStream_(corkStream) { channel_->request()->setRemoteAddress(endpoint->remoteAddress()); channel_->request()->setLocalAddress(endpoint->localAddress()); TRACE("$0 ctor", this); } Connection::~Connection() { TRACE("$0 dtor", this); } void Connection::onOpen() { TRACE("$0 onOpen", this); ::xzero::Connection::onOpen(); // TODO support TCP_DEFER_ACCEPT here #if 0 if (connector()->deferAccept()) onFillable(); else wantFill(); #else wantFill(); #endif } void Connection::onClose() { TRACE("$0 onClose", this); ::xzero::Connection::onClose(); } void Connection::abort() { TRACE("$0 abort()", this); channel_->response()->setBytesTransmitted(generator_.bytesTransmitted()); channel_->responseEnd(); TRACE("$0 abort", this); endpoint()->close(); } void Connection::completed() { TRACE("$0 completed", this); if (channel_->request()->method() != HttpMethod::HEAD && !generator_.isChunked() && generator_.remainingContentLength() > 0) RAISE(IllegalStateError, "Invalid State. Response not fully written but completed() invoked."); generator_.generateTrailer(channel_->response()->trailers()); if (writer_.empty()) { onResponseComplete(true); } else { setCompleter(std::bind(&Connection::onResponseComplete, this, std::placeholders::_1)); wantFlush(); } } void Connection::upgrade(const std::string& protocol, std::function<void(EndPoint*)> callback) { TRACE("upgrade: $0", protocol); upgradeCallback_ = callback; } void Connection::onResponseComplete(bool succeed) { TRACE("$0 onResponseComplete($1)", this, succeed ? "succeed" : "failure"); channel_->response()->setBytesTransmitted(generator_.bytesTransmitted()); channel_->responseEnd(); if (!succeed) { // writing trailer failed. do not attempt to do anything on the wire. return; } if (channel_->response()->status() == HttpStatus::SwitchingProtocols) { TRACE("upgrade in action. releasing HTTP/1 connection and invoking callback"); auto upgrade = upgradeCallback_; auto ep = endpoint(); onClose(); ep->setConnection(nullptr); upgrade(ep); TRACE("upgrade complete"); if (ep->connection()) ep->connection()->onOpen(); else ep->close(); return; } if (channel_->isPersistent()) { TRACE("$0 onResponseComplete: keep-alive was enabled", this); // re-use on keep-alive channel_->reset(); generator_.reset(); endpoint()->setCorking(false); if (inputOffset_ < inputBuffer_.size()) { // have some request pipelined TRACE("$0 completed.onComplete: pipelined read", this); executor()->execute(std::bind(&Connection::parseFragment, this)); } else { // wait for next request TRACE("$0 completed.onComplete: keep-alive read", this); wantFill(); } } else { endpoint()->close(); } } void Connection::send(HttpResponseInfo& responseInfo, const BufferRef& chunk, CompletionHandler onComplete) { setCompleter(onComplete, responseInfo.status()); TRACE("$0 send(BufferRef, status=$1, persistent=$2, chunkSize=$2)", this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no", chunk.size()); patchResponseInfo(responseInfo); if (corkStream_) endpoint()->setCorking(true); generator_.generateResponse(responseInfo, chunk); wantFlush(); } void Connection::send(HttpResponseInfo& responseInfo, Buffer&& chunk, CompletionHandler onComplete) { setCompleter(onComplete, responseInfo.status()); TRACE("$0 send(Buffer, status=$1, persistent=$2, chunkSize=$3)", this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no", chunk.size()); patchResponseInfo(responseInfo); if (corkStream_) endpoint()->setCorking(true); generator_.generateResponse(responseInfo, std::move(chunk)); wantFlush(); } void Connection::send(HttpResponseInfo& responseInfo, FileView&& chunk, CompletionHandler onComplete) { setCompleter(onComplete, responseInfo.status()); TRACE("$0 send(FileView, status=$1, persistent=$2, fd=$3, chunkSize=$4)", this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no", chunk.handle(), chunk.size()); patchResponseInfo(responseInfo); if (corkStream_) endpoint()->setCorking(true); generator_.generateResponse(responseInfo, std::move(chunk)); wantFlush(); } void Connection::setCompleter(CompletionHandler cb) { if (cb && onComplete_) RAISE(IllegalStateError, "There is still another completion hook."); onComplete_ = std::move(cb); } void Connection::setCompleter(CompletionHandler onComplete, HttpStatus status) { // make sure, that on ContinueRequest we do actually continue with // the prior request if (status != HttpStatus::ContinueRequest) { setCompleter(onComplete); } else { setCompleter([this, onComplete](bool s) { wantFill(); if (onComplete) { onComplete(s); } }); } } void Connection::invokeCompleter(bool success) { if (onComplete_) { TRACE("$0 invoking completion callback", this); auto callback = std::move(onComplete_); onComplete_ = nullptr; callback(success); } } void Connection::patchResponseInfo(HttpResponseInfo& responseInfo) { if (static_cast<int>(responseInfo.status()) >= 200) { // patch in HTTP transport-layer headers if (channel_->isPersistent() && requestCount_ < requestMax_) { ++requestCount_; char keepAlive[64]; snprintf(keepAlive, sizeof(keepAlive), "timeout=%llu, max=%zu", (unsigned long long) maxKeepAlive_.seconds(), requestMax_ - requestCount_); responseInfo.headers().append("Connection", "Keep-Alive", ", "); responseInfo.headers().push_back("Keep-Alive", keepAlive); } else { channel_->setPersistent(false); responseInfo.headers().append("Connection", "closed", ", "); } } } void Connection::send(Buffer&& chunk, CompletionHandler onComplete) { setCompleter(onComplete); TRACE("$0 send(Buffer, chunkSize=$1)", this, chunk.size()); generator_.generateBody(std::move(chunk)); wantFlush(); } void Connection::send(const BufferRef& chunk, CompletionHandler onComplete) { setCompleter(onComplete); TRACE("$0 send(BufferRef, chunkSize=$1)", this, chunk.size()); generator_.generateBody(chunk); wantFlush(); } void Connection::send(FileView&& chunk, CompletionHandler onComplete) { setCompleter(onComplete); TRACE("$0 send(FileView, chunkSize=$1)", this, chunk.size()); generator_.generateBody(std::move(chunk)); wantFlush(); } void Connection::setInputBufferSize(size_t size) { TRACE("$0 setInputBufferSize($1)", this, size); inputBuffer_.reserve(size); } void Connection::onFillable() { TRACE("$0 onFillable", this); TRACE("$0 onFillable: calling fill()", this); if (endpoint()->fill(&inputBuffer_) == 0) { TRACE("$0 onFillable: fill() returned 0", this); // RAISE("client EOF"); abort(); return; } parseFragment(); } void Connection::parseFragment() { try { TRACE("parseFragment: calling parseFragment ($0 into $1)", inputOffset_, inputBuffer_.size()); TRACE("dump: '$0'", inputBuffer_.ref(inputOffset_)); size_t n = parser_.parseFragment(inputBuffer_.ref(inputOffset_)); TRACE("parseFragment: called ($0 into $1) => $2 ($3)", inputOffset_, inputBuffer_.size(), n, parser_.state()); inputOffset_ += n; // on a partial read we must make sure that we wait for more input if (parser_.state() != Parser::MESSAGE_BEGIN) { wantFill(); } } catch (const BadMessage& e) { TRACE("$0 parseFragment: BadMessage caught (while in state $1). $2", this, to_string(channel_->state()), e.what()); if (channel_->response()->version() == HttpVersion::UNKNOWN) channel_->response()->setVersion(HttpVersion::VERSION_0_9); if (channel_->state() == HttpChannelState::READING) channel_->setState(HttpChannelState::HANDLING); channel_->response()->sendError(e.httpCode(), e.what()); } } void Connection::onFlushable() { TRACE("$0 onFlushable", this); if (channel_->state() != HttpChannelState::SENDING) channel_->setState(HttpChannelState::SENDING); const bool complete = writer_.flush(endpoint()); if (complete) { TRACE("$0 onFlushable: completed. ($1)", this, (onComplete_ ? "onComplete cb set" : "onComplete cb not set")); channel_->setState(HttpChannelState::HANDLING); invokeCompleter(true); } else { // continue flushing as we still have data pending wantFlush(); } } void Connection::onInterestFailure(const std::exception& error) { TRACE("$0 onInterestFailure($1): $2", this, typeid(error).name(), error.what()); // TODO: improve logging here, as this eats our exception here. // e.g. via (factory or connector)->error(error); logError("Connection", error, "Unhandled exception caught in I/O loop"); invokeCompleter(false); abort(); } } // namespace http1 } // namespace http template<> std::string StringUtil::toString(http::http1::Connection* c) { return StringUtil::toString(c->endpoint()->remoteAddress()); } } // namespace xzero <commit_msg>[http1] Connection: fixes a bug in wrong value of the Connection response header.<commit_after>// This file is part of the "x0" project, http://github.com/christianparpart/x0> // (c) 2009-2016 Christian Parpart <trapni@gmail.com> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/http/http1/Connection.h> #include <xzero/http/http1/Channel.h> #include <xzero/http/HttpDateGenerator.h> #include <xzero/http/HttpResponseInfo.h> #include <xzero/http/HttpResponse.h> #include <xzero/http/HttpRequest.h> #include <xzero/http/BadMessage.h> #include <xzero/net/Connection.h> #include <xzero/net/EndPoint.h> #include <xzero/net/EndPointWriter.h> #include <xzero/executor/Executor.h> #include <xzero/logging.h> #include <xzero/RuntimeError.h> #include <xzero/StringUtil.h> #include <xzero/sysconfig.h> #include <cassert> #include <cstdlib> namespace xzero { namespace http { namespace http1 { #define ERROR(msg...) logError("http.http1.Connection", msg) #if !defined(NDEBUG) #define TRACE(msg...) logTrace("http.http1.Connection", msg) #else #define TRACE(msg...) do {} while (0) #endif Connection::Connection(EndPoint* endpoint, Executor* executor, const HttpHandler& handler, HttpDateGenerator* dateGenerator, HttpOutputCompressor* outputCompressor, size_t maxRequestUriLength, size_t maxRequestBodyLength, size_t maxRequestCount, Duration maxKeepAlive, bool corkStream) : ::xzero::Connection(endpoint, executor), channel_(new Channel( this, executor, handler, maxRequestUriLength, maxRequestBodyLength, dateGenerator, outputCompressor)), parser_(Parser::REQUEST, channel_.get()), inputBuffer_(), inputOffset_(0), writer_(), onComplete_(), generator_(&writer_), maxKeepAlive_(maxKeepAlive), requestCount_(0), requestMax_(maxRequestCount), corkStream_(corkStream) { channel_->request()->setRemoteAddress(endpoint->remoteAddress()); channel_->request()->setLocalAddress(endpoint->localAddress()); TRACE("$0 ctor", this); } Connection::~Connection() { TRACE("$0 dtor", this); } void Connection::onOpen() { TRACE("$0 onOpen", this); ::xzero::Connection::onOpen(); // TODO support TCP_DEFER_ACCEPT here #if 0 if (connector()->deferAccept()) onFillable(); else wantFill(); #else wantFill(); #endif } void Connection::onClose() { TRACE("$0 onClose", this); ::xzero::Connection::onClose(); } void Connection::abort() { TRACE("$0 abort()", this); channel_->response()->setBytesTransmitted(generator_.bytesTransmitted()); channel_->responseEnd(); TRACE("$0 abort", this); endpoint()->close(); } void Connection::completed() { TRACE("$0 completed", this); if (channel_->request()->method() != HttpMethod::HEAD && !generator_.isChunked() && generator_.remainingContentLength() > 0) RAISE(IllegalStateError, "Invalid State. Response not fully written but completed() invoked."); generator_.generateTrailer(channel_->response()->trailers()); if (writer_.empty()) { onResponseComplete(true); } else { setCompleter(std::bind(&Connection::onResponseComplete, this, std::placeholders::_1)); wantFlush(); } } void Connection::upgrade(const std::string& protocol, std::function<void(EndPoint*)> callback) { TRACE("upgrade: $0", protocol); upgradeCallback_ = callback; } void Connection::onResponseComplete(bool succeed) { TRACE("$0 onResponseComplete($1)", this, succeed ? "succeed" : "failure"); channel_->response()->setBytesTransmitted(generator_.bytesTransmitted()); channel_->responseEnd(); if (!succeed) { // writing trailer failed. do not attempt to do anything on the wire. return; } if (channel_->response()->status() == HttpStatus::SwitchingProtocols) { TRACE("upgrade in action. releasing HTTP/1 connection and invoking callback"); auto upgrade = upgradeCallback_; auto ep = endpoint(); onClose(); ep->setConnection(nullptr); upgrade(ep); TRACE("upgrade complete"); if (ep->connection()) ep->connection()->onOpen(); else ep->close(); return; } if (channel_->isPersistent()) { TRACE("$0 onResponseComplete: keep-alive was enabled", this); // re-use on keep-alive channel_->reset(); generator_.reset(); endpoint()->setCorking(false); if (inputOffset_ < inputBuffer_.size()) { // have some request pipelined TRACE("$0 completed.onComplete: pipelined read", this); executor()->execute(std::bind(&Connection::parseFragment, this)); } else { // wait for next request TRACE("$0 completed.onComplete: keep-alive read", this); wantFill(); } } else { endpoint()->close(); } } void Connection::send(HttpResponseInfo& responseInfo, const BufferRef& chunk, CompletionHandler onComplete) { setCompleter(onComplete, responseInfo.status()); TRACE("$0 send(BufferRef, status=$1, persistent=$2, chunkSize=$2)", this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no", chunk.size()); patchResponseInfo(responseInfo); if (corkStream_) endpoint()->setCorking(true); generator_.generateResponse(responseInfo, chunk); wantFlush(); } void Connection::send(HttpResponseInfo& responseInfo, Buffer&& chunk, CompletionHandler onComplete) { setCompleter(onComplete, responseInfo.status()); TRACE("$0 send(Buffer, status=$1, persistent=$2, chunkSize=$3)", this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no", chunk.size()); patchResponseInfo(responseInfo); if (corkStream_) endpoint()->setCorking(true); generator_.generateResponse(responseInfo, std::move(chunk)); wantFlush(); } void Connection::send(HttpResponseInfo& responseInfo, FileView&& chunk, CompletionHandler onComplete) { setCompleter(onComplete, responseInfo.status()); TRACE("$0 send(FileView, status=$1, persistent=$2, fd=$3, chunkSize=$4)", this, responseInfo.status(), channel_->isPersistent() ? "yes" : "no", chunk.handle(), chunk.size()); patchResponseInfo(responseInfo); if (corkStream_) endpoint()->setCorking(true); generator_.generateResponse(responseInfo, std::move(chunk)); wantFlush(); } void Connection::setCompleter(CompletionHandler cb) { if (cb && onComplete_) RAISE(IllegalStateError, "There is still another completion hook."); onComplete_ = std::move(cb); } void Connection::setCompleter(CompletionHandler onComplete, HttpStatus status) { // make sure, that on ContinueRequest we do actually continue with // the prior request if (status != HttpStatus::ContinueRequest) { setCompleter(onComplete); } else { setCompleter([this, onComplete](bool s) { wantFill(); if (onComplete) { onComplete(s); } }); } } void Connection::invokeCompleter(bool success) { if (onComplete_) { TRACE("$0 invoking completion callback", this); auto callback = std::move(onComplete_); onComplete_ = nullptr; callback(success); } } void Connection::patchResponseInfo(HttpResponseInfo& responseInfo) { if (static_cast<int>(responseInfo.status()) >= 200) { // patch in HTTP transport-layer headers if (channel_->isPersistent() && requestCount_ < requestMax_) { ++requestCount_; char keepAlive[64]; snprintf(keepAlive, sizeof(keepAlive), "timeout=%llu, max=%zu", (unsigned long long) maxKeepAlive_.seconds(), requestMax_ - requestCount_); responseInfo.headers().append("Connection", "Keep-Alive", ", "); responseInfo.headers().push_back("Keep-Alive", keepAlive); } else { channel_->setPersistent(false); responseInfo.headers().append("Connection", "close", ", "); } } } void Connection::send(Buffer&& chunk, CompletionHandler onComplete) { setCompleter(onComplete); TRACE("$0 send(Buffer, chunkSize=$1)", this, chunk.size()); generator_.generateBody(std::move(chunk)); wantFlush(); } void Connection::send(const BufferRef& chunk, CompletionHandler onComplete) { setCompleter(onComplete); TRACE("$0 send(BufferRef, chunkSize=$1)", this, chunk.size()); generator_.generateBody(chunk); wantFlush(); } void Connection::send(FileView&& chunk, CompletionHandler onComplete) { setCompleter(onComplete); TRACE("$0 send(FileView, chunkSize=$1)", this, chunk.size()); generator_.generateBody(std::move(chunk)); wantFlush(); } void Connection::setInputBufferSize(size_t size) { TRACE("$0 setInputBufferSize($1)", this, size); inputBuffer_.reserve(size); } void Connection::onFillable() { TRACE("$0 onFillable", this); TRACE("$0 onFillable: calling fill()", this); if (endpoint()->fill(&inputBuffer_) == 0) { TRACE("$0 onFillable: fill() returned 0", this); // RAISE("client EOF"); abort(); return; } parseFragment(); } void Connection::parseFragment() { try { TRACE("parseFragment: calling parseFragment ($0 into $1)", inputOffset_, inputBuffer_.size()); TRACE("dump: '$0'", inputBuffer_.ref(inputOffset_)); size_t n = parser_.parseFragment(inputBuffer_.ref(inputOffset_)); TRACE("parseFragment: called ($0 into $1) => $2 ($3)", inputOffset_, inputBuffer_.size(), n, parser_.state()); inputOffset_ += n; // on a partial read we must make sure that we wait for more input if (parser_.state() != Parser::MESSAGE_BEGIN) { wantFill(); } } catch (const BadMessage& e) { TRACE("$0 parseFragment: BadMessage caught (while in state $1). $2", this, to_string(channel_->state()), e.what()); if (channel_->response()->version() == HttpVersion::UNKNOWN) channel_->response()->setVersion(HttpVersion::VERSION_0_9); if (channel_->state() == HttpChannelState::READING) channel_->setState(HttpChannelState::HANDLING); channel_->response()->sendError(e.httpCode(), e.what()); } } void Connection::onFlushable() { TRACE("$0 onFlushable", this); if (channel_->state() != HttpChannelState::SENDING) channel_->setState(HttpChannelState::SENDING); const bool complete = writer_.flush(endpoint()); if (complete) { TRACE("$0 onFlushable: completed. ($1)", this, (onComplete_ ? "onComplete cb set" : "onComplete cb not set")); channel_->setState(HttpChannelState::HANDLING); invokeCompleter(true); } else { // continue flushing as we still have data pending wantFlush(); } } void Connection::onInterestFailure(const std::exception& error) { TRACE("$0 onInterestFailure($1): $2", this, typeid(error).name(), error.what()); // TODO: improve logging here, as this eats our exception here. // e.g. via (factory or connector)->error(error); logError("Connection", error, "Unhandled exception caught in I/O loop"); invokeCompleter(false); abort(); } } // namespace http1 } // namespace http template<> std::string StringUtil::toString(http::http1::Connection* c) { return StringUtil::toString(c->endpoint()->remoteAddress()); } } // namespace xzero <|endoftext|>
<commit_before>/* FS.cpp - file system wrapper Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "FS.h" #include "FSImpl.h" using namespace fs; static bool sflags(const char* mode, OpenMode& om, AccessMode& am); size_t File::write(uint8_t c) { if (!_p) return 0; _p->write(&c, 1); } size_t File::write(const uint8_t *buf, size_t size) { if (!_p) return 0; _p->write(buf, size); } int File::available() { if (!_p) return false; return _p->size() - _p->position(); } int File::read() { if (!_p) return -1; uint8_t result; if (_p->read(&result, 1) != 1) { return -1; } return result; } size_t File::read(uint8_t* buf, size_t size) { if (!_p) return -1; return _p->read(buf, size); } int File::peek() { if (!_p) return -1; size_t curPos = _p->position(); int result = read(); seek(curPos, SeekSet); return result; } void File::flush() { if (!_p) return; _p->flush(); } bool File::seek(uint32_t pos, SeekMode mode) { if (!_p) return false; return _p->seek(pos, mode); } size_t File::position() const { if (!_p) return 0; return _p->position(); } size_t File::size() const { if (!_p) return 0; return _p->size(); } void File::close() { if (_p) { _p->close(); _p = nullptr; } } File::operator bool() const { return !!_p; } const char* File::name() const { if (!_p) return nullptr; return _p->name(); } File Dir::openFile(const char* mode) { if (!_impl) { return File(); } OpenMode om; AccessMode am; if (!sflags(mode, om, am)) { DEBUGV("Dir::openFile: invalid mode `%s`\r\n", mode); return File(); } return File(_impl->openFile(om, am)); } String Dir::fileName() { if (!_impl) { return String(); } return _impl->fileName(); } size_t Dir::fileSize() { if (!_impl) { return 0; } return _impl->fileSize(); } bool Dir::next() { if (!_impl) { return false; } return _impl->next(); } bool FS::begin() { if (!_impl) { return false; } return _impl->begin(); } File FS::open(const String& path, const char* mode) { return open(path.c_str(), mode); } File FS::open(const char* path, const char* mode) { if (!_impl) { return File(); } OpenMode om; AccessMode am; if (!sflags(mode, om, am)) { DEBUGV("FS::open: invalid mode `%s`\r\n", mode); return File(); } return File(_impl->open(path, om, am)); } Dir FS::openDir(const char* path) { if (!_impl) { return Dir(); } return Dir(_impl->openDir(path)); } Dir FS::openDir(const String& path) { return openDir(path.c_str()); } bool FS::remove(const char* path) { if (!_impl) { return false; } return _impl->remove(path); } bool FS::remove(const String& path) { return remove(path.c_str()); } bool FS::rename(const char* pathFrom, const char* pathTo) { if (!_impl) { return false; } return _impl->rename(pathFrom, pathTo); } bool FS::rename(const String& pathFrom, const String& pathTo) { return rename(pathFrom.c_str(), pathTo.c_str()); } static bool sflags(const char* mode, OpenMode& om, AccessMode& am) { switch (mode[0]) { case 'r': am = AM_READ; om = OM_DEFAULT; break; case 'w': am = AM_WRITE; om = (OpenMode) (OM_CREATE | OM_TRUNCATE); break; case 'a': am = AM_WRITE; om = (OpenMode) (OM_CREATE | OM_APPEND); break; default: return false; } switch(mode[1]) { case '+': am = (AccessMode) (AM_WRITE | AM_READ); break; case 0: break; default: return false; } return true; } #if defined(FS_FREESTANDING_FUNCTIONS) /* TODO: move these functions to public API: */ File open(const char* path, const char* mode); File open(String& path, const char* mode); Dir openDir(const char* path); Dir openDir(String& path); template<> bool mount<FS>(FS& fs, const char* mountPoint); /* */ struct MountEntry { FSImplPtr fs; String path; MountEntry* next; }; static MountEntry* s_mounted = nullptr; template<> bool mount<FS>(FS& fs, const char* mountPoint) { FSImplPtr p = fs._impl; if (!p || !p->mount()) { DEBUGV("FSImpl mount failed\r\n"); return false; } !make sure mountPoint has trailing '/' here MountEntry* entry = new MountEntry; entry->fs = p; entry->path = mountPoint; entry->next = s_mounted; s_mounted = entry; return true; } /* iterate over MountEntries and look for the ones which match the path */ File open(const char* path, const char* mode) { OpenMode om; AccessMode am; if (!sflags(mode, om, am)) { DEBUGV("open: invalid mode `%s`\r\n", mode); return File(); } for (MountEntry* entry = s_mounted; entry; entry = entry->next) { size_t offset = entry->path.length(); if (strstr(path, entry->path.c_str())) { File result = entry->fs->open(path + offset); if (result) return result; } } return File(); } File open(const String& path, const char* mode) { return FS::open(path.c_str(), mode); } Dir openDir(const String& path) { return openDir(path.c_str()); } #endif <commit_msg>Fix return value of FS::write methods<commit_after>/* FS.cpp - file system wrapper Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "FS.h" #include "FSImpl.h" using namespace fs; static bool sflags(const char* mode, OpenMode& om, AccessMode& am); size_t File::write(uint8_t c) { if (!_p) return 0; return _p->write(&c, 1); } size_t File::write(const uint8_t *buf, size_t size) { if (!_p) return 0; return _p->write(buf, size); } int File::available() { if (!_p) return false; return _p->size() - _p->position(); } int File::read() { if (!_p) return -1; uint8_t result; if (_p->read(&result, 1) != 1) { return -1; } return result; } size_t File::read(uint8_t* buf, size_t size) { if (!_p) return -1; return _p->read(buf, size); } int File::peek() { if (!_p) return -1; size_t curPos = _p->position(); int result = read(); seek(curPos, SeekSet); return result; } void File::flush() { if (!_p) return; _p->flush(); } bool File::seek(uint32_t pos, SeekMode mode) { if (!_p) return false; return _p->seek(pos, mode); } size_t File::position() const { if (!_p) return 0; return _p->position(); } size_t File::size() const { if (!_p) return 0; return _p->size(); } void File::close() { if (_p) { _p->close(); _p = nullptr; } } File::operator bool() const { return !!_p; } const char* File::name() const { if (!_p) return nullptr; return _p->name(); } File Dir::openFile(const char* mode) { if (!_impl) { return File(); } OpenMode om; AccessMode am; if (!sflags(mode, om, am)) { DEBUGV("Dir::openFile: invalid mode `%s`\r\n", mode); return File(); } return File(_impl->openFile(om, am)); } String Dir::fileName() { if (!_impl) { return String(); } return _impl->fileName(); } size_t Dir::fileSize() { if (!_impl) { return 0; } return _impl->fileSize(); } bool Dir::next() { if (!_impl) { return false; } return _impl->next(); } bool FS::begin() { if (!_impl) { return false; } return _impl->begin(); } File FS::open(const String& path, const char* mode) { return open(path.c_str(), mode); } File FS::open(const char* path, const char* mode) { if (!_impl) { return File(); } OpenMode om; AccessMode am; if (!sflags(mode, om, am)) { DEBUGV("FS::open: invalid mode `%s`\r\n", mode); return File(); } return File(_impl->open(path, om, am)); } Dir FS::openDir(const char* path) { if (!_impl) { return Dir(); } return Dir(_impl->openDir(path)); } Dir FS::openDir(const String& path) { return openDir(path.c_str()); } bool FS::remove(const char* path) { if (!_impl) { return false; } return _impl->remove(path); } bool FS::remove(const String& path) { return remove(path.c_str()); } bool FS::rename(const char* pathFrom, const char* pathTo) { if (!_impl) { return false; } return _impl->rename(pathFrom, pathTo); } bool FS::rename(const String& pathFrom, const String& pathTo) { return rename(pathFrom.c_str(), pathTo.c_str()); } static bool sflags(const char* mode, OpenMode& om, AccessMode& am) { switch (mode[0]) { case 'r': am = AM_READ; om = OM_DEFAULT; break; case 'w': am = AM_WRITE; om = (OpenMode) (OM_CREATE | OM_TRUNCATE); break; case 'a': am = AM_WRITE; om = (OpenMode) (OM_CREATE | OM_APPEND); break; default: return false; } switch(mode[1]) { case '+': am = (AccessMode) (AM_WRITE | AM_READ); break; case 0: break; default: return false; } return true; } #if defined(FS_FREESTANDING_FUNCTIONS) /* TODO: move these functions to public API: */ File open(const char* path, const char* mode); File open(String& path, const char* mode); Dir openDir(const char* path); Dir openDir(String& path); template<> bool mount<FS>(FS& fs, const char* mountPoint); /* */ struct MountEntry { FSImplPtr fs; String path; MountEntry* next; }; static MountEntry* s_mounted = nullptr; template<> bool mount<FS>(FS& fs, const char* mountPoint) { FSImplPtr p = fs._impl; if (!p || !p->mount()) { DEBUGV("FSImpl mount failed\r\n"); return false; } !make sure mountPoint has trailing '/' here MountEntry* entry = new MountEntry; entry->fs = p; entry->path = mountPoint; entry->next = s_mounted; s_mounted = entry; return true; } /* iterate over MountEntries and look for the ones which match the path */ File open(const char* path, const char* mode) { OpenMode om; AccessMode am; if (!sflags(mode, om, am)) { DEBUGV("open: invalid mode `%s`\r\n", mode); return File(); } for (MountEntry* entry = s_mounted; entry; entry = entry->next) { size_t offset = entry->path.length(); if (strstr(path, entry->path.c_str())) { File result = entry->fs->open(path + offset); if (result) return result; } } return File(); } File open(const String& path, const char* mode) { return FS::open(path.c_str(), mode); } Dir openDir(const String& path) { return openDir(path.c_str()); } #endif <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/binary_cache.hpp> #include <miopen/md5.hpp> #include "test.hpp" void check_cache_file() { auto p = miopen::GetCacheFile("gfx", "base", "args", false); CHECK(p.filename().string() == "base.o"); } void check_cache_str() { auto p = miopen::GetCacheFile("gfx", "base", "args", true); auto name = miopen::md5("base"); CHECK(p.filename().string() == name + ".o"); } int main() { check_cache_file(); check_cache_str(); } <commit_msg>Formatting<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/binary_cache.hpp> #include <miopen/md5.hpp> #include "test.hpp" void check_cache_file() { auto p = miopen::GetCacheFile("gfx", "base", "args", false); CHECK(p.filename().string() == "base.o"); } void check_cache_str() { auto p = miopen::GetCacheFile("gfx", "base", "args", true); auto name = miopen::md5("base"); CHECK(p.filename().string() == name + ".o"); } int main() { check_cache_file(); check_cache_str(); } <|endoftext|>
<commit_before>#include "IMUModel.h" //TODO: remove pragma, problem with eigens optimization stuff "because conversion sequence for the argument is better" #if defined(__GNUC__) #pragma GCC diagnostic ignored "-Wconversion" #endif IMUModel::IMUModel(): integrated(1,0,0,0) { DEBUG_REQUEST_REGISTER("IMUModel:reset_filter", "reset filter", false); DEBUG_REQUEST_REGISTER("IMUModel:reloadParameters", "", false); DEBUG_REQUEST_REGISTER("IMUModel:enableFilterWhileWalking", "enables filter update while walking", false); ukf_acc_global.P = Eigen::Matrix<double,3,3>::Identity(); // covariance matrix of current state ukf_rot.P = Eigen::Matrix<double,3,3>::Identity(); // covariance matrix of current state getDebugParameterList().add(&imuParameters); reloadParameters(); } IMUModel::~IMUModel() { getDebugParameterList().remove(&imuParameters); } void IMUModel::execute(){ DEBUG_REQUEST("IMUModel:reset_filter", ukf_rot.reset(); ukf_acc_global.reset(); integrated=Eigen::Quaterniond(1,0,0,0); ); DEBUG_REQUEST("IMUModel:reloadParameters", reloadParameters(); ); ukf_rot.generateSigmaPoints(); Eigen::Vector3d gyro; // gyro z axis seems to measure in opposite direction (turning left measures negative angular velocity, should be positive) gyro << getGyrometerData().data.x, getGyrometerData().data.y, -getGyrometerData().data.z; ukf_rot.predict(gyro,0.01); // getRobotInfo().getBasicTimeStepInSecond() // don't generate sigma points again because the process noise would be applied a second time // ukf.generateSigmaPoints(); Eigen::Vector3d acceleration = Eigen::Vector3d(getAccelerometerData().data.x, getAccelerometerData().data.y, getAccelerometerData().data.z); IMU_RotationMeasurement z; z << acceleration.normalized(); if(getMotionStatus().currentMotion == motion::walk){ //TODO: mhmhmhmh... if(imuParameters.enableWhileWalking){ ukf_rot.update(z, R_rotation_walk); } } else { ukf_rot.update(z, R_rotation); } IMU_AccMeasurementGlobal z_acc = ukf_rot.state.getRotationAsQuaternion()._transformVector(acceleration); double u_acc = 0; ukf_acc_global.generateSigmaPoints(); ukf_acc_global.predict(u_acc, 0.01); // getRobotInfo().getBasicTimeStepInSecond() ukf_acc_global.update(z_acc, R_acc); writeIMUData(); plots(); lastFrameInfo = getFrameInfo(); } void IMUModel::writeIMUData(){ // raw sensor values getIMUData().rotational_velocity_sensor = getGyrometerData().data; getIMUData().acceleration_sensor = getAccelerometerData().data; // global position data getIMUData().location += getIMUData().velocity * 0.01; // is this a timestep? getIMUData().velocity += getIMUData().acceleration * 0.01; // is this a timestep? getRobotInfo().getBasicTimeStepInSecond() getIMUData().acceleration.x = ukf_acc_global.state.acceleration()(0,0); getIMUData().acceleration.y = ukf_acc_global.state.acceleration()(1,0); getIMUData().acceleration.z = ukf_acc_global.state.acceleration()(2,0) + 9.81; //Math::g Eigen::Quaterniond q; q = ukf_rot.state.getRotationAsQuaternion(); Eigen::Vector3d angles = q.toRotationMatrix().eulerAngles(0,1,2); getIMUData().rotation.x = angles(0); getIMUData().rotation.y = angles(1); getIMUData().rotation.z = angles(2); // from inertiasensorfilter getIMUData().orientation = Vector2d(atan2(q.toRotationMatrix()(2,1), q.toRotationMatrix()(2,2)), atan2(-q.toRotationMatrix()(2,0), q.toRotationMatrix()(2,2))); // only to enable transparent switching with InertiaSensorFilter //getInertialModel().orientation = getIMUData().orientation; } void IMUModel::plots(){ // --- for testing integration Eigen::Matrix3d rot_vel_mat; // getGyrometerData().data.z is inverted! rot_vel_mat << 1 , getGyrometerData().data.z*0.01, getGyrometerData().data.y*0.01, -getGyrometerData().data.z*0.01, 1, -getGyrometerData().data.x*0.01, -getGyrometerData().data.y*0.01, getGyrometerData().data.x*0.01, 1; // continue rotation assuming constant velocity integrated = integrated * Eigen::Quaterniond(rot_vel_mat); Vector3d translation(0,250,250); LINE_3D(ColorClasses::red, translation, translation + quaternionToVector3D(integrated) * 100.0); LINE_3D(ColorClasses::blue, translation, translation + quaternionToVector3D(ukf_rot.state.getRotationAsQuaternion()) * 100.0); PLOT("IMUModel:Error:relative_to_pure_integration[°]", Math::toDegrees(Eigen::AngleAxisd(integrated*ukf_rot.state.getRotationAsQuaternion().inverse()).angle())); // --- end Eigen::Vector3d temp2 = ukf_rot.state.rotation(); Vector3d rot_vec(temp2(0),temp2(1),temp2(2)); RotationMatrix rot(rot_vec); Pose3D pose(rot); pose.translation = Vector3d(0,0,250); // plot gravity Eigen::Vector3d acceleration; acceleration << getAccelerometerData().data.x, getAccelerometerData().data.y, getAccelerometerData().data.z; Eigen::Vector3d temp3 = ukf_rot.state.getRotationAsQuaternion()._transformVector(acceleration); Vector3d gravity(6*temp3(0),6*temp3(1),6*temp3(2)); COLOR_CUBE(30, pose); LINE_3D(ColorClasses::black, pose.translation, pose.translation + gravity*10.0); PLOT("IMUModel:Measurement:rotational_velocity:x", getGyrometerData().data.x); PLOT("IMUModel:Measurement:rotational_velocity:y", getGyrometerData().data.y); PLOT("IMUModel:Measurement:rotational_velocity:z", getGyrometerData().data.z); } void IMUModel::reloadParameters() { /* parameters for stand */ // covariances of the acceleration filter ukf_acc_global.Q << imuParameters.stand.processNoiseAccQ00, 0, 0, 0, imuParameters.stand.processNoiseAccQ11, 0, 0, 0, imuParameters.stand.processNoiseAccQ22; // covariances of the rotation filter ukf_rot.Q << imuParameters.stand.processNoiseRotationQ00, 0, 0, 0, imuParameters.stand.processNoiseRotationQ11, 0, 0, 0, imuParameters.stand.processNoiseRotationQ22; // measurement covariance matrix for the acceleration while stepping R_acc << imuParameters.stand.measurementNoiseAccR00, imuParameters.stand.measurementNoiseAccR01, imuParameters.stand.measurementNoiseAccR02, imuParameters.stand.measurementNoiseAccR01, imuParameters.stand.measurementNoiseAccR11, imuParameters.stand.measurementNoiseAccR12, imuParameters.stand.measurementNoiseAccR02, imuParameters.stand.measurementNoiseAccR12, imuParameters.stand.measurementNoiseAccR22; // measurement covariance matrix for the rotation while stepping R_rotation << imuParameters.stand.measurementNoiseRotationR00, imuParameters.stand.measurementNoiseRotationR01, imuParameters.stand.measurementNoiseRotationR02, imuParameters.stand.measurementNoiseRotationR01, imuParameters.stand.measurementNoiseRotationR11, imuParameters.stand.measurementNoiseRotationR12, imuParameters.stand.measurementNoiseRotationR02, imuParameters.stand.measurementNoiseRotationR12, imuParameters.stand.measurementNoiseRotationR22; /* parameters or walk */ // covariances of the acceleration filter ukf_acc_global.Q << imuParameters.walk.processNoiseAccQ00, 0, 0, 0, imuParameters.walk.processNoiseAccQ11, 0, 0, 0, imuParameters.walk.processNoiseAccQ22; // covariances of the rotation filter ukf_rot.Q << imuParameters.walk.processNoiseRotationQ00, 0, 0, 0, imuParameters.walk.processNoiseRotationQ11, 0, 0, 0, imuParameters.walk.processNoiseRotationQ22; // measurement covariance matrix for the acceleration while stepping R_acc_walk << imuParameters.walk.measurementNoiseAccR00, imuParameters.walk.measurementNoiseAccR01, imuParameters.walk.measurementNoiseAccR02, imuParameters.walk.measurementNoiseAccR01, imuParameters.walk.measurementNoiseAccR11, imuParameters.walk.measurementNoiseAccR12, imuParameters.walk.measurementNoiseAccR02, imuParameters.walk.measurementNoiseAccR12, imuParameters.walk.measurementNoiseAccR22; // measurement covariance matrix for the rotation while stepping R_rotation_walk << imuParameters.walk.measurementNoiseRotationR00, imuParameters.walk.measurementNoiseRotationR01, imuParameters.walk.measurementNoiseRotationR02, imuParameters.walk.measurementNoiseRotationR01, imuParameters.walk.measurementNoiseRotationR11, imuParameters.walk.measurementNoiseRotationR12, imuParameters.walk.measurementNoiseRotationR02, imuParameters.walk.measurementNoiseRotationR12, imuParameters.walk.measurementNoiseRotationR22; } #if defined(__GNUC__) #pragma GCC diagnostic pop #endif <commit_msg>rotation angle export from rotation matrix which is used for the 3d plot<commit_after>#include "IMUModel.h" //TODO: remove pragma, problem with eigens optimization stuff "because conversion sequence for the argument is better" #if defined(__GNUC__) #pragma GCC diagnostic ignored "-Wconversion" #endif IMUModel::IMUModel(): integrated(1,0,0,0) { DEBUG_REQUEST_REGISTER("IMUModel:reset_filter", "reset filter", false); DEBUG_REQUEST_REGISTER("IMUModel:reloadParameters", "", false); DEBUG_REQUEST_REGISTER("IMUModel:enableFilterWhileWalking", "enables filter update while walking", false); ukf_acc_global.P = Eigen::Matrix<double,3,3>::Identity(); // covariance matrix of current state ukf_rot.P = Eigen::Matrix<double,3,3>::Identity(); // covariance matrix of current state getDebugParameterList().add(&imuParameters); reloadParameters(); } IMUModel::~IMUModel() { getDebugParameterList().remove(&imuParameters); } void IMUModel::execute(){ DEBUG_REQUEST("IMUModel:reset_filter", ukf_rot.reset(); ukf_acc_global.reset(); integrated=Eigen::Quaterniond(1,0,0,0); ); DEBUG_REQUEST("IMUModel:reloadParameters", reloadParameters(); ); ukf_rot.generateSigmaPoints(); Eigen::Vector3d gyro; // gyro z axis seems to measure in opposite direction (turning left measures negative angular velocity, should be positive) gyro << getGyrometerData().data.x, getGyrometerData().data.y, -getGyrometerData().data.z; ukf_rot.predict(gyro,0.01); // getRobotInfo().getBasicTimeStepInSecond() // don't generate sigma points again because the process noise would be applied a second time // ukf.generateSigmaPoints(); Eigen::Vector3d acceleration = Eigen::Vector3d(getAccelerometerData().data.x, getAccelerometerData().data.y, getAccelerometerData().data.z); IMU_RotationMeasurement z; z << acceleration.normalized(); if(getMotionStatus().currentMotion == motion::walk){ //TODO: mhmhmhmh... if(imuParameters.enableWhileWalking){ ukf_rot.update(z, R_rotation_walk); } } else { ukf_rot.update(z, R_rotation); } IMU_AccMeasurementGlobal z_acc = ukf_rot.state.getRotationAsQuaternion()._transformVector(acceleration); double u_acc = 0; ukf_acc_global.generateSigmaPoints(); ukf_acc_global.predict(u_acc, 0.01); // getRobotInfo().getBasicTimeStepInSecond() ukf_acc_global.update(z_acc, R_acc); writeIMUData(); plots(); lastFrameInfo = getFrameInfo(); } void IMUModel::writeIMUData(){ // raw sensor values getIMUData().rotational_velocity_sensor = getGyrometerData().data; getIMUData().acceleration_sensor = getAccelerometerData().data; // global position data getIMUData().location += getIMUData().velocity * 0.01; // is this a timestep? getIMUData().velocity += getIMUData().acceleration * 0.01; // is this a timestep? getRobotInfo().getBasicTimeStepInSecond() getIMUData().acceleration.x = ukf_acc_global.state.acceleration()(0,0); getIMUData().acceleration.y = ukf_acc_global.state.acceleration()(1,0); getIMUData().acceleration.z = ukf_acc_global.state.acceleration()(2,0) + 9.81; //Math::g // convert to framework compliant x,y,z angles Eigen::Vector3d temp2 = ukf_rot.state.rotation(); Vector3d rot_vec(temp2(0),temp2(1),temp2(2)); RotationMatrix rot(rot_vec); getIMUData().rotation.x = rot.getXAngle(); getIMUData().rotation.y = rot.getYAngle(); getIMUData().rotation.z = rot.getZAngle(); // from inertiasensorfilter //getIMUData().orientation = Vector2d(atan2( q.toRotationMatrix()(2,1), q.toRotationMatrix()(2,2)), // atan2(-q.toRotationMatrix()(2,0), q.toRotationMatrix()(2,2))); getIMUData().orientation = Vector2d(atan2( rot[1].z, rot[2].z), atan2(-rot[0].z, rot[2].z)); // only to enable transparent switching with InertiaSensorFilter //getInertialModel().orientation = getIMUData().orientation; } void IMUModel::plots(){ // --- for testing integration Eigen::Matrix3d rot_vel_mat; // getGyrometerData().data.z is inverted! rot_vel_mat << 1 , getGyrometerData().data.z*0.01, getGyrometerData().data.y*0.01, -getGyrometerData().data.z*0.01, 1, -getGyrometerData().data.x*0.01, -getGyrometerData().data.y*0.01, getGyrometerData().data.x*0.01, 1; // continue rotation assuming constant velocity integrated = integrated * Eigen::Quaterniond(rot_vel_mat); Vector3d translation(0,250,250); LINE_3D(ColorClasses::red, translation, translation + quaternionToVector3D(integrated) * 100.0); LINE_3D(ColorClasses::blue, translation, translation + quaternionToVector3D(ukf_rot.state.getRotationAsQuaternion()) * 100.0); PLOT("IMUModel:Error:relative_to_pure_integration[°]", Math::toDegrees(Eigen::AngleAxisd(integrated*ukf_rot.state.getRotationAsQuaternion().inverse()).angle())); // --- end Eigen::Vector3d temp2 = ukf_rot.state.rotation(); Vector3d rot_vec(temp2(0),temp2(1),temp2(2)); RotationMatrix rot(rot_vec); Pose3D pose(rot); pose.translation = Vector3d(0,0,250); // plot gravity Eigen::Vector3d acceleration; acceleration << getAccelerometerData().data.x, getAccelerometerData().data.y, getAccelerometerData().data.z; Eigen::Vector3d temp3 = ukf_rot.state.getRotationAsQuaternion()._transformVector(acceleration); Vector3d gravity(6*temp3(0),6*temp3(1),6*temp3(2)); COLOR_CUBE(30, pose); LINE_3D(ColorClasses::black, pose.translation, pose.translation + gravity*10.0); PLOT("IMUModel:Measurement:rotational_velocity:x", getGyrometerData().data.x); PLOT("IMUModel:Measurement:rotational_velocity:y", getGyrometerData().data.y); PLOT("IMUModel:Measurement:rotational_velocity:z", getGyrometerData().data.z); } void IMUModel::reloadParameters() { /* parameters for stand */ // covariances of the acceleration filter ukf_acc_global.Q << imuParameters.stand.processNoiseAccQ00, 0, 0, 0, imuParameters.stand.processNoiseAccQ11, 0, 0, 0, imuParameters.stand.processNoiseAccQ22; // covariances of the rotation filter ukf_rot.Q << imuParameters.stand.processNoiseRotationQ00, 0, 0, 0, imuParameters.stand.processNoiseRotationQ11, 0, 0, 0, imuParameters.stand.processNoiseRotationQ22; // measurement covariance matrix for the acceleration while stepping R_acc << imuParameters.stand.measurementNoiseAccR00, imuParameters.stand.measurementNoiseAccR01, imuParameters.stand.measurementNoiseAccR02, imuParameters.stand.measurementNoiseAccR01, imuParameters.stand.measurementNoiseAccR11, imuParameters.stand.measurementNoiseAccR12, imuParameters.stand.measurementNoiseAccR02, imuParameters.stand.measurementNoiseAccR12, imuParameters.stand.measurementNoiseAccR22; // measurement covariance matrix for the rotation while stepping R_rotation << imuParameters.stand.measurementNoiseRotationR00, imuParameters.stand.measurementNoiseRotationR01, imuParameters.stand.measurementNoiseRotationR02, imuParameters.stand.measurementNoiseRotationR01, imuParameters.stand.measurementNoiseRotationR11, imuParameters.stand.measurementNoiseRotationR12, imuParameters.stand.measurementNoiseRotationR02, imuParameters.stand.measurementNoiseRotationR12, imuParameters.stand.measurementNoiseRotationR22; /* parameters or walk */ // covariances of the acceleration filter ukf_acc_global.Q << imuParameters.walk.processNoiseAccQ00, 0, 0, 0, imuParameters.walk.processNoiseAccQ11, 0, 0, 0, imuParameters.walk.processNoiseAccQ22; // covariances of the rotation filter ukf_rot.Q << imuParameters.walk.processNoiseRotationQ00, 0, 0, 0, imuParameters.walk.processNoiseRotationQ11, 0, 0, 0, imuParameters.walk.processNoiseRotationQ22; // measurement covariance matrix for the acceleration while stepping R_acc_walk << imuParameters.walk.measurementNoiseAccR00, imuParameters.walk.measurementNoiseAccR01, imuParameters.walk.measurementNoiseAccR02, imuParameters.walk.measurementNoiseAccR01, imuParameters.walk.measurementNoiseAccR11, imuParameters.walk.measurementNoiseAccR12, imuParameters.walk.measurementNoiseAccR02, imuParameters.walk.measurementNoiseAccR12, imuParameters.walk.measurementNoiseAccR22; // measurement covariance matrix for the rotation while stepping R_rotation_walk << imuParameters.walk.measurementNoiseRotationR00, imuParameters.walk.measurementNoiseRotationR01, imuParameters.walk.measurementNoiseRotationR02, imuParameters.walk.measurementNoiseRotationR01, imuParameters.walk.measurementNoiseRotationR11, imuParameters.walk.measurementNoiseRotationR12, imuParameters.walk.measurementNoiseRotationR02, imuParameters.walk.measurementNoiseRotationR12, imuParameters.walk.measurementNoiseRotationR22; } #if defined(__GNUC__) #pragma GCC diagnostic pop #endif <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <string> #include "lru.h" #include <chrono> #include <future> #include <random> using namespace std; using namespace ::testing; TEST(LruTest,AddTest) { LruCache<int,string> cache(50); cache.add(5,"some"); ASSERT_STREQ(cache.get(5)->c_str(), "some"); } TEST(LruTest,WithoutAdditionTest) { LruCache<int,string> cache(50); ASSERT_FALSE(cache.get(5)); } TEST(LruTest,EvictTest) { LruCache<int,string> cache(2); cache.add(1,"apple"); cache.add(2,"bee"); cache.add(3,"cat"); ASSERT_FALSE(cache.get(1)); ASSERT_STREQ(cache.get(2)->c_str(), "bee"); ASSERT_STREQ(cache.get(3)->c_str(), "cat"); } const std::string getRandomString(const int stringLength) { std::uniform_int_distribution<int> d(30, 126); std::random_device rd1; // uses RDRND or /dev/urandom std::string retString(' ',stringLength); for (int i = 0; i < stringLength; i++) { *(const_cast<char*>(retString.data())) = static_cast<char>(d(rd1)); } return retString; } const std::chrono::microseconds getTimingForInsertTest(const int cacheSize, const int numDataPoints, const int numberOfThreads = 5) { LruCache<int,std::string> cache(cacheSize * numberOfThreads); std::uniform_int_distribution<int> d(0, numberOfItems * numberOfThreads * 10); std::random_device rd1; // uses RDRND or /dev/urandom std::vector<std::pair<int,std::string> > dataVector[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) { for (int j = 0; j < numDataPoints; j++) { dataVector[i].push_back(std::make_pair(d(rd1), getRandomString(15))); } } std::vector<std::future<void> > futures; auto t1 = std::chrono::high_resolution_clock::now(); for (int i = 0; i < numberOfThreads; i++) { futures.push_back(async(std::launch::async,[&cache,dataVector,i] () { for(auto& dataItem : dataVector[i]) { cache.add(dataItem.first,dataItem.second); } })); } for (auto& future : futures) { future.wait(); } auto t2 = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1); } TEST(LruTest,AddTimingTest) { std::chrono::microseconds doAddTestAndReturnTime() { std::cout << "Random Add Test took " << std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() << " microseconds\n"; } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Fixed the compilation errors in tests.cpp<commit_after>#include <gtest/gtest.h> #include <string> #include "lru.h" #include <chrono> #include <future> #include <random> using namespace std; using namespace ::testing; TEST(LruTest,AddTest) { LruCache<int,string> cache(50); cache.add(5,"some"); ASSERT_STREQ(cache.get(5)->c_str(), "some"); } TEST(LruTest,WithoutAdditionTest) { LruCache<int,string> cache(50); ASSERT_FALSE(cache.get(5)); } TEST(LruTest,EvictTest) { LruCache<int,string> cache(2); cache.add(1,"apple"); cache.add(2,"bee"); cache.add(3,"cat"); ASSERT_FALSE(cache.get(1)); ASSERT_STREQ(cache.get(2)->c_str(), "bee"); ASSERT_STREQ(cache.get(3)->c_str(), "cat"); } const std::string getRandomString(const int stringLength) { std::uniform_int_distribution<int> d(30, 126); std::random_device rd1; // uses RDRND or /dev/urandom std::string retString(' ',stringLength); for (int i = 0; i < stringLength; i++) { *(const_cast<char*>(retString.data())) = static_cast<char>(d(rd1)); } return retString; } void insertToCache(LruCache<int,std::string>* cache, const std::vector<std::pair<int,std::string> >& dataVector) { for(auto& dataItem : dataVector) { cache->add(dataItem.first,dataItem.second); } } const std::chrono::microseconds getTimingForInsertTest(const int cacheSize, const int numDataPoints, const int numberOfThreads = 5) { LruCache<int,std::string> cache(cacheSize); std::uniform_int_distribution<int> d(0, numDataPoints * 10); std::random_device rd1; // uses RDRND or /dev/urandom std::vector<std::pair<int,std::string> > dataVector[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) { for (int j = 0; j < numDataPoints; j++) { dataVector[i].push_back(std::make_pair(d(rd1), getRandomString(15))); } } std::vector<std::future<void> > futures; auto t1 = std::chrono::high_resolution_clock::now(); for (int i = 0; i < numberOfThreads; i++) { futures.push_back(std::async( std::bind(insertToCache, &cache, std::cref(dataVector[i])))); } for (auto& future : futures) { future.wait(); } auto t2 = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1); } TEST(LruTest,AddTimingTest) { std::chrono::microseconds durationForTest = getTimingForInsertTest(500,500,5); std::cout << "Random Add Test took " << durationForTest.count() << " microseconds\n"; } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // INPUTS: {DEM_srtm} // OUTPUTS: {DEMToImageGenerator.tif} , {pretty_DEMToImageGenerator.png} // 6.5 44.5 500 500 0.002 0.002 // // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // \index{otb::DEMToImageGenerator} // \index{otb::DEMHandler} // // // The following example illustrates the use of the otb::DEMToImageGenerator class. // The aim of this class is to generate an image from the srtm data (precising the start extraction // latitude and longitude point). Each pixel is a geographic point and its intensity is // the altitude of the point. // If srtm doesn't have altitude information for a point, the altitude value is set at -32768 (value of the srtm norm). // // Let's look at the minimal code required to use this algorithm. First, the following header // defining the \doxygen{otb}{DEMToImageGenerator} class must be included. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbDEMToImageGenerator.h" // Software Guide : EndCodeSnippet #include "itkRescaleIntensityImageFilter.h" #include "itkThresholdImageFilter.h" #include "itkExceptionObject.h" #include "otbImageFileWriter.h" #include "otbImage.h" int main(int argc, char * argv[]) { if(argc<10) { std::cout << argv[0] <<" DEM folder path , output filename , pretty output filename , Longitude Output Orign point , Latitude Output Origin point , X Output Size, Y Output size , X Spacing , Y Spacing" << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // The image type is now defined using pixel type and // dimension. The output image is defined as an \doxygen{otb}{Image}. // // Software Guide : EndLatex char * folderPath = argv[1]; char * outputName = argv[2]; // Software Guide : BeginCodeSnippet const unsigned int Dimension = 2; typedef otb::Image<double , Dimension> ImageType; // Software Guide : EndCodeSnippet // The writer is defined typedef otb::ImageFileWriter<ImageType> WriterType; // Software Guide : BeginLatex // // The DEMToImageGenerator is defined using the image pixel // type as a template parameter. After that, the object can be instancied. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::DEMToImageGenerator<ImageType> DEMToImageGeneratorType; DEMToImageGeneratorType::Pointer object = DEMToImageGeneratorType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Input parameter types are defined to set the value in the DEMToImageGenerator. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef DEMToImageGeneratorType::SizeType SizeType; typedef DEMToImageGeneratorType::SpacingType SpacingType; typedef DEMToImageGeneratorType::DEMHandlerType DEMHandlerType; typedef DEMHandlerType::PointType PointType; // Software Guide : EndCodeSnippet // Instantiating writer WriterType::Pointer writer = WriterType::New(); // Software Guide : BeginLatex // // The path to the DEM folder is given to the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet object->SetDEMDirectoryPath(folderPath); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The origin (Longitude/Latitude) of the output image in the DEM is given to the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet PointType origin; origin[0] = ::atof(argv[4]); origin[1] = ::atof(argv[5]); object->SetOutputOrigin(origin); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The size (in Pixel) of the output image is given to the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet SizeType size; size[0] = ::atoi(argv[6]); size[1] = ::atoi(argv[7]); object->SetOutputSize(size); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The spacing (step between to consecutive pixel) is given to the filter. // By default, this spacing is set at 0.001. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet SpacingType spacing; spacing[0] = ::atof(argv[8]); spacing[1] = ::atof(argv[9]); object->SetOutputSpacing(spacing); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The output image name is given to the writer and // the filter output is linked to the writer input. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet writer->SetFileName( outputName ); writer->SetInput( object->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The invocation of the \code{Update()} method on the writer triggers the // execution of the pipeline. It is recommended to place update calls in a // \code{try/catch} block in case errors occur and exceptions are thrown. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "Exception itk::ExceptionObject thrown !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } // Software Guide : EndCodeSnippet catch( ... ) { std::cout << "Unknown exception thrown !" << std::endl; return EXIT_FAILURE; } // Pretty image creation for the printing typedef otb::Image<unsigned char, Dimension> OutputPrettyImageType; typedef otb::ImageFileWriter<OutputPrettyImageType> WriterPrettyType; typedef itk::RescaleIntensityImageFilter< ImageType, OutputPrettyImageType> RescalerType; typedef itk::ThresholdImageFilter< ImageType > ThresholderType; ThresholderType::Pointer thresholder = ThresholderType::New(); RescalerType::Pointer rescaler = RescalerType::New(); WriterPrettyType::Pointer prettyWriter = WriterPrettyType::New(); thresholder->SetInput( object->GetOutput() ); thresholder->SetOutsideValue( 0.0 ); thresholder->ThresholdBelow( 0.0 ); thresholder->Update(); rescaler->SetInput( thresholder->GetOutput() ); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); prettyWriter->SetFileName( argv[3] ); prettyWriter->SetInput( rescaler->GetOutput() ); try { prettyWriter->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } catch( ... ) { std::cout << "Unknown exception !" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; // Software Guide : BeginLatex // // Let's now run this example using as input the Srtm datas contained in // \code{DEM_srtm} folder. // // // \begin{figure} \center // \includegraphics[width=0.24\textwidth]{pretty_DEMToImageGenerator.eps} // \itkcaption[ARVI Example]{DEMToImageGenerator image.} // \label{fig:DEMToImageGenerator} // \end{figure} // // Software Guide : EndLatex } <commit_msg>Un directory ne peut pas etre INPUT pour BeginCommandLineArguments<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // OUTPUTS: {DEMToImageGenerator.tif} // OUTPUTS: {pretty_DEMToImageGenerator.png} // 6.5 44.5 500 500 0.002 0.002 ${OTB_SOURCE_DIR}/Examples/Data/DEM_srtm // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // \index{otb::DEMToImageGenerator} // \index{otb::DEMHandler} // // // The following example illustrates the use of the otb::DEMToImageGenerator class. // The aim of this class is to generate an image from the srtm data (precising the start extraction // latitude and longitude point). Each pixel is a geographic point and its intensity is // the altitude of the point. // If srtm doesn't have altitude information for a point, the altitude value is set at -32768 (value of the srtm norm). // // Let's look at the minimal code required to use this algorithm. First, the following header // defining the \doxygen{otb}{DEMToImageGenerator} class must be included. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbDEMToImageGenerator.h" // Software Guide : EndCodeSnippet #include "itkRescaleIntensityImageFilter.h" #include "itkThresholdImageFilter.h" #include "itkExceptionObject.h" #include "otbImageFileWriter.h" #include "otbImage.h" int main(int argc, char * argv[]) { if(argc<10) { std::cout << argv[0] <<" output filename , pretty output filename , Longitude Output Orign point , Latitude Output Origin point , X Output Size, Y Output size , X Spacing , Y Spacing, DEM folder path" << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // The image type is now defined using pixel type and // dimension. The output image is defined as an \doxygen{otb}{Image}. // // Software Guide : EndLatex char * folderPath = argv[9]; char * outputName = argv[1]; // Software Guide : BeginCodeSnippet const unsigned int Dimension = 2; typedef otb::Image<double , Dimension> ImageType; // Software Guide : EndCodeSnippet // The writer is defined typedef otb::ImageFileWriter<ImageType> WriterType; // Software Guide : BeginLatex // // The DEMToImageGenerator is defined using the image pixel // type as a template parameter. After that, the object can be instancied. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::DEMToImageGenerator<ImageType> DEMToImageGeneratorType; DEMToImageGeneratorType::Pointer object = DEMToImageGeneratorType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Input parameter types are defined to set the value in the DEMToImageGenerator. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef DEMToImageGeneratorType::SizeType SizeType; typedef DEMToImageGeneratorType::SpacingType SpacingType; typedef DEMToImageGeneratorType::DEMHandlerType DEMHandlerType; typedef DEMHandlerType::PointType PointType; // Software Guide : EndCodeSnippet // Instantiating writer WriterType::Pointer writer = WriterType::New(); // Software Guide : BeginLatex // // The path to the DEM folder is given to the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet object->SetDEMDirectoryPath(folderPath); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The origin (Longitude/Latitude) of the output image in the DEM is given to the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet PointType origin; origin[0] = ::atof(argv[3]); origin[1] = ::atof(argv[4]); object->SetOutputOrigin(origin); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The size (in Pixel) of the output image is given to the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet SizeType size; size[0] = ::atoi(argv[5]); size[1] = ::atoi(argv[6]); object->SetOutputSize(size); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The spacing (step between to consecutive pixel) is given to the filter. // By default, this spacing is set at 0.001. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet SpacingType spacing; spacing[0] = ::atof(argv[7]); spacing[1] = ::atof(argv[8]); object->SetOutputSpacing(spacing); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The output image name is given to the writer and // the filter output is linked to the writer input. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet writer->SetFileName( outputName ); writer->SetInput( object->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The invocation of the \code{Update()} method on the writer triggers the // execution of the pipeline. It is recommended to place update calls in a // \code{try/catch} block in case errors occur and exceptions are thrown. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "Exception itk::ExceptionObject thrown !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } // Software Guide : EndCodeSnippet catch( ... ) { std::cout << "Unknown exception thrown !" << std::endl; return EXIT_FAILURE; } // Pretty image creation for the printing typedef otb::Image<unsigned char, Dimension> OutputPrettyImageType; typedef otb::ImageFileWriter<OutputPrettyImageType> WriterPrettyType; typedef itk::RescaleIntensityImageFilter< ImageType, OutputPrettyImageType> RescalerType; typedef itk::ThresholdImageFilter< ImageType > ThresholderType; ThresholderType::Pointer thresholder = ThresholderType::New(); RescalerType::Pointer rescaler = RescalerType::New(); WriterPrettyType::Pointer prettyWriter = WriterPrettyType::New(); thresholder->SetInput( object->GetOutput() ); thresholder->SetOutsideValue( 0.0 ); thresholder->ThresholdBelow( 0.0 ); thresholder->Update(); rescaler->SetInput( thresholder->GetOutput() ); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); prettyWriter->SetFileName( argv[2] ); prettyWriter->SetInput( rescaler->GetOutput() ); try { prettyWriter->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } catch( ... ) { std::cout << "Unknown exception !" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; // Software Guide : BeginLatex // // Let's now run this example using as input the Srtm datas contained in // \code{DEM\_srtm} folder. // // // \begin{figure} \center // \includegraphics[width=0.24\textwidth]{pretty_DEMToImageGenerator.eps} // \itkcaption[ARVI Example]{DEMToImageGenerator image.} // \label{fig:DEMToImageGenerator} // \end{figure} // // Software Guide : EndLatex } <|endoftext|>
<commit_before>/* Basic Server code for CMPT 276, Spring 2016. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "TableCache.h" #include "config.h" #include "make_unique.h" #include "azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using web::http::http_headers; using web::http::http_request; using web::http::methods; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; constexpr const char* def_url = "http://localhost:34568"; const string create_table {"CreateTable"}; const string delete_table {"DeleteTable"}; const string update_entity {"UpdateEntity"}; const string delete_entity {"DeleteEntity"}; /* Cache of opened tables */ TableCache table_cache {storage_connection_string}; /* Convert properties represented in Azure Storage type to prop_vals_t type. */ prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) { for (const auto v : properties) { if (v.second.property_type() == edm_type::string) { values.push_back(make_pair(v.first, value::string(v.second.string_value()))); } else if (v.second.property_type() == edm_type::datetime) { values.push_back(make_pair(v.first, value::string(v.second.str()))); } else if(v.second.property_type() == edm_type::int32) { values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); } else if(v.second.property_type() == edm_type::int64) { values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); } else if(v.second.property_type() == edm_type::double_floating_point) { values.push_back(make_pair(v.first, value::number(v.second.double_value()))); } else if(v.second.property_type() == edm_type::boolean) { values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); } else { values.push_back(make_pair(v.first, value::string(v.second.str()))); } } return values; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } /* Top-level routine for processing all HTTP GET requests. GET is the only request that has no command. All operands specify the value(s) to be retrieved. */ void handle_get(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** GET " << path << endl; auto paths = uri::split_path(path); // Need at least a table name if (paths.size() < 1) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[0])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } // GET all entries in table if (paths.size() == 1) { table_query query {}; table_query_iterator end; table_query_iterator it = table.execute_query(query); vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } message.reply(status_codes::OK, value::array(key_vec)); return; } // GET specific entry: Partition == paths[1], Row == paths[2] table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])}; table_result retrieve_result {table.execute(retrieve_operation)}; cout << "HTTP code: " << retrieve_result.http_status_code() << endl; if (retrieve_result.http_status_code() == status_codes::NotFound) { message.reply(status_codes::NotFound); return; } table_entity entity {retrieve_result.entity()}; table_entity::properties_type properties {entity.properties()}; // If the entity has any properties, return them as JSON prop_vals_t values (get_properties(properties)); if (values.size() > 0) message.reply(status_codes::OK, value::object(values)); else message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP POST requests. */ void handle_post(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and a table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Create table (idempotent if table exists) if (paths[0] == create_table) { cout << "Create " << table_name << endl; bool created {table.create_if_not_exists()}; cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl; if (created) message.reply(status_codes::Created); else message.reply(status_codes::Accepted); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP PUT requests. */ void handle_put(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** PUT " << path << endl; auto paths = uri::split_path(path); // Need at least an operation, table name, partition, and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[1])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } table_entity entity {paths[2], paths[3]}; // Update entity if (paths[0] == update_entity) { cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl; table_entity::properties_type& properties = entity.properties(); for (const auto v : get_json_body(message)) { properties[v.first] = entity_property {v.second}; } table_operation operation {table_operation::insert_or_merge_entity(entity)}; table_result op_result {table.execute(operation)}; message.reply(status_codes::OK); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP DELETE requests. */ void handle_delete(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** DELETE " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Delete table if (paths[0] == delete_table) { cout << "Delete " << table_name << endl; if ( ! table.exists()) { message.reply(status_codes::NotFound); } table.delete_table(); table_cache.delete_entry(table_name); message.reply(status_codes::OK); } // Delete entity else if (paths[0] == delete_entity) { // For delete entity, also need partition and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } table_entity entity {paths[2], paths[3]}; cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl; table_operation operation {table_operation::delete_entity(entity)}; table_result op_result {table.execute(operation)}; int code {op_result.http_status_code()}; if (code == status_codes::OK || code == status_codes::NoContent) message.reply(status_codes::OK); else message.reply(code); } else { message.reply(status_codes::BadRequest); } } /* Main server routine Install handlers for the HTTP requests and open the listener, which processes each request asynchronously. Wait for a carriage return, then shut the server down. */ int main (int argc, char const * argv[]) { http_listener listener {def_url}; listener.support(methods::GET, &handle_get); listener.support(methods::POST, &handle_post); listener.support(methods::PUT, &handle_put); listener.support(methods::DEL, &handle_delete); listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <commit_msg>add GET all from partion basic functionality<commit_after>/* Basic Server code for CMPT 276, Spring 2016. */ #include <exception> #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <cpprest/base_uri.h> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <pplx/pplxtasks.h> #include <was/common.h> #include <was/storage_account.h> #include <was/table.h> #include "TableCache.h" #include "config.h" #include "make_unique.h" #include "azure_keys.h" using azure::storage::cloud_storage_account; using azure::storage::storage_credentials; using azure::storage::storage_exception; using azure::storage::cloud_table; using azure::storage::cloud_table_client; using azure::storage::edm_type; using azure::storage::entity_property; using azure::storage::table_entity; using azure::storage::table_operation; using azure::storage::table_query; using azure::storage::table_query_iterator; using azure::storage::table_result; using pplx::extensibility::critical_section_t; using pplx::extensibility::scoped_critical_section_t; using std::cin; using std::cout; using std::endl; using std::getline; using std::make_pair; using std::pair; using std::string; using std::unordered_map; using std::vector; using web::http::http_headers; using web::http::http_request; using web::http::methods; using web::http::status_codes; using web::http::uri; using web::json::value; using web::http::experimental::listener::http_listener; using prop_vals_t = vector<pair<string,value>>; constexpr const char* def_url = "http://localhost:34568"; const string create_table {"CreateTable"}; const string delete_table {"DeleteTable"}; const string update_entity {"UpdateEntity"}; const string delete_entity {"DeleteEntity"}; /* Cache of opened tables */ TableCache table_cache {storage_connection_string}; /* Convert properties represented in Azure Storage type to prop_vals_t type. */ prop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) { for (const auto v : properties) { if (v.second.property_type() == edm_type::string) { values.push_back(make_pair(v.first, value::string(v.second.string_value()))); } else if (v.second.property_type() == edm_type::datetime) { values.push_back(make_pair(v.first, value::string(v.second.str()))); } else if(v.second.property_type() == edm_type::int32) { values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); } else if(v.second.property_type() == edm_type::int64) { values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); } else if(v.second.property_type() == edm_type::double_floating_point) { values.push_back(make_pair(v.first, value::number(v.second.double_value()))); } else if(v.second.property_type() == edm_type::boolean) { values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); } else { values.push_back(make_pair(v.first, value::string(v.second.str()))); } } return values; } /* Given an HTTP message with a JSON body, return the JSON body as an unordered map of strings to strings. Note that all types of JSON values are returned as strings. Use C++ conversion utilities to convert to numbers or dates as necessary. */ unordered_map<string,string> get_json_body(http_request message) { unordered_map<string,string> results {}; const http_headers& headers {message.headers()}; auto content_type (headers.find("Content-Type")); if (content_type == headers.end() || content_type->second != "application/json") return results; value json{}; message.extract_json(true) .then([&json](value v) -> bool { json = v; return true; }) .wait(); if (json.is_object()) { for (const auto& v : json.as_object()) { if (v.second.is_string()) { results[v.first] = v.second.as_string(); } else { results[v.first] = v.second.serialize(); } } } return results; } /* Top-level routine for processing all HTTP GET requests. GET is the only request that has no command. All operands specify the value(s) to be retrieved. */ void handle_get(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** GET " << path << endl; auto paths = uri::split_path(path); // Need at least a table name if (paths.size() < 1) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[0])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } // GET all entries in table if (paths.size() == 1) { table_query query {}; table_query_iterator end; table_query_iterator it = table.execute_query(query); vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } message.reply(status_codes::OK, value::array(key_vec)); return; } // GET all entities from a specific partition: Partition == paths[1], * == paths[2] if (paths[2] == "*") { // Create Query cout << "This works" << endl; table_query query {}; table_query_iterator end; query.set_filter_string(azure::storage::table_query::generate_filter_condition("PartitionKey", azure::storage::query_comparison_operator::equal, paths[1])); // Execute Query table_query_iterator it = table.execute_query(query); // Parse into vector vector<value> key_vec; while (it != end) { cout << "Key: " << it->partition_key() << " / " << it->row_key() << endl; prop_vals_t keys { make_pair("Partition",value::string(it->partition_key())), make_pair("Row", value::string(it->row_key()))}; keys = get_properties(it->properties(), keys); key_vec.push_back(value::object(keys)); ++it; } // message reply message.reply(status_codes::OK, value::array(key_vec)); return; } // GET specific entry: Partition == paths[1], Row == paths[2] table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])}; table_result retrieve_result {table.execute(retrieve_operation)}; cout << "HTTP code: " << retrieve_result.http_status_code() << endl; if (retrieve_result.http_status_code() == status_codes::NotFound) { message.reply(status_codes::NotFound); return; } table_entity entity {retrieve_result.entity()}; table_entity::properties_type properties {entity.properties()}; // If the entity has any properties, return them as JSON prop_vals_t values (get_properties(properties)); if (values.size() > 0) message.reply(status_codes::OK, value::object(values)); else message.reply(status_codes::OK); } /* Top-level routine for processing all HTTP POST requests. */ void handle_post(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** POST " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and a table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Create table (idempotent if table exists) if (paths[0] == create_table) { cout << "Create " << table_name << endl; bool created {table.create_if_not_exists()}; cout << "Administrative table URI " << table.uri().primary_uri().to_string() << endl; if (created) message.reply(status_codes::Created); else message.reply(status_codes::Accepted); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP PUT requests. */ void handle_put(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** PUT " << path << endl; auto paths = uri::split_path(path); // Need at least an operation, table name, partition, and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } cloud_table table {table_cache.lookup_table(paths[1])}; if ( ! table.exists()) { message.reply(status_codes::NotFound); return; } table_entity entity {paths[2], paths[3]}; // Update entity if (paths[0] == update_entity) { cout << "Update " << entity.partition_key() << " / " << entity.row_key() << endl; table_entity::properties_type& properties = entity.properties(); for (const auto v : get_json_body(message)) { properties[v.first] = entity_property {v.second}; } table_operation operation {table_operation::insert_or_merge_entity(entity)}; table_result op_result {table.execute(operation)}; message.reply(status_codes::OK); } else { message.reply(status_codes::BadRequest); } } /* Top-level routine for processing all HTTP DELETE requests. */ void handle_delete(http_request message) { string path {uri::decode(message.relative_uri().path())}; cout << endl << "**** DELETE " << path << endl; auto paths = uri::split_path(path); // Need at least an operation and table name if (paths.size() < 2) { message.reply(status_codes::BadRequest); return; } string table_name {paths[1]}; cloud_table table {table_cache.lookup_table(table_name)}; // Delete table if (paths[0] == delete_table) { cout << "Delete " << table_name << endl; if ( ! table.exists()) { message.reply(status_codes::NotFound); } table.delete_table(); table_cache.delete_entry(table_name); message.reply(status_codes::OK); } // Delete entity else if (paths[0] == delete_entity) { // For delete entity, also need partition and row if (paths.size() < 4) { message.reply(status_codes::BadRequest); return; } table_entity entity {paths[2], paths[3]}; cout << "Delete " << entity.partition_key() << " / " << entity.row_key()<< endl; table_operation operation {table_operation::delete_entity(entity)}; table_result op_result {table.execute(operation)}; int code {op_result.http_status_code()}; if (code == status_codes::OK || code == status_codes::NoContent) message.reply(status_codes::OK); else message.reply(code); } else { message.reply(status_codes::BadRequest); } } /* Main server routine Install handlers for the HTTP requests and open the listener, which processes each request asynchronously. Wait for a carriage return, then shut the server down. */ int main (int argc, char const * argv[]) { http_listener listener {def_url}; listener.support(methods::GET, &handle_get); listener.support(methods::POST, &handle_post); listener.support(methods::PUT, &handle_put); listener.support(methods::DEL, &handle_delete); listener.open().wait(); // Wait for listener to complete starting cout << "Enter carriage return to stop server." << endl; string line; getline(std::cin, line); // Shut it down listener.close().wait(); cout << "Closed" << endl; } <|endoftext|>
<commit_before>#include "positiontracker.h" #include <cmath> #include <common/config/configmanager.h> PositionTracker::PositionTracker() : LOnGPSData(this), LOnMotionCommand(this), LOnIMUData(this) { } Position PositionTracker::GetPosition() { return _current_estimate; } Position PositionTracker::UpdateWithMeasurement(Position S, Position Measurement) { Position result; result.Latitude = ( S.Latitude*Measurement.Latitude.Variance + Measurement.Latitude*S.Latitude.Variance ) / (S.Latitude.Variance+Measurement.Latitude.Variance); result.Longitude = ( S.Longitude*Measurement.Longitude.Variance + Measurement.Longitude*S.Longitude.Variance ) / (S.Longitude.Variance+Measurement.Longitude.Variance); result.Heading = ( S.Heading*Measurement.Heading.Variance + Measurement.Heading*S.Heading.Variance ) / (S.Heading.Variance+Measurement.Heading.Variance); result.Latitude.Variance = ( 1.0 / (1.0/S.Latitude.Variance + 1.0 / Measurement.Latitude.Variance) ); result.Longitude.Variance = ( 1.0 / (1.0/S.Longitude.Variance + 1.0 / Measurement.Longitude.Variance) ); result.Heading.Variance = ( 1.0 / (1.0/S.Heading.Variance + 1.0 / Measurement.Heading.Variance) ); return result; } Position PositionTracker::UpdateWithMotion(Position S, Position Delta) { Position result; result.Latitude = S.Latitude + Delta.Latitude; result.Longitude = S.Longitude + Delta.Longitude; result.Heading = S.Heading + Delta.Heading; result.Latitude.Variance = S.Latitude.Variance + Delta.Latitude.Variance; result.Longitude.Variance = S.Longitude.Variance + Delta.Longitude.Variance; result.Heading.Variance = S.Heading.Variance + Delta.Heading.Variance; return result; } Position PositionTracker::DeltaFromMotionCommand(MotorCommand cmd) { /* * TODO - Need to make sure this accounts for the time it takes to actually get to where we're going. * Perhaps fire this after the motion command is done. */ using namespace std; double V = ( cmd.rightVel + cmd.leftVel ) / 2.0; double W = ( cmd.rightVel - cmd.leftVel ) / ConfigManager::Instance().getValue("Robot", "Baseline", 1.0); double t = cmd.millis / 1000.0; double R = V/W; Position delta; double theta = _current_estimate.Heading * M_PI/180.0; double thetaPrime = (_current_estimate.Heading + W*t) * M_PI/180.0; delta.Heading = W*t; delta.Latitude = R*(cos(theta) - cos(thetaPrime)); delta.Longitude = R*(sin(thetaPrime) - sin(theta)); // TODO - handle variances return delta; } Position PositionTracker::MeasurementFromIMUData(IMUData data) { // Uses the "Destination point given distance and bearing from start point" described here: // http://www.movable-type.co.uk/scripts/latlong.html#destPoint Position measurement; double lat1 = _current_estimate.Latitude; double lon1 = _current_estimate.Latitude; double hed1 = _current_estimate.Heading; double dx = data.X /* * time*time */; double dy = data.Y /* * time*time */; double d = sqrt(dx*dx + dy*dy); // Distance travelled double R = 6378137; // radius of Earth measurement.Latitude = asin(sin(lat1)*cos(d/R)+cos(lat1)*sin(d/R)*cos(hed1)); measurement.Longitude = (lon1 + atan2(sin(hed1)*sin(d/R)*cos(lat1),cos(d/R)-sin(lat1)*sin(measurement.Latitude))); measurement.Heading = (atan2((measurement.Longitude-lon1)*sin(lat1), cos(measurement.Latitude)*sin(lat1)-sin(measurement.Latitude)*cos(lat1)*cos(measurement.Longitude-lon1))); measurement.Heading = (measurement.Heading+180); while(measurement.Heading >= 360) measurement.Heading = (measurement.Heading - 360); while(measurement.Heading < 0) measurement.Heading = (measurement.Heading + 360); // TODO - handle variances return measurement; } void PositionTracker::OnGPSData(GPSData data) { Position measurement; measurement.Latitude = data.Lat(); measurement.Longitude = data.Long(); // TODO - make sure the GPS actually outputs heading data measurement.Heading = data.Heading(); // TODO - handle variances _current_estimate = UpdateWithMeasurement(_current_estimate, measurement); } void PositionTracker::OnIMUData(IMUData data) { _current_estimate = UpdateWithMeasurement(_current_estimate, MeasurementFromIMUData(data)); } void PositionTracker::OnMotionCommand(MotorCommand cmd) { /* * TODO - Need to make sure this accounts for the time it takes to actually get to where we're going. * Perhaps fire this after the motion command is done. */ _current_estimate = UpdateWithMotion(_current_estimate, DeltaFromMotionCommand(cmd)); } <commit_msg>Adds more TODO comments.<commit_after>#include "positiontracker.h" #include <cmath> #include <common/config/configmanager.h> PositionTracker::PositionTracker() : LOnGPSData(this), LOnMotionCommand(this), LOnIMUData(this) { } Position PositionTracker::GetPosition() { return _current_estimate; } Position PositionTracker::UpdateWithMeasurement(Position S, Position Measurement) { Position result; result.Latitude = ( S.Latitude*Measurement.Latitude.Variance + Measurement.Latitude*S.Latitude.Variance ) / (S.Latitude.Variance+Measurement.Latitude.Variance); result.Longitude = ( S.Longitude*Measurement.Longitude.Variance + Measurement.Longitude*S.Longitude.Variance ) / (S.Longitude.Variance+Measurement.Longitude.Variance); result.Heading = ( S.Heading*Measurement.Heading.Variance + Measurement.Heading*S.Heading.Variance ) / (S.Heading.Variance+Measurement.Heading.Variance); result.Latitude.Variance = ( 1.0 / (1.0/S.Latitude.Variance + 1.0 / Measurement.Latitude.Variance) ); result.Longitude.Variance = ( 1.0 / (1.0/S.Longitude.Variance + 1.0 / Measurement.Longitude.Variance) ); result.Heading.Variance = ( 1.0 / (1.0/S.Heading.Variance + 1.0 / Measurement.Heading.Variance) ); return result; } Position PositionTracker::UpdateWithMotion(Position S, Position Delta) { Position result; result.Latitude = S.Latitude + Delta.Latitude; result.Longitude = S.Longitude + Delta.Longitude; result.Heading = S.Heading + Delta.Heading; result.Latitude.Variance = S.Latitude.Variance + Delta.Latitude.Variance; result.Longitude.Variance = S.Longitude.Variance + Delta.Longitude.Variance; result.Heading.Variance = S.Heading.Variance + Delta.Heading.Variance; return result; } Position PositionTracker::DeltaFromMotionCommand(MotorCommand cmd) { /* * TODO - Need to make sure this accounts for the time it takes to actually get to where we're going. * Perhaps fire this after the motion command is done. */ /* * TODO!!! - This will fail spectacularly if W is zero (ie. straight forward or backward) * This is very much not good. */ using namespace std; double V = ( cmd.rightVel + cmd.leftVel ) / 2.0; double W = ( cmd.rightVel - cmd.leftVel ) / ConfigManager::Instance().getValue("Robot", "Baseline", 1.0); double t = cmd.millis / 1000.0; double R = V/W; Position delta; double theta = _current_estimate.Heading * M_PI/180.0; double thetaPrime = (_current_estimate.Heading + W*t) * M_PI/180.0; delta.Heading = W*t; delta.Latitude = R*(cos(theta) - cos(thetaPrime)); delta.Longitude = R*(sin(thetaPrime) - sin(theta)); // TODO - handle variances return delta; } Position PositionTracker::MeasurementFromIMUData(IMUData data) { // Uses the "Destination point given distance and bearing from start point" described here: // http://www.movable-type.co.uk/scripts/latlong.html#destPoint Position measurement; double lat1 = _current_estimate.Latitude; double lon1 = _current_estimate.Latitude; double hed1 = _current_estimate.Heading; double dx = data.X /* * time*time */; double dy = data.Y /* * time*time */; double d = sqrt(dx*dx + dy*dy); // Distance travelled double R = 6378137; // radius of Earth measurement.Latitude = asin(sin(lat1)*cos(d/R)+cos(lat1)*sin(d/R)*cos(hed1)); measurement.Longitude = (lon1 + atan2(sin(hed1)*sin(d/R)*cos(lat1),cos(d/R)-sin(lat1)*sin(measurement.Latitude))); measurement.Heading = (atan2((measurement.Longitude-lon1)*sin(lat1), cos(measurement.Latitude)*sin(lat1)-sin(measurement.Latitude)*cos(lat1)*cos(measurement.Longitude-lon1))); measurement.Heading = (measurement.Heading+180); while(measurement.Heading >= 360) measurement.Heading = (measurement.Heading - 360); while(measurement.Heading < 0) measurement.Heading = (measurement.Heading + 360); // TODO - handle variances return measurement; } void PositionTracker::OnGPSData(GPSData data) { Position measurement; measurement.Latitude = data.Lat(); measurement.Longitude = data.Long(); // TODO - make sure the GPS actually outputs heading data measurement.Heading = data.Heading(); // TODO - handle variances _current_estimate = UpdateWithMeasurement(_current_estimate, measurement); } void PositionTracker::OnIMUData(IMUData data) { _current_estimate = UpdateWithMeasurement(_current_estimate, MeasurementFromIMUData(data)); } void PositionTracker::OnMotionCommand(MotorCommand cmd) { /* * TODO - Need to make sure this accounts for the time it takes to actually get to where we're going. * Perhaps fire this after the motion command is done. */ _current_estimate = UpdateWithMotion(_current_estimate, DeltaFromMotionCommand(cmd)); } <|endoftext|>
<commit_before>#define WIN32_LEAN_AND_MEAN #include <SDKDDKVer.h> #include <windows.h> #include "HookAPI.h" #include "TeamSpeak.h" #include <ws2tcpip.h> #include <atomic> #include <list> #include <concurrent_queue.h> #pragma comment (lib, "Ws2_32.lib") // Default buffer length #define BUFLEN 4096 // Socket used for TeamSpeak communication std::atomic<SOCKET> client = NULL; // Lua state used when requiring script files std::atomic<lua_State *> state = NULL; // Boolean telling the socket thread whether to keep the network loop running std::atomic<bool> running = false; // Boolean telling if the TeamSpeak mod has been initialized std::atomic<bool> initialized = true; // Queue of commands to be sent to the Lua script Concurrency::concurrent_queue<String *> queue; // Chat message history, its length and status std::list<ChatMessage *> history; unsigned int max_history = 20; bool loading_history = false; // Id of last client to send a private message String last_sender; // Text and cursor position of the chat input box String input_text; float input_position; // Tries to connect to TeamSpeak using ClientQuery // Returns a new socket or NULL on failure SOCKET Connect(PCSTR hostname, PCSTR port) { // Create a structure used for containing the socket information WSADATA wsaData; int result = WSAStartup(MAKEWORD(2, 2), &wsaData); if (result != 0) return NULL; // Create a structure used for containing the connection information struct addrinfo *info, *ptr, hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; result = getaddrinfo(hostname, port, &hints, &info); // Cleanup on failure if (result != 0) { WSACleanup(); return NULL; } // Try to connect to the specified address SOCKET client = INVALID_SOCKET; for (ptr = info; ptr != NULL; ptr = ptr->ai_next) { client = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); // Cleanup and stop on failure if (client == INVALID_SOCKET) { WSACleanup(); return NULL; } result = connect(client, ptr->ai_addr, (int)ptr->ai_addrlen); // Cleanup but try to continue on failure if (result == SOCKET_ERROR) { closesocket(client); client = INVALID_SOCKET; continue; } break; } // Release the address information strcuture from memory freeaddrinfo(info); // Return NULL if the connection could not be established if (client == INVALID_SOCKET) { WSACleanup(); return NULL; } // Set keep alive to true for the socket char value = 1; setsockopt(client, SOL_SOCKET, SO_KEEPALIVE, &value, sizeof(value)); return client; } // Socket thread // Executes a loop reading messages and passing them to the Lua script DWORD WINAPI Main(LPVOID param) { int length; char buffer[BUFLEN]; char *ptr, *context; const char *separator = "\n\r"; const char *command = "clientnotifyregister schandlerid=0 event=any\n"; // Start the network loop for (running = true; running;) { // Connect to the local TeamSpeak ClientQuery and retry on failure client = Connect("127.0.0.1", "25639"); if (client == NULL) continue; // Receive the initial ClientQuery headers for (int header = 182; header > 0; header -= length) length = recv(client, buffer, BUFLEN, 0); // Send a "listen to all events" command and receive its response send(client, command, strlen(command), 0); recv(client, buffer, BUFLEN, 0); // Read messages from the ClientQuery input stream do { // Receive a message and null terminate it buffer[length = recv(client, buffer, BUFLEN, 0)] = 0; // Split up different messages that might be in the same buffer ptr = strtok_s(buffer, separator, &context); while (ptr != NULL) { // Copy the messages to heap memory and save them to a queue queue.push(new String(ptr)); ptr = strtok_s(NULL, separator, &context); } } while (length > 0 && running); // Once the connection is closed clean up all of its resources { SOCKET socket = client; client = NULL; closesocket(socket); WSACleanup(); } } return 0; } // Called by the Lua script when a TeamSpeak command is used // Sends a message using the ClientQuery socket int SendCommand(lua_State *L) { // Stop if the socket is not connected or no message has been sent if (client == NULL || lua_type(L, 1) == LUA_TNONE) return 0; // Send the message const char *buffer = lua_tostring(L, 1); send(client, buffer, strlen(buffer), 0); send(client, "\n", 1, 0); return 0; } // Called by the Lua script when a new message is received // Saves a message to chat history int SaveChatMessage(lua_State *L) { // Stop if chat history is disabled or being loaded if (loading_history || max_history < 1) return 0; // Create a new message ChatMessage *message = new ChatMessage(); message->sender = String(lua_tostring(L, 1)); message->message = String(lua_tostring(L, 2)); // Save the Color userdata directly message->color = *(Color *)lua_touserdata(L, 3); message->icon = String(lua_tostring(L, 4)); // Insert the message at the end of the chat history history.push_back(message); // Remove the first few messages if the limit has been reached while (history.size() > max_history) { delete history.front(); history.pop_front(); } return 0; } // Called by the Lua script once the chat gui loads // Loads all messages from chat histor into the chat int LoadChatMessages(lua_State *L) { // Stop if there is no chat history or we didn't recive a chat gui if (history.empty() || lua_type(L, 1) == LUA_TNONE) return 0; loading_history = true; // Stores the current message ChatMessage *message; bool is_private; // Get the private TeamSpeak message color lua_getglobal(L, "TS"); lua_getfield(L, -1, "Options"); lua_getfield(L, -1, "colors"); lua_getfield(L, -1, "private"); int private_color = lua_gettop(L); // Get the private TeamSpeak message formatter lua_getfield(L, -4, "Formatters"); lua_getfield(L, -1, "private"); int private_formatter = lua_gettop(L); // And load each message inside the chat history for (auto i = history.begin(); i != history.end(); i++) { message = *i; lua_getfield(L, 1, "receive_message"); lua_pushvalue(L, 1); lua_pushlstring(L, message->sender.value(), message->sender.length()); lua_pushlstring(L, message->message.value(), message->message.length()); // Recreate and push the userdata message->color.push(L); // Check if this is a private message is_private = lua_equal(L, -1, private_color) == 1; // Set an icon if required if (message->icon.value() == NULL) lua_pushnil(L); else lua_pushlstring(L, message->icon.value(), message->icon.length()); lua_pcall(L, 5, 0, 0); // Format the last message if it was private if (is_private) { lua_pushvalue(L, 1); lua_pcall(L, 1, 0, 0); } } loading_history = false; return 0; } // Requires the TeamSpeak Lua script and loads it into the game void WINAPI OnRequire(lua_State *L, LPCSTR file, LPVOID param) { // If the required file matches any we need to override if (strcmp(file, "lib/managers/chatmanager") == 0 || strcmp(file, "lib/managers/hud/hudchat") == 0 || strcmp(file, "lib/utils/game_state_machine/gamestatemachine") == 0) { // Check if the global TeamSpeak variable has been defined lua_getglobal(L, "TS"); int type = lua_type(L, -1); // Load the main script for the required file if (luaL_loadfile(L, "TeamSpeak/TeamSpeak.lua") == 0) { // And execute it lua_pcall(L, 0, LUA_MULTRET, 0); // Make sure to only initalize once for each state if (type != LUA_TNIL) return; // Index the global TeamSpeak variable lua_getglobal(L, "TS"); int index = lua_gettop(L); // Load Lua variables if (last_sender != NULL) { lua_pushlstring(L, last_sender.value(), last_sender.length()); lua_setfield(L, index, "last_sender"); } if (input_text != NULL) { lua_createtable(L, 0, 2); lua_pushlstring(L, input_text.value(), input_text.length()); lua_setfield(L, -2, "text"); lua_pushfloat(L, input_position); lua_setfield(L, -2, "position"); lua_setfield(L, index, "input"); } // Check the chat history option lua_getfield(L, index, "Options"); lua_getfield(L, -1, "chat_history"); max_history = (unsigned int)lua_tonumber(L, -1); // Map C++ functions in Lua lua_pushcfunction(L, &SendCommand); lua_setfield(L, index, "send_command"); lua_pushcfunction(L, &SaveChatMessage); lua_setfield(L, index, "save_chat_message"); // Register a Lua hook for loading messages if chat history is enabled if (max_history > 0) { lua_getfield(L, index, "Hooks"); lua_getfield(L, -1, "add"); lua_pushvalue(L, -2); lua_pushstring(L, "ChatGUI:Load"); lua_pushcfunction(L, &LoadChatMessages); lua_pcall(L, 3, 0, 0); } // Note that the Lua side of this mod still requires initialization initialized = false; // Save the current Lua state and create the network thread state = L; if (!running) CreateThread(NULL, 0, Main, NULL, 0, NULL); } } } // Runs on game ticks and sends messages from TeamSpeak to the Lua script void WINAPI OnGameTick(lua_State *L, LPCSTR type, LPVOID param) { // Make sure this is the correct Lua state if (L != state) return; if (strcmp(type, "update") == 0) { // Index the global TeamSpeak variable lua_getglobal(L, "TS"); int index = lua_gettop(L); // Initialize the Lua part of the mod if a connection // to ClientQuery has been established if (!initialized && client != NULL) { initialized = true; // Update the list of clients connected to the server lua_getfield(L, index, "fetch_info"); lua_pcall(L, 0, 0, 0); } // Pass any recived messages from TeamSpeak to Lua if (!queue.empty()) { lua_getfield(L, index, "Hooks"); for (String *message; queue.try_pop(message);) { lua_getfield(L, -1, "call"); lua_pushvalue(L, -2); lua_pushstring(L, "TeamSpeak:Receive"); lua_pushlstring(L, message->value(), message->length()); lua_pcall(L, 3, 0, 0); delete message; } } } else if (strcmp(type, "destroy") == 0) { // Index the global TeamSpeak variable lua_getglobal(L, "TS"); int index = lua_gettop(L); // Store Lua variables lua_getfield(L, index, "last_sender"); if (lua_type(L, -1) != LUA_TNIL) last_sender = String(lua_tostring(L, -1)); lua_getfield(L, index, "input"); if (lua_type(L, -1) != LUA_TNIL) { lua_getfield(L, -1, "text"); input_text = String(lua_tostring(L, -1)); lua_getfield(L, -2, "position"); input_position = lua_tonumber(L, -1); } } } // DLL entry point BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: // Register a callback for when the game requires an internal file RegisterCallback(REQUIRE_CALLBACK, &OnRequire, NULL); // Register a callback for game ticks RegisterCallback(GAMETICK_CALLBACK, &OnGameTick, NULL); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: // Stop the network loop running = false; // Free memory for (String *message; !queue.empty();) if (queue.try_pop(message)) delete message; for (; !history.empty(); history.pop_front()) delete history.front(); break; } return TRUE; } <commit_msg>fix unformatted messages bug<commit_after>#define WIN32_LEAN_AND_MEAN #include <SDKDDKVer.h> #include <windows.h> #include "HookAPI.h" #include "TeamSpeak.h" #include <ws2tcpip.h> #include <atomic> #include <list> #include <concurrent_queue.h> #pragma comment (lib, "Ws2_32.lib") // Default buffer length #define BUFLEN 4096 // Socket used for TeamSpeak communication std::atomic<SOCKET> client = NULL; // Lua state used when requiring script files std::atomic<lua_State *> state = NULL; // Boolean telling the socket thread whether to keep the network loop running std::atomic<bool> running = false; // Boolean telling if the TeamSpeak mod has been initialized std::atomic<bool> initialized = true; // Queue of commands to be sent to the Lua script Concurrency::concurrent_queue<String *> queue; // Chat message history, its length and status std::list<ChatMessage *> history; unsigned int max_history = 20; bool loading_history = false; // Id of last client to send a private message String last_sender; // Text and cursor position of the chat input box String input_text; float input_position; // Tries to connect to TeamSpeak using ClientQuery // Returns a new socket or NULL on failure SOCKET Connect(PCSTR hostname, PCSTR port) { // Create a structure used for containing the socket information WSADATA wsaData; int result = WSAStartup(MAKEWORD(2, 2), &wsaData); if (result != 0) return NULL; // Create a structure used for containing the connection information struct addrinfo *info, *ptr, hints; ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; result = getaddrinfo(hostname, port, &hints, &info); // Cleanup on failure if (result != 0) { WSACleanup(); return NULL; } // Try to connect to the specified address SOCKET client = INVALID_SOCKET; for (ptr = info; ptr != NULL; ptr = ptr->ai_next) { client = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); // Cleanup and stop on failure if (client == INVALID_SOCKET) { WSACleanup(); return NULL; } result = connect(client, ptr->ai_addr, (int)ptr->ai_addrlen); // Cleanup but try to continue on failure if (result == SOCKET_ERROR) { closesocket(client); client = INVALID_SOCKET; continue; } break; } // Release the address information strcuture from memory freeaddrinfo(info); // Return NULL if the connection could not be established if (client == INVALID_SOCKET) { WSACleanup(); return NULL; } // Set keep alive to true for the socket char value = 1; setsockopt(client, SOL_SOCKET, SO_KEEPALIVE, &value, sizeof(value)); return client; } // Socket thread // Executes a loop reading messages and passing them to the Lua script DWORD WINAPI Main(LPVOID param) { int length; char buffer[BUFLEN]; char *ptr, *context; const char *separator = "\n\r"; const char *command = "clientnotifyregister schandlerid=0 event=any\n"; // Start the network loop for (running = true; running;) { // Connect to the local TeamSpeak ClientQuery and retry on failure client = Connect("127.0.0.1", "25639"); if (client == NULL) continue; // Receive the initial ClientQuery headers for (int header = 182; header > 0; header -= length) length = recv(client, buffer, BUFLEN, 0); // Send a "listen to all events" command and receive its response send(client, command, strlen(command), 0); recv(client, buffer, BUFLEN, 0); // Read messages from the ClientQuery input stream do { // Receive a message and null terminate it buffer[length = recv(client, buffer, BUFLEN, 0)] = 0; // Split up different messages that might be in the same buffer ptr = strtok_s(buffer, separator, &context); while (ptr != NULL) { // Copy the messages to heap memory and save them to a queue queue.push(new String(ptr)); ptr = strtok_s(NULL, separator, &context); } } while (length > 0 && running); // Once the connection is closed clean up all of its resources { SOCKET socket = client; client = NULL; closesocket(socket); WSACleanup(); } } return 0; } // Called by the Lua script when a TeamSpeak command is used // Sends a message using the ClientQuery socket int SendCommand(lua_State *L) { // Stop if the socket is not connected or no message has been sent if (client == NULL || lua_type(L, 1) == LUA_TNONE) return 0; // Send the message const char *buffer = lua_tostring(L, 1); send(client, buffer, strlen(buffer), 0); send(client, "\n", 1, 0); return 0; } // Called by the Lua script when a new message is received // Saves a message to chat history int SaveChatMessage(lua_State *L) { // Stop if chat history is disabled or being loaded if (loading_history || max_history < 1) return 0; // Create a new message ChatMessage *message = new ChatMessage(); message->sender = String(lua_tostring(L, 1)); message->message = String(lua_tostring(L, 2)); // Save the Color userdata directly message->color = *(Color *)lua_touserdata(L, 3); message->icon = String(lua_tostring(L, 4)); // Insert the message at the end of the chat history history.push_back(message); // Remove the first few messages if the limit has been reached while (history.size() > max_history) { delete history.front(); history.pop_front(); } return 0; } // Called by the Lua script once the chat gui loads // Loads all messages from chat histor into the chat int LoadChatMessages(lua_State *L) { // Stop if there is no chat history or we didn't recive a chat gui if (history.empty() || lua_type(L, 1) == LUA_TNONE) return 0; loading_history = true; // Stores the current message ChatMessage *message; bool is_private; // Get the private message color lua_getglobal(L, "TS"); lua_getfield(L, -1, "Options"); lua_getfield(L, -1, "colors"); lua_getfield(L, -1, "private"); int private_color = lua_gettop(L); // Get the TeamSpeak message formatters lua_getfield(L, -4, "Formatters"); // And load each message inside the chat history for (auto i = history.begin(); i != history.end(); i++) { message = *i; lua_getfield(L, 1, "receive_message"); lua_pushvalue(L, 1); lua_pushlstring(L, message->sender.value(), message->sender.length()); lua_pushlstring(L, message->message.value(), message->message.length()); // Recreate and push the userdata message->color.push(L); // Check if this is a private message is_private = lua_equal(L, -1, private_color) == 1; // Set an icon if required if (message->icon.value() == NULL) lua_pushnil(L); else lua_pushlstring(L, message->icon.value(), message->icon.length()); lua_pcall(L, 5, 0, 0); // Format the last message if required if (is_private) { // Call the private formatter lua_getfield(L, -1, "private"); lua_pushvalue(L, 1); lua_pcall(L, 1, 0, 0); } } loading_history = false; return 0; } // Requires the TeamSpeak Lua script and loads it into the game void WINAPI OnRequire(lua_State *L, LPCSTR file, LPVOID param) { // If the required file matches any we need to override if (strcmp(file, "lib/managers/chatmanager") == 0 || strcmp(file, "lib/managers/hud/hudchat") == 0 || strcmp(file, "lib/utils/game_state_machine/gamestatemachine") == 0) { // Check if the global TeamSpeak variable has been defined lua_getglobal(L, "TS"); int type = lua_type(L, -1); // Load the main script for the required file if (luaL_loadfile(L, "TeamSpeak/TeamSpeak.lua") == 0) { // And execute it lua_pcall(L, 0, LUA_MULTRET, 0); // Make sure to only initalize once for each state if (type != LUA_TNIL) return; // Index the global TeamSpeak variable lua_getglobal(L, "TS"); int index = lua_gettop(L); // Load Lua variables if (last_sender != NULL) { lua_pushlstring(L, last_sender.value(), last_sender.length()); lua_setfield(L, index, "last_sender"); } if (input_text != NULL) { lua_createtable(L, 0, 2); lua_pushlstring(L, input_text.value(), input_text.length()); lua_setfield(L, -2, "text"); lua_pushfloat(L, input_position); lua_setfield(L, -2, "position"); lua_setfield(L, index, "input"); } // Check the chat history option lua_getfield(L, index, "Options"); lua_getfield(L, -1, "chat_history"); max_history = (unsigned int)lua_tonumber(L, -1); // Map C++ functions in Lua lua_pushcfunction(L, &SendCommand); lua_setfield(L, index, "send_command"); lua_pushcfunction(L, &SaveChatMessage); lua_setfield(L, index, "save_chat_message"); // Register a Lua hook for loading messages if chat history is enabled if (max_history > 0) { lua_getfield(L, index, "Hooks"); lua_getfield(L, -1, "add"); lua_pushvalue(L, -2); lua_pushstring(L, "ChatGUI:Load"); lua_pushcfunction(L, &LoadChatMessages); lua_pcall(L, 3, 0, 0); } // Note that the Lua side of this mod still requires initialization initialized = false; // Save the current Lua state and create the network thread state = L; if (!running) CreateThread(NULL, 0, Main, NULL, 0, NULL); } } } // Runs on game ticks and sends messages from TeamSpeak to the Lua script void WINAPI OnGameTick(lua_State *L, LPCSTR type, LPVOID param) { // Make sure this is the correct Lua state if (L != state) return; if (strcmp(type, "update") == 0) { // Index the global TeamSpeak variable lua_getglobal(L, "TS"); int index = lua_gettop(L); // Initialize the Lua part of the mod if a connection // to ClientQuery has been established if (!initialized && client != NULL) { initialized = true; // Update the list of clients connected to the server lua_getfield(L, index, "fetch_info"); lua_pcall(L, 0, 0, 0); } // Pass any recived messages from TeamSpeak to Lua if (!queue.empty()) { lua_getfield(L, index, "Hooks"); for (String *message; queue.try_pop(message);) { lua_getfield(L, -1, "call"); lua_pushvalue(L, -2); lua_pushstring(L, "TeamSpeak:Receive"); lua_pushlstring(L, message->value(), message->length()); lua_pcall(L, 3, 0, 0); delete message; } } } else if (strcmp(type, "destroy") == 0) { // Index the global TeamSpeak variable lua_getglobal(L, "TS"); int index = lua_gettop(L); // Store Lua variables lua_getfield(L, index, "last_sender"); if (lua_type(L, -1) != LUA_TNIL) last_sender = String(lua_tostring(L, -1)); lua_getfield(L, index, "input"); if (lua_type(L, -1) != LUA_TNIL) { lua_getfield(L, -1, "text"); input_text = String(lua_tostring(L, -1)); lua_getfield(L, -2, "position"); input_position = lua_tonumber(L, -1); } } } // DLL entry point BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: // Register a callback for when the game requires an internal file RegisterCallback(REQUIRE_CALLBACK, &OnRequire, NULL); // Register a callback for game ticks RegisterCallback(GAMETICK_CALLBACK, &OnGameTick, NULL); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: // Stop the network loop running = false; // Free memory for (String *message; !queue.empty();) if (queue.try_pop(message)) delete message; for (; !history.empty(); history.pop_front()) delete history.front(); break; } return TRUE; } <|endoftext|>
<commit_before>/* * TableJoin.cpp * * Copyright (C) 2016-2017 by VISUS (University of Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "TableJoin.h" #include <limits> using namespace megamol::stdplugin::datatools; using namespace megamol::stdplugin::datatools::table; using namespace megamol; std::string TableJoin::ModuleName = std::string("TableJoin"); size_t hash_combine(size_t lhs, size_t rhs) { lhs ^= rhs + 0x9e3779b9 + (lhs << 6) + (lhs >> 2); return lhs; } TableJoin::TableJoin(void) : core::Module(), firstTableInSlot("firstTableIn", "First input"), secondTableInSlot("secondTableIn", "Second input"), dataOutSlot("dataOut", "Output"), frameID(-1), firstDataHash(std::numeric_limits<unsigned long>::max()), secondDataHash(std::numeric_limits<unsigned long>::max()) { this->firstTableInSlot.SetCompatibleCall<TableDataCallDescription>(); this->MakeSlotAvailable(&this->firstTableInSlot); this->secondTableInSlot.SetCompatibleCall<TableDataCallDescription>(); this->MakeSlotAvailable(&this->secondTableInSlot); this->dataOutSlot.SetCallback(TableDataCall::ClassName(), TableDataCall::FunctionName(0), &TableJoin::processData); this->dataOutSlot.SetCallback(TableDataCall::ClassName(), TableDataCall::FunctionName(1), &TableJoin::getExtent); this->MakeSlotAvailable(&this->dataOutSlot); } TableJoin::~TableJoin(void) { this->Release(); } bool TableJoin::create(void) { return true; } void TableJoin::release(void) { } bool TableJoin::processData(core::Call &c) { try { TableDataCall *outCall = dynamic_cast<TableDataCall *>(&c); if (outCall == NULL) return false; TableDataCall *firstInCall = this->firstTableInSlot.CallAs<TableDataCall>(); if (firstInCall == NULL) return false; TableDataCall *secondInCall = this->secondTableInSlot.CallAs<TableDataCall>(); if (secondInCall == NULL) return false; // check time compatibility if (firstInCall->GetFrameCount() != secondInCall->GetFrameCount()) { vislib::sys::Log::DefaultLog.WriteError(_T("%hs: Cannot join tables. ") _T("They are required to have equal frame count\n"), ModuleName.c_str()); return false; } // request frame data firstInCall->SetFrameID(outCall->GetFrameID()); secondInCall->SetFrameID(outCall->GetFrameID()); // issue calls if (!(*firstInCall)()) return false; if (!(*secondInCall)()) return false; if (this->firstDataHash != firstInCall->DataHash() || this->secondDataHash != secondInCall->DataHash() || this->frameID != firstInCall->GetFrameID() || this->frameID != secondInCall->GetFrameID()) { this->firstDataHash = firstInCall->DataHash(); this->secondDataHash = secondInCall->DataHash(); ASSERT(firstInCall->GetFrameID() == secondInCall->GetFrameID()); this->frameID = firstInCall->GetFrameID(); // retrieve data auto firstRowsCount = firstInCall->GetRowsCount(); auto firstColumnCount = firstInCall->GetColumnsCount(); auto firstColumnInfos = firstInCall->GetColumnsInfos(); auto firstData = firstInCall->GetData(); auto secondRowsCount = secondInCall->GetRowsCount(); auto secondColumnCount = secondInCall->GetColumnsCount(); auto secondColumnInfos = secondInCall->GetColumnsInfos(); auto secondData = secondInCall->GetData(); // concatenate this->rows_count = std::max(firstRowsCount, secondRowsCount); this->column_count = firstColumnCount + secondColumnCount; this->column_info.clear(); this->column_info.reserve(this->column_count); memcpy(this->column_info.data(), firstColumnInfos, sizeof(TableDataCall::ColumnInfo)*firstColumnCount); memcpy(&(this->column_info.data()[firstColumnCount]), secondColumnInfos, sizeof(TableDataCall::ColumnInfo)*secondColumnCount); this->data.clear(); this->data.resize(this->rows_count * this->column_count); this->concatenate(this->data.data(), this->rows_count, this->column_count, firstData, firstRowsCount, firstColumnCount, secondData, secondRowsCount, secondColumnCount); } outCall->SetFrameCount(firstInCall->GetFrameCount()); outCall->SetFrameID(this->frameID); outCall->SetDataHash(hash_combine(this->firstDataHash, this->secondDataHash)); outCall->Set(this->column_count, this->rows_count, this->column_info.data(), this->data.data()); } catch (...) { vislib::sys::Log::DefaultLog.WriteError(_T("Failed to execute %hs::processData\n"), ModuleName.c_str()); return false; } return true; } void TableJoin::concatenate( float* const out, const size_t rowCount, const size_t columnCount, const float* const first, const size_t firstRowCount, const size_t firstColumnCount, const float* const second, const size_t secondRowCount, const size_t secondColumnCount) { assert(rowCount >= firstRowCount && rowCount >= secondRowCount && "Not enough rows"); assert(columnCount >= firstColumnCount + secondColumnCount && "Not enough columns"); for (size_t row = 0; row < firstRowCount; row++) { float* outR = &out[row * columnCount]; memcpy(outR, &first[row * firstColumnCount], sizeof(float) * firstColumnCount); } for (size_t row = firstRowCount; row < rowCount; row++) { for (size_t col = 0; col < firstColumnCount; col++) { out[col + row * columnCount] = NAN; } } for (size_t row = 0; row < secondRowCount; row++) { float* outR = &out[firstColumnCount + row * columnCount]; memcpy(outR, &second[row * secondColumnCount], sizeof(float) * secondColumnCount); } for (size_t row = secondRowCount; row < rowCount; row++) { for (size_t col = 0; col < secondColumnCount; col++) { out[col + firstColumnCount + row * columnCount] = NAN; } } } bool TableJoin::getExtent(core::Call &c) { try { TableDataCall *outCall = dynamic_cast<TableDataCall *>(&c); if (outCall == NULL) return false; TableDataCall *inCall = this->firstTableInSlot.CallAs<TableDataCall>(); if (inCall == NULL) return false; inCall->SetFrameID(outCall->GetFrameID()); if (!(*inCall)(1)) return false; outCall->SetFrameCount(inCall->GetFrameCount()); outCall->SetDataHash(hash_combine(this->firstDataHash, this->secondDataHash)); } catch (...) { vislib::sys::Log::DefaultLog.WriteError(_T("Failed to execute %hs::getExtent\n"), ModuleName.c_str()); return false; } return true; } <commit_msg>fix-tablejoin<commit_after>/* * TableJoin.cpp * * Copyright (C) 2016-2017 by VISUS (University of Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "TableJoin.h" #include <limits> using namespace megamol::stdplugin::datatools; using namespace megamol::stdplugin::datatools::table; using namespace megamol; std::string TableJoin::ModuleName = std::string("TableJoin"); size_t hash_combine(size_t lhs, size_t rhs) { lhs ^= rhs + 0x9e3779b9 + (lhs << 6) + (lhs >> 2); return lhs; } TableJoin::TableJoin(void) : core::Module(), firstTableInSlot("firstTableIn", "First input"), secondTableInSlot("secondTableIn", "Second input"), dataOutSlot("dataOut", "Output"), frameID(-1), firstDataHash(std::numeric_limits<unsigned long>::max()), secondDataHash(std::numeric_limits<unsigned long>::max()) { this->firstTableInSlot.SetCompatibleCall<TableDataCallDescription>(); this->MakeSlotAvailable(&this->firstTableInSlot); this->secondTableInSlot.SetCompatibleCall<TableDataCallDescription>(); this->MakeSlotAvailable(&this->secondTableInSlot); this->dataOutSlot.SetCallback(TableDataCall::ClassName(), TableDataCall::FunctionName(0), &TableJoin::processData); this->dataOutSlot.SetCallback(TableDataCall::ClassName(), TableDataCall::FunctionName(1), &TableJoin::getExtent); this->MakeSlotAvailable(&this->dataOutSlot); } TableJoin::~TableJoin(void) { this->Release(); } bool TableJoin::create(void) { return true; } void TableJoin::release(void) { } bool TableJoin::processData(core::Call &c) { try { TableDataCall *outCall = dynamic_cast<TableDataCall *>(&c); if (outCall == NULL) return false; TableDataCall *firstInCall = this->firstTableInSlot.CallAs<TableDataCall>(); if (firstInCall == NULL) return false; TableDataCall *secondInCall = this->secondTableInSlot.CallAs<TableDataCall>(); if (secondInCall == NULL) return false; // call getHash before check of frame count if (!(*firstInCall)(1)) return false; if (!(*secondInCall)(1)) return false; // check time compatibility if (firstInCall->GetFrameCount() != secondInCall->GetFrameCount()) { vislib::sys::Log::DefaultLog.WriteError(_T("%hs: Cannot join tables. ") _T("They are required to have equal frame count\n"), ModuleName.c_str()); return false; } // request frame data firstInCall->SetFrameID(outCall->GetFrameID()); secondInCall->SetFrameID(outCall->GetFrameID()); // issue calls if (!(*firstInCall)()) return false; if (!(*secondInCall)()) return false; if (this->firstDataHash != firstInCall->DataHash() || this->secondDataHash != secondInCall->DataHash() || this->frameID != firstInCall->GetFrameID() || this->frameID != secondInCall->GetFrameID()) { this->firstDataHash = firstInCall->DataHash(); this->secondDataHash = secondInCall->DataHash(); ASSERT(firstInCall->GetFrameID() == secondInCall->GetFrameID()); this->frameID = firstInCall->GetFrameID(); // retrieve data auto firstRowsCount = firstInCall->GetRowsCount(); auto firstColumnCount = firstInCall->GetColumnsCount(); auto firstColumnInfos = firstInCall->GetColumnsInfos(); auto firstData = firstInCall->GetData(); auto secondRowsCount = secondInCall->GetRowsCount(); auto secondColumnCount = secondInCall->GetColumnsCount(); auto secondColumnInfos = secondInCall->GetColumnsInfos(); auto secondData = secondInCall->GetData(); // concatenate this->rows_count = std::max(firstRowsCount, secondRowsCount); this->column_count = firstColumnCount + secondColumnCount; this->column_info.clear(); this->column_info.reserve(this->column_count); memcpy(this->column_info.data(), firstColumnInfos, sizeof(TableDataCall::ColumnInfo)*firstColumnCount); memcpy(&(this->column_info.data()[firstColumnCount]), secondColumnInfos, sizeof(TableDataCall::ColumnInfo)*secondColumnCount); this->data.clear(); this->data.resize(this->rows_count * this->column_count); this->concatenate(this->data.data(), this->rows_count, this->column_count, firstData, firstRowsCount, firstColumnCount, secondData, secondRowsCount, secondColumnCount); } outCall->SetFrameCount(firstInCall->GetFrameCount()); outCall->SetFrameID(this->frameID); outCall->SetDataHash(hash_combine(this->firstDataHash, this->secondDataHash)); outCall->Set(this->column_count, this->rows_count, this->column_info.data(), this->data.data()); } catch (...) { vislib::sys::Log::DefaultLog.WriteError(_T("Failed to execute %hs::processData\n"), ModuleName.c_str()); return false; } return true; } void TableJoin::concatenate( float* const out, const size_t rowCount, const size_t columnCount, const float* const first, const size_t firstRowCount, const size_t firstColumnCount, const float* const second, const size_t secondRowCount, const size_t secondColumnCount) { assert(rowCount >= firstRowCount && rowCount >= secondRowCount && "Not enough rows"); assert(columnCount >= firstColumnCount + secondColumnCount && "Not enough columns"); for (size_t row = 0; row < firstRowCount; row++) { float* outR = &out[row * columnCount]; memcpy(outR, &first[row * firstColumnCount], sizeof(float) * firstColumnCount); } for (size_t row = firstRowCount; row < rowCount; row++) { for (size_t col = 0; col < firstColumnCount; col++) { out[col + row * columnCount] = NAN; } } for (size_t row = 0; row < secondRowCount; row++) { float* outR = &out[firstColumnCount + row * columnCount]; memcpy(outR, &second[row * secondColumnCount], sizeof(float) * secondColumnCount); } for (size_t row = secondRowCount; row < rowCount; row++) { for (size_t col = 0; col < secondColumnCount; col++) { out[col + firstColumnCount + row * columnCount] = NAN; } } } bool TableJoin::getExtent(core::Call &c) { try { TableDataCall *outCall = dynamic_cast<TableDataCall *>(&c); if (outCall == NULL) return false; TableDataCall *inCall = this->firstTableInSlot.CallAs<TableDataCall>(); if (inCall == NULL) return false; inCall->SetFrameID(outCall->GetFrameID()); if (!(*inCall)(1)) return false; outCall->SetFrameCount(inCall->GetFrameCount()); outCall->SetDataHash(hash_combine(this->firstDataHash, this->secondDataHash)); } catch (...) { vislib::sys::Log::DefaultLog.WriteError(_T("Failed to execute %hs::getExtent\n"), ModuleName.c_str()); return false; } return true; } <|endoftext|>
<commit_before>#include "vast/search.h" #include "vast/expression.h" #include "vast/optional.h" #include "vast/query.h" #include "vast/util/make_unique.h" #include "vast/util/trial.h" namespace vast { using namespace cppa; search_actor::search_actor(actor_ptr archive, actor_ptr index, actor_ptr schema_manager) : archive_{std::move(archive)}, index_{std::move(index)}, schema_manager_{std::move(schema_manager)} { } void search_actor::act() { trap_exit(true); auto parse_ast = [=](std::string const& str) -> optional<expr::ast> { auto ast = expr::ast::parse(str); if (ast) return std::move(*ast); last_parse_error_ = ast.failure().msg(); return {}; }; become( on(atom("EXIT"), arg_match) >> [=](uint32_t reason) { for (auto& p : clients_) { for (auto& q : p.second.queries) { VAST_LOG_ACTOR_DEBUG("sends EXIT to query " << VAST_ACTOR_ID(q)); send_exit(q, reason); } send(p.first, atom("exited")); } quit(reason); }, on(atom("DOWN"), arg_match) >> [=](uint32_t reason) { VAST_LOG_ACTOR_DEBUG( "received DOWN from client " << VAST_ACTOR_ID(last_sender())); for (auto& q : clients_[last_sender()].queries) { VAST_LOG_ACTOR_DEBUG("sends EXIT to query " << VAST_ACTOR_ID(q)); send_exit(q, reason); } clients_.erase(last_sender()); }, on(atom("query"), atom("create"), parse_ast) >> [=](expr::ast const& ast) -> continue_helper { auto client = last_sender(); monitor(client); VAST_LOG_ACTOR_INFO("got new client " << VAST_ACTOR_ID(client) << " asking for " << ast); auto qry = spawn<query_actor>(archive_, client, ast); return sync_send(index_, atom("query"), ast, qry).then( on(atom("success")) >> [=] { clients_[client].queries.insert(qry); return make_any_tuple(ast, qry); }, on(atom("error"), arg_match) >> [=](std::string const&) { send_exit(qry, exit::error); return last_dequeued(); }); }, on(atom("query"), atom("create"), arg_match) >> [=](std::string const& q) { VAST_LOG_ACTOR_VERBOSE("ignores invalid query: " << q); return make_any_tuple(atom("error"), last_parse_error_); }, others() >> [=] { VAST_LOG_ACTOR_ERROR("got unexpected message from " << VAST_ACTOR_ID(last_sender()) << ": " << to_string(last_dequeued())); }); } char const* search_actor::description() const { return "search"; } } // namespace vast <commit_msg>Only monitor clients with successful queries.<commit_after>#include "vast/search.h" #include "vast/expression.h" #include "vast/optional.h" #include "vast/query.h" #include "vast/util/make_unique.h" #include "vast/util/trial.h" namespace vast { using namespace cppa; search_actor::search_actor(actor_ptr archive, actor_ptr index, actor_ptr schema_manager) : archive_{std::move(archive)}, index_{std::move(index)}, schema_manager_{std::move(schema_manager)} { } void search_actor::act() { trap_exit(true); auto parse_ast = [=](std::string const& str) -> optional<expr::ast> { auto ast = expr::ast::parse(str); if (ast) return std::move(*ast); last_parse_error_ = ast.failure().msg(); return {}; }; become( on(atom("EXIT"), arg_match) >> [=](uint32_t reason) { for (auto& p : clients_) { for (auto& q : p.second.queries) { VAST_LOG_ACTOR_DEBUG("sends EXIT to query " << VAST_ACTOR_ID(q)); send_exit(q, reason); } send(p.first, atom("exited")); } quit(reason); }, on(atom("DOWN"), arg_match) >> [=](uint32_t reason) { VAST_LOG_ACTOR_DEBUG( "received DOWN from client " << VAST_ACTOR_ID(last_sender())); for (auto& q : clients_[last_sender()].queries) { VAST_LOG_ACTOR_DEBUG("sends EXIT to query " << VAST_ACTOR_ID(q)); send_exit(q, reason); } clients_.erase(last_sender()); }, on(atom("query"), atom("create"), parse_ast) >> [=](expr::ast const& ast) -> continue_helper { auto client = last_sender(); VAST_LOG_ACTOR_INFO("got new client " << VAST_ACTOR_ID(client) << " asking for " << ast); auto qry = spawn<query_actor>(archive_, client, ast); return sync_send(index_, atom("query"), ast, qry).then( on(atom("success")) >> [=] { monitor(client); clients_[client].queries.insert(qry); return make_any_tuple(ast, qry); }, on(atom("error"), arg_match) >> [=](std::string const&) { send_exit(qry, exit::error); return last_dequeued(); }); }, on(atom("query"), atom("create"), arg_match) >> [=](std::string const& q) { VAST_LOG_ACTOR_VERBOSE("ignores invalid query: " << q); return make_any_tuple(atom("error"), last_parse_error_); }, others() >> [=] { VAST_LOG_ACTOR_ERROR("got unexpected message from " << VAST_ACTOR_ID(last_sender()) << ": " << to_string(last_dequeued())); }); } char const* search_actor::description() const { return "search"; } } // namespace vast <|endoftext|>
<commit_before>// // The following pseudo header file isn't actually valid C++ code, but is // intended to document the L0_L1 UDP packet format in a C++-like syntax. // For real packet-encoding code, see intensity_network_ostream.cpp. // // We don't bother network-encoding ints and floats, under the assumption // that all nodes in the network are Intel CPUs with little-endian ints // and IEEE 754 floats. // // The packet header size in bytes is currently // 24 + 2*nbeam + 2*nfreq + 8*nbeam*nfreq // // For full CHIME, we expect to use (nbeam, nfreq, nupfreq, ntsamp) = (8, 4, 16, 16) // which gives a 304-byte header and an 8192-byte data segment. // // For the pathfinder, I'm currently using (nbeam, nfreq, nupfreq, ntsamp) = (1, 32, 1, 256) // which gives a 346-byte header and an 8192-byte data segment. // struct L0_L1_header { // This file describes protocol version 1. // A 32-bit protocol number is overkill, but means that all fields below are aligned on their // "natural" boundaries (i.e. fields with size Nbytes have byte offsets which are multiples of Nbytes) uint32_t protocol_version; // byte offset 0 // Size of the 'data' array in bytes, where a negative size means "bitshuffle-compressed". // If positive, must equal (nbeam * nfreq * nupfreq * ntsamp) int16_t data_nbytes; // byte offset 4 // This is the duration of a time sample, in FPGA counts. // The duration in seconds is dt = (2.5e-6 * fpga_counts_per_sample) uint16_t fpga_counts_per_sample; // byte offset 6 // This is the time index (in FPGA counts) of the first time sample in the packet. // The packet sender is responsible for "unwrapping" the 32-bit FPGA timestamp to 64 bits. // Must be divisible by fpga_counts_per_sample. uint64_t fpga_count; // byte offset 8 uint16_t nbeam; // number of beams in packet, byte offset 16 uint16_t nfreq; // number of "FPGA" frequency channels between 0 and 1024, byte offset 18 uint16_t nupfreq; // upsampling factor (probably either 1 or 16), byte offset 20 uint16_t ntsamp; // number of time samples in packet, byte offset 22 // The beams and FPGA freqencies in a particular (L0,L1) pair are not assumed contiguous. uint16_t beam_ids[nbeam]; // beam_ids are between 0 and 1024 for full chime, byte offset of array is 24 uint16_t freq_ids[nfreq]; // freq_ids are between 0 and 1024 for full chime, byte offset of array is (24+2*nbeam) // // The intensities are 8-bit encoded with 'scale' and 'offset' parameters: // Floating-point intensity = scale * (8-bit value) + offset // // A design decision: what granularity should the scale and offset parameters have? // I thought it made sense to allow the scale and offset to depend on both beam and // frequency. This increases the header size so that the header is ~4% of the total // packet. While not negligible, this increase seemed small enough to be a reasonable // price for the robustness of per-(beam,frequency) encoding. // float32 scale[nbeam * nfreq]; // byte offset (24 + 2*nbeam + 2*nfreq) float32 offset[nbeam * nfreq]; // byte offset (24 + 2*nbeam + 2*nfreq + 2*nbeam*nfreq) // 8-bit encoded data, as a 4D array with shape (nbeam, nfreq, nupfreq, ntsamp). // We need a sentinel value to indicate "this entry in the array is invalid". // We currently take both endpoint values to be sentinels, i.e. if a byte is either // 0x00 or 0xff, it should be treated as masked. uint8_t data[ abs(data_nbytes) ]; // byte offset (24 + 2*nbeam + 2*nfreq + 4*nbeam*nfreq) }; <commit_msg>fix typo in comment<commit_after>// // The following pseudo header file isn't actually valid C++ code, but is // intended to document the L0_L1 UDP packet format in a C++-like syntax. // For real packet-encoding code, see intensity_network_ostream.cpp. // // We don't bother network-encoding ints and floats, under the assumption // that all nodes in the network are Intel CPUs with little-endian ints // and IEEE 754 floats. // // The packet header size in bytes is currently // 24 + 2*nbeam + 2*nfreq + 8*nbeam*nfreq // // For full CHIME, we expect to use (nbeam, nfreq, nupfreq, ntsamp) = (8, 4, 16, 16) // which gives a 304-byte header and an 8192-byte data segment. // // For the pathfinder, I'm currently using (nbeam, nfreq, nupfreq, ntsamp) = (1, 32, 1, 256) // which gives a 346-byte header and an 8192-byte data segment. // struct L0_L1_header { // This file describes protocol version 1. // A 32-bit protocol number is overkill, but means that all fields below are aligned on their // "natural" boundaries (i.e. fields with size Nbytes have byte offsets which are multiples of Nbytes) uint32_t protocol_version; // byte offset 0 // Size of the 'data' array in bytes, where a negative size means "bitshuffle-compressed". // If positive, must equal (nbeam * nfreq * nupfreq * ntsamp) int16_t data_nbytes; // byte offset 4 // This is the duration of a time sample, in FPGA counts. // The duration in seconds is dt = (2.56e-6 * fpga_counts_per_sample) uint16_t fpga_counts_per_sample; // byte offset 6 // This is the time index (in FPGA counts) of the first time sample in the packet. // The packet sender is responsible for "unwrapping" the 32-bit FPGA timestamp to 64 bits. // Must be divisible by fpga_counts_per_sample. uint64_t fpga_count; // byte offset 8 uint16_t nbeam; // number of beams in packet, byte offset 16 uint16_t nfreq; // number of "FPGA" frequency channels between 0 and 1024, byte offset 18 uint16_t nupfreq; // upsampling factor (probably either 1 or 16), byte offset 20 uint16_t ntsamp; // number of time samples in packet, byte offset 22 // The beams and FPGA freqencies in a particular (L0,L1) pair are not assumed contiguous. uint16_t beam_ids[nbeam]; // beam_ids are between 0 and 1024 for full chime, byte offset of array is 24 uint16_t freq_ids[nfreq]; // freq_ids are between 0 and 1024 for full chime, byte offset of array is (24+2*nbeam) // // The intensities are 8-bit encoded with 'scale' and 'offset' parameters: // Floating-point intensity = scale * (8-bit value) + offset // // A design decision: what granularity should the scale and offset parameters have? // I thought it made sense to allow the scale and offset to depend on both beam and // frequency. This increases the header size so that the header is ~4% of the total // packet. While not negligible, this increase seemed small enough to be a reasonable // price for the robustness of per-(beam,frequency) encoding. // float32 scale[nbeam * nfreq]; // byte offset (24 + 2*nbeam + 2*nfreq) float32 offset[nbeam * nfreq]; // byte offset (24 + 2*nbeam + 2*nfreq + 2*nbeam*nfreq) // 8-bit encoded data, as a 4D array with shape (nbeam, nfreq, nupfreq, ntsamp). // We need a sentinel value to indicate "this entry in the array is invalid". // We currently take both endpoint values to be sentinels, i.e. if a byte is either // 0x00 or 0xff, it should be treated as masked. uint8_t data[ abs(data_nbytes) ]; // byte offset (24 + 2*nbeam + 2*nfreq + 4*nbeam*nfreq) }; <|endoftext|>
<commit_before>// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include <vector> #include "pink/src/worker_thread.h" #include "pink/include/pink_conn.h" #include "pink/src/pink_item.h" #include "pink/src/pink_epoll.h" namespace pink { WorkerThread::WorkerThread(ConnFactory *conn_factory, ServerThread* server_thread, int cron_interval) : private_data_(nullptr), server_thread_(server_thread), conn_factory_(conn_factory), cron_interval_(cron_interval), keepalive_timeout_(kDefaultKeepAliveTime) { /* * install the protobuf handler here */ pink_epoll_ = new PinkEpoll(); int fds[2]; if (pipe(fds)) { exit(-1); } notify_receive_fd_ = fds[0]; notify_send_fd_ = fds[1]; pink_epoll_->PinkAddEvent(notify_receive_fd_, EPOLLIN | EPOLLERR | EPOLLHUP); } WorkerThread::~WorkerThread() { delete(pink_epoll_); } int WorkerThread::conn_num() const { slash::ReadLock l(&rwlock_); return conns_.size(); } std::vector<ServerThread::ConnInfo> WorkerThread::conns_info() const { std::vector<ServerThread::ConnInfo> result; slash::ReadLock l(&rwlock_); for (auto& conn : conns_) { result.push_back({ conn.first, conn.second->ip_port(), conn.second->last_interaction() }); } return result; } PinkConn* WorkerThread::MoveConnOut(int fd) { slash::WriteLock l(&rwlock_); PinkConn* conn = nullptr; auto iter = conns_.find(fd); if (iter != conns_.end()) { int fd = iter->first; conn = iter->second; pink_epoll_->PinkDelEvent(fd); conns_.erase(iter); } return conn; } void *WorkerThread::ThreadMain() { int nfds; PinkFiredEvent *pfe = NULL; char bb[1]; PinkItem ti; PinkConn *in_conn = NULL; struct timeval when; gettimeofday(&when, NULL); struct timeval now = when; when.tv_sec += (cron_interval_ / 1000); when.tv_usec += ((cron_interval_ % 1000) * 1000); int timeout = cron_interval_; if (timeout <= 0) { timeout = PINK_CRON_INTERVAL; } while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, NULL); if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { DoCronTask(); when.tv_sec = now.tv_sec + (cron_interval_ / 1000); when.tv_usec = now.tv_usec + ((cron_interval_ % 1000) * 1000); timeout = cron_interval_; } } nfds = pink_epoll_->PinkPoll(timeout); for (int i = 0; i < nfds; i++) { pfe = (pink_epoll_->firedevent()) + i; if (pfe->fd == notify_receive_fd_) { if (pfe->mask & EPOLLIN) { read(notify_receive_fd_, bb, 1); { slash::MutexLock l(&mutex_); ti = conn_queue_.front(); conn_queue_.pop(); } PinkConn *tc = conn_factory_->NewPinkConn( ti.fd(), ti.ip_port(), server_thread_, private_data_); if (!tc || !tc->SetNonblock()) { delete tc; continue; } #ifdef __ENABLE_SSL // Create SSL failed if (server_thread_->security() && !tc->CreateSSL(server_thread_->ssl_ctx())) { CloseFd(tc); delete tc; continue; } #endif { slash::WriteLock l(&rwlock_); conns_[ti.fd()] = tc; } pink_epoll_->PinkAddEvent(ti.fd(), EPOLLIN); } else { continue; } } else { in_conn = NULL; int should_close = 0; if (pfe == NULL) { continue; } std::map<int, PinkConn *>::iterator iter = conns_.find(pfe->fd); if (iter == conns_.end()) { pink_epoll_->PinkDelEvent(pfe->fd); continue; } in_conn = iter->second; if (pfe->mask & EPOLLOUT && in_conn->is_reply()) { WriteStatus write_status = in_conn->SendReply(); in_conn->set_last_interaction(now); if (write_status == kWriteAll) { pink_epoll_->PinkModEvent(pfe->fd, 0, EPOLLIN); // Remove EPOLLOUT in_conn->set_is_reply(false); } else if (write_status == kWriteHalf) { pink_epoll_->PinkModEvent(pfe->fd, EPOLLIN, EPOLLOUT); continue; // send all write buffer, // in case of next GetRequest() // pollute the write buffer } else if (write_status == kWriteError) { should_close = 1; } } if (!should_close && pfe->mask & EPOLLIN) { ReadStatus getRes = in_conn->GetRequest(); in_conn->set_last_interaction(now); if (getRes != kReadAll && getRes != kReadHalf) { // kReadError kReadClose kFullError kParseError kDealError should_close = 1; } else if (in_conn->is_reply()) { WriteStatus write_status = in_conn->SendReply(); if (write_status == kWriteAll) { in_conn->set_is_reply(false); } else if (write_status == kWriteHalf) { pink_epoll_->PinkModEvent(pfe->fd, EPOLLIN, EPOLLOUT); } else if (write_status == kWriteError) { should_close = 1; } } else { continue; } } if ((pfe->mask & EPOLLERR) || (pfe->mask & EPOLLHUP) || should_close) { { slash::WriteLock l(&rwlock_); pink_epoll_->PinkDelEvent(pfe->fd); CloseFd(in_conn); delete(in_conn); in_conn = NULL; conns_.erase(pfe->fd); } } } // connection event } // for (int i = 0; i < nfds; i++) } // while (!should_stop()) Cleanup(); return NULL; } void WorkerThread::DoCronTask() { struct timeval now; gettimeofday(&now, NULL); slash::WriteLock l(&rwlock_); // Check whether close all connection slash::MutexLock kl(&killer_mutex_); if (deleting_conn_ipport_.count(kKillAllConnsTask)) { for (auto& conn : conns_) { CloseFd(conn.second); delete conn.second; } conns_.clear(); deleting_conn_ipport_.clear(); return; } std::map<int, PinkConn*>::iterator iter = conns_.begin(); while (iter != conns_.end()) { PinkConn* conn = iter->second; // Check connection should be closed if (deleting_conn_ipport_.count(conn->ip_port())) { CloseFd(conn); deleting_conn_ipport_.erase(conn->ip_port()); delete conn; iter = conns_.erase(iter); continue; } // Check keepalive timeout connection if (keepalive_timeout_ > 0 && (now.tv_sec - conn->last_interaction().tv_sec > keepalive_timeout_)) { CloseFd(conn); server_thread_->handle_->FdTimeoutHandle(conn->fd(), conn->ip_port()); delete conn; iter = conns_.erase(iter); continue; } // Maybe resize connection buffer conn->TryResizeBuffer(); ++iter; } } bool WorkerThread::TryKillConn(const std::string& ip_port) { bool find = false; if (ip_port != kKillAllConnsTask) { slash::ReadLock l(&rwlock_); for (auto& iter : conns_) { if (iter.second->ip_port() == ip_port) { find = true; break; } } } if (find || ip_port == kKillAllConnsTask) { slash::MutexLock l(&killer_mutex_); deleting_conn_ipport_.insert(ip_port); return true; } return false; } void WorkerThread::CloseFd(PinkConn* conn) { close(conn->fd()); server_thread_->handle_->FdClosedHandle(conn->fd(), conn->ip_port()); } void WorkerThread::Cleanup() { slash::WriteLock l(&rwlock_); for (auto& iter : conns_) { CloseFd(iter.second); delete iter.second; } conns_.clear(); } }; // namespace pink <commit_msg>bugfix epollout processing<commit_after>// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include <vector> #include "pink/src/worker_thread.h" #include "pink/include/pink_conn.h" #include "pink/src/pink_item.h" #include "pink/src/pink_epoll.h" namespace pink { WorkerThread::WorkerThread(ConnFactory *conn_factory, ServerThread* server_thread, int cron_interval) : private_data_(nullptr), server_thread_(server_thread), conn_factory_(conn_factory), cron_interval_(cron_interval), keepalive_timeout_(kDefaultKeepAliveTime) { /* * install the protobuf handler here */ pink_epoll_ = new PinkEpoll(); int fds[2]; if (pipe(fds)) { exit(-1); } notify_receive_fd_ = fds[0]; notify_send_fd_ = fds[1]; pink_epoll_->PinkAddEvent(notify_receive_fd_, EPOLLIN | EPOLLERR | EPOLLHUP); } WorkerThread::~WorkerThread() { delete(pink_epoll_); } int WorkerThread::conn_num() const { slash::ReadLock l(&rwlock_); return conns_.size(); } std::vector<ServerThread::ConnInfo> WorkerThread::conns_info() const { std::vector<ServerThread::ConnInfo> result; slash::ReadLock l(&rwlock_); for (auto& conn : conns_) { result.push_back({ conn.first, conn.second->ip_port(), conn.second->last_interaction() }); } return result; } PinkConn* WorkerThread::MoveConnOut(int fd) { slash::WriteLock l(&rwlock_); PinkConn* conn = nullptr; auto iter = conns_.find(fd); if (iter != conns_.end()) { int fd = iter->first; conn = iter->second; pink_epoll_->PinkDelEvent(fd); conns_.erase(iter); } return conn; } void *WorkerThread::ThreadMain() { int nfds; PinkFiredEvent *pfe = NULL; char bb[1]; PinkItem ti; PinkConn *in_conn = NULL; struct timeval when; gettimeofday(&when, NULL); struct timeval now = when; when.tv_sec += (cron_interval_ / 1000); when.tv_usec += ((cron_interval_ % 1000) * 1000); int timeout = cron_interval_; if (timeout <= 0) { timeout = PINK_CRON_INTERVAL; } while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, NULL); if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { DoCronTask(); when.tv_sec = now.tv_sec + (cron_interval_ / 1000); when.tv_usec = now.tv_usec + ((cron_interval_ % 1000) * 1000); timeout = cron_interval_; } } nfds = pink_epoll_->PinkPoll(timeout); for (int i = 0; i < nfds; i++) { pfe = (pink_epoll_->firedevent()) + i; if (pfe->fd == notify_receive_fd_) { if (pfe->mask & EPOLLIN) { read(notify_receive_fd_, bb, 1); { slash::MutexLock l(&mutex_); ti = conn_queue_.front(); conn_queue_.pop(); } PinkConn *tc = conn_factory_->NewPinkConn( ti.fd(), ti.ip_port(), server_thread_, private_data_); if (!tc || !tc->SetNonblock()) { delete tc; continue; } #ifdef __ENABLE_SSL // Create SSL failed if (server_thread_->security() && !tc->CreateSSL(server_thread_->ssl_ctx())) { CloseFd(tc); delete tc; continue; } #endif { slash::WriteLock l(&rwlock_); conns_[ti.fd()] = tc; } pink_epoll_->PinkAddEvent(ti.fd(), EPOLLIN); } else { continue; } } else { in_conn = NULL; int should_close = 0; if (pfe == NULL) { continue; } std::map<int, PinkConn *>::iterator iter = conns_.find(pfe->fd); if (iter == conns_.end()) { pink_epoll_->PinkDelEvent(pfe->fd); continue; } in_conn = iter->second; if (pfe->mask & EPOLLOUT && in_conn->is_reply()) { WriteStatus write_status = in_conn->SendReply(); in_conn->set_last_interaction(now); if (write_status == kWriteAll) { pink_epoll_->PinkModEvent(pfe->fd, 0, EPOLLIN); // Remove EPOLLOUT in_conn->set_is_reply(false); } else if (write_status == kWriteHalf) { pink_epoll_->PinkModEvent(pfe->fd, EPOLLIN, EPOLLOUT); continue; // send all write buffer, // in case of next GetRequest() // pollute the write buffer } else if (write_status == kWriteError) { should_close = 1; } } if (!should_close && pfe->mask & EPOLLIN) { ReadStatus getRes = in_conn->GetRequest(); in_conn->set_last_interaction(now); if (getRes != kReadAll && getRes != kReadHalf) { // kReadError kReadClose kFullError kParseError kDealError should_close = 1; } else if (in_conn->is_reply()) { WriteStatus write_status = in_conn->SendReply(); if (write_status == kWriteAll) { in_conn->set_is_reply(false); } else if (write_status == kWriteHalf) { pink_epoll_->PinkModEvent(pfe->fd, EPOLLIN, EPOLLOUT); } else if (write_status == kWriteError) { should_close = 1; } } else { continue; } } if (pfe->mask & EPOLLOUT) { WriteStatus write_status = in_conn->SendReply(); in_conn->set_last_interaction(now); if (write_status == kWriteAll) { in_conn->set_is_reply(false); pink_epoll_->PinkModEvent(pfe->fd, 0, EPOLLIN); } else if (write_status == kWriteHalf) { continue; } else if (write_status == kWriteError) { should_close = 1; } } if ((pfe->mask & EPOLLERR) || (pfe->mask & EPOLLHUP) || should_close) { { slash::WriteLock l(&rwlock_); pink_epoll_->PinkDelEvent(pfe->fd); CloseFd(in_conn); delete(in_conn); in_conn = NULL; conns_.erase(pfe->fd); } } } // connection event } // for (int i = 0; i < nfds; i++) } // while (!should_stop()) Cleanup(); return NULL; } void WorkerThread::DoCronTask() { struct timeval now; gettimeofday(&now, NULL); slash::WriteLock l(&rwlock_); // Check whether close all connection slash::MutexLock kl(&killer_mutex_); if (deleting_conn_ipport_.count(kKillAllConnsTask)) { for (auto& conn : conns_) { CloseFd(conn.second); delete conn.second; } conns_.clear(); deleting_conn_ipport_.clear(); return; } std::map<int, PinkConn*>::iterator iter = conns_.begin(); while (iter != conns_.end()) { PinkConn* conn = iter->second; // Check connection should be closed if (deleting_conn_ipport_.count(conn->ip_port())) { CloseFd(conn); deleting_conn_ipport_.erase(conn->ip_port()); delete conn; iter = conns_.erase(iter); continue; } // Check keepalive timeout connection if (keepalive_timeout_ > 0 && (now.tv_sec - conn->last_interaction().tv_sec > keepalive_timeout_)) { CloseFd(conn); server_thread_->handle_->FdTimeoutHandle(conn->fd(), conn->ip_port()); delete conn; iter = conns_.erase(iter); continue; } // Maybe resize connection buffer conn->TryResizeBuffer(); ++iter; } } bool WorkerThread::TryKillConn(const std::string& ip_port) { bool find = false; if (ip_port != kKillAllConnsTask) { slash::ReadLock l(&rwlock_); for (auto& iter : conns_) { if (iter.second->ip_port() == ip_port) { find = true; break; } } } if (find || ip_port == kKillAllConnsTask) { slash::MutexLock l(&killer_mutex_); deleting_conn_ipport_.insert(ip_port); return true; } return false; } void WorkerThread::CloseFd(PinkConn* conn) { close(conn->fd()); server_thread_->handle_->FdClosedHandle(conn->fd(), conn->ip_port()); } void WorkerThread::Cleanup() { slash::WriteLock l(&rwlock_); for (auto& iter : conns_) { CloseFd(iter.second); delete iter.second; } conns_.clear(); } }; // namespace pink <|endoftext|>
<commit_before>//===--- GenClosure.cpp - Miscellaneous IR Generation for Expressions -----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements IR generation for closures, e.g. ImplicitClosureExpr. // //===----------------------------------------------------------------------===// #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/Stmt.h" #include "swift/AST/Types.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "IRGenFunction.h" #include "IRGenModule.h" #include "Explosion.h" #include "StructLayout.h" #include "GenClosure.h" using namespace swift; using namespace irgen; void swift::irgen::emitClosure(IRGenFunction &IGF, CapturingExpr *E, Explosion &explosion) { assert(isa<FuncExpr>(E) || isa<ClosureExpr>(E)); ArrayRef<Pattern*> Patterns; if (FuncExpr *FE = dyn_cast<FuncExpr>(E)) Patterns = FE->getParamPatterns(); else Patterns = cast<ClosureExpr>(E)->getParamPatterns(); // Create the IR function. llvm::FunctionType *fnType = IGF.IGM.getFunctionType(E->getType(), ExplosionKind::Minimal, 0, true); llvm::Function *fn = llvm::Function::Create(fnType, llvm::GlobalValue::InternalLinkage, "closure", &IGF.IGM.Module); IRGenFunction innerIGF(IGF.IGM, E->getType(), Patterns, ExplosionKind::Minimal, /*uncurry level*/ 0, fn, Prologue::StandardWithContext); llvm::Value *ContextPtr = IGF.IGM.RefCountedNull; // There are three places we need to generate code for captures: in the // current function, to store the captures to a capture block; in the inner // function, to load the captures from the capture block; and the destructor // for the capture block. // FIXME: Not generating the destructor for the capture block yet; figure out // how to do that once we actually have destructors. if (!E->getCaptures().empty()) { SmallVector<const TypeInfo *, 4> Fields; for (ValueDecl *D : E->getCaptures()) { Type RefTy = LValueType::get(D->getType(), LValueType::Qual::DefaultForVar, IGF.IGM.Context); const TypeInfo &typeInfo = IGF.getFragileTypeInfo(RefTy); Fields.push_back(&typeInfo); } StructLayout layout(IGF.IGM, LayoutKind::HeapObject, LayoutStrategy::Optimal, Fields); // Allocate the capture block llvm::Value *size = llvm::ConstantInt::get(IGF.IGM.SizeTy, layout.getSize().getValue()); llvm::CallInst *allocation = IGF.Builder.CreateCall(IGF.IGM.getAllocFn(), size); allocation->setDoesNotThrow(); allocation->setName(".capturealloc"); ContextPtr = allocation; llvm::Type *CapturesType = layout.getType()->getPointerTo(); llvm::Value *CaptureStruct = IGF.Builder.CreateBitCast(allocation, CapturesType); llvm::Value *InnerStruct = innerIGF.Builder.CreateBitCast(innerIGF.ContextPtr, CapturesType); // Emit stores and loads for capture block for (unsigned i = 0, e = E->getCaptures().size(); i != e; ++i) { ValueDecl *D = E->getCaptures()[i]; OwnedAddress Var = IGF.getLocal(D); unsigned StructIdx = layout.getElements()[i].StructIndex; llvm::Value *CaptureAddr = IGF.Builder.CreateStructGEP(CaptureStruct, StructIdx); llvm::Value *CaptureValueAddr = IGF.Builder.CreateStructGEP(CaptureAddr, 0); llvm::Value *CaptureOwnerAddr = IGF.Builder.CreateStructGEP(CaptureAddr, 1); IGF.Builder.CreateStore(Var.getOwner(), CaptureOwnerAddr); IGF.Builder.CreateStore(Var.getAddressPointer(), CaptureValueAddr); llvm::Value *InnerAddr = innerIGF.Builder.CreateStructGEP(InnerStruct, StructIdx); llvm::Value *InnerValueAddr = innerIGF.Builder.CreateStructGEP(InnerAddr, 0); llvm::Value *InnerOwnerAddr = innerIGF.Builder.CreateStructGEP(InnerAddr, 1); Address InnerValue(innerIGF.Builder.CreateLoad(InnerValueAddr), Var.getAddress().getAlignment()); OwnedAddress InnerLocal(InnerValue, innerIGF.Builder.CreateLoad(InnerOwnerAddr)); innerIGF.setLocal(D, InnerLocal); } } if (FuncExpr *FE = dyn_cast<FuncExpr>(E)) { innerIGF.emitFunctionTopLevel(FE->getBody()); } else { // Emit the body of the closure as if it were a single return // statement. ReturnStmt ret(SourceLoc(), cast<ClosureExpr>(E)->getBody()); innerIGF.emitStmt(&ret); } // Build the explosion result. explosion.add(IGF.Builder.CreateBitCast(fn, IGF.IGM.Int8PtrTy)); explosion.add(ContextPtr); } <commit_msg>Add an unsupported error for curried local functions for the moment.<commit_after>//===--- GenClosure.cpp - Miscellaneous IR Generation for Expressions -----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements IR generation for closures, e.g. ImplicitClosureExpr. // //===----------------------------------------------------------------------===// #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/Stmt.h" #include "swift/AST/Types.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "IRGenFunction.h" #include "IRGenModule.h" #include "Explosion.h" #include "StructLayout.h" #include "GenClosure.h" using namespace swift; using namespace irgen; void swift::irgen::emitClosure(IRGenFunction &IGF, CapturingExpr *E, Explosion &explosion) { assert(isa<FuncExpr>(E) || isa<ClosureExpr>(E)); ArrayRef<Pattern*> Patterns; if (FuncExpr *FE = dyn_cast<FuncExpr>(E)) Patterns = FE->getParamPatterns(); else Patterns = cast<ClosureExpr>(E)->getParamPatterns(); if (Patterns.size() != 1) { IGF.unimplemented(E->getLoc(), "curried local functions"); return IGF.emitFakeExplosion(IGF.getFragileTypeInfo(E->getType()), explosion); } // Create the IR function. llvm::FunctionType *fnType = IGF.IGM.getFunctionType(E->getType(), ExplosionKind::Minimal, 0, true); llvm::Function *fn = llvm::Function::Create(fnType, llvm::GlobalValue::InternalLinkage, "closure", &IGF.IGM.Module); IRGenFunction innerIGF(IGF.IGM, E->getType(), Patterns, ExplosionKind::Minimal, /*uncurry level*/ 0, fn, Prologue::StandardWithContext); llvm::Value *ContextPtr = IGF.IGM.RefCountedNull; // There are three places we need to generate code for captures: in the // current function, to store the captures to a capture block; in the inner // function, to load the captures from the capture block; and the destructor // for the capture block. // FIXME: Not generating the destructor for the capture block yet; figure out // how to do that once we actually have destructors. if (!E->getCaptures().empty()) { SmallVector<const TypeInfo *, 4> Fields; for (ValueDecl *D : E->getCaptures()) { Type RefTy = LValueType::get(D->getType(), LValueType::Qual::DefaultForVar, IGF.IGM.Context); const TypeInfo &typeInfo = IGF.getFragileTypeInfo(RefTy); Fields.push_back(&typeInfo); } StructLayout layout(IGF.IGM, LayoutKind::HeapObject, LayoutStrategy::Optimal, Fields); // Allocate the capture block llvm::Value *size = llvm::ConstantInt::get(IGF.IGM.SizeTy, layout.getSize().getValue()); llvm::CallInst *allocation = IGF.Builder.CreateCall(IGF.IGM.getAllocFn(), size); allocation->setDoesNotThrow(); allocation->setName(".capturealloc"); ContextPtr = allocation; llvm::Type *CapturesType = layout.getType()->getPointerTo(); llvm::Value *CaptureStruct = IGF.Builder.CreateBitCast(allocation, CapturesType); llvm::Value *InnerStruct = innerIGF.Builder.CreateBitCast(innerIGF.ContextPtr, CapturesType); // Emit stores and loads for capture block for (unsigned i = 0, e = E->getCaptures().size(); i != e; ++i) { ValueDecl *D = E->getCaptures()[i]; OwnedAddress Var = IGF.getLocal(D); unsigned StructIdx = layout.getElements()[i].StructIndex; llvm::Value *CaptureAddr = IGF.Builder.CreateStructGEP(CaptureStruct, StructIdx); llvm::Value *CaptureValueAddr = IGF.Builder.CreateStructGEP(CaptureAddr, 0); llvm::Value *CaptureOwnerAddr = IGF.Builder.CreateStructGEP(CaptureAddr, 1); IGF.Builder.CreateStore(Var.getOwner(), CaptureOwnerAddr); IGF.Builder.CreateStore(Var.getAddressPointer(), CaptureValueAddr); llvm::Value *InnerAddr = innerIGF.Builder.CreateStructGEP(InnerStruct, StructIdx); llvm::Value *InnerValueAddr = innerIGF.Builder.CreateStructGEP(InnerAddr, 0); llvm::Value *InnerOwnerAddr = innerIGF.Builder.CreateStructGEP(InnerAddr, 1); Address InnerValue(innerIGF.Builder.CreateLoad(InnerValueAddr), Var.getAddress().getAlignment()); OwnedAddress InnerLocal(InnerValue, innerIGF.Builder.CreateLoad(InnerOwnerAddr)); innerIGF.setLocal(D, InnerLocal); } } if (FuncExpr *FE = dyn_cast<FuncExpr>(E)) { innerIGF.emitFunctionTopLevel(FE->getBody()); } else { // Emit the body of the closure as if it were a single return // statement. ReturnStmt ret(SourceLoc(), cast<ClosureExpr>(E)->getBody()); innerIGF.emitStmt(&ret); } // Build the explosion result. explosion.add(IGF.Builder.CreateBitCast(fn, IGF.IGM.Int8PtrTy)); explosion.add(ContextPtr); } <|endoftext|>
<commit_before>/* This file is part of the Kate project. * * Copyright (C) 2010 Christoph Cullmann <cullmann@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "katesnippets.h" #include "snippetcompletionmodel.h" #include "katesnippetglobal.h" #include "snippetview.h" #include <QAction> #include <QBoxLayout> #include <KActionCollection> #include <KXMLGUIFactory> #include <KToolBar> #include <KLocalizedString> #include <KPluginFactory> #include <KTextEditor/CodeCompletionInterface> K_PLUGIN_FACTORY_WITH_JSON(KateSnippetsPluginFactory, "katesnippetsplugin.json", registerPlugin<KateSnippetsPlugin>();) KateSnippetsPlugin::KateSnippetsPlugin(QObject *parent, const QList<QVariant> &) : KTextEditor::Plugin(parent) , m_snippetGlobal(new KateSnippetGlobal(this)) { } KateSnippetsPlugin::~KateSnippetsPlugin() { } QObject *KateSnippetsPlugin::createView(KTextEditor::MainWindow *mainWindow) { KateSnippetsPluginView *view = new KateSnippetsPluginView(this, mainWindow); return view; } KateSnippetsPluginView::KateSnippetsPluginView(KateSnippetsPlugin *plugin, KTextEditor::MainWindow *mainWindow) : QObject(mainWindow), m_plugin(plugin), m_mainWindow(mainWindow), m_toolView(0), m_snippets(0) { KXMLGUIClient::setComponentName(QLatin1String("katesnippets"), i18n("Snippets tool view")); setXMLFile(QLatin1String("ui.rc")); // Toolview for snippets m_toolView.reset(mainWindow->createToolView(0, QLatin1String("kate_private_plugin_katesnippetsplugin"), KTextEditor::MainWindow::Right, QIcon::fromTheme(QLatin1String("document-new")), i18n("Snippets"))); m_toolView->setLayout(new QHBoxLayout()); // add snippets widget m_snippets.reset(KateSnippetGlobal::self()->snippetWidget()); m_snippets->setParent(m_toolView.data()); m_snippets->setupActionsForWindow(m_toolView.data()); // snippets toolbar KToolBar *topToolbar = new KToolBar(m_toolView.data(), "snippetsToolBar"); topToolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); topToolbar->addActions(m_snippets->actions()); static_cast<QBoxLayout *>(m_toolView->layout())->insertWidget(0, topToolbar); // register this view m_plugin->mViews.append(this); // create actions QAction *a = actionCollection()->addAction(QLatin1String("tools_create_snippet")); a->setIcon(QIcon::fromTheme(QLatin1String("document-new"))); a->setText(i18n("Create Snippet")); connect(a, &QAction::triggered, this, &KateSnippetsPluginView::createSnippet); a = actionCollection()->addAction(QLatin1String("tools_snippets")); a->setText(i18n("Snippets...")); connect(a, &QAction::triggered, this, &KateSnippetsPluginView::showSnippetsDialog); connect(mainWindow, &KTextEditor::MainWindow::viewCreated, this, &KateSnippetsPluginView::slotViewCreated); /** * connect for all already existing views */ foreach (KTextEditor::View *view, mainWindow->views()) { slotViewCreated(view); } auto factory = m_mainWindow->guiFactory(); if ( factory ) { factory->addClient(this); } } KateSnippetsPluginView::~KateSnippetsPluginView() { // cleanup for all views Q_FOREACH (auto view, m_textViews) { if (! view) { continue; } auto iface = qobject_cast<KTextEditor::CodeCompletionInterface *>(view); iface->unregisterCompletionModel(KateSnippetGlobal::self()->completionModel()); } m_mainWindow->guiFactory()->removeClient(this); // unregister this view m_plugin->mViews.removeAll(this); } void KateSnippetsPluginView::slotViewCreated(KTextEditor::View *view) { m_textViews.append(QPointer<KTextEditor::View>(view)); // add snippet completion auto model = KateSnippetGlobal::self()->completionModel(); auto iface = qobject_cast<KTextEditor::CodeCompletionInterface *>(view); iface->unregisterCompletionModel(model); iface->registerCompletionModel(model); } void KateSnippetsPluginView::createSnippet() { KateSnippetGlobal::self()->createSnippet(m_mainWindow->activeView()); } void KateSnippetsPluginView::showSnippetsDialog() { KateSnippetGlobal::self()->showDialog(m_mainWindow->activeView()); } #include "katesnippets.moc" <commit_msg>Use QStringLiteral<commit_after>/* This file is part of the Kate project. * * Copyright (C) 2010 Christoph Cullmann <cullmann@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "katesnippets.h" #include "snippetcompletionmodel.h" #include "katesnippetglobal.h" #include "snippetview.h" #include <QAction> #include <QBoxLayout> #include <KActionCollection> #include <KXMLGUIFactory> #include <KToolBar> #include <KLocalizedString> #include <KPluginFactory> #include <KTextEditor/CodeCompletionInterface> K_PLUGIN_FACTORY_WITH_JSON(KateSnippetsPluginFactory, "katesnippetsplugin.json", registerPlugin<KateSnippetsPlugin>();) KateSnippetsPlugin::KateSnippetsPlugin(QObject *parent, const QList<QVariant> &) : KTextEditor::Plugin(parent) , m_snippetGlobal(new KateSnippetGlobal(this)) { } KateSnippetsPlugin::~KateSnippetsPlugin() { } QObject *KateSnippetsPlugin::createView(KTextEditor::MainWindow *mainWindow) { KateSnippetsPluginView *view = new KateSnippetsPluginView(this, mainWindow); return view; } KateSnippetsPluginView::KateSnippetsPluginView(KateSnippetsPlugin *plugin, KTextEditor::MainWindow *mainWindow) : QObject(mainWindow), m_plugin(plugin), m_mainWindow(mainWindow), m_toolView(0), m_snippets(0) { KXMLGUIClient::setComponentName(QStringLiteral("katesnippets"), i18n("Snippets tool view")); setXMLFile(QStringLiteral("ui.rc")); // Toolview for snippets m_toolView.reset(mainWindow->createToolView(0, QStringLiteral("kate_private_plugin_katesnippetsplugin"), KTextEditor::MainWindow::Right, QIcon::fromTheme(QStringLiteral("document-new")), i18n("Snippets"))); m_toolView->setLayout(new QHBoxLayout()); // add snippets widget m_snippets.reset(KateSnippetGlobal::self()->snippetWidget()); m_snippets->setParent(m_toolView.data()); m_snippets->setupActionsForWindow(m_toolView.data()); // snippets toolbar KToolBar *topToolbar = new KToolBar(m_toolView.data(), "snippetsToolBar"); topToolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); topToolbar->addActions(m_snippets->actions()); static_cast<QBoxLayout *>(m_toolView->layout())->insertWidget(0, topToolbar); // register this view m_plugin->mViews.append(this); // create actions QAction *a = actionCollection()->addAction(QStringLiteral("tools_create_snippet")); a->setIcon(QIcon::fromTheme(QStringLiteral("document-new"))); a->setText(i18n("Create Snippet")); connect(a, &QAction::triggered, this, &KateSnippetsPluginView::createSnippet); a = actionCollection()->addAction(QStringLiteral("tools_snippets")); a->setText(i18n("Snippets...")); connect(a, &QAction::triggered, this, &KateSnippetsPluginView::showSnippetsDialog); connect(mainWindow, &KTextEditor::MainWindow::viewCreated, this, &KateSnippetsPluginView::slotViewCreated); /** * connect for all already existing views */ foreach (KTextEditor::View *view, mainWindow->views()) { slotViewCreated(view); } auto factory = m_mainWindow->guiFactory(); if ( factory ) { factory->addClient(this); } } KateSnippetsPluginView::~KateSnippetsPluginView() { // cleanup for all views Q_FOREACH (auto view, m_textViews) { if (! view) { continue; } auto iface = qobject_cast<KTextEditor::CodeCompletionInterface *>(view); iface->unregisterCompletionModel(KateSnippetGlobal::self()->completionModel()); } m_mainWindow->guiFactory()->removeClient(this); // unregister this view m_plugin->mViews.removeAll(this); } void KateSnippetsPluginView::slotViewCreated(KTextEditor::View *view) { m_textViews.append(QPointer<KTextEditor::View>(view)); // add snippet completion auto model = KateSnippetGlobal::self()->completionModel(); auto iface = qobject_cast<KTextEditor::CodeCompletionInterface *>(view); iface->unregisterCompletionModel(model); iface->registerCompletionModel(model); } void KateSnippetsPluginView::createSnippet() { KateSnippetGlobal::self()->createSnippet(m_mainWindow->activeView()); } void KateSnippetsPluginView::showSnippetsDialog() { KateSnippetGlobal::self()->showDialog(m_mainWindow->activeView()); } #include "katesnippets.moc" <|endoftext|>
<commit_before>#include <cstdint> #include <vector> #include <memory> #include <iostream> #include <fstream> #include <exception> #include <type_traits> #include <random> #include "gtest/gtest.h" using namespace std; struct My_Base{}; template <typename T> struct S_P : public My_Base { typedef shared_ptr<T> Pointer_T; }; template <typename T> struct U_P : public My_Base { typedef unique_ptr<T> Pointer_T; }; template <typename T> struct R_P : public My_Base { typedef T* Pointer_T; }; template <typename T> struct V_T : public My_Base { typedef T Pointer_T; }; template <typename C> struct My_Trait{ typedef typename C::Pointer_T type;}; class Filewrapper{ istream* the_file; template <typename T> using pointer_t = typename My_Trait<T>::type; public: Filewrapper(string filename){ filebuf* fb = new filebuf(); the_file = new ifstream();//filename); fb->open(filename, ios_base::in); the_file->rdbuf(fb); } Filewrapper(istream* src) : the_file ( src ) {} Filewrapper(Filewrapper&) = delete; Filewrapper(Filewrapper&& src) : the_file (src.the_file){} bool Is_Valid(){ return (the_file != nullptr); } int64_t Get_Value(){ int64_t val; if ( !( (*the_file) >> val) ) { cerr << "Read failure"; throw std::exception(); } return val; } template <class wrapper> static pointer_t<wrapper > Construct(string filename_){ pointer_t<wrapper > return_value { new Filewrapper(filename_) }; return return_value; } template <class wrapper> static pointer_t<wrapper > ConstructIS (istream* is_){ pointer_t<wrapper > return_value { new Filewrapper(is_) }; return return_value; } }; template <> Filewrapper::pointer_t<V_T<Filewrapper> > Filewrapper::Construct<V_T<Filewrapper>> (string filename_){ pointer_t<V_T<Filewrapper> > return_value { Filewrapper(filename_) }; return return_value; } template <> Filewrapper::pointer_t<V_T<Filewrapper> > Filewrapper::ConstructIS<V_T<Filewrapper>> (istream* is_){ pointer_t<V_T<Filewrapper> > return_value { Filewrapper(is_) }; return return_value; } class Filewrapper_Maker{ template <typename T> using pointer_t = typename My_Trait<T>::type; public: static Filewrapper Make(string filename_){ Filewrapper ret_val (filename_); return ret_val;} static Filewrapper Make(istream* src_str){ Filewrapper ret_val (src_str); return ret_val; } static shared_ptr<Filewrapper> Make_P (string filename_){ shared_ptr<Filewrapper> filewrapper_ = make_shared<Filewrapper>(filename_); return filewrapper_; } static shared_ptr<Filewrapper> Make_P (istream* is_){ shared_ptr<Filewrapper> filewrapper_ = make_shared<Filewrapper>(is_); return filewrapper_; } template <template <typename> class U> static typename My_Trait<U<Filewrapper>>::type Make_Template ( string filename_){ typename My_Trait<U <Filewrapper> >::type wrapper = Filewrapper::Construct<U<Filewrapper>>( filename_ ); return wrapper; } template <template <typename> class U> static typename My_Trait<U<Filewrapper>>::type Make_Template ( istream* my_stream){ typename My_Trait<U <Filewrapper> >::type wrapper = Filewrapper::ConstructIS<U<Filewrapper>>( my_stream ); return wrapper; } }; class Filewrapper_Test : public ::testing::Test{ void SetUp(){ ofstream datafile(path, ios_base::trunc); mt19937 generator; uniform_int_distribution<int64_t> distribution(numeric_limits<int64_t>::min() ); for (int i = 0; i < 20; ++i) values.push_back(distribution(generator)); for (auto i : values) datafile << i << endl; } protected: string path = "/tmp/sample.file.txt"; vector<int64_t> values; }; TEST_F(Filewrapper_Test, T001_File_Wrapper_By_Value_String_Constructor){ Filewrapper my_wrapper (path); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T002_File_Wrapper_By_Value_Pass_IFstream_Pointer_In_Scope){ ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper my_wrapper (my_file); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T003_File_Wrapper_By_Value_Pass_Filewrapper_RvalRef_In_Scope){ ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper my_wrapper = Filewrapper(my_file); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T004_File_Wrapper_By_Pointer_Pass_Path){ Filewrapper* my_wrapper = new Filewrapper(path); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T005_File_Wrapper_By_Pointer_Pass_IFstream_Pointer_In_Scope){ ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper* my_wrapper = new Filewrapper(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T006_File_Wrapper_By_Pointer_Pass_IFstream_Pointer_Out_Scope){ Filewrapper* my_wrapper; { ifstream* my_file = new ifstream(); my_file->open(path); my_wrapper = new Filewrapper (my_file); } ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T007_File_Wrapper_By_Pointer_Pass_Filewrapper_RvalRef_In_Scope){ Filewrapper* my_wrapper; { ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper* temp_wrapper = new Filewrapper (my_file); my_wrapper = std::move(temp_wrapper); } ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T008_File_Wrapper_By_Value_Factory_Shared_Ptr_String){ Filewrapper my_wrapper = Filewrapper_Maker::Make(path); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T009_File_Wrapper_By_Value_Factory_Shared_Ptr_ISStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper my_wrapper = Filewrapper_Maker::Make(my_file); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T010_File_Wrapper_Shared_Ptr_Factory_Shared_Ptr_String){ auto my_wrapper = Filewrapper_Maker::Make_P(path); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T011_File_Wrapper_Shared_Ptr_Factory_Shared_Ptr_ISStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T012_File_Wrapper_Template_Factory_Shared_Ptr_String){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_Template<S_P>(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T013_File_Wrapper_Template_Factory_Shared_Ptr_IStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T014_File_Wrapper_Template_Factory_Unique_Ptr_String){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T015_File_Wrapper_Template_Factory_Unique_Ptr_IStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T016_File_Wrapper_Template_Factory_Shared_Ptr_String){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T017_File_Wrapper_Template_Factory_Raw_Ptr_IStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } int main(int argc, char *argv[]) { ::testing::InitGoogleTest ( &argc, argv ); int result = RUN_ALL_TESTS(); // bool success = ::testing::Run_All_Tests(); return 0; } <commit_msg>Make some portability changes to the code, to allow it to run on Visual Studio.<commit_after>#include <cstdint> #include <vector> #include <memory> #include <iostream> #include <fstream> #include <exception> #include <type_traits> #include <random> #include "gtest/gtest.h" using namespace std; struct My_Base{}; template <typename T> struct S_P : public My_Base { typedef shared_ptr<T> Pointer_T; }; template <typename T> struct U_P : public My_Base { typedef unique_ptr<T> Pointer_T; }; template <typename T> struct R_P : public My_Base { typedef T* Pointer_T; }; template <typename T> struct V_T : public My_Base { typedef T Pointer_T; }; template <typename C> struct My_Trait{ typedef typename C::Pointer_T type;}; class Filewrapper{ istream* the_file; public: template <typename T> using pointer_t = typename My_Trait<T>::type; Filewrapper(string filename){ filebuf* fb = new filebuf(); the_file = new ifstream();//filename); fb->open(filename, ios_base::in); the_file->rdbuf(fb); } Filewrapper(istream* src) : the_file ( src ) {} Filewrapper(Filewrapper&) = delete; Filewrapper(Filewrapper&& src) : the_file (src.the_file){} bool Is_Valid(){ return (the_file != nullptr); } int64_t Get_Value(){ int64_t val; if ( !( (*the_file) >> val) ) { cerr << "Read failure"; throw std::exception(); } return val; } template <class wrapper> static pointer_t<wrapper > Construct(string filename_){ pointer_t<wrapper > return_value { new Filewrapper(filename_) }; return return_value; } template <class wrapper> static pointer_t<wrapper > ConstructIS (istream* is_){ pointer_t<wrapper > return_value { new Filewrapper(is_) }; return return_value; } }; template <> Filewrapper::pointer_t<V_T<Filewrapper> > Filewrapper::Construct<V_T<Filewrapper>> (string filename_){ pointer_t<V_T<Filewrapper> > return_value { Filewrapper(filename_) }; return std::move( return_value ); } template <> Filewrapper::pointer_t<V_T<Filewrapper> > Filewrapper::ConstructIS<V_T<Filewrapper>> (istream* is_){ pointer_t<V_T<Filewrapper> > return_value { Filewrapper(is_) }; return std::move(return_value); } class Filewrapper_Maker{ template <typename T> using pointer_t = typename My_Trait<T>::type; public: static Filewrapper Make(string filename_){ Filewrapper ret_val (filename_); return std::move( ret_val );} static Filewrapper Make(istream* src_str){ Filewrapper ret_val (src_str); return std::move(ret_val); } static shared_ptr<Filewrapper> Make_P (string filename_){ shared_ptr<Filewrapper> filewrapper_ = make_shared<Filewrapper>(filename_); return filewrapper_; } static shared_ptr<Filewrapper> Make_P (istream* is_){ shared_ptr<Filewrapper> filewrapper_ = make_shared<Filewrapper>(is_); return filewrapper_; } template <template <typename> class U> static typename My_Trait<U<Filewrapper>>::type Make_Template ( string filename_){ typename My_Trait<U <Filewrapper> >::type wrapper = Filewrapper::Construct<U<Filewrapper>>( filename_ ); return wrapper; } template <template <typename> class U> static typename My_Trait<U<Filewrapper>>::type Make_Template ( istream* my_stream){ typename My_Trait<U <Filewrapper> >::type wrapper = Filewrapper::ConstructIS<U<Filewrapper>>( my_stream ); return wrapper; } }; class Filewrapper_Test : public ::testing::Test{ void SetUp(){ ofstream datafile(path, ios_base::trunc); mt19937 generator; uniform_int_distribution<int64_t> distribution(numeric_limits<int64_t>::min() ); for (int i = 0; i < 20; ++i) values.push_back(distribution(generator)); for (auto i : values) datafile << i << endl; } protected: #ifndef _MSC_VER string path = "/tmp/sample.file.txt"; #else string path = "c:\\temp\\sample.file.txt"; #endif vector<int64_t> values; }; TEST_F(Filewrapper_Test, T001_File_Wrapper_By_Value_String_Constructor){ Filewrapper my_wrapper (path); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T002_File_Wrapper_By_Value_Pass_IFstream_Pointer_In_Scope){ ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper my_wrapper (my_file); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T003_File_Wrapper_By_Value_Pass_Filewrapper_RvalRef_In_Scope){ ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper my_wrapper = Filewrapper(my_file); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T004_File_Wrapper_By_Pointer_Pass_Path){ Filewrapper* my_wrapper = new Filewrapper(path); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T005_File_Wrapper_By_Pointer_Pass_IFstream_Pointer_In_Scope){ ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper* my_wrapper = new Filewrapper(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T006_File_Wrapper_By_Pointer_Pass_IFstream_Pointer_Out_Scope){ Filewrapper* my_wrapper; { ifstream* my_file = new ifstream(); my_file->open(path); my_wrapper = new Filewrapper (my_file); } ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T007_File_Wrapper_By_Pointer_Pass_Filewrapper_RvalRef_In_Scope){ Filewrapper* my_wrapper; { ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper* temp_wrapper = new Filewrapper (my_file); my_wrapper = std::move(temp_wrapper); } ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T008_File_Wrapper_By_Value_Factory_Shared_Ptr_String){ Filewrapper my_wrapper = Filewrapper_Maker::Make(path); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T009_File_Wrapper_By_Value_Factory_Shared_Ptr_ISStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); Filewrapper my_wrapper = Filewrapper_Maker::Make(my_file); ASSERT_TRUE(my_wrapper.Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper.Get_Value()); } TEST_F(Filewrapper_Test, T010_File_Wrapper_Shared_Ptr_Factory_Shared_Ptr_String){ auto my_wrapper = Filewrapper_Maker::Make_P(path); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T011_File_Wrapper_Shared_Ptr_Factory_Shared_Ptr_ISStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T012_File_Wrapper_Template_Factory_Shared_Ptr_String){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_Template<S_P>(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T013_File_Wrapper_Template_Factory_Shared_Ptr_IStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T014_File_Wrapper_Template_Factory_Unique_Ptr_String){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T015_File_Wrapper_Template_Factory_Unique_Ptr_IStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T016_File_Wrapper_Template_Factory_Shared_Ptr_String){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } TEST_F(Filewrapper_Test, T017_File_Wrapper_Template_Factory_Raw_Ptr_IStream_Ptr){ ifstream* my_file = new ifstream(); my_file->open(path); shared_ptr<Filewrapper> my_wrapper = Filewrapper_Maker::Make_P(my_file); ASSERT_TRUE(my_wrapper->Is_Valid()); for (int i = 0; i < 20; ++i) EXPECT_EQ(values[i], my_wrapper->Get_Value()); } int main(int argc, char *argv[]) { ::testing::InitGoogleTest ( &argc, argv ); int result = RUN_ALL_TESTS(); // bool success = ::testing::Run_All_Tests(); system("pause"); return 0; } <|endoftext|>
<commit_before>#include "../../shader_structs/forward_render.h" #include "../example_common.h" using namespace put; using namespace put::ecs; pen::window_creation_params pen_window{ 1280, // width 720, // height 4, // MSAA samples "rasterizer_state" // window title / process name }; namespace { const u32 num_rs = 4; // cull front, cull back, cull none, wireframe u32 cube_entity[num_rs]; hash_id raster_states[] = {PEN_HASH("default"), PEN_HASH("front_face_cull"), PEN_HASH("no_cull"), PEN_HASH("wireframe")}; } // namespace void render_raster_states(const scene_view& view) { ecs_scene* scene = view.scene; for (u32 i = 0; i < num_rs; ++i) { u32 ci = cube_entity[i]; cmp_geometry& geom = scene->geometries[ci]; pmfx::set_technique_perm(view.pmfx_shader, view.technique, 0); pen::renderer_set_constant_buffer(view.cb_view, 0, pen::CBUFFER_BIND_PS | pen::CBUFFER_BIND_VS); pen::renderer_set_constant_buffer(scene->cbuffer[ci], 1, pen::CBUFFER_BIND_PS | pen::CBUFFER_BIND_VS); pen::renderer_set_constant_buffer(scene->materials[ci].material_cbuffer, 7, pen::CBUFFER_BIND_PS | pen::CBUFFER_BIND_VS); // set textures cmp_samplers& samplers = scene->samplers[ci]; for (u32 s = 0; s < MAX_TECHNIQUE_SAMPLER_BINDINGS; ++s) { if (!samplers.sb[s].handle) continue; pen::renderer_set_texture(samplers.sb[s].handle, samplers.sb[s].sampler_state, samplers.sb[s].sampler_unit, pen::TEXTURE_BIND_PS); } pen::renderer_set_constant_buffer(scene->forward_light_buffer, 3, pen::CBUFFER_BIND_PS); pen::renderer_set_vertex_buffer(geom.vertex_buffer, 0, geom.vertex_size, 0); pen::renderer_set_index_buffer(geom.index_buffer, geom.index_type, 0); // set rs u32 rs = pmfx::get_render_state(raster_states[i], pmfx::RS_RASTERIZER); pen::renderer_set_rasterizer_state(rs); pen::renderer_draw_indexed(geom.num_indices, 0, 0, PEN_PT_TRIANGLELIST); } } void example_setup(ecs::ecs_scene* scene, camera& cam) { put::scene_view_renderer svr_raster_states; svr_raster_states.name = "ces_render_raster_states"; svr_raster_states.id_name = PEN_HASH(svr_raster_states.name.c_str()); svr_raster_states.render_function = &render_raster_states; pmfx::register_scene_view_renderer(svr_raster_states); pmfx::init("data/configs/rasterizer_state.jsn"); clear_scene(scene); material_resource* default_material = get_material_resource(PEN_HASH("default_material")); geometry_resource* box = get_geometry_resource(PEN_HASH("cube")); // add light u32 light = get_new_entity(scene); scene->names[light] = "front_light"; scene->id_name[light] = PEN_HASH("front_light"); scene->lights[light].colour = vec3f::one(); scene->lights[light].direction = vec3f::one(); scene->lights[light].type = LIGHT_TYPE_DIR; scene->transforms[light].translation = vec3f::zero(); scene->transforms[light].rotation = quat(); scene->transforms[light].scale = vec3f::one(); scene->entities[light] |= CMP_LIGHT; scene->entities[light] |= CMP_TRANSFORM; // add a few cubes vec3f pos = vec3f(-(f32)(num_rs - 1) * 2.0f * 5.0f, 0.0f, 0.0f); for (u32 i = 0; i < num_rs; ++i) { u32 ci = get_new_entity(scene); cube_entity[i] = ci; scene->names[ci] = "cube"; scene->transforms[ci].translation = pos; scene->transforms[ci].rotation = quat(); scene->transforms[ci].scale = vec3f(5.0f, 5.0f, 5.0f); scene->entities[ci] |= CMP_TRANSFORM; scene->parents[ci] = ci; instantiate_geometry(box, scene, ci); instantiate_material(default_material, scene, ci); instantiate_model_cbuffer(scene, ci); pos.x += 4.0f * 5.0f; } } void example_update(ecs::ecs_scene* scene, camera& cam, f32 dt) { } <commit_msg>- compile fix<commit_after>#include "../example_common.h" #include "../../shader_structs/forward_render.h" using namespace put; using namespace put::ecs; pen::window_creation_params pen_window{ 1280, // width 720, // height 4, // MSAA samples "rasterizer_state" // window title / process name }; namespace { const u32 num_rs = 4; // cull front, cull back, cull none, wireframe u32 cube_entity[num_rs]; hash_id raster_states[] = {PEN_HASH("default"), PEN_HASH("front_face_cull"), PEN_HASH("no_cull"), PEN_HASH("wireframe")}; } // namespace void render_raster_states(const scene_view& view) { ecs_scene* scene = view.scene; for (u32 i = 0; i < num_rs; ++i) { u32 ci = cube_entity[i]; cmp_geometry& geom = scene->geometries[ci]; pmfx::set_technique_perm(view.pmfx_shader, view.technique, 0); pen::renderer_set_constant_buffer(view.cb_view, 0, pen::CBUFFER_BIND_PS | pen::CBUFFER_BIND_VS); pen::renderer_set_constant_buffer(scene->cbuffer[ci], 1, pen::CBUFFER_BIND_PS | pen::CBUFFER_BIND_VS); pen::renderer_set_constant_buffer(scene->materials[ci].material_cbuffer, 7, pen::CBUFFER_BIND_PS | pen::CBUFFER_BIND_VS); // set textures cmp_samplers& samplers = scene->samplers[ci]; for (u32 s = 0; s < MAX_TECHNIQUE_SAMPLER_BINDINGS; ++s) { if (!samplers.sb[s].handle) continue; pen::renderer_set_texture(samplers.sb[s].handle, samplers.sb[s].sampler_state, samplers.sb[s].sampler_unit, pen::TEXTURE_BIND_PS); } pen::renderer_set_constant_buffer(scene->forward_light_buffer, 3, pen::CBUFFER_BIND_PS); pen::renderer_set_vertex_buffer(geom.vertex_buffer, 0, geom.vertex_size, 0); pen::renderer_set_index_buffer(geom.index_buffer, geom.index_type, 0); // set rs u32 rs = pmfx::get_render_state(raster_states[i], pmfx::RS_RASTERIZER); pen::renderer_set_rasterizer_state(rs); pen::renderer_draw_indexed(geom.num_indices, 0, 0, PEN_PT_TRIANGLELIST); } } void example_setup(ecs::ecs_scene* scene, camera& cam) { put::scene_view_renderer svr_raster_states; svr_raster_states.name = "ces_render_raster_states"; svr_raster_states.id_name = PEN_HASH(svr_raster_states.name.c_str()); svr_raster_states.render_function = &render_raster_states; pmfx::register_scene_view_renderer(svr_raster_states); pmfx::init("data/configs/rasterizer_state.jsn"); clear_scene(scene); material_resource* default_material = get_material_resource(PEN_HASH("default_material")); geometry_resource* box = get_geometry_resource(PEN_HASH("cube")); // add light u32 light = get_new_entity(scene); scene->names[light] = "front_light"; scene->id_name[light] = PEN_HASH("front_light"); scene->lights[light].colour = vec3f::one(); scene->lights[light].direction = vec3f::one(); scene->lights[light].type = LIGHT_TYPE_DIR; scene->transforms[light].translation = vec3f::zero(); scene->transforms[light].rotation = quat(); scene->transforms[light].scale = vec3f::one(); scene->entities[light] |= CMP_LIGHT; scene->entities[light] |= CMP_TRANSFORM; // add a few cubes vec3f pos = vec3f(-(f32)(num_rs - 1) * 2.0f * 5.0f, 0.0f, 0.0f); for (u32 i = 0; i < num_rs; ++i) { u32 ci = get_new_entity(scene); cube_entity[i] = ci; scene->names[ci] = "cube"; scene->transforms[ci].translation = pos; scene->transforms[ci].rotation = quat(); scene->transforms[ci].scale = vec3f(5.0f, 5.0f, 5.0f); scene->entities[ci] |= CMP_TRANSFORM; scene->parents[ci] = ci; instantiate_geometry(box, scene, ci); instantiate_material(default_material, scene, ci); instantiate_model_cbuffer(scene, ci); pos.x += 4.0f * 5.0f; } } void example_update(ecs::ecs_scene* scene, camera& cam, f32 dt) { } <|endoftext|>
<commit_before>#ifndef VEXCL_TYPES_HPP #define VEXCL_TYPES_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru> 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. */ /** * \file vexcl/types.hpp * \author Pascal Germroth <pascal@ensieve.org> * \brief Support for using native C++ and OpenCL types in expressions. */ #include <string> #include <type_traits> #include <stdexcept> #include <iostream> #include <sstream> #if defined(VEXCL_BACKEND_OPENCL) # ifndef __CL_ENABLE_EXCEPTIONS # define __CL_ENABLE_EXCEPTIONS # endif # include <CL/cl.hpp> #elif defined(VEXCL_BACKEND_CUDA) # include <CL/cl_platform.h> #else # error Neither OpenCL nor CUDA backend is selected #endif /// \cond INTERNAL typedef unsigned int uint; typedef unsigned char uchar; namespace vex { /// Get the corresponding scalar type for a CL vector (or scalar) type. /** \code cl_scalar_of<cl_float4>::type == cl_float \endcode */ template <class T> struct cl_scalar_of {}; /// Get the corresponding vector type for a CL scalar type. /** \code cl_vector_of<cl_float, 4>::type == cl_float4 \endcode */ template <class T, int dim> struct cl_vector_of {}; /// Get the number of values in a CL vector (or scalar) type. /** \code cl_vector_length<cl_float4>::value == 4 \endcode */ template <class T> struct cl_vector_length {}; } // namespace vex #define VEXCL_BIN_OP(name, len, op) \ inline cl_##name##len &operator op## =(cl_##name##len & a, \ const cl_##name##len & b) { \ for (size_t i = 0; i < len; i++) \ a.s[i] op## = b.s[i]; \ return a; \ } \ inline cl_##name##len operator op(const cl_##name##len & a, \ const cl_##name##len & b) { \ cl_##name##len res = a; \ return res op## = b; \ } // `scalar OP vector` acts like `(vector_t)(scalar) OP vector` in OpenCl: // all components are set to the scalar value. #define VEXCL_BIN_SCALAR_OP(name, len, op) \ inline cl_##name##len &operator op## =(cl_##name##len & a, \ const cl_##name & b) { \ for (size_t i = 0; i < len; i++) \ a.s[i] op## = b; \ return a; \ } \ inline cl_##name##len operator op(const cl_##name##len & a, \ const cl_##name & b) { \ cl_##name##len res = a; \ return res op## = b; \ } \ inline cl_##name##len operator op(const cl_##name & a, \ const cl_##name##len & b) { \ cl_##name##len res = b; \ return res op## = a; \ } #define VEXCL_VEC_TYPE(name, len) \ VEXCL_BIN_OP(name, len, +) \ VEXCL_BIN_OP(name, len, -) \ VEXCL_BIN_OP(name, len, *) \ VEXCL_BIN_OP(name, len, /) \ VEXCL_BIN_SCALAR_OP(name, len, +) \ VEXCL_BIN_SCALAR_OP(name, len, -) \ VEXCL_BIN_SCALAR_OP(name, len, *) \ VEXCL_BIN_SCALAR_OP(name, len, /) \ inline cl_##name##len operator-(const cl_##name##len & a) { \ cl_##name##len res; \ for (size_t i = 0; i < len; i++) \ res.s[i] = -a.s[i]; \ return res; \ } \ inline std::ostream &operator<<(std::ostream & os, \ const cl_##name##len & value) { \ os << "(" #name #len ")("; \ for (std::size_t i = 0; i < len; i++) { \ if (i != 0) \ os << ','; \ os << value.s[i]; \ } \ return os << ')'; \ } \ namespace vex { \ template <> struct cl_scalar_of<cl_##name##len> { \ typedef cl_##name type; \ }; \ template <> struct cl_vector_of<cl_##name, len> { \ typedef cl_##name##len type; \ }; \ template <> \ struct cl_vector_length<cl_##name##len> \ : std::integral_constant<unsigned, len> { }; \ } #define VEXCL_TYPES(name) \ VEXCL_VEC_TYPE(name, 2) \ VEXCL_VEC_TYPE(name, 4) \ VEXCL_VEC_TYPE(name, 8) \ VEXCL_VEC_TYPE(name, 16) \ namespace vex { \ template <> struct cl_scalar_of<cl_##name> { \ typedef cl_##name type; \ }; \ template <> struct cl_vector_of<cl_##name, 1> { \ typedef cl_##name type; \ }; \ template <> \ struct cl_vector_length<cl_##name> : std::integral_constant<unsigned, 1> {}; \ } #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4146) #endif VEXCL_TYPES(float) VEXCL_TYPES(double) VEXCL_TYPES(char) VEXCL_TYPES(uchar) VEXCL_TYPES(short) VEXCL_TYPES(ushort) VEXCL_TYPES(int) VEXCL_TYPES(uint) VEXCL_TYPES(long) VEXCL_TYPES(ulong) #ifdef _MSC_VER # pragma warning(pop) #endif #undef VEXCL_BIN_OP #undef VEXCL_BIN_SCALAR_OP #undef VEXCL_VEC_TYPE #undef VEXCL_TYPES namespace vex { /// Convert each element of the vector to another type. template<class To, class From> inline To cl_convert(const From &val) { const size_t n = cl_vector_length<To>::value; static_assert(n == cl_vector_length<From>::value, "Vectors must be same length."); To out; for(size_t i = 0 ; i != n ; i++) out.s[i] = val.s[i]; return out; } /// Declares a type as CL native, allows using it as a literal. template <class T> struct is_cl_native : std::false_type {}; /// Convert typename to string. template <class T, class Enable = void> struct type_name_impl; template <class T> inline std::string type_name() { return type_name_impl<T>::get(); } template<typename T> struct type_name_impl<T&> { static std::string get() { return type_name_impl<T>::get() + " &"; } }; #define VEXCL_STRINGIFY(name) \ template<> struct type_name_impl<cl_##name> { \ static std::string get() { return #name; } \ }; #define VEXCL_NATIVE(name) \ template<> struct is_cl_native<cl_##name> : std::true_type { }; // enable use of OpenCL vector types as literals #define VEXCL_VEC_TYPE(name, len) \ template <> struct type_name_impl<cl_##name##len> { \ static std::string get() { return #name #len; } \ }; \ template <> struct is_cl_native<cl_##name##len> : std::true_type { }; #define VEXCL_TYPES(name) \ VEXCL_STRINGIFY(name) \ VEXCL_NATIVE(name) \ VEXCL_VEC_TYPE(name, 2) \ VEXCL_VEC_TYPE(name, 4) \ VEXCL_VEC_TYPE(name, 8) \ VEXCL_VEC_TYPE(name, 16) VEXCL_TYPES(float) VEXCL_TYPES(double) VEXCL_TYPES(char) VEXCL_TYPES(uchar) VEXCL_TYPES(short) VEXCL_TYPES(ushort) VEXCL_TYPES(int) VEXCL_TYPES(uint) VEXCL_TYPES(long) VEXCL_TYPES(ulong) #undef VEXCL_TYPES #undef VEXCL_VEC_TYPE #undef VEXCL_STRINGIFY // One can not pass these to the kernel, but the overloads are useful template <> struct type_name_impl<bool> { static std::string get() { return "bool"; } }; template <> struct type_name_impl<void> { static std::string get() { return "void"; } }; // char and cl_char are different types. Hence, special handling is required: template <> struct type_name_impl<char> { static std::string get() { return "char"; } }; template <> struct is_cl_native<char> : std::true_type {}; template <> struct cl_vector_length<char> : std::integral_constant<unsigned, 1> {}; template <> struct cl_scalar_of<char> { typedef char type; }; #if defined(__APPLE__) template <> struct type_name_impl<size_t> : public type_name_impl< boost::if_c< sizeof(std::size_t) == sizeof(uint), cl_uint, cl_ulong >::type > {}; template <> struct type_name_impl<ptrdiff_t> : public type_name_impl< boost::if_c< sizeof(std::size_t) == sizeof(uint), cl_int, cl_long >::type > {}; template <> struct is_cl_native<size_t> : std::true_type {}; template <> struct is_cl_native<ptrdiff_t> : std::true_type {}; template <> struct cl_vector_length<size_t> : std::integral_constant<unsigned, 1> {}; template <> struct cl_vector_length<ptrdiff_t> : std::integral_constant<unsigned, 1> {}; template <> struct cl_scalar_of<size_t> { typedef size_t type; }; template <> struct cl_vector_of<size_t, 1> { typedef size_t type; }; template <> struct cl_scalar_of<ptrdiff_t> { typedef ptrdiff_t type; }; template <> struct cl_vector_of<ptrdiff_t, 1> { typedef ptrdiff_t type; }; #endif template <class T> struct is_cl_scalar : std::integral_constant< bool, is_cl_native<T>::value && (cl_vector_length<T>::value == 1) > {}; template <class T> struct is_cl_vector : std::integral_constant< bool, is_cl_native<T>::value && (cl_vector_length<T>::value > 1) > {}; } /// \endcond #endif <commit_msg>fix boost::mpl::if_c namespace<commit_after>#ifndef VEXCL_TYPES_HPP #define VEXCL_TYPES_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru> 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. */ /** * \file vexcl/types.hpp * \author Pascal Germroth <pascal@ensieve.org> * \brief Support for using native C++ and OpenCL types in expressions. */ #include <string> #include <type_traits> #include <stdexcept> #include <iostream> #include <sstream> #if defined(VEXCL_BACKEND_OPENCL) # ifndef __CL_ENABLE_EXCEPTIONS # define __CL_ENABLE_EXCEPTIONS # endif # include <CL/cl.hpp> #elif defined(VEXCL_BACKEND_CUDA) # include <CL/cl_platform.h> #else # error Neither OpenCL nor CUDA backend is selected #endif /// \cond INTERNAL typedef unsigned int uint; typedef unsigned char uchar; namespace vex { /// Get the corresponding scalar type for a CL vector (or scalar) type. /** \code cl_scalar_of<cl_float4>::type == cl_float \endcode */ template <class T> struct cl_scalar_of {}; /// Get the corresponding vector type for a CL scalar type. /** \code cl_vector_of<cl_float, 4>::type == cl_float4 \endcode */ template <class T, int dim> struct cl_vector_of {}; /// Get the number of values in a CL vector (or scalar) type. /** \code cl_vector_length<cl_float4>::value == 4 \endcode */ template <class T> struct cl_vector_length {}; } // namespace vex #define VEXCL_BIN_OP(name, len, op) \ inline cl_##name##len &operator op## =(cl_##name##len & a, \ const cl_##name##len & b) { \ for (size_t i = 0; i < len; i++) \ a.s[i] op## = b.s[i]; \ return a; \ } \ inline cl_##name##len operator op(const cl_##name##len & a, \ const cl_##name##len & b) { \ cl_##name##len res = a; \ return res op## = b; \ } // `scalar OP vector` acts like `(vector_t)(scalar) OP vector` in OpenCl: // all components are set to the scalar value. #define VEXCL_BIN_SCALAR_OP(name, len, op) \ inline cl_##name##len &operator op## =(cl_##name##len & a, \ const cl_##name & b) { \ for (size_t i = 0; i < len; i++) \ a.s[i] op## = b; \ return a; \ } \ inline cl_##name##len operator op(const cl_##name##len & a, \ const cl_##name & b) { \ cl_##name##len res = a; \ return res op## = b; \ } \ inline cl_##name##len operator op(const cl_##name & a, \ const cl_##name##len & b) { \ cl_##name##len res = b; \ return res op## = a; \ } #define VEXCL_VEC_TYPE(name, len) \ VEXCL_BIN_OP(name, len, +) \ VEXCL_BIN_OP(name, len, -) \ VEXCL_BIN_OP(name, len, *) \ VEXCL_BIN_OP(name, len, /) \ VEXCL_BIN_SCALAR_OP(name, len, +) \ VEXCL_BIN_SCALAR_OP(name, len, -) \ VEXCL_BIN_SCALAR_OP(name, len, *) \ VEXCL_BIN_SCALAR_OP(name, len, /) \ inline cl_##name##len operator-(const cl_##name##len & a) { \ cl_##name##len res; \ for (size_t i = 0; i < len; i++) \ res.s[i] = -a.s[i]; \ return res; \ } \ inline std::ostream &operator<<(std::ostream & os, \ const cl_##name##len & value) { \ os << "(" #name #len ")("; \ for (std::size_t i = 0; i < len; i++) { \ if (i != 0) \ os << ','; \ os << value.s[i]; \ } \ return os << ')'; \ } \ namespace vex { \ template <> struct cl_scalar_of<cl_##name##len> { \ typedef cl_##name type; \ }; \ template <> struct cl_vector_of<cl_##name, len> { \ typedef cl_##name##len type; \ }; \ template <> \ struct cl_vector_length<cl_##name##len> \ : std::integral_constant<unsigned, len> { }; \ } #define VEXCL_TYPES(name) \ VEXCL_VEC_TYPE(name, 2) \ VEXCL_VEC_TYPE(name, 4) \ VEXCL_VEC_TYPE(name, 8) \ VEXCL_VEC_TYPE(name, 16) \ namespace vex { \ template <> struct cl_scalar_of<cl_##name> { \ typedef cl_##name type; \ }; \ template <> struct cl_vector_of<cl_##name, 1> { \ typedef cl_##name type; \ }; \ template <> \ struct cl_vector_length<cl_##name> : std::integral_constant<unsigned, 1> {}; \ } #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4146) #endif VEXCL_TYPES(float) VEXCL_TYPES(double) VEXCL_TYPES(char) VEXCL_TYPES(uchar) VEXCL_TYPES(short) VEXCL_TYPES(ushort) VEXCL_TYPES(int) VEXCL_TYPES(uint) VEXCL_TYPES(long) VEXCL_TYPES(ulong) #ifdef _MSC_VER # pragma warning(pop) #endif #undef VEXCL_BIN_OP #undef VEXCL_BIN_SCALAR_OP #undef VEXCL_VEC_TYPE #undef VEXCL_TYPES namespace vex { /// Convert each element of the vector to another type. template<class To, class From> inline To cl_convert(const From &val) { const size_t n = cl_vector_length<To>::value; static_assert(n == cl_vector_length<From>::value, "Vectors must be same length."); To out; for(size_t i = 0 ; i != n ; i++) out.s[i] = val.s[i]; return out; } /// Declares a type as CL native, allows using it as a literal. template <class T> struct is_cl_native : std::false_type {}; /// Convert typename to string. template <class T, class Enable = void> struct type_name_impl; template <class T> inline std::string type_name() { return type_name_impl<T>::get(); } template<typename T> struct type_name_impl<T&> { static std::string get() { return type_name_impl<T>::get() + " &"; } }; #define VEXCL_STRINGIFY(name) \ template<> struct type_name_impl<cl_##name> { \ static std::string get() { return #name; } \ }; #define VEXCL_NATIVE(name) \ template<> struct is_cl_native<cl_##name> : std::true_type { }; // enable use of OpenCL vector types as literals #define VEXCL_VEC_TYPE(name, len) \ template <> struct type_name_impl<cl_##name##len> { \ static std::string get() { return #name #len; } \ }; \ template <> struct is_cl_native<cl_##name##len> : std::true_type { }; #define VEXCL_TYPES(name) \ VEXCL_STRINGIFY(name) \ VEXCL_NATIVE(name) \ VEXCL_VEC_TYPE(name, 2) \ VEXCL_VEC_TYPE(name, 4) \ VEXCL_VEC_TYPE(name, 8) \ VEXCL_VEC_TYPE(name, 16) VEXCL_TYPES(float) VEXCL_TYPES(double) VEXCL_TYPES(char) VEXCL_TYPES(uchar) VEXCL_TYPES(short) VEXCL_TYPES(ushort) VEXCL_TYPES(int) VEXCL_TYPES(uint) VEXCL_TYPES(long) VEXCL_TYPES(ulong) #undef VEXCL_TYPES #undef VEXCL_VEC_TYPE #undef VEXCL_STRINGIFY // One can not pass these to the kernel, but the overloads are useful template <> struct type_name_impl<bool> { static std::string get() { return "bool"; } }; template <> struct type_name_impl<void> { static std::string get() { return "void"; } }; // char and cl_char are different types. Hence, special handling is required: template <> struct type_name_impl<char> { static std::string get() { return "char"; } }; template <> struct is_cl_native<char> : std::true_type {}; template <> struct cl_vector_length<char> : std::integral_constant<unsigned, 1> {}; template <> struct cl_scalar_of<char> { typedef char type; }; #if defined(__APPLE__) template <> struct type_name_impl<size_t> : public type_name_impl< boost::mpl::if_c< sizeof(std::size_t) == sizeof(uint), cl_uint, cl_ulong >::type > {}; template <> struct type_name_impl<ptrdiff_t> : public type_name_impl< boost::mpl::if_c< sizeof(std::size_t) == sizeof(uint), cl_int, cl_long >::type > {}; template <> struct is_cl_native<size_t> : std::true_type {}; template <> struct is_cl_native<ptrdiff_t> : std::true_type {}; template <> struct cl_vector_length<size_t> : std::integral_constant<unsigned, 1> {}; template <> struct cl_vector_length<ptrdiff_t> : std::integral_constant<unsigned, 1> {}; template <> struct cl_scalar_of<size_t> { typedef size_t type; }; template <> struct cl_vector_of<size_t, 1> { typedef size_t type; }; template <> struct cl_scalar_of<ptrdiff_t> { typedef ptrdiff_t type; }; template <> struct cl_vector_of<ptrdiff_t, 1> { typedef ptrdiff_t type; }; #endif template <class T> struct is_cl_scalar : std::integral_constant< bool, is_cl_native<T>::value && (cl_vector_length<T>::value == 1) > {}; template <class T> struct is_cl_vector : std::integral_constant< bool, is_cl_native<T>::value && (cl_vector_length<T>::value > 1) > {}; } /// \endcond #endif <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/report/CReport.cpp,v $ $Revision: 1.46 $ $Name: $ $Author: shoops $ $Date: 2006/04/20 15:27:06 $ End CVS Header */ #include "copasi.h" #include "CReportDefinition.h" #include "CReport.h" #include "CCopasiContainer.h" #include "CCopasiTimer.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "utilities/CDirEntry.h" ////////////////////////////////////////////////// // //class CReport // ////////////////////////////////////////////////// CReport::CReport(const CCopasiContainer * pParent): CCopasiContainer("Report", pParent, "Report"), COutputInterface(), mpOstream(NULL), mStreamOwner(false), mpReportDef(NULL), mTarget(""), mAppend(true), mFooterObjectList(), mBodyObjectList(), mHeaderObjectList(), mpHeader(NULL), mpBody(NULL), mpFooter(NULL) {} CReport::CReport(const CReport & src, const CCopasiContainer * pParent): CCopasiContainer("Report", pParent, "Report"), COutputInterface(), mpOstream(src.mpOstream), mStreamOwner(false), mpReportDef(src.mpReportDef), mTarget(src.mTarget), mAppend(src.mAppend), mFooterObjectList(src.mFooterObjectList), mBodyObjectList(src.mBodyObjectList), mHeaderObjectList(src.mHeaderObjectList), mpHeader(src.mpHeader), mpBody(src.mpBody), mpFooter(src.mpFooter) {} CReport::~CReport() {cleanup();} void CReport::cleanup() { mHeaderObjectList.clear(); mBodyObjectList.clear(); mFooterObjectList.clear(); finish(); } CReportDefinition* CReport::getReportDefinition() {return mpReportDef;} void CReport::setReportDefinition(CReportDefinition* reportDef) {mpReportDef = reportDef;} const std::string& CReport::getTarget() const {return mTarget;} void CReport::setTarget(std::string target) {mTarget = target;} bool CReport::append() const {return mAppend;} void CReport::setAppend(bool append) {mAppend = append;} void CReport::output(const Activity & activity) { switch (activity) { case COutputInterface::BEFORE: printHeader(); break; case COutputInterface::DURING: printBody(); break; case COutputInterface::AFTER: printFooter(); break; } } void CReport::separate(const Activity & activity) { if (!mpOstream) return; (*mpOstream) << std::endl; } void CReport::finish() { if (mStreamOwner) pdelete(mpOstream); mpOstream = NULL; mStreamOwner = false; } void CReport::printHeader() { if (!mpOstream) return; if (mpHeader) switch (mState) { case Compiled: mpHeader->printHeader(); mState = HeaderHeader; return; case HeaderHeader: mpHeader->printBody(); mState = HeaderBody; return; case HeaderBody: mpHeader->printBody(); return; case HeaderFooter: mpHeader->printFooter(); return; default: return; } if (mState == HeaderFooter) return; mState = HeaderFooter; std::vector< CCopasiObject * >::iterator it = mHeaderObjectList.begin(); std::vector< CCopasiObject * >::iterator end = mHeaderObjectList.end(); if (it == end) return; for (; it != end; ++it) (*it)->print(mpOstream); (*mpOstream) << std::endl; } void CReport::printBody() { if (!mpOstream) return; // Close the header part if (mState < HeaderFooter) { mState = HeaderFooter; if (mpHeader) mpHeader->printFooter(); } if (mpBody) switch (mState) { case HeaderFooter: mpBody->printHeader(); mState = BodyHeader; return; case BodyHeader: mpBody->printBody(); mState = BodyBody; return; case BodyBody: mpBody->printBody(); return; case BodyFooter: mpBody->printFooter(); return; default: return; } if (mState == BodyFooter) return; mState = BodyBody; std::vector< CCopasiObject * >::iterator it = mBodyObjectList.begin(); std::vector< CCopasiObject * >::iterator end = mBodyObjectList.end(); if (it == end) return; for (; it != end; ++it) (*it)->print(mpOstream); (*mpOstream) << std::endl; } void CReport::printFooter() { if (!mpOstream) return; // Close the body part if (mState < BodyFooter) { mState = BodyFooter; if (mpBody) mpBody->printFooter(); } if (mpFooter) switch (mState) { case BodyFooter: mpFooter->printHeader(); mState = FooterHeader; return; case FooterHeader: mpFooter->printBody(); mState = FooterBody; return; case FooterBody: mpFooter->printBody(); return; case FooterFooter: mpFooter->printFooter(); return; default: return; } if (mState == FooterFooter) return; mState = FooterFooter; std::vector< CCopasiObject * >::iterator it = mFooterObjectList.begin(); std::vector< CCopasiObject * >::iterator end = mFooterObjectList.end(); if (it == end) return; for (; it != end; ++it) (*it)->print(mpOstream); (*mpOstream) << std::endl; } // Compile the List of Report Objects; // Support Parellel bool CReport::compile(std::vector< CCopasiContainer * > listOfContainer) { bool success = true; // check if there is a Report Definition Defined if (!mpReportDef) return false; listOfContainer.push_back(this); if (mpReportDef->isTable()) if (!mpReportDef->preCompileTable(listOfContainer)) success = false; generateObjectsFromName(&listOfContainer, mHeaderObjectList, mpHeader, mpReportDef->getHeaderAddr()); if (mpHeader) success &= compileChildReport(mpHeader, listOfContainer); generateObjectsFromName(&listOfContainer, mBodyObjectList, mpBody, mpReportDef->getBodyAddr()); if (mpBody) success &= compileChildReport(mpBody, listOfContainer); generateObjectsFromName(&listOfContainer, mFooterObjectList, mpFooter, mpReportDef->getFooterAddr()); if (mpFooter) success &= compileChildReport(mpFooter, listOfContainer); mState = Compiled; return success; } std::ostream * CReport::open(std::ostream * pOstream) { if (mStreamOwner) pdelete(mpOstream); if (pOstream) { mpOstream = pOstream; mStreamOwner = false; } else if (mTarget != "") { if (CDirEntry::isRelativePath(mTarget) && !CDirEntry::makePathAbsolute(mTarget, CCopasiDataModel::Global->getFileName())) mTarget = CDirEntry::fileName(mTarget); mpOstream = new std::ofstream; mStreamOwner = true; if (mAppend) ((std::ofstream *) mpOstream)-> open(mTarget.c_str(), std::ios_base::out | std::ios_base::app); else ((std::ofstream *) mpOstream)-> open(mTarget.c_str(), std::ios_base::out); if (!((std::ofstream *) mpOstream)->is_open()) pdelete(mpOstream); if (mpOstream) mpOstream->precision(mpReportDef->getPrecision()); } return mpOstream; } std::ostream * CReport::getStream() const {return mpOstream;} // make to support parallel tasks void CReport::generateObjectsFromName(const std::vector< CCopasiContainer * > * pListOfContainer, std::vector<CCopasiObject*> & objectList, CReport *& pReport, const std::vector<CRegisteredObjectName>* nameVector) { objectList.clear(); unsigned C_INT32 i; CCopasiObject* pSelected; for (i = 0; i < nameVector->size(); i++) { pSelected = CCopasiContainer::ObjectFromName(*pListOfContainer, (*nameVector)[i]); if (!i && (pReport = dynamic_cast< CReport * >(pSelected))) return; if (pSelected) { COutputInterface::mObjects.insert(pSelected); objectList.push_back(pSelected); } } } bool CReport::compileChildReport(CReport * pReport, std::vector< CCopasiContainer * > listOfContainer) { bool success = pReport->compile(listOfContainer); const std::set< CCopasiObject * > & Objects = pReport->COutputInterface::getObjects(); std::set< CCopasiObject * >::const_iterator it = Objects.begin(); std::set< CCopasiObject * >::const_iterator end = Objects.end(); for (; it != end; ++it) COutputInterface::mObjects.insert(*it); return success; } <commit_msg>mState is now initialized in the constructor to "Invalid".<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/report/CReport.cpp,v $ $Revision: 1.47 $ $Name: $ $Author: shoops $ $Date: 2006/04/20 15:50:23 $ End CVS Header */ #include "copasi.h" #include "CReportDefinition.h" #include "CReport.h" #include "CCopasiContainer.h" #include "CCopasiTimer.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "utilities/CDirEntry.h" ////////////////////////////////////////////////// // //class CReport // ////////////////////////////////////////////////// CReport::CReport(const CCopasiContainer * pParent): CCopasiContainer("Report", pParent, "Report"), COutputInterface(), mpOstream(NULL), mStreamOwner(false), mpReportDef(NULL), mTarget(""), mAppend(true), mFooterObjectList(), mBodyObjectList(), mHeaderObjectList(), mpHeader(NULL), mpBody(NULL), mpFooter(NULL), mState(Invalid) {} CReport::CReport(const CReport & src, const CCopasiContainer * pParent): CCopasiContainer("Report", pParent, "Report"), COutputInterface(), mpOstream(src.mpOstream), mStreamOwner(false), mpReportDef(src.mpReportDef), mTarget(src.mTarget), mAppend(src.mAppend), mFooterObjectList(src.mFooterObjectList), mBodyObjectList(src.mBodyObjectList), mHeaderObjectList(src.mHeaderObjectList), mpHeader(src.mpHeader), mpBody(src.mpBody), mpFooter(src.mpFooter), mState(Invalid) {} CReport::~CReport() {cleanup();} void CReport::cleanup() { mHeaderObjectList.clear(); mBodyObjectList.clear(); mFooterObjectList.clear(); finish(); } CReportDefinition* CReport::getReportDefinition() {return mpReportDef;} void CReport::setReportDefinition(CReportDefinition* reportDef) {mpReportDef = reportDef;} const std::string& CReport::getTarget() const {return mTarget;} void CReport::setTarget(std::string target) {mTarget = target;} bool CReport::append() const {return mAppend;} void CReport::setAppend(bool append) {mAppend = append;} void CReport::output(const Activity & activity) { switch (activity) { case COutputInterface::BEFORE: printHeader(); break; case COutputInterface::DURING: printBody(); break; case COutputInterface::AFTER: printFooter(); break; } } void CReport::separate(const Activity & activity) { if (!mpOstream) return; (*mpOstream) << std::endl; } void CReport::finish() { if (mStreamOwner) pdelete(mpOstream); mpOstream = NULL; mStreamOwner = false; mState = Invalid; } void CReport::printHeader() { if (!mpOstream) return; if (mpHeader) switch (mState) { case Compiled: mpHeader->printHeader(); mState = HeaderHeader; return; case HeaderHeader: mpHeader->printBody(); mState = HeaderBody; return; case HeaderBody: mpHeader->printBody(); return; case HeaderFooter: mpHeader->printFooter(); return; default: return; } if (mState == HeaderFooter) return; mState = HeaderFooter; std::vector< CCopasiObject * >::iterator it = mHeaderObjectList.begin(); std::vector< CCopasiObject * >::iterator end = mHeaderObjectList.end(); if (it == end) return; for (; it != end; ++it) (*it)->print(mpOstream); (*mpOstream) << std::endl; } void CReport::printBody() { if (!mpOstream) return; // Close the header part if (mState < HeaderFooter) { mState = HeaderFooter; if (mpHeader) mpHeader->printFooter(); } if (mpBody) switch (mState) { case HeaderFooter: mpBody->printHeader(); mState = BodyHeader; return; case BodyHeader: mpBody->printBody(); mState = BodyBody; return; case BodyBody: mpBody->printBody(); return; case BodyFooter: mpBody->printFooter(); return; default: return; } if (mState == BodyFooter) return; mState = BodyBody; std::vector< CCopasiObject * >::iterator it = mBodyObjectList.begin(); std::vector< CCopasiObject * >::iterator end = mBodyObjectList.end(); if (it == end) return; for (; it != end; ++it) (*it)->print(mpOstream); (*mpOstream) << std::endl; } void CReport::printFooter() { if (!mpOstream) return; // Close the body part if (mState < BodyFooter) { mState = BodyFooter; if (mpBody) mpBody->printFooter(); } if (mpFooter) switch (mState) { case BodyFooter: mpFooter->printHeader(); mState = FooterHeader; return; case FooterHeader: mpFooter->printBody(); mState = FooterBody; return; case FooterBody: mpFooter->printBody(); return; case FooterFooter: mpFooter->printFooter(); return; default: return; } if (mState == FooterFooter) return; mState = FooterFooter; std::vector< CCopasiObject * >::iterator it = mFooterObjectList.begin(); std::vector< CCopasiObject * >::iterator end = mFooterObjectList.end(); if (it == end) return; for (; it != end; ++it) (*it)->print(mpOstream); (*mpOstream) << std::endl; } // Compile the List of Report Objects; // Support Parellel bool CReport::compile(std::vector< CCopasiContainer * > listOfContainer) { bool success = true; // check if there is a Report Definition Defined if (!mpReportDef) return false; listOfContainer.push_back(this); if (mpReportDef->isTable()) if (!mpReportDef->preCompileTable(listOfContainer)) success = false; generateObjectsFromName(&listOfContainer, mHeaderObjectList, mpHeader, mpReportDef->getHeaderAddr()); if (mpHeader) success &= compileChildReport(mpHeader, listOfContainer); generateObjectsFromName(&listOfContainer, mBodyObjectList, mpBody, mpReportDef->getBodyAddr()); if (mpBody) success &= compileChildReport(mpBody, listOfContainer); generateObjectsFromName(&listOfContainer, mFooterObjectList, mpFooter, mpReportDef->getFooterAddr()); if (mpFooter) success &= compileChildReport(mpFooter, listOfContainer); mState = Compiled; return success; } std::ostream * CReport::open(std::ostream * pOstream) { if (mStreamOwner) pdelete(mpOstream); if (pOstream) { mpOstream = pOstream; mStreamOwner = false; } else if (mTarget != "") { if (CDirEntry::isRelativePath(mTarget) && !CDirEntry::makePathAbsolute(mTarget, CCopasiDataModel::Global->getFileName())) mTarget = CDirEntry::fileName(mTarget); mpOstream = new std::ofstream; mStreamOwner = true; if (mAppend) ((std::ofstream *) mpOstream)-> open(mTarget.c_str(), std::ios_base::out | std::ios_base::app); else ((std::ofstream *) mpOstream)-> open(mTarget.c_str(), std::ios_base::out); if (!((std::ofstream *) mpOstream)->is_open()) pdelete(mpOstream); if (mpOstream) mpOstream->precision(mpReportDef->getPrecision()); } return mpOstream; } std::ostream * CReport::getStream() const {return mpOstream;} // make to support parallel tasks void CReport::generateObjectsFromName(const std::vector< CCopasiContainer * > * pListOfContainer, std::vector<CCopasiObject*> & objectList, CReport *& pReport, const std::vector<CRegisteredObjectName>* nameVector) { objectList.clear(); unsigned C_INT32 i; CCopasiObject* pSelected; for (i = 0; i < nameVector->size(); i++) { pSelected = CCopasiContainer::ObjectFromName(*pListOfContainer, (*nameVector)[i]); if (!i && (pReport = dynamic_cast< CReport * >(pSelected))) return; if (pSelected) { COutputInterface::mObjects.insert(pSelected); objectList.push_back(pSelected); } } } bool CReport::compileChildReport(CReport * pReport, std::vector< CCopasiContainer * > listOfContainer) { bool success = pReport->compile(listOfContainer); const std::set< CCopasiObject * > & Objects = pReport->COutputInterface::getObjects(); std::set< CCopasiObject * >::const_iterator it = Objects.begin(); std::set< CCopasiObject * >::const_iterator end = Objects.end(); for (; it != end; ++it) COutputInterface::mObjects.insert(*it); return success; } <|endoftext|>
<commit_before>//===- TGLexer.cpp - Lexer for TableGen -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implement the Lexer for TableGen. // //===----------------------------------------------------------------------===// #include "TGLexer.h" #include "llvm/TableGen/Error.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Twine.h" #include <cctype> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> #include "llvm/Config/config.h" using namespace llvm; TGLexer::TGLexer(SourceMgr &SM) : SrcMgr(SM) { CurBuffer = 0; CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = CurBuf->getBufferStart(); TokStart = 0; } SMLoc TGLexer::getLoc() const { return SMLoc::getFromPointer(TokStart); } /// ReturnError - Set the error to the specified string at the specified /// location. This is defined to always return tgtok::Error. tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) { PrintError(Loc, Msg); return tgtok::Error; } int TGLexer::getNextChar() { char CurChar = *CurPtr++; switch (CurChar) { default: return (unsigned char)CurChar; case 0: { // A nul character in the stream is either the end of the current buffer or // a random nul in the file. Disambiguate that here. if (CurPtr-1 != CurBuf->getBufferEnd()) return 0; // Just whitespace. // If this is the end of an included file, pop the parent file off the // include stack. SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); if (ParentIncludeLoc != SMLoc()) { CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc); CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = ParentIncludeLoc.getPointer(); return getNextChar(); } // Otherwise, return end of file. --CurPtr; // Another call to lex will return EOF again. return EOF; } case '\n': case '\r': // Handle the newline character by ignoring it and incrementing the line // count. However, be careful about 'dos style' files with \n\r in them. // Only treat a \n\r or \r\n as a single line. if ((*CurPtr == '\n' || (*CurPtr == '\r')) && *CurPtr != CurChar) ++CurPtr; // Eat the two char newline sequence. return '\n'; } } int TGLexer::peekNextChar(int Index) { return *(CurPtr + Index); } tgtok::TokKind TGLexer::LexToken() { TokStart = CurPtr; // This always consumes at least one character. int CurChar = getNextChar(); switch (CurChar) { default: // Handle letters: [a-zA-Z_] if (isalpha(CurChar) || CurChar == '_') return LexIdentifier(); // Unknown character, emit an error. return ReturnError(TokStart, "Unexpected character"); case EOF: return tgtok::Eof; case ':': return tgtok::colon; case ';': return tgtok::semi; case '.': return tgtok::period; case ',': return tgtok::comma; case '<': return tgtok::less; case '>': return tgtok::greater; case ']': return tgtok::r_square; case '{': return tgtok::l_brace; case '}': return tgtok::r_brace; case '(': return tgtok::l_paren; case ')': return tgtok::r_paren; case '=': return tgtok::equal; case '?': return tgtok::question; case '#': return tgtok::paste; case 0: case ' ': case '\t': case '\n': case '\r': // Ignore whitespace. return LexToken(); case '/': // If this is the start of a // comment, skip until the end of the line or // the end of the buffer. if (*CurPtr == '/') SkipBCPLComment(); else if (*CurPtr == '*') { if (SkipCComment()) return tgtok::Error; } else // Otherwise, this is an error. return ReturnError(TokStart, "Unexpected character"); return LexToken(); case '-': case '+': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { int NextChar = 0; if (isdigit(CurChar)) { // Allow identifiers to start with a number if it is followed by // an identifier. This can happen with paste operations like // foo#8i. int i = 0; do { NextChar = peekNextChar(i++); } while (isdigit(NextChar)); if (NextChar == 'x' || NextChar == 'b') { // If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most // likely a number. int NextNextChar = peekNextChar(i); switch (NextNextChar) { default: break; case '0': case '1': if (NextChar == 'b') return LexNumber(); // Fallthrough case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': if (NextChar == 'x') return LexNumber(); break; } } } if (isalpha(NextChar) || NextChar == '_') return LexIdentifier(); return LexNumber(); } case '"': return LexString(); case '$': return LexVarName(); case '[': return LexBracket(); case '!': return LexExclaim(); } } /// LexString - Lex "[^"]*" tgtok::TokKind TGLexer::LexString() { const char *StrStart = CurPtr; CurStrVal = ""; while (*CurPtr != '"') { // If we hit the end of the buffer, report an error. if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd()) return ReturnError(StrStart, "End of file in string literal"); if (*CurPtr == '\n' || *CurPtr == '\r') return ReturnError(StrStart, "End of line in string literal"); if (*CurPtr != '\\') { CurStrVal += *CurPtr++; continue; } ++CurPtr; switch (*CurPtr) { case '\\': case '\'': case '"': // These turn into their literal character. CurStrVal += *CurPtr++; break; case 't': CurStrVal += '\t'; ++CurPtr; break; case 'n': CurStrVal += '\n'; ++CurPtr; break; case '\n': case '\r': return ReturnError(CurPtr, "escaped newlines not supported in tblgen"); // If we hit the end of the buffer, report an error. case '\0': if (CurPtr == CurBuf->getBufferEnd()) return ReturnError(StrStart, "End of file in string literal"); // FALL THROUGH default: return ReturnError(CurPtr, "invalid escape in string literal"); } } ++CurPtr; return tgtok::StrVal; } tgtok::TokKind TGLexer::LexVarName() { if (!isalpha(CurPtr[0]) && CurPtr[0] != '_') return ReturnError(TokStart, "Invalid variable name"); // Otherwise, we're ok, consume the rest of the characters. const char *VarNameStart = CurPtr++; while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_') ++CurPtr; CurStrVal.assign(VarNameStart, CurPtr); return tgtok::VarName; } tgtok::TokKind TGLexer::LexIdentifier() { // The first letter is [a-zA-Z_#]. const char *IdentStart = TokStart; // Match the rest of the identifier regex: [0-9a-zA-Z_#]* while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_') ++CurPtr; // Check to see if this identifier is a keyword. StringRef Str(IdentStart, CurPtr-IdentStart); if (Str == "include") { if (LexInclude()) return tgtok::Error; return Lex(); } tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(Str) .Case("int", tgtok::Int) .Case("bit", tgtok::Bit) .Case("bits", tgtok::Bits) .Case("string", tgtok::String) .Case("list", tgtok::List) .Case("code", tgtok::Code) .Case("dag", tgtok::Dag) .Case("class", tgtok::Class) .Case("def", tgtok::Def) .Case("defm", tgtok::Defm) .Case("multiclass", tgtok::MultiClass) .Case("field", tgtok::Field) .Case("let", tgtok::Let) .Case("in", tgtok::In) .Default(tgtok::Id); if (Kind == tgtok::Id) CurStrVal.assign(Str.begin(), Str.end()); return Kind; } /// LexInclude - We just read the "include" token. Get the string token that /// comes next and enter the include. bool TGLexer::LexInclude() { // The token after the include must be a string. tgtok::TokKind Tok = LexToken(); if (Tok == tgtok::Error) return true; if (Tok != tgtok::StrVal) { PrintError(getLoc(), "Expected filename after include"); return true; } // Get the string. std::string Filename = CurStrVal; std::string IncludedFile; CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr), IncludedFile); if (CurBuffer == -1) { PrintError(getLoc(), "Could not find include file '" + Filename + "'"); return true; } Dependencies.push_back(IncludedFile); // Save the line number and lex buffer of the includer. CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = CurBuf->getBufferStart(); return false; } void TGLexer::SkipBCPLComment() { ++CurPtr; // skip the second slash. while (1) { switch (*CurPtr) { case '\n': case '\r': return; // Newline is end of comment. case 0: // If this is the end of the buffer, end the comment. if (CurPtr == CurBuf->getBufferEnd()) return; break; } // Otherwise, skip the character. ++CurPtr; } } /// SkipCComment - This skips C-style /**/ comments. The only difference from C /// is that we allow nesting. bool TGLexer::SkipCComment() { ++CurPtr; // skip the star. unsigned CommentDepth = 1; while (1) { int CurChar = getNextChar(); switch (CurChar) { case EOF: PrintError(TokStart, "Unterminated comment!"); return true; case '*': // End of the comment? if (CurPtr[0] != '/') break; ++CurPtr; // End the */. if (--CommentDepth == 0) return false; break; case '/': // Start of a nested comment? if (CurPtr[0] != '*') break; ++CurPtr; ++CommentDepth; break; } } } /// LexNumber - Lex: /// [-+]?[0-9]+ /// 0x[0-9a-fA-F]+ /// 0b[01]+ tgtok::TokKind TGLexer::LexNumber() { if (CurPtr[-1] == '0') { if (CurPtr[0] == 'x') { ++CurPtr; const char *NumStart = CurPtr; while (isxdigit(CurPtr[0])) ++CurPtr; // Requires at least one hex digit. if (CurPtr == NumStart) return ReturnError(TokStart, "Invalid hexadecimal number"); errno = 0; CurIntVal = strtoll(NumStart, 0, 16); if (errno == EINVAL) return ReturnError(TokStart, "Invalid hexadecimal number"); if (errno == ERANGE) { errno = 0; CurIntVal = (int64_t)strtoull(NumStart, 0, 16); if (errno == EINVAL) return ReturnError(TokStart, "Invalid hexadecimal number"); if (errno == ERANGE) return ReturnError(TokStart, "Hexadecimal number out of range"); } return tgtok::IntVal; } else if (CurPtr[0] == 'b') { ++CurPtr; const char *NumStart = CurPtr; while (CurPtr[0] == '0' || CurPtr[0] == '1') ++CurPtr; // Requires at least one binary digit. if (CurPtr == NumStart) return ReturnError(CurPtr-2, "Invalid binary number"); CurIntVal = strtoll(NumStart, 0, 2); return tgtok::IntVal; } } // Check for a sign without a digit. if (!isdigit(CurPtr[0])) { if (CurPtr[-1] == '-') return tgtok::minus; else if (CurPtr[-1] == '+') return tgtok::plus; } while (isdigit(CurPtr[0])) ++CurPtr; CurIntVal = strtoll(TokStart, 0, 10); return tgtok::IntVal; } /// LexBracket - We just read '['. If this is a code block, return it, /// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]' tgtok::TokKind TGLexer::LexBracket() { if (CurPtr[0] != '{') return tgtok::l_square; ++CurPtr; const char *CodeStart = CurPtr; while (1) { int Char = getNextChar(); if (Char == EOF) break; if (Char != '}') continue; Char = getNextChar(); if (Char == EOF) break; if (Char == ']') { CurStrVal.assign(CodeStart, CurPtr-2); return tgtok::CodeFragment; } } return ReturnError(CodeStart-2, "Unterminated Code Block"); } /// LexExclaim - Lex '!' and '![a-zA-Z]+'. tgtok::TokKind TGLexer::LexExclaim() { if (!isalpha(*CurPtr)) return ReturnError(CurPtr - 1, "Invalid \"!operator\""); const char *Start = CurPtr++; while (isalpha(*CurPtr)) ++CurPtr; // Check to see which operator this is. tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start)) .Case("eq", tgtok::XEq) .Case("if", tgtok::XIf) .Case("head", tgtok::XHead) .Case("tail", tgtok::XTail) .Case("con", tgtok::XConcat) .Case("shl", tgtok::XSHL) .Case("sra", tgtok::XSRA) .Case("srl", tgtok::XSRL) .Case("cast", tgtok::XCast) .Case("empty", tgtok::XEmpty) .Case("subst", tgtok::XSubst) .Case("foreach", tgtok::XForEach) .Case("strconcat", tgtok::XStrConcat) .Default(tgtok::Error); return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator"); } <commit_msg>TableGen: add a comment<commit_after>//===- TGLexer.cpp - Lexer for TableGen -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implement the Lexer for TableGen. // //===----------------------------------------------------------------------===// #include "TGLexer.h" #include "llvm/TableGen/Error.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Twine.h" #include <cctype> #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> #include "llvm/Config/config.h" // for strtoull()/strtoll() define using namespace llvm; TGLexer::TGLexer(SourceMgr &SM) : SrcMgr(SM) { CurBuffer = 0; CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = CurBuf->getBufferStart(); TokStart = 0; } SMLoc TGLexer::getLoc() const { return SMLoc::getFromPointer(TokStart); } /// ReturnError - Set the error to the specified string at the specified /// location. This is defined to always return tgtok::Error. tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) { PrintError(Loc, Msg); return tgtok::Error; } int TGLexer::getNextChar() { char CurChar = *CurPtr++; switch (CurChar) { default: return (unsigned char)CurChar; case 0: { // A nul character in the stream is either the end of the current buffer or // a random nul in the file. Disambiguate that here. if (CurPtr-1 != CurBuf->getBufferEnd()) return 0; // Just whitespace. // If this is the end of an included file, pop the parent file off the // include stack. SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer); if (ParentIncludeLoc != SMLoc()) { CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc); CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = ParentIncludeLoc.getPointer(); return getNextChar(); } // Otherwise, return end of file. --CurPtr; // Another call to lex will return EOF again. return EOF; } case '\n': case '\r': // Handle the newline character by ignoring it and incrementing the line // count. However, be careful about 'dos style' files with \n\r in them. // Only treat a \n\r or \r\n as a single line. if ((*CurPtr == '\n' || (*CurPtr == '\r')) && *CurPtr != CurChar) ++CurPtr; // Eat the two char newline sequence. return '\n'; } } int TGLexer::peekNextChar(int Index) { return *(CurPtr + Index); } tgtok::TokKind TGLexer::LexToken() { TokStart = CurPtr; // This always consumes at least one character. int CurChar = getNextChar(); switch (CurChar) { default: // Handle letters: [a-zA-Z_] if (isalpha(CurChar) || CurChar == '_') return LexIdentifier(); // Unknown character, emit an error. return ReturnError(TokStart, "Unexpected character"); case EOF: return tgtok::Eof; case ':': return tgtok::colon; case ';': return tgtok::semi; case '.': return tgtok::period; case ',': return tgtok::comma; case '<': return tgtok::less; case '>': return tgtok::greater; case ']': return tgtok::r_square; case '{': return tgtok::l_brace; case '}': return tgtok::r_brace; case '(': return tgtok::l_paren; case ')': return tgtok::r_paren; case '=': return tgtok::equal; case '?': return tgtok::question; case '#': return tgtok::paste; case 0: case ' ': case '\t': case '\n': case '\r': // Ignore whitespace. return LexToken(); case '/': // If this is the start of a // comment, skip until the end of the line or // the end of the buffer. if (*CurPtr == '/') SkipBCPLComment(); else if (*CurPtr == '*') { if (SkipCComment()) return tgtok::Error; } else // Otherwise, this is an error. return ReturnError(TokStart, "Unexpected character"); return LexToken(); case '-': case '+': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { int NextChar = 0; if (isdigit(CurChar)) { // Allow identifiers to start with a number if it is followed by // an identifier. This can happen with paste operations like // foo#8i. int i = 0; do { NextChar = peekNextChar(i++); } while (isdigit(NextChar)); if (NextChar == 'x' || NextChar == 'b') { // If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most // likely a number. int NextNextChar = peekNextChar(i); switch (NextNextChar) { default: break; case '0': case '1': if (NextChar == 'b') return LexNumber(); // Fallthrough case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': if (NextChar == 'x') return LexNumber(); break; } } } if (isalpha(NextChar) || NextChar == '_') return LexIdentifier(); return LexNumber(); } case '"': return LexString(); case '$': return LexVarName(); case '[': return LexBracket(); case '!': return LexExclaim(); } } /// LexString - Lex "[^"]*" tgtok::TokKind TGLexer::LexString() { const char *StrStart = CurPtr; CurStrVal = ""; while (*CurPtr != '"') { // If we hit the end of the buffer, report an error. if (*CurPtr == 0 && CurPtr == CurBuf->getBufferEnd()) return ReturnError(StrStart, "End of file in string literal"); if (*CurPtr == '\n' || *CurPtr == '\r') return ReturnError(StrStart, "End of line in string literal"); if (*CurPtr != '\\') { CurStrVal += *CurPtr++; continue; } ++CurPtr; switch (*CurPtr) { case '\\': case '\'': case '"': // These turn into their literal character. CurStrVal += *CurPtr++; break; case 't': CurStrVal += '\t'; ++CurPtr; break; case 'n': CurStrVal += '\n'; ++CurPtr; break; case '\n': case '\r': return ReturnError(CurPtr, "escaped newlines not supported in tblgen"); // If we hit the end of the buffer, report an error. case '\0': if (CurPtr == CurBuf->getBufferEnd()) return ReturnError(StrStart, "End of file in string literal"); // FALL THROUGH default: return ReturnError(CurPtr, "invalid escape in string literal"); } } ++CurPtr; return tgtok::StrVal; } tgtok::TokKind TGLexer::LexVarName() { if (!isalpha(CurPtr[0]) && CurPtr[0] != '_') return ReturnError(TokStart, "Invalid variable name"); // Otherwise, we're ok, consume the rest of the characters. const char *VarNameStart = CurPtr++; while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_') ++CurPtr; CurStrVal.assign(VarNameStart, CurPtr); return tgtok::VarName; } tgtok::TokKind TGLexer::LexIdentifier() { // The first letter is [a-zA-Z_#]. const char *IdentStart = TokStart; // Match the rest of the identifier regex: [0-9a-zA-Z_#]* while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr == '_') ++CurPtr; // Check to see if this identifier is a keyword. StringRef Str(IdentStart, CurPtr-IdentStart); if (Str == "include") { if (LexInclude()) return tgtok::Error; return Lex(); } tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(Str) .Case("int", tgtok::Int) .Case("bit", tgtok::Bit) .Case("bits", tgtok::Bits) .Case("string", tgtok::String) .Case("list", tgtok::List) .Case("code", tgtok::Code) .Case("dag", tgtok::Dag) .Case("class", tgtok::Class) .Case("def", tgtok::Def) .Case("defm", tgtok::Defm) .Case("multiclass", tgtok::MultiClass) .Case("field", tgtok::Field) .Case("let", tgtok::Let) .Case("in", tgtok::In) .Default(tgtok::Id); if (Kind == tgtok::Id) CurStrVal.assign(Str.begin(), Str.end()); return Kind; } /// LexInclude - We just read the "include" token. Get the string token that /// comes next and enter the include. bool TGLexer::LexInclude() { // The token after the include must be a string. tgtok::TokKind Tok = LexToken(); if (Tok == tgtok::Error) return true; if (Tok != tgtok::StrVal) { PrintError(getLoc(), "Expected filename after include"); return true; } // Get the string. std::string Filename = CurStrVal; std::string IncludedFile; CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr), IncludedFile); if (CurBuffer == -1) { PrintError(getLoc(), "Could not find include file '" + Filename + "'"); return true; } Dependencies.push_back(IncludedFile); // Save the line number and lex buffer of the includer. CurBuf = SrcMgr.getMemoryBuffer(CurBuffer); CurPtr = CurBuf->getBufferStart(); return false; } void TGLexer::SkipBCPLComment() { ++CurPtr; // skip the second slash. while (1) { switch (*CurPtr) { case '\n': case '\r': return; // Newline is end of comment. case 0: // If this is the end of the buffer, end the comment. if (CurPtr == CurBuf->getBufferEnd()) return; break; } // Otherwise, skip the character. ++CurPtr; } } /// SkipCComment - This skips C-style /**/ comments. The only difference from C /// is that we allow nesting. bool TGLexer::SkipCComment() { ++CurPtr; // skip the star. unsigned CommentDepth = 1; while (1) { int CurChar = getNextChar(); switch (CurChar) { case EOF: PrintError(TokStart, "Unterminated comment!"); return true; case '*': // End of the comment? if (CurPtr[0] != '/') break; ++CurPtr; // End the */. if (--CommentDepth == 0) return false; break; case '/': // Start of a nested comment? if (CurPtr[0] != '*') break; ++CurPtr; ++CommentDepth; break; } } } /// LexNumber - Lex: /// [-+]?[0-9]+ /// 0x[0-9a-fA-F]+ /// 0b[01]+ tgtok::TokKind TGLexer::LexNumber() { if (CurPtr[-1] == '0') { if (CurPtr[0] == 'x') { ++CurPtr; const char *NumStart = CurPtr; while (isxdigit(CurPtr[0])) ++CurPtr; // Requires at least one hex digit. if (CurPtr == NumStart) return ReturnError(TokStart, "Invalid hexadecimal number"); errno = 0; CurIntVal = strtoll(NumStart, 0, 16); if (errno == EINVAL) return ReturnError(TokStart, "Invalid hexadecimal number"); if (errno == ERANGE) { errno = 0; CurIntVal = (int64_t)strtoull(NumStart, 0, 16); if (errno == EINVAL) return ReturnError(TokStart, "Invalid hexadecimal number"); if (errno == ERANGE) return ReturnError(TokStart, "Hexadecimal number out of range"); } return tgtok::IntVal; } else if (CurPtr[0] == 'b') { ++CurPtr; const char *NumStart = CurPtr; while (CurPtr[0] == '0' || CurPtr[0] == '1') ++CurPtr; // Requires at least one binary digit. if (CurPtr == NumStart) return ReturnError(CurPtr-2, "Invalid binary number"); CurIntVal = strtoll(NumStart, 0, 2); return tgtok::IntVal; } } // Check for a sign without a digit. if (!isdigit(CurPtr[0])) { if (CurPtr[-1] == '-') return tgtok::minus; else if (CurPtr[-1] == '+') return tgtok::plus; } while (isdigit(CurPtr[0])) ++CurPtr; CurIntVal = strtoll(TokStart, 0, 10); return tgtok::IntVal; } /// LexBracket - We just read '['. If this is a code block, return it, /// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]' tgtok::TokKind TGLexer::LexBracket() { if (CurPtr[0] != '{') return tgtok::l_square; ++CurPtr; const char *CodeStart = CurPtr; while (1) { int Char = getNextChar(); if (Char == EOF) break; if (Char != '}') continue; Char = getNextChar(); if (Char == EOF) break; if (Char == ']') { CurStrVal.assign(CodeStart, CurPtr-2); return tgtok::CodeFragment; } } return ReturnError(CodeStart-2, "Unterminated Code Block"); } /// LexExclaim - Lex '!' and '![a-zA-Z]+'. tgtok::TokKind TGLexer::LexExclaim() { if (!isalpha(*CurPtr)) return ReturnError(CurPtr - 1, "Invalid \"!operator\""); const char *Start = CurPtr++; while (isalpha(*CurPtr)) ++CurPtr; // Check to see which operator this is. tgtok::TokKind Kind = StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start)) .Case("eq", tgtok::XEq) .Case("if", tgtok::XIf) .Case("head", tgtok::XHead) .Case("tail", tgtok::XTail) .Case("con", tgtok::XConcat) .Case("shl", tgtok::XSHL) .Case("sra", tgtok::XSRA) .Case("srl", tgtok::XSRL) .Case("cast", tgtok::XCast) .Case("empty", tgtok::XEmpty) .Case("subst", tgtok::XSubst) .Case("foreach", tgtok::XForEach) .Case("strconcat", tgtok::XStrConcat) .Default(tgtok::Error); return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator"); } <|endoftext|>
<commit_before>/* * Launch WAS child processes. * * author: Max Kellermann <mk@cm4all.com> */ #include "was_launch.hxx" #include "fd_util.h" #include "fd-util.h" #include "exec.hxx" #include "child_options.hxx" #include "sigutil.h" #include "gerrno.h" #include "util/ConstBuffer.hxx" #include <daemon/log.h> #include <inline/compiler.h> #include <sys/socket.h> #include <stdio.h> #include <unistd.h> #include <string.h> #ifdef __linux #include <sched.h> #endif struct was_run_args { sigset_t signals; const struct child_options *options; int control_fd, input_fd, output_fd; ConstBuffer<const char *> env; Exec exec; }; gcc_noreturn static int was_run(void *ctx) { struct was_run_args *args = (struct was_run_args *)ctx; install_default_signal_handlers(); leave_signal_section(&args->signals); args->options->SetupStderr(); namespace_options_setup(&args->options->ns); rlimit_options_apply(&args->options->rlimits); dup2(args->input_fd, 0); dup2(args->output_fd, 1); /* fd2 is retained */ dup2(args->control_fd, 3); clearenv(); for (auto i : args->env) putenv(const_cast<char *>(i)); args->exec.DoExec(); } bool was_launch(struct was_process *process, const char *executable_path, ConstBuffer<const char *> args, ConstBuffer<const char *> env, const struct child_options *options, GError **error_r) { int control_fds[2], input_fds[2], output_fds[2]; if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) { set_error_errno_msg(error_r, "failed to create socket pair"); return false; } if (pipe_cloexec(input_fds) < 0) { set_error_errno_msg(error_r, "failed to create first pipe"); close(control_fds[0]); close(control_fds[1]); return false; } if (pipe_cloexec(output_fds) < 0) { set_error_errno_msg(error_r, "failed to create second pipe"); close(control_fds[0]); close(control_fds[1]); close(input_fds[0]); close(input_fds[1]); return false; } struct was_run_args run_args = { .options = options, .control_fd = control_fds[1], .output_fd = input_fds[1], .input_fd = output_fds[0], .env = env, }; jail_wrapper_insert(run_args.exec, &options->jail, nullptr); run_args.exec.Append(executable_path); for (auto i : args) run_args.exec.Append(i); int clone_flags = SIGCHLD; clone_flags = namespace_options_clone_flags(&options->ns, clone_flags); /* avoid race condition due to libevent signal handler in child process */ enter_signal_section(&run_args.signals); char stack[8192]; long pid = clone(was_run, stack + sizeof(stack), clone_flags, &run_args); if (pid < 0) { leave_signal_section(&run_args.signals); set_error_errno_msg(error_r, "clone() failed"); close(control_fds[0]); close(control_fds[1]); close(input_fds[0]); close(input_fds[1]); close(output_fds[0]); close(output_fds[1]); return false; } leave_signal_section(&run_args.signals); close(control_fds[1]); close(input_fds[1]); close(output_fds[0]); fd_set_nonblock(input_fds[0], true); fd_set_nonblock(output_fds[1], true); process->pid = pid; process->control_fd = control_fds[0]; process->input_fd = input_fds[0]; process->output_fd = output_fds[1]; return true; } <commit_msg>was_launch: move Exec setup to child process<commit_after>/* * Launch WAS child processes. * * author: Max Kellermann <mk@cm4all.com> */ #include "was_launch.hxx" #include "fd_util.h" #include "fd-util.h" #include "exec.hxx" #include "child_options.hxx" #include "sigutil.h" #include "gerrno.h" #include "util/ConstBuffer.hxx" #include <daemon/log.h> #include <inline/compiler.h> #include <sys/socket.h> #include <stdio.h> #include <unistd.h> #include <string.h> #ifdef __linux #include <sched.h> #endif struct was_run_args { sigset_t signals; const struct child_options *options; int control_fd, input_fd, output_fd; const char *executable_path; ConstBuffer<const char *> args; ConstBuffer<const char *> env; }; gcc_noreturn static int was_run(void *ctx) { struct was_run_args *args = (struct was_run_args *)ctx; install_default_signal_handlers(); leave_signal_section(&args->signals); args->options->SetupStderr(); namespace_options_setup(&args->options->ns); rlimit_options_apply(&args->options->rlimits); dup2(args->input_fd, 0); dup2(args->output_fd, 1); /* fd2 is retained */ dup2(args->control_fd, 3); clearenv(); for (auto i : args->env) putenv(const_cast<char *>(i)); Exec exec; jail_wrapper_insert(exec, &args->options->jail, nullptr); exec.Append(args->executable_path); for (auto i : args->args) exec.Append(i); exec.DoExec(); } bool was_launch(struct was_process *process, const char *executable_path, ConstBuffer<const char *> args, ConstBuffer<const char *> env, const struct child_options *options, GError **error_r) { int control_fds[2], input_fds[2], output_fds[2]; if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) { set_error_errno_msg(error_r, "failed to create socket pair"); return false; } if (pipe_cloexec(input_fds) < 0) { set_error_errno_msg(error_r, "failed to create first pipe"); close(control_fds[0]); close(control_fds[1]); return false; } if (pipe_cloexec(output_fds) < 0) { set_error_errno_msg(error_r, "failed to create second pipe"); close(control_fds[0]); close(control_fds[1]); close(input_fds[0]); close(input_fds[1]); return false; } struct was_run_args run_args = { .options = options, .control_fd = control_fds[1], .output_fd = input_fds[1], .input_fd = output_fds[0], .executable_path = executable_path, .args = args, .env = env, }; int clone_flags = SIGCHLD; clone_flags = namespace_options_clone_flags(&options->ns, clone_flags); /* avoid race condition due to libevent signal handler in child process */ enter_signal_section(&run_args.signals); char stack[8192]; long pid = clone(was_run, stack + sizeof(stack), clone_flags, &run_args); if (pid < 0) { leave_signal_section(&run_args.signals); set_error_errno_msg(error_r, "clone() failed"); close(control_fds[0]); close(control_fds[1]); close(input_fds[0]); close(input_fds[1]); close(output_fds[0]); close(output_fds[1]); return false; } leave_signal_section(&run_args.signals); close(control_fds[1]); close(input_fds[1]); close(output_fds[0]); fd_set_nonblock(input_fds[0], true); fd_set_nonblock(output_fds[1], true); process->pid = pid; process->control_fd = control_fds[0]; process->input_fd = input_fds[0]; process->output_fd = output_fds[1]; return true; } <|endoftext|>
<commit_before>/* * This file is part of OpenModelica. * * Copyright (c) 1998-CurrentYear, Linköping University, * Department of Computer and Information Science, * SE-58183 Linköping, Sweden. * * All rights reserved. * * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 * AND THIS OSMC PUBLIC LICENSE (OSMC-PL). * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S * ACCEPTANCE OF THE OSMC PUBLIC LICENSE. * * The OpenModelica software and the Open Source Modelica * Consortium (OSMC) Public License (OSMC-PL) are obtained * from Linköping University, either from the above address, * from the URLs: http://www.ida.liu.se/projects/OpenModelica or * http://www.openmodelica.org, and in the OpenModelica distribution. * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. * * This program is distributed WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS * OF OSMC-PL. * * See the full OSMC Public License conditions for more details. * */ /* * HopsanGUI * Fluid and Mechatronic Systems, Department of Management and Engineering, Linköping University * Main Authors 2009-2010: Robert Braun, Björn Eriksson, Peter Nordin * Contributors 2009-2010: Mikael Axin, Alessandro Dell'Amico, Karl Pettersson, Ingo Staack */ #include "GUIUtilities.h" using namespace std; //! @brief This function extracts the name from a text stream //! @return The extracted name without quotes, empty string if failed //! It is assumed that the name was saved OK. but error indicated by empty string QString readName(QTextStream &rTextStream) { QString tempName; rTextStream >> tempName; if (tempName.startsWith("\"")) { while (!tempName.endsWith("\"")) { if (rTextStream.atEnd()) { return QString(""); //Empty string (failed) } else { QString tmpstr; rTextStream >> tmpstr; tempName.append(" " + tmpstr); } } return tempName.remove("\"").trimmed(); //Remove quotes and trimm (just to be sure) } else { return QString(""); //Empty string (failed) } } //! @brief Convenience function if you dont have a stream to read from //! @return The extracted name without quotes, empty string if failed //! It is assumed that the name was saved OK. but error indicated by empty string QString readName(QString namestring) { QTextStream namestream(&namestring); return readName(namestream); } //! @brief This function may be used to add quotes around string, usefull for saving names. Ex: "string" QString addQuotes(QString str) { str.prepend("\""); str.append("\""); return str; } //! @brief Use this function to calculate the placement of the ports on a subsystem icon. //! @param[in] w width of the subsystem icon //! @param[in] h heigth of the subsystem icon //! @param[in] angle the angle of the line between center and the actual port //! @param[out] x the new calculated horizontal placement for the port //! @param[out] y the new calculated vertical placement for the port void calcSubsystemPortPosition(const double w, const double h, const double angle, double &x, double &y) { if(angle>3.1415*3.0/2.0) { x=-max(min(h/tan(angle), w), -w); y=max(min(w*tan(angle), h), -h); } else if(angle>3.1415) { x=-max(min(h/tan(angle), w), -w); y=-max(min(w*tan(angle), h), -h); } else if(angle>3.1415/2.0) { x=max(min(h/tan(angle), w), -w); y=-max(min(w*tan(angle), h), -h); } else { x=max(min(h/tan(angle), w), -w); y=max(min(w*tan(angle), h), -h); } } <commit_msg>added a function in utililities<commit_after>/* * This file is part of OpenModelica. * * Copyright (c) 1998-CurrentYear, Linköping University, * Department of Computer and Information Science, * SE-58183 Linköping, Sweden. * * All rights reserved. * * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 * AND THIS OSMC PUBLIC LICENSE (OSMC-PL). * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S * ACCEPTANCE OF THE OSMC PUBLIC LICENSE. * * The OpenModelica software and the Open Source Modelica * Consortium (OSMC) Public License (OSMC-PL) are obtained * from Linköping University, either from the above address, * from the URLs: http://www.ida.liu.se/projects/OpenModelica or * http://www.openmodelica.org, and in the OpenModelica distribution. * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. * * This program is distributed WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS * OF OSMC-PL. * * See the full OSMC Public License conditions for more details. * */ /* * HopsanGUI * Fluid and Mechatronic Systems, Department of Management and Engineering, Linköping University * Main Authors 2009-2010: Robert Braun, Björn Eriksson, Peter Nordin * Contributors 2009-2010: Mikael Axin, Alessandro Dell'Amico, Karl Pettersson, Ingo Staack */ //! //! @file GUIUtilities.cpp //! @author All <flumes@liu.se> //! @date 2010-10-09 //! //! @brief Contains a class for misc utilities //! //$Id$ #include "GUIUtilities.h" using namespace std; //! @brief This function extracts the name from a text stream //! @return The extracted name without quotes, empty string if failed //! It is assumed that the name was saved OK. but error indicated by empty string QString readName(QTextStream &rTextStream) { QString tempName; rTextStream >> tempName; if (tempName.startsWith("\"")) { while (!tempName.endsWith("\"")) { if (rTextStream.atEnd()) { return QString(""); //Empty string (failed) } else { QString tmpstr; rTextStream >> tmpstr; tempName.append(" " + tmpstr); } } return tempName.remove("\"").trimmed(); //Remove quotes and trimm (just to be sure) } else { return QString(""); //Empty string (failed) } } //! @brief Convenience function if you dont have a stream to read from //! @return The extracted name without quotes, empty string if failed //! It is assumed that the name was saved OK. but error indicated by empty string QString readName(QString namestring) { QTextStream namestream(&namestring); return readName(namestream); } //! @brief This function may be used to add quotes around string, usefull for saving names. Ex: "string" QString addQuotes(QString str) { str.prepend("\""); str.append("\""); return str; } //! @brief Use this function to calculate the placement of the ports on a subsystem icon. //! @param[in] w width of the subsystem icon //! @param[in] h heigth of the subsystem icon //! @param[in] angle the angle of the line between center and the actual port //! @param[out] x the new calculated horizontal placement for the port //! @param[out] y the new calculated vertical placement for the port void calcSubsystemPortPosition(const double w, const double h, const double angle, double &x, double &y) { if(angle>3.1415*3.0/2.0) { x=-max(min(h/tan(angle), w), -w); y=max(min(w*tan(angle), h), -h); } else if(angle>3.1415) { x=-max(min(h/tan(angle), w), -w); y=-max(min(w*tan(angle), h), -h); } else if(angle>3.1415/2.0) { x=max(min(h/tan(angle), w), -w); y=-max(min(w*tan(angle), h), -h); } else { x=max(min(h/tan(angle), w), -w); y=max(min(w*tan(angle), h), -h); } } <|endoftext|>
<commit_before>/* * IceWM * * Copyright (C) 1997-2001 Marko Macek */ #include "config.h" #include "ylib.h" #include <X11/keysym.h> #include "wmcontainer.h" #include "wmframe.h" #include "yxapp.h" #include "prefs.h" #include <stdio.h> YClientContainer::YClientContainer(YWindow *parent, YFrameWindow *frame) :YWindow(parent) { fFrame = frame; fHaveGrab = false; fHaveActionGrab = false; setStyle(wsManager); setDoubleBuffer(false); setPointer(YXApplication::leftPointer); } YClientContainer::~YClientContainer() { releaseButtons(); } void YClientContainer::handleButton(const XButtonEvent &button) { bool doRaise = false; bool doActivate = false; bool firstClick = false; if (!(button.state & ControlMask) && (buttonRaiseMask & (1 << (button.button - 1))) && (!useMouseWheel || (button.button != 4 && button.button != 5))) { if (focusOnClickClient) { if (!getFrame()->isTypeDock()) { doActivate = true; if (getFrame()->canFocusByMouse() && !getFrame()->focused()) firstClick = true; } } if (raiseOnClickClient) { doRaise = true; if (getFrame()->canRaise()) firstClick = true; } } #if 1 if (clientMouseActions) { unsigned int k = button.button + XK_Pointer_Button1 - 1; unsigned int m = KEY_MODMASK(button.state); unsigned int vm = VMod(m); if (IS_WMKEY(k, vm, gMouseWinSize)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); int px = button.x + x(); int py = button.y + y(); int gx = (px * 3 / (int)width() - 1); int gy = (py * 3 / (int)height() - 1); if (gx < 0) gx = -1; if (gx > 0) gx = 1; if (gy < 0) gy = -1; if (gy > 0) gy = 1; bool doMove = (gx == 0 && gy == 0) ? true : false; int mx, my; if (doMove) { mx = px; my = py; } else { mx = button.x_root; my = button.y_root; } if ((doMove && getFrame()->canMove()) || (!doMove && getFrame()->canSize())) { getFrame()->startMoveSize(doMove, 1, gx, gy, mx, my); } return ; } else if (IS_WMKEY(k, vm, gMouseWinMove)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); if (getFrame()->canMove()) { int px = button.x + x(); int py = button.y + y(); getFrame()->startMoveSize(1, 1, 0, 0, px, py); } return ; } else if (IS_WMKEY(k, vm, gMouseWinRaise)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); getFrame()->wmRaise(); return ; } } #endif ///!!! do this first? if (doActivate && getFrame()->getInputFocusHint()) getFrame()->activate(); if (doRaise) getFrame()->wmRaise(); ///!!! it might be nice if this was per-window option (app-request) if (!firstClick || passFirstClickToClient) XAllowEvents(xapp->display(), ReplayPointer, CurrentTime); else XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); XSync(xapp->display(), False); } // manage button grab on frame window to capture clicks to client window // we want to keep the grab when: // focusOnClickClient && not focused // || raiseOnClickClient && not can be raised // ('not on top' != 'can be raised') // the difference is when we have transients and explicitFocus // also there is the difference with layers and multiple workspaces void YClientContainer::grabButtons() { grabActions(); if (!fHaveGrab && (clickFocus || focusOnClickClient || raiseOnClickClient)) { fHaveGrab = true; XGrabButton(xapp->display(), AnyButton, AnyModifier, handle(), True, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None); } } void YClientContainer::releaseButtons() { if (fHaveGrab) { fHaveGrab = false; XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle()); fHaveActionGrab = false; } grabActions(); } void YClientContainer::regrabMouse() { XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle()); if (fHaveActionGrab) { fHaveActionGrab = false; grabActions(); } if (fHaveGrab ) { fHaveGrab = false; grabButtons(); } } void YClientContainer::grabActions() { if (clientMouseActions) { if (!fHaveActionGrab) { fHaveActionGrab = true; #ifndef NO_KEYBIND if (gMouseWinMove.key != 0) grabVButton(gMouseWinMove.key - XK_Pointer_Button1 + 1, gMouseWinMove.mod); if (gMouseWinSize.key != 0) grabVButton(gMouseWinSize.key - XK_Pointer_Button1 + 1, gMouseWinSize.mod); if (gMouseWinRaise.key != 0) grabVButton(gMouseWinRaise.key - XK_Pointer_Button1 + 1, gMouseWinRaise.mod); #endif } } } void YClientContainer::handleConfigureRequest(const XConfigureRequestEvent &configureRequest) { MSG(("configure request in frame")); if (getFrame() && configureRequest.window == getFrame()->client()->handle()) { XConfigureRequestEvent cre = configureRequest; getFrame()->configureClient(cre); } } void YClientContainer::handleMapRequest(const XMapRequestEvent &mapRequest) { if (mapRequest.window == getFrame()->client()->handle()) { manager->lockFocus(); getFrame()->setState(WinStateMinimized | WinStateHidden | WinStateRollup, 0); manager->unlockFocus(); bool doActivate = true; getFrame()->updateFocusOnMap(doActivate); if (doActivate) { getFrame()->activateWindow(true); } } } void YClientContainer::handleCrossing(const XCrossingEvent &crossing) { if (getFrame() && pointerColormap) { if (crossing.type == EnterNotify) manager->setColormapWindow(getFrame()); else if (crossing.type == LeaveNotify && crossing.detail != NotifyInferior && crossing.mode == NotifyNormal && manager->colormapWindow() == getFrame()) { manager->setColormapWindow(0); } } } // vim: set sw=4 ts=4 et: <commit_msg>more wat was intended here<commit_after>/* * IceWM * * Copyright (C) 1997-2001 Marko Macek */ #include "config.h" #include "ylib.h" #include <X11/keysym.h> #include "wmcontainer.h" #include "wmframe.h" #include "yxapp.h" #include "prefs.h" #include <stdio.h> YClientContainer::YClientContainer(YWindow *parent, YFrameWindow *frame) :YWindow(parent) { fFrame = frame; fHaveGrab = false; fHaveActionGrab = false; setStyle(wsManager); setDoubleBuffer(false); setPointer(YXApplication::leftPointer); } YClientContainer::~YClientContainer() { releaseButtons(); } void YClientContainer::handleButton(const XButtonEvent &button) { bool doRaise = false; bool doActivate = false; bool firstClick = false; if (!(button.state & ControlMask) && (buttonRaiseMask & (1 << (button.button - 1))) && (!useMouseWheel || (button.button != 4 && button.button != 5))) { if (focusOnClickClient) { if (!getFrame()->isTypeDock()) { doActivate = true; if (getFrame()->canFocusByMouse() && !getFrame()->focused()) firstClick = true; } } if (raiseOnClickClient) { doRaise = true; if (getFrame()->canRaise()) firstClick = true; } } #if 1 if (clientMouseActions) { unsigned int k = button.button + XK_Pointer_Button1 - 1; unsigned int m = KEY_MODMASK(button.state); unsigned int vm = VMod(m); if (IS_WMKEY(k, vm, gMouseWinSize)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); int px = button.x + x(); int py = button.y + y(); int gx = (px * 3 / (int)width() - 1); int gy = (py * 3 / (int)height() - 1); if (gx < 0) gx = -1; if (gx > 0) gx = 1; if (gy < 0) gy = -1; if (gy > 0) gy = 1; bool doMove = (gx == 0 && gy == 0) ? true : false; int mx, my; if (doMove) { mx = px; my = py; } else { mx = button.x_root; my = button.y_root; } if ((doMove && getFrame()->canMove()) || (!doMove && getFrame()->canSize())) { getFrame()->startMoveSize(doMove, 1, gx, gy, mx, my); } return ; } else if (IS_WMKEY(k, vm, gMouseWinMove)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); if (getFrame()->canMove()) { int px = button.x + x(); int py = button.y + y(); getFrame()->startMoveSize(1, 1, 0, 0, px, py); } return ; } else if (IS_WMKEY(k, vm, gMouseWinRaise)) { XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); getFrame()->wmRaise(); return ; } } #endif ///!!! do this first? if (doActivate) if (!getFrame()->avoidFocus()) getFrame()->activate(); if (doRaise) getFrame()->wmRaise(); ///!!! it might be nice if this was per-window option (app-request) if (!firstClick || passFirstClickToClient) XAllowEvents(xapp->display(), ReplayPointer, CurrentTime); else XAllowEvents(xapp->display(), AsyncPointer, CurrentTime); XSync(xapp->display(), False); } // manage button grab on frame window to capture clicks to client window // we want to keep the grab when: // focusOnClickClient && not focused // || raiseOnClickClient && not can be raised // ('not on top' != 'can be raised') // the difference is when we have transients and explicitFocus // also there is the difference with layers and multiple workspaces void YClientContainer::grabButtons() { grabActions(); if (!fHaveGrab && (clickFocus || focusOnClickClient || raiseOnClickClient)) { fHaveGrab = true; XGrabButton(xapp->display(), AnyButton, AnyModifier, handle(), True, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None); } } void YClientContainer::releaseButtons() { if (fHaveGrab) { fHaveGrab = false; XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle()); fHaveActionGrab = false; } grabActions(); } void YClientContainer::regrabMouse() { XUngrabButton(xapp->display(), AnyButton, AnyModifier, handle()); if (fHaveActionGrab) { fHaveActionGrab = false; grabActions(); } if (fHaveGrab ) { fHaveGrab = false; grabButtons(); } } void YClientContainer::grabActions() { if (clientMouseActions) { if (!fHaveActionGrab) { fHaveActionGrab = true; #ifndef NO_KEYBIND if (gMouseWinMove.key != 0) grabVButton(gMouseWinMove.key - XK_Pointer_Button1 + 1, gMouseWinMove.mod); if (gMouseWinSize.key != 0) grabVButton(gMouseWinSize.key - XK_Pointer_Button1 + 1, gMouseWinSize.mod); if (gMouseWinRaise.key != 0) grabVButton(gMouseWinRaise.key - XK_Pointer_Button1 + 1, gMouseWinRaise.mod); #endif } } } void YClientContainer::handleConfigureRequest(const XConfigureRequestEvent &configureRequest) { MSG(("configure request in frame")); if (getFrame() && configureRequest.window == getFrame()->client()->handle()) { XConfigureRequestEvent cre = configureRequest; getFrame()->configureClient(cre); } } void YClientContainer::handleMapRequest(const XMapRequestEvent &mapRequest) { if (mapRequest.window == getFrame()->client()->handle()) { manager->lockFocus(); getFrame()->setState(WinStateMinimized | WinStateHidden | WinStateRollup, 0); manager->unlockFocus(); bool doActivate = true; getFrame()->updateFocusOnMap(doActivate); if (doActivate) { getFrame()->activateWindow(true); } } } void YClientContainer::handleCrossing(const XCrossingEvent &crossing) { if (getFrame() && pointerColormap) { if (crossing.type == EnterNotify) manager->setColormapWindow(getFrame()); else if (crossing.type == LeaveNotify && crossing.detail != NotifyInferior && crossing.mode == NotifyNormal && manager->colormapWindow() == getFrame()) { manager->setColormapWindow(0); } } } // vim: set sw=4 ts=4 et: <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2018 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "FlashSimBlockDevice.h" #include "platform/mbed_assert.h" #include "platform/mbed_atomic.h" #include <algorithm> #include <stdlib.h> #include <string.h> #include "mbed_assert.h" namespace mbed { static const bd_size_t min_blank_buf_size = 32; static inline uint32_t align_up(bd_size_t val, bd_size_t size) { return (((val - 1) / size) + 1) * size; } FlashSimBlockDevice::FlashSimBlockDevice(BlockDevice *bd, uint8_t erase_value) : _erase_value(erase_value), _blank_buf_size(0), _blank_buf(0), _bd(bd), _init_ref_count(0), _is_initialized(false) { MBED_ASSERT(bd); } FlashSimBlockDevice::~FlashSimBlockDevice() { deinit(); delete[] _blank_buf; } int FlashSimBlockDevice::init() { int err; uint32_t val = core_util_atomic_incr_u32(&_init_ref_count, 1); if (val != 1) { return BD_ERROR_OK; } err = _bd->init(); if (err) { goto fail; } _blank_buf_size = align_up(min_blank_buf_size, _bd->get_program_size()); if (!_blank_buf) { _blank_buf = new uint8_t[_blank_buf_size]; MBED_ASSERT(_blank_buf); } _is_initialized = true; return BD_ERROR_OK; fail: _is_initialized = false; _init_ref_count = 0; return err; } int FlashSimBlockDevice::deinit() { if (!_is_initialized) { return BD_ERROR_OK; } uint32_t val = core_util_atomic_decr_u32(&_init_ref_count, 1); if (val) { return BD_ERROR_OK; } _is_initialized = false; return _bd->deinit(); } int FlashSimBlockDevice::sync() { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->sync(); } bd_size_t FlashSimBlockDevice::get_read_size() const { if (!_is_initialized) { return 0; } return _bd->get_read_size(); } bd_size_t FlashSimBlockDevice::get_program_size() const { if (!_is_initialized) { return 0; } return _bd->get_program_size(); } bd_size_t FlashSimBlockDevice::get_erase_size() const { if (!_is_initialized) { return 0; } return _bd->get_erase_size(); } bd_size_t FlashSimBlockDevice::get_erase_size(bd_addr_t addr) const { if (!_is_initialized) { return 0; } return _bd->get_erase_size(addr); } bd_size_t FlashSimBlockDevice::size() const { if (!_is_initialized) { return 0; } return _bd->size(); } int FlashSimBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->read(b, addr, size); } int FlashSimBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } if (!is_valid_program(addr, size)) { return BD_ERROR_DEVICE_ERROR; } bd_addr_t curr_addr = addr; bd_size_t curr_size = size; const uint8_t *buf = (const uint8_t *) b; while (curr_size) { bd_size_t read_size = std::min(_blank_buf_size, curr_size); int ret = _bd->read(_blank_buf, curr_addr, read_size); if (ret) { return ret; } for (bd_size_t i = 0; i < read_size; i++) { // Allow either programming on blanks or programming the same value // (as real flash devices do) if ((_blank_buf[i] != _erase_value) && (_blank_buf[i] != *buf)) { return BD_ERROR_NOT_ERASED; } buf++; } curr_addr += read_size; curr_size -= read_size; } return _bd->program(b, addr, size); } int FlashSimBlockDevice::erase(bd_addr_t addr, bd_size_t size) { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } if (!is_valid_erase(addr, size)) { return BD_ERROR_DEVICE_ERROR; } bd_addr_t curr_addr = addr; bd_size_t curr_size = size; memset(_blank_buf, _erase_value, (unsigned int) _blank_buf_size); while (curr_size) { bd_size_t prog_size = std::min(_blank_buf_size, curr_size); int ret = _bd->program(_blank_buf, curr_addr, prog_size); if (ret) { return ret; } curr_addr += prog_size; curr_size -= prog_size; } return BD_ERROR_OK; } int FlashSimBlockDevice::get_erase_value() const { return _erase_value; } const char *FlashSimBlockDevice::get_type() const { if (_bd != NULL) { return _bd->get_type(); } return NULL; } } // namespace mbed <commit_msg>FlashSimBlockDevice: initialize blanks buffer<commit_after>/* mbed Microcontroller Library * Copyright (c) 2018 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "FlashSimBlockDevice.h" #include "platform/mbed_assert.h" #include "platform/mbed_atomic.h" #include <algorithm> #include <stdlib.h> #include <string.h> #include "mbed_assert.h" namespace mbed { static const bd_size_t min_blank_buf_size = 32; static inline uint32_t align_up(bd_size_t val, bd_size_t size) { return (((val - 1) / size) + 1) * size; } FlashSimBlockDevice::FlashSimBlockDevice(BlockDevice *bd, uint8_t erase_value) : _erase_value(erase_value), _blank_buf_size(0), _blank_buf(0), _bd(bd), _init_ref_count(0), _is_initialized(false) { MBED_ASSERT(bd); } FlashSimBlockDevice::~FlashSimBlockDevice() { deinit(); delete[] _blank_buf; } int FlashSimBlockDevice::init() { int err; uint32_t val = core_util_atomic_incr_u32(&_init_ref_count, 1); if (val != 1) { return BD_ERROR_OK; } err = _bd->init(); if (err) { goto fail; } _blank_buf_size = align_up(min_blank_buf_size, _bd->get_program_size()); if (!_blank_buf) { _blank_buf = new uint8_t[_blank_buf_size]; memset(_blank_buf, 0, _blank_buf_size); MBED_ASSERT(_blank_buf); } _is_initialized = true; return BD_ERROR_OK; fail: _is_initialized = false; _init_ref_count = 0; return err; } int FlashSimBlockDevice::deinit() { if (!_is_initialized) { return BD_ERROR_OK; } uint32_t val = core_util_atomic_decr_u32(&_init_ref_count, 1); if (val) { return BD_ERROR_OK; } _is_initialized = false; return _bd->deinit(); } int FlashSimBlockDevice::sync() { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->sync(); } bd_size_t FlashSimBlockDevice::get_read_size() const { if (!_is_initialized) { return 0; } return _bd->get_read_size(); } bd_size_t FlashSimBlockDevice::get_program_size() const { if (!_is_initialized) { return 0; } return _bd->get_program_size(); } bd_size_t FlashSimBlockDevice::get_erase_size() const { if (!_is_initialized) { return 0; } return _bd->get_erase_size(); } bd_size_t FlashSimBlockDevice::get_erase_size(bd_addr_t addr) const { if (!_is_initialized) { return 0; } return _bd->get_erase_size(addr); } bd_size_t FlashSimBlockDevice::size() const { if (!_is_initialized) { return 0; } return _bd->size(); } int FlashSimBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size) { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } return _bd->read(b, addr, size); } int FlashSimBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } if (!is_valid_program(addr, size)) { return BD_ERROR_DEVICE_ERROR; } bd_addr_t curr_addr = addr; bd_size_t curr_size = size; const uint8_t *buf = (const uint8_t *) b; while (curr_size) { bd_size_t read_size = std::min(_blank_buf_size, curr_size); int ret = _bd->read(_blank_buf, curr_addr, read_size); if (ret) { return ret; } for (bd_size_t i = 0; i < read_size; i++) { // Allow either programming on blanks or programming the same value // (as real flash devices do) if ((_blank_buf[i] != _erase_value) && (_blank_buf[i] != *buf)) { return BD_ERROR_NOT_ERASED; } buf++; } curr_addr += read_size; curr_size -= read_size; } return _bd->program(b, addr, size); } int FlashSimBlockDevice::erase(bd_addr_t addr, bd_size_t size) { if (!_is_initialized) { return BD_ERROR_DEVICE_ERROR; } if (!is_valid_erase(addr, size)) { return BD_ERROR_DEVICE_ERROR; } bd_addr_t curr_addr = addr; bd_size_t curr_size = size; memset(_blank_buf, _erase_value, (unsigned int) _blank_buf_size); while (curr_size) { bd_size_t prog_size = std::min(_blank_buf_size, curr_size); int ret = _bd->program(_blank_buf, curr_addr, prog_size); if (ret) { return ret; } curr_addr += prog_size; curr_size -= prog_size; } return BD_ERROR_OK; } int FlashSimBlockDevice::get_erase_value() const { return _erase_value; } const char *FlashSimBlockDevice::get_type() const { if (_bd != NULL) { return _bd->get_type(); } return NULL; } } // namespace mbed <|endoftext|>
<commit_before><commit_msg>Disable PersonalDataManagerTest.ImportFormDataNotEnoughFilledFields<commit_after><|endoftext|>
<commit_before><commit_msg>fix chart background color<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: templwin.hxx,v $ * * $Revision: 1.26 $ * * last change: $Author: hr $ $Date: 2003-03-27 14:37:41 $ * * 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 _SVTOOLS_TEMPLWIN_HXX #define _SVTOOLS_TEMPLWIN_HXX #ifndef _TOOLS_RESARY_HXX #include <tools/resary.hxx> #endif #ifndef _SV_SPLITWIN_HXX #include <vcl/splitwin.hxx> #endif #ifndef _SV_TOOLBOX_HXX #include <vcl/toolbox.hxx> #endif #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif #ifndef _HEADBAR_HXX #include "headbar.hxx" #endif #ifndef _SVT_FILEVIEW_HXX #include "fileview.hxx" #endif #ifndef _ICNVW_HXX #include "ivctrl.hxx" #endif #ifndef _SVTOOLS_SVMEDIT2_HXX #include "svmedit2.hxx" #endif namespace com{ namespace sun { namespace star { namespace awt { class XWindow; } } } }; namespace com{ namespace sun { namespace star { namespace frame { class XFrame; } } } }; namespace com{ namespace sun { namespace star { namespace io { class XPersist; } } } }; // class SvtDummyHeaderBar_Impl ------------------------------------------ class SvtDummyHeaderBar_Impl : public Window { private: void UpdateBackgroundColor(); public: SvtDummyHeaderBar_Impl( Window* pParent ); ~SvtDummyHeaderBar_Impl(); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; // class SvtIconWindow_Impl ---------------------------------------------- class SvtIconWindow_Impl : public Window { private: SvtDummyHeaderBar_Impl aDummyHeaderBar; // spaceholder instead of HeaderBar SvtIconChoiceCtrl aIconCtrl; String aNewDocumentRootURL; String aTemplateRootURL; String aMyDocumentsRootURL; String aSamplesFolderRootURL; long nMaxTextLength; SvxIconChoiceCtrlEntry* GetEntry( const String& rURL ) const; public: SvtIconWindow_Impl( Window* pParent ); ~SvtIconWindow_Impl(); virtual void Resize(); inline long GetMaxTextLength() const { return nMaxTextLength; } inline void SetClickHdl( const Link& rLink ) { aIconCtrl.SetClickHdl( rLink ); } inline String GetTemplateRootURL() const { return aTemplateRootURL; } String GetSelectedIconURL() const; String GetSelectedIconText() const; String GetCursorPosIconURL() const; String GetIconText( const String& rURL ) const; void InvalidateIconControl(); void SetCursorPos( ULONG nPos ); ULONG GetCursorPos() const; ULONG GetSelectEntryPos() const; void SetFocus(); long CalcHeight() const; sal_Bool IsRootURL( const String& rURL ) const; ULONG GetRootPos( const String& rURL ) const; void UpdateIcons( sal_Bool _bHiContrast ); inline sal_Bool ProcessKeyEvent( const KeyEvent& rKEvt ); inline const String& GetSamplesFolderURL() const; void SelectFolder(sal_Int32 nFolderPos); }; inline sal_Bool SvtIconWindow_Impl::ProcessKeyEvent( const KeyEvent& rKEvt ) { return ( rKEvt.GetKeyCode().IsMod2() ? aIconCtrl.DoKeyInput( rKEvt ) : sal_False ); } inline const String& SvtIconWindow_Impl::GetSamplesFolderURL() const { return aSamplesFolderRootURL; } // class SvtFileViewWindow_Impl ------------------------------------------ class SvtTemplateWindow; class SvtFileViewWindow_Impl : public Window { private: SvtTemplateWindow& rParent; SvtFileView aFileView; Link aNewFolderLink; String aCurrentRootURL; String aFolderURL; String aSamplesFolderURL; sal_Bool bIsTemplateFolder; ::com::sun::star::uno::Sequence< ::rtl::OUString > GetNewDocContents() const; public: SvtFileViewWindow_Impl( SvtTemplateWindow* pParent, const String& rSamplesFolderURL ); ~SvtFileViewWindow_Impl(); virtual void Resize(); inline void SetSelectHdl( const Link& rLink ) { aFileView.SetSelectHdl( rLink ); } inline void SetDoubleClickHdl( const Link& rLink ) { aFileView.SetDoubleClickHdl( rLink ); } inline void SetNewFolderHdl( const Link& rLink ) { aNewFolderLink = rLink; } inline void ResetCursor() { aFileView.ResetCursor(); } inline sal_Bool IsTemplateFolder() const { return bIsTemplateFolder; } inline String GetFolderURL() const { return aFolderURL; } inline String GetRootURL() const { return aCurrentRootURL; } inline void OpenRoot( const String& rRootURL ) { aCurrentRootURL = rRootURL; OpenFolder( rRootURL ); } String GetSelectedFile() const; void OpenFolder( const String& rURL ); sal_Bool HasPreviousLevel( String& rURL ) const; String GetFolderTitle() const; void SetFocus(); }; // class SvtFrameWindow_Impl --------------------------------------------- class SvtDocInfoTable_Impl : public ResStringArray { private: String aEmptyString; public: SvtDocInfoTable_Impl(); const String& GetString( long nId ) const; }; class SvtExtendedMultiLineEdit_Impl : public ExtMultiLineEdit { public: SvtExtendedMultiLineEdit_Impl( Window* pParent ); inline ~SvtExtendedMultiLineEdit_Impl() {} virtual void Resize(); inline void Clear() { SetText( String() ); } void InsertEntry( const String& rTitle, const String& rValue ); }; class SvtFrameWindow_Impl : public Window { private: ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > xFrame; ::com::sun::star::uno::Reference < ::com::sun::star::io::XPersist > xDocInfo; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > xWindow; SvtExtendedMultiLineEdit_Impl* pEditWin; Window* pTextWin; Window* pEmptyWin; LanguageType eLangType; SvtDocInfoTable_Impl aInfoTable; String aCurrentURL; ::rtl::OUString m_aOpenURL; sal_Bool bDocInfo; void ShowDocInfo( const String& rURL ); void ViewEditWin(); void ViewTextWin(); void ViewEmptyWin(); void ViewNonEmptyWin(); // views depending on bDocInfo public: SvtFrameWindow_Impl( Window* pParent ); ~SvtFrameWindow_Impl(); virtual void Resize(); void OpenFile( const String& rURL, sal_Bool bPreview, sal_Bool bIsTemplate, sal_Bool bAsTemplate ); void ToggleView( sal_Bool bDocInfo ); }; // class SvtTemplateWindow ----------------------------------------------- class HistoryList_Impl; class SvtTemplateWindow : public Window { private: ToolBox aFileViewTB; ToolBox aFrameWinTB; SplitWindow aSplitWin; SvtIconWindow_Impl* pIconWin; SvtFileViewWindow_Impl* pFileWin; SvtFrameWindow_Impl* pFrameWin; HistoryList_Impl* pHistoryList; Link aSelectHdl; Link aDoubleClickHdl; Link aNewFolderHdl; Link aSendFocusHdl; Timer aSelectTimer; String aFolderTitle; virtual void Resize(); DECL_LINK( IconClickHdl_Impl, SvtIconChoiceCtrl* ); DECL_LINK( FileSelectHdl_Impl, SvtFileView* ); DECL_LINK( FileDblClickHdl_Impl, SvtFileView* ); DECL_LINK( NewFolderHdl_Impl, SvtFileView* ); DECL_LINK( TimeoutHdl_Impl, Timer* ); DECL_LINK( ClickHdl_Impl, ToolBox* ); DECL_LINK( ResizeHdl_Impl, SplitWindow* ); // used for split and initial setting of toolbar pos void PrintFile( const String& rURL ); void AppendHistoryURL( const String& rURL, ULONG nGroup ); void OpenHistory(); void DoAction( USHORT nAction ); void InitToolBoxes(); void InitToolBoxImages(); void UpdateIcons(); protected: virtual long PreNotify( NotifyEvent& rNEvt ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); public: SvtTemplateWindow( Window* pParent ); ~SvtTemplateWindow(); inline void SetSelectHdl( const Link& rLink ) { aSelectHdl = rLink; } inline void SetDoubleClickHdl( const Link& rLink ) { aDoubleClickHdl = rLink; } inline void SetNewFolderHdl( const Link& rLink ) { aNewFolderHdl = rLink; } inline void SetSendFocusHdl( const Link& rLink ) { aSendFocusHdl = rLink; } inline sal_Bool IsTemplateFolderOpen() const { return pFileWin->IsTemplateFolder(); } inline sal_Bool HasIconWinFocus() const { return pIconWin->HasChildPathFocus(); } void ReadViewSettings( ); void WriteViewSettings( ); sal_Bool IsFileSelected() const; String GetSelectedFile() const; void OpenFile( sal_Bool bNotAsTemplate ); String GetFolderTitle() const; void SetFocus( sal_Bool bIconWin ); void OpenTemplateRoot(); void SetPrevLevelButtonState( const String& rURL ); // sets state (enable/disable) for previous level button void ClearHistory(); long CalcHeight() const; void SelectFolder(sal_Int32 nFolderPosition); }; #endif // _SVTOOLS_TEMPLWIN_HXX <commit_msg>INTEGRATION: CWS mergebuild (1.26.172); FILE MERGED 2004/01/29 11:55:43 hjs 1.26.172.1: #i8252# chng. resmgr creation parameters from LanguageType to ::com::sun::star::lang::Locale<commit_after>/************************************************************************* * * $RCSfile: templwin.hxx,v $ * * $Revision: 1.27 $ * * last change: $Author: hjs $ $Date: 2004-06-25 16:33:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVTOOLS_TEMPLWIN_HXX #define _SVTOOLS_TEMPLWIN_HXX #ifndef _TOOLS_RESARY_HXX #include <tools/resary.hxx> #endif #ifndef _SV_SPLITWIN_HXX #include <vcl/splitwin.hxx> #endif #ifndef _SV_TOOLBOX_HXX #include <vcl/toolbox.hxx> #endif #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif #ifndef _HEADBAR_HXX #include "headbar.hxx" #endif #ifndef _SVT_FILEVIEW_HXX #include "fileview.hxx" #endif #ifndef _ICNVW_HXX #include "ivctrl.hxx" #endif #ifndef _SVTOOLS_SVMEDIT2_HXX #include "svmedit2.hxx" #endif #ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_ #include <com/sun/star/lang/Locale.hpp> #endif namespace com{ namespace sun { namespace star { namespace awt { class XWindow; } } } }; namespace com{ namespace sun { namespace star { namespace frame { class XFrame; } } } }; namespace com{ namespace sun { namespace star { namespace io { class XPersist; } } } }; // class SvtDummyHeaderBar_Impl ------------------------------------------ class SvtDummyHeaderBar_Impl : public Window { private: void UpdateBackgroundColor(); public: SvtDummyHeaderBar_Impl( Window* pParent ); ~SvtDummyHeaderBar_Impl(); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; // class SvtIconWindow_Impl ---------------------------------------------- class SvtIconWindow_Impl : public Window { private: SvtDummyHeaderBar_Impl aDummyHeaderBar; // spaceholder instead of HeaderBar SvtIconChoiceCtrl aIconCtrl; String aNewDocumentRootURL; String aTemplateRootURL; String aMyDocumentsRootURL; String aSamplesFolderRootURL; long nMaxTextLength; SvxIconChoiceCtrlEntry* GetEntry( const String& rURL ) const; public: SvtIconWindow_Impl( Window* pParent ); ~SvtIconWindow_Impl(); virtual void Resize(); inline long GetMaxTextLength() const { return nMaxTextLength; } inline void SetClickHdl( const Link& rLink ) { aIconCtrl.SetClickHdl( rLink ); } inline String GetTemplateRootURL() const { return aTemplateRootURL; } String GetSelectedIconURL() const; String GetSelectedIconText() const; String GetCursorPosIconURL() const; String GetIconText( const String& rURL ) const; void InvalidateIconControl(); void SetCursorPos( ULONG nPos ); ULONG GetCursorPos() const; ULONG GetSelectEntryPos() const; void SetFocus(); long CalcHeight() const; sal_Bool IsRootURL( const String& rURL ) const; ULONG GetRootPos( const String& rURL ) const; void UpdateIcons( sal_Bool _bHiContrast ); inline sal_Bool ProcessKeyEvent( const KeyEvent& rKEvt ); inline const String& GetSamplesFolderURL() const; void SelectFolder(sal_Int32 nFolderPos); }; inline sal_Bool SvtIconWindow_Impl::ProcessKeyEvent( const KeyEvent& rKEvt ) { return ( rKEvt.GetKeyCode().IsMod2() ? aIconCtrl.DoKeyInput( rKEvt ) : sal_False ); } inline const String& SvtIconWindow_Impl::GetSamplesFolderURL() const { return aSamplesFolderRootURL; } // class SvtFileViewWindow_Impl ------------------------------------------ class SvtTemplateWindow; class SvtFileViewWindow_Impl : public Window { private: SvtTemplateWindow& rParent; SvtFileView aFileView; Link aNewFolderLink; String aCurrentRootURL; String aFolderURL; String aSamplesFolderURL; sal_Bool bIsTemplateFolder; ::com::sun::star::uno::Sequence< ::rtl::OUString > GetNewDocContents() const; public: SvtFileViewWindow_Impl( SvtTemplateWindow* pParent, const String& rSamplesFolderURL ); ~SvtFileViewWindow_Impl(); virtual void Resize(); inline void SetSelectHdl( const Link& rLink ) { aFileView.SetSelectHdl( rLink ); } inline void SetDoubleClickHdl( const Link& rLink ) { aFileView.SetDoubleClickHdl( rLink ); } inline void SetNewFolderHdl( const Link& rLink ) { aNewFolderLink = rLink; } inline void ResetCursor() { aFileView.ResetCursor(); } inline sal_Bool IsTemplateFolder() const { return bIsTemplateFolder; } inline String GetFolderURL() const { return aFolderURL; } inline String GetRootURL() const { return aCurrentRootURL; } inline void OpenRoot( const String& rRootURL ) { aCurrentRootURL = rRootURL; OpenFolder( rRootURL ); } String GetSelectedFile() const; void OpenFolder( const String& rURL ); sal_Bool HasPreviousLevel( String& rURL ) const; String GetFolderTitle() const; void SetFocus(); }; // class SvtFrameWindow_Impl --------------------------------------------- class SvtDocInfoTable_Impl : public ResStringArray { private: String aEmptyString; public: SvtDocInfoTable_Impl(); const String& GetString( long nId ) const; }; class SvtExtendedMultiLineEdit_Impl : public ExtMultiLineEdit { public: SvtExtendedMultiLineEdit_Impl( Window* pParent ); inline ~SvtExtendedMultiLineEdit_Impl() {} virtual void Resize(); inline void Clear() { SetText( String() ); } void InsertEntry( const String& rTitle, const String& rValue ); }; class SvtFrameWindow_Impl : public Window { private: ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > xFrame; ::com::sun::star::uno::Reference < ::com::sun::star::io::XPersist > xDocInfo; ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > xWindow; SvtExtendedMultiLineEdit_Impl* pEditWin; Window* pTextWin; Window* pEmptyWin; ::com::sun::star::lang::Locale aLocale; SvtDocInfoTable_Impl aInfoTable; String aCurrentURL; ::rtl::OUString m_aOpenURL; sal_Bool bDocInfo; void ShowDocInfo( const String& rURL ); void ViewEditWin(); void ViewTextWin(); void ViewEmptyWin(); void ViewNonEmptyWin(); // views depending on bDocInfo public: SvtFrameWindow_Impl( Window* pParent ); ~SvtFrameWindow_Impl(); virtual void Resize(); void OpenFile( const String& rURL, sal_Bool bPreview, sal_Bool bIsTemplate, sal_Bool bAsTemplate ); void ToggleView( sal_Bool bDocInfo ); }; // class SvtTemplateWindow ----------------------------------------------- class HistoryList_Impl; class SvtTemplateWindow : public Window { private: ToolBox aFileViewTB; ToolBox aFrameWinTB; SplitWindow aSplitWin; SvtIconWindow_Impl* pIconWin; SvtFileViewWindow_Impl* pFileWin; SvtFrameWindow_Impl* pFrameWin; HistoryList_Impl* pHistoryList; Link aSelectHdl; Link aDoubleClickHdl; Link aNewFolderHdl; Link aSendFocusHdl; Timer aSelectTimer; String aFolderTitle; virtual void Resize(); DECL_LINK( IconClickHdl_Impl, SvtIconChoiceCtrl* ); DECL_LINK( FileSelectHdl_Impl, SvtFileView* ); DECL_LINK( FileDblClickHdl_Impl, SvtFileView* ); DECL_LINK( NewFolderHdl_Impl, SvtFileView* ); DECL_LINK( TimeoutHdl_Impl, Timer* ); DECL_LINK( ClickHdl_Impl, ToolBox* ); DECL_LINK( ResizeHdl_Impl, SplitWindow* ); // used for split and initial setting of toolbar pos void PrintFile( const String& rURL ); void AppendHistoryURL( const String& rURL, ULONG nGroup ); void OpenHistory(); void DoAction( USHORT nAction ); void InitToolBoxes(); void InitToolBoxImages(); void UpdateIcons(); protected: virtual long PreNotify( NotifyEvent& rNEvt ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); public: SvtTemplateWindow( Window* pParent ); ~SvtTemplateWindow(); inline void SetSelectHdl( const Link& rLink ) { aSelectHdl = rLink; } inline void SetDoubleClickHdl( const Link& rLink ) { aDoubleClickHdl = rLink; } inline void SetNewFolderHdl( const Link& rLink ) { aNewFolderHdl = rLink; } inline void SetSendFocusHdl( const Link& rLink ) { aSendFocusHdl = rLink; } inline sal_Bool IsTemplateFolderOpen() const { return pFileWin->IsTemplateFolder(); } inline sal_Bool HasIconWinFocus() const { return pIconWin->HasChildPathFocus(); } void ReadViewSettings( ); void WriteViewSettings( ); sal_Bool IsFileSelected() const; String GetSelectedFile() const; void OpenFile( sal_Bool bNotAsTemplate ); String GetFolderTitle() const; void SetFocus( sal_Bool bIconWin ); void OpenTemplateRoot(); void SetPrevLevelButtonState( const String& rURL ); // sets state (enable/disable) for previous level button void ClearHistory(); long CalcHeight() const; void SelectFolder(sal_Int32 nFolderPosition); }; #endif // _SVTOOLS_TEMPLWIN_HXX <|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 "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include <algorithm> #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/navigation_controller.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/views/dom_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/common/url_constants.h" #include "gfx/rect.h" namespace { const int kKeyboardHeight = 300; } // namespace /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, public: TouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame, BrowserView* browser_view) : OpaqueBrowserFrameView(frame, browser_view), keyboard_showing_(false), keyboard_(NULL) { registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::FOCUS_CHANGED_IN_PAGE, NotificationService::AllSources()); } TouchBrowserFrameView::~TouchBrowserFrameView() { } void TouchBrowserFrameView::Layout() { OpaqueBrowserFrameView::Layout(); if (!keyboard_) return; keyboard_->SetBounds(GetBoundsForReservedArea()); keyboard_->SetVisible(keyboard_showing_); keyboard_->Layout(); } /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, protected: int TouchBrowserFrameView::GetReservedHeight() const { if (keyboard_showing_) return kKeyboardHeight; return 0; } /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, private: void TouchBrowserFrameView::InitVirtualKeyboard() { if (keyboard_) return; keyboard_ = new DOMView; Profile* keyboard_profile = browser_view()->browser()->profile(); DCHECK(keyboard_profile) << "Profile required for virtual keyboard."; GURL keyboard_url(chrome::kChromeUIKeyboardURL); keyboard_->Init(keyboard_profile, SiteInstance::CreateSiteInstanceForURL(keyboard_profile, keyboard_url)); keyboard_->LoadURL(keyboard_url); keyboard_->SetVisible(false); AddChildView(keyboard_); } void TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) { if (should_show_keyboard) InitVirtualKeyboard(); if (should_show_keyboard == keyboard_showing_) return; DCHECK(keyboard_); keyboard_showing_ = should_show_keyboard; // Because the NonClientFrameView is a sibling of the ClientView, we rely on // the parent to resize the ClientView instead of resizing it directly. GetParent()->Layout(); // The keyboard that pops up may end up hiding the text entry. So make sure // the renderer scrolls when necessary to keep the textfield visible. if (keyboard_showing_) { RenderViewHost* host = browser_view()->browser()->GetSelectedTabContents()->render_view_host(); host->ScrollFocusedEditableNodeIntoView(); } } void TouchBrowserFrameView::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { Browser* browser = browser_view()->browser(); if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) { // Only modify the keyboard state if the notification is coming from // a source within the same Browser. Source<RenderViewHost> specific_source(source); for (int i = 0; i < browser->tab_count(); ++i) { if (browser->GetTabContentsAt(i)->render_view_host() == specific_source.ptr()) { UpdateKeyboardAndLayout(*Details<const bool>(details).ptr()); break; } } } else if (type == NotificationType::NAV_ENTRY_COMMITTED) { Browser* source_browser = Browser::GetBrowserForController( Source<NavigationController>(source).ptr(), NULL); // If the Browser for the keyboard has navigated, hide the keyboard. if (source_browser == browser) { UpdateKeyboardAndLayout(false); } } } <commit_msg>Adding proper authentication to the DOM based login screen.<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 "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include <algorithm> #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/navigation_controller.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/views/dom_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/common/url_constants.h" #include "gfx/rect.h" namespace { const int kKeyboardHeight = 300; } // namespace /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, public: TouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame, BrowserView* browser_view) : OpaqueBrowserFrameView(frame, browser_view), keyboard_showing_(false), keyboard_(NULL) { registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::FOCUS_CHANGED_IN_PAGE, NotificationService::AllSources()); } TouchBrowserFrameView::~TouchBrowserFrameView() { } void TouchBrowserFrameView::Layout() { OpaqueBrowserFrameView::Layout(); if (!keyboard_) return; keyboard_->SetBounds(GetBoundsForReservedArea()); keyboard_->SetVisible(keyboard_showing_); keyboard_->Layout(); } /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, protected: int TouchBrowserFrameView::GetReservedHeight() const { if (keyboard_showing_) return kKeyboardHeight; return 0; } /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, private: void TouchBrowserFrameView::InitVirtualKeyboard() { if (keyboard_) return; keyboard_ = new DOMView; Profile* keyboard_profile = browser_view()->browser()->profile(); DCHECK(keyboard_profile) << "Profile required for virtual keyboard."; GURL keyboard_url(chrome::kChromeUIKeyboardURL); keyboard_->Init(keyboard_profile, SiteInstance::CreateSiteInstanceForURL(keyboard_profile, keyboard_url)); keyboard_->LoadURL(keyboard_url); keyboard_->SetVisible(false); AddChildView(keyboard_); } void TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) { if (should_show_keyboard) InitVirtualKeyboard(); if (should_show_keyboard == keyboard_showing_) return; DCHECK(keyboard_); keyboard_showing_ = should_show_keyboard; // Because the NonClientFrameView is a sibling of the ClientView, we rely on // the parent to resize the ClientView instead of resizing it directly. GetParent()->Layout(); // The keyboard that pops up may end up hiding the text entry. So make sure // the renderer scrolls when necessary to keep the textfield visible. if (keyboard_showing_) { RenderViewHost* host = browser_view()->browser()->GetSelectedTabContents()->render_view_host(); host->ScrollFocusedEditableNodeIntoView(); } } void TouchBrowserFrameView::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { Browser* browser = browser_view()->browser(); if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) { // Only modify the keyboard state if the currently active tab sent the // notification. if (browser->GetSelectedTabContents()->render_view_host() == Source<RenderViewHost>(source).ptr()) { UpdateKeyboardAndLayout(*Details<const bool>(details).ptr()); } } else if (type == NotificationType::NAV_ENTRY_COMMITTED) { Browser* source_browser = Browser::GetBrowserForController( Source<NavigationController>(source).ptr(), NULL); // If the Browser for the keyboard has navigated, hide the keyboard. if (source_browser == browser) { UpdateKeyboardAndLayout(false); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkSelectionSource.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information. =========================================================================*/ #include "vtkSelectionSource.h" #include "vtkCommand.h" #include "vtkIdTypeArray.h" #include "vtkDoubleArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkSelection.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkTrivialProducer.h" #include "vtkstd/vector" #include "vtkstd/set" vtkCxxRevisionMacro(vtkSelectionSource, "1.11"); vtkStandardNewMacro(vtkSelectionSource); class vtkSelectionSourceInternals { public: vtkSelectionSourceInternals() { this->Values = NULL; } ~vtkSelectionSourceInternals() { if (this->Values) { this->Values->Delete(); } } typedef vtkstd::set<vtkIdType> IDSetType; typedef vtkstd::vector<IDSetType> IDsType; IDsType IDs; vtkAbstractArray *Values; }; //---------------------------------------------------------------------------- vtkSelectionSource::vtkSelectionSource() { this->SetNumberOfInputPorts(0); this->Internal = new vtkSelectionSourceInternals; this->ContentType = vtkSelection::INDICES; this->FieldType = vtkSelection::CELL; this->ContainingCells = 1; this->PreserveTopology = 0; this->Inverse = 0; this->ExactTest = 1; this->ShowBounds = 0; this->ArrayName = NULL; } //---------------------------------------------------------------------------- vtkSelectionSource::~vtkSelectionSource() { delete this->Internal; if (this->ArrayName) { delete[] this->ArrayName; } } //---------------------------------------------------------------------------- void vtkSelectionSource::RemoveAllIDs() { this->Internal->IDs.clear(); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelectionSource::RemoveAllValues() { if (this->Internal->Values) { this->Internal->Values->Reset(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSelectionSource::AddID(vtkIdType proc, vtkIdType id) { if (this->ContentType != vtkSelection::GLOBALIDS && this->ContentType != vtkSelection::INDICES) { return; } // proc == -1 means all processes. All other are stored at index proc+1 proc++; if (proc >= (vtkIdType)this->Internal->IDs.size()) { this->Internal->IDs.resize(proc+1); } vtkSelectionSourceInternals::IDSetType& idSet = this->Internal->IDs[proc]; idSet.insert(id); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelectionSource::AddLocation(double x, double y, double z) { if (this->ContentType != vtkSelection::LOCATIONS) { return; } vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values); if (da) { da->InsertNextTuple3(x,y,z); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSelectionSource::AddThreshold(double min, double max) { if (this->ContentType != vtkSelection::THRESHOLDS) { return; } vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values); if (da) { da->InsertNextValue(min); da->InsertNextValue(max); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSelectionSource::SetFrustum(double *vertices) { if (this->ContentType != vtkSelection::FRUSTUM) { return; } vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values); if (da) { double *data = da->GetPointer(0); memcpy(data, vertices, 32*sizeof(double)); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSelectionSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "ContentType: " ; switch (this->ContentType) { case vtkSelection::SELECTIONS: os << "SELECTIONS"; break; case vtkSelection::COMPOSITE_SELECTIONS: os << "COMPOSITE_SELECTIONS"; break; case vtkSelection::GLOBALIDS: os << "GLOBALIDS"; break; case vtkSelection::VALUES: os << "VALUES"; break; case vtkSelection::INDICES: os << "INDICES"; break; case vtkSelection::FRUSTUM: os << "FRUSTUM"; break; case vtkSelection::LOCATIONS: os << "LOCATIONS"; break; case vtkSelection::THRESHOLDS: os << "THRESHOLDS"; break; default: os << "UNKNOWN"; } os << endl; os << indent << "FieldType: " ; switch (this->FieldType) { case vtkSelection::CELL: os << "CELL"; break; case vtkSelection::POINT: os << "POINT"; break; default: os << "UNKNOWN"; } os << endl; os << indent << "ContainingCells: "; os << (this->ContainingCells?"CELLS":"POINTS") << endl; os << indent << "PreserveTopology: " << this->PreserveTopology << endl; os << indent << "Inverse: " << this->Inverse << endl; os << indent << "ExactTest: " << this->ExactTest << endl; os << indent << "ShowBounds: " << this->ShowBounds << endl; os << indent << "ArrayName: " << (this->ArrayName?this->ArrayName:"NULL") << endl; } //---------------------------------------------------------------------------- int vtkSelectionSource::RequestInformation( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector) { // We can handle multiple piece request. vtkInformation* info = outputVector->GetInformationObject(0); info->Set( vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); return 1; } //---------------------------------------------------------------------------- int vtkSelectionSource::RequestData( vtkInformation* vtkNotUsed( request ), vtkInformationVector** vtkNotUsed( inputVector ), vtkInformationVector* outputVector ) { vtkSelection* output = vtkSelection::GetData(outputVector); vtkInformation* outInfo = outputVector->GetInformationObject(0); int piece = 0; if (outInfo->Has( vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER())) { piece = outInfo->Get( vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); } if ( (this->ContentType == vtkSelection::GLOBALIDS) || (this->ContentType == vtkSelection::INDICES)) { // Number of selected items common to all pieces vtkIdType numCommonElems = 0; if (!this->Internal->IDs.empty()) { numCommonElems = this->Internal->IDs[0].size(); } if (piece+1 >= (int)this->Internal->IDs.size() && numCommonElems == 0) { vtkDebugMacro("No selection for piece: " << piece); return 1; } // idx == 0 is the list for all pieces // idx == piece+1 is the list for the current piece size_t pids[2] = {0, piece+1}; for(int i=0; i<2; i++) { size_t idx = pids[i]; if (idx >= this->Internal->IDs.size()) { continue; } vtkSelectionSourceInternals::IDSetType& selSet = this->Internal->IDs[idx]; if (selSet.size() > 0) { output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), this->ContentType); output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), this->FieldType); // Create the selection list vtkIdTypeArray* selectionList = vtkIdTypeArray::New(); selectionList->SetNumberOfTuples(selSet.size()); // iterate over ids and insert to the selection list vtkSelectionSourceInternals::IDSetType::iterator iter = selSet.begin(); for (vtkIdType idx2=0; iter != selSet.end(); iter++, idx2++) { selectionList->SetValue(idx2, *iter); } output->SetSelectionList(selectionList); selectionList->Delete(); } } } if ( (this->ContentType == vtkSelection::LOCATIONS) && (this->Internal->Values != 0) ) { output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), this->ContentType); output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), this->FieldType); // Create the selection list vtkAbstractArray* selectionList = this->Internal->Values->NewInstance(); selectionList->DeepCopy(this->Internal->Values); output->SetSelectionList(selectionList); selectionList->Delete(); } if ( (this->ContentType == vtkSelection::THRESHOLDS) && (this->Internal->Values != 0) ) { output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), this->ContentType); output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), this->FieldType); // Create the selection list vtkAbstractArray* selectionList = this->Internal->Values->NewInstance(); selectionList->DeepCopy(this->Internal->Values); output->SetSelectionList(selectionList); selectionList->Delete(); } if ( (this->ContentType == vtkSelection::FRUSTUM) && (this->Internal->Values != 0) ) { output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), this->ContentType); output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), this->FieldType); // Create the selection list vtkAbstractArray* selectionList = this->Internal->Values->NewInstance(); selectionList->DeepCopy(this->Internal->Values); output->SetSelectionList(selectionList); selectionList->Delete(); } output->GetProperties()->Set(vtkSelection::CONTAINING_CELLS(), this->ContainingCells); output->GetProperties()->Set(vtkSelection::PRESERVE_TOPOLOGY(), this->PreserveTopology); output->GetProperties()->Set(vtkSelection::INVERSE(), this->Inverse); output->GetProperties()->Set(vtkSelection::ARRAY_NAME(), this->ArrayName); output->GetProperties()->Set(vtkSelection::EXACT_TEST(), this->ExactTest); output->GetProperties()->Set(vtkSelection::SHOW_BOUNDS(), this->ShowBounds); return 1; } //------------------------------------------------------------------------------ void vtkSelectionSource::SetContentType(int value) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting ContentType to " << value); if (this->ContentType != value) { this->ContentType = value; this->RemoveAllIDs(); this->RemoveAllValues(); if (this->Internal->Values) { this->Internal->Values->Delete(); } switch (value) { case vtkSelection::LOCATIONS: { vtkDoubleArray *da = vtkDoubleArray::New(); da->SetNumberOfComponents(3); da->SetNumberOfTuples(0); this->Internal->Values = da; break; } case vtkSelection::THRESHOLDS: { vtkDoubleArray *da = vtkDoubleArray::New(); da->SetNumberOfComponents(1); da->SetNumberOfTuples(0); this->Internal->Values = da; break; } case vtkSelection::FRUSTUM: { vtkDoubleArray *da = vtkDoubleArray::New(); da->SetNumberOfComponents(4); da->SetNumberOfTuples(8); this->Internal->Values = da; break; } default: break; } this->Modified(); } } <commit_msg>ENH: Modified code to set ContentType in IDs selection case for emplty selection, so that extract selection filter will pass the content type checking.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkSelectionSource.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information. =========================================================================*/ #include "vtkSelectionSource.h" #include "vtkCommand.h" #include "vtkIdTypeArray.h" #include "vtkDoubleArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkSelection.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkTrivialProducer.h" #include "vtkstd/vector" #include "vtkstd/set" vtkCxxRevisionMacro(vtkSelectionSource, "1.12"); vtkStandardNewMacro(vtkSelectionSource); class vtkSelectionSourceInternals { public: vtkSelectionSourceInternals() { this->Values = NULL; } ~vtkSelectionSourceInternals() { if (this->Values) { this->Values->Delete(); } } typedef vtkstd::set<vtkIdType> IDSetType; typedef vtkstd::vector<IDSetType> IDsType; IDsType IDs; vtkAbstractArray *Values; }; //---------------------------------------------------------------------------- vtkSelectionSource::vtkSelectionSource() { this->SetNumberOfInputPorts(0); this->Internal = new vtkSelectionSourceInternals; this->ContentType = vtkSelection::INDICES; this->FieldType = vtkSelection::CELL; this->ContainingCells = 1; this->PreserveTopology = 0; this->Inverse = 0; this->ExactTest = 1; this->ShowBounds = 0; this->ArrayName = NULL; } //---------------------------------------------------------------------------- vtkSelectionSource::~vtkSelectionSource() { delete this->Internal; if (this->ArrayName) { delete[] this->ArrayName; } } //---------------------------------------------------------------------------- void vtkSelectionSource::RemoveAllIDs() { this->Internal->IDs.clear(); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelectionSource::RemoveAllValues() { if (this->Internal->Values) { this->Internal->Values->Reset(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSelectionSource::AddID(vtkIdType proc, vtkIdType id) { if (this->ContentType != vtkSelection::GLOBALIDS && this->ContentType != vtkSelection::INDICES) { return; } // proc == -1 means all processes. All other are stored at index proc+1 proc++; if (proc >= (vtkIdType)this->Internal->IDs.size()) { this->Internal->IDs.resize(proc+1); } vtkSelectionSourceInternals::IDSetType& idSet = this->Internal->IDs[proc]; idSet.insert(id); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelectionSource::AddLocation(double x, double y, double z) { if (this->ContentType != vtkSelection::LOCATIONS) { return; } vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values); if (da) { da->InsertNextTuple3(x,y,z); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSelectionSource::AddThreshold(double min, double max) { if (this->ContentType != vtkSelection::THRESHOLDS) { return; } vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values); if (da) { da->InsertNextValue(min); da->InsertNextValue(max); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSelectionSource::SetFrustum(double *vertices) { if (this->ContentType != vtkSelection::FRUSTUM) { return; } vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values); if (da) { double *data = da->GetPointer(0); memcpy(data, vertices, 32*sizeof(double)); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSelectionSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "ContentType: " ; switch (this->ContentType) { case vtkSelection::SELECTIONS: os << "SELECTIONS"; break; case vtkSelection::COMPOSITE_SELECTIONS: os << "COMPOSITE_SELECTIONS"; break; case vtkSelection::GLOBALIDS: os << "GLOBALIDS"; break; case vtkSelection::VALUES: os << "VALUES"; break; case vtkSelection::INDICES: os << "INDICES"; break; case vtkSelection::FRUSTUM: os << "FRUSTUM"; break; case vtkSelection::LOCATIONS: os << "LOCATIONS"; break; case vtkSelection::THRESHOLDS: os << "THRESHOLDS"; break; default: os << "UNKNOWN"; } os << endl; os << indent << "FieldType: " ; switch (this->FieldType) { case vtkSelection::CELL: os << "CELL"; break; case vtkSelection::POINT: os << "POINT"; break; default: os << "UNKNOWN"; } os << endl; os << indent << "ContainingCells: "; os << (this->ContainingCells?"CELLS":"POINTS") << endl; os << indent << "PreserveTopology: " << this->PreserveTopology << endl; os << indent << "Inverse: " << this->Inverse << endl; os << indent << "ExactTest: " << this->ExactTest << endl; os << indent << "ShowBounds: " << this->ShowBounds << endl; os << indent << "ArrayName: " << (this->ArrayName?this->ArrayName:"NULL") << endl; } //---------------------------------------------------------------------------- int vtkSelectionSource::RequestInformation( vtkInformation* vtkNotUsed(request), vtkInformationVector** vtkNotUsed(inputVector), vtkInformationVector* outputVector) { // We can handle multiple piece request. vtkInformation* info = outputVector->GetInformationObject(0); info->Set( vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); return 1; } //---------------------------------------------------------------------------- int vtkSelectionSource::RequestData( vtkInformation* vtkNotUsed( request ), vtkInformationVector** vtkNotUsed( inputVector ), vtkInformationVector* outputVector ) { vtkSelection* output = vtkSelection::GetData(outputVector); vtkInformation* outInfo = outputVector->GetInformationObject(0); int piece = 0; if (outInfo->Has( vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER())) { piece = outInfo->Get( vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); } if ( (this->ContentType == vtkSelection::GLOBALIDS) || (this->ContentType == vtkSelection::INDICES)) { output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), this->ContentType); output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), this->FieldType); // Number of selected items common to all pieces vtkIdType numCommonElems = 0; if (!this->Internal->IDs.empty()) { numCommonElems = this->Internal->IDs[0].size(); } if (piece+1 >= (int)this->Internal->IDs.size() && numCommonElems == 0) { vtkDebugMacro("No selection for piece: " << piece); return 1; } // idx == 0 is the list for all pieces // idx == piece+1 is the list for the current piece size_t pids[2] = {0, piece+1}; for(int i=0; i<2; i++) { size_t idx = pids[i]; if (idx >= this->Internal->IDs.size()) { continue; } vtkSelectionSourceInternals::IDSetType& selSet = this->Internal->IDs[idx]; if (selSet.size() > 0) { // Create the selection list vtkIdTypeArray* selectionList = vtkIdTypeArray::New(); selectionList->SetNumberOfTuples(selSet.size()); // iterate over ids and insert to the selection list vtkSelectionSourceInternals::IDSetType::iterator iter = selSet.begin(); for (vtkIdType idx2=0; iter != selSet.end(); iter++, idx2++) { selectionList->SetValue(idx2, *iter); } output->SetSelectionList(selectionList); selectionList->Delete(); } } } if ( (this->ContentType == vtkSelection::LOCATIONS) && (this->Internal->Values != 0) ) { output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), this->ContentType); output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), this->FieldType); // Create the selection list vtkAbstractArray* selectionList = this->Internal->Values->NewInstance(); selectionList->DeepCopy(this->Internal->Values); output->SetSelectionList(selectionList); selectionList->Delete(); } if ( (this->ContentType == vtkSelection::THRESHOLDS) && (this->Internal->Values != 0) ) { output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), this->ContentType); output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), this->FieldType); // Create the selection list vtkAbstractArray* selectionList = this->Internal->Values->NewInstance(); selectionList->DeepCopy(this->Internal->Values); output->SetSelectionList(selectionList); selectionList->Delete(); } if ( (this->ContentType == vtkSelection::FRUSTUM) && (this->Internal->Values != 0) ) { output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(), this->ContentType); output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), this->FieldType); // Create the selection list vtkAbstractArray* selectionList = this->Internal->Values->NewInstance(); selectionList->DeepCopy(this->Internal->Values); output->SetSelectionList(selectionList); selectionList->Delete(); } output->GetProperties()->Set(vtkSelection::CONTAINING_CELLS(), this->ContainingCells); output->GetProperties()->Set(vtkSelection::PRESERVE_TOPOLOGY(), this->PreserveTopology); output->GetProperties()->Set(vtkSelection::INVERSE(), this->Inverse); output->GetProperties()->Set(vtkSelection::ARRAY_NAME(), this->ArrayName); output->GetProperties()->Set(vtkSelection::EXACT_TEST(), this->ExactTest); output->GetProperties()->Set(vtkSelection::SHOW_BOUNDS(), this->ShowBounds); return 1; } //------------------------------------------------------------------------------ void vtkSelectionSource::SetContentType(int value) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting ContentType to " << value); if (this->ContentType != value) { this->ContentType = value; this->RemoveAllIDs(); this->RemoveAllValues(); if (this->Internal->Values) { this->Internal->Values->Delete(); } switch (value) { case vtkSelection::LOCATIONS: { vtkDoubleArray *da = vtkDoubleArray::New(); da->SetNumberOfComponents(3); da->SetNumberOfTuples(0); this->Internal->Values = da; break; } case vtkSelection::THRESHOLDS: { vtkDoubleArray *da = vtkDoubleArray::New(); da->SetNumberOfComponents(1); da->SetNumberOfTuples(0); this->Internal->Values = da; break; } case vtkSelection::FRUSTUM: { vtkDoubleArray *da = vtkDoubleArray::New(); da->SetNumberOfComponents(4); da->SetNumberOfTuples(8); this->Internal->Values = da; break; } default: break; } this->Modified(); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scrptfld.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2008-03-12 12:20:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _DOCUFLD_HXX #include <docufld.hxx> #endif #ifndef _UNOFLDMID_H #include <unofldmid.h> #endif #ifndef _COMCORE_HRC #include <comcore.hrc> #endif #ifndef _TOOLS_RESID_HXX #include <tools/resid.hxx> #endif using namespace ::com::sun::star; using ::rtl::OUString; /*-------------------------------------------------------------------- Beschreibung: ScriptField --------------------------------------------------------------------*/ SwScriptFieldType::SwScriptFieldType( SwDoc* pD ) : SwFieldType( RES_SCRIPTFLD ), pDoc( pD ) {} SwFieldType* SwScriptFieldType::Copy() const { return new SwScriptFieldType( pDoc ); } /*-------------------------------------------------------------------- Beschreibung: SwScriptField --------------------------------------------------------------------*/ SwScriptField::SwScriptField( SwScriptFieldType* pInitType, const String& rType, const String& rCode, BOOL bURL ) : SwField( pInitType ), sType( rType ), sCode( rCode ), bCodeURL( bURL ) { } String SwScriptField::GetDescription() const { return SW_RES(STR_SCRIPT); } String SwScriptField::Expand() const { return aEmptyStr; } SwField* SwScriptField::Copy() const { return new SwScriptField( (SwScriptFieldType*)GetTyp(), sType, sCode, bCodeURL ); } /*-------------------------------------------------------------------- Beschreibung: Type setzen --------------------------------------------------------------------*/ void SwScriptField::SetPar1( const String& rStr ) { sType = rStr; } const String& SwScriptField::GetPar1() const { return sType; } /*-------------------------------------------------------------------- Beschreibung: Code setzen --------------------------------------------------------------------*/ void SwScriptField::SetPar2( const String& rStr ) { sCode = rStr; } String SwScriptField::GetPar2() const { return sCode; } /*-----------------05.03.98 15:00------------------- --------------------------------------------------*/ BOOL SwScriptField::QueryValue( uno::Any& rAny, USHORT nWhichId ) const { switch( nWhichId ) { case FIELD_PROP_PAR1: rAny <<= OUString( sType ); break; case FIELD_PROP_PAR2: rAny <<= OUString( sCode ); break; case FIELD_PROP_BOOL1: rAny.setValue(&bCodeURL, ::getBooleanCppuType()); break; default: DBG_ERROR("illegal property"); } return TRUE; } /*-----------------05.03.98 15:00------------------- --------------------------------------------------*/ BOOL SwScriptField::PutValue( const uno::Any& rAny, USHORT nWhichId ) { switch( nWhichId ) { case FIELD_PROP_PAR1: ::GetString( rAny, sType ); break; case FIELD_PROP_PAR2: ::GetString( rAny, sCode ); break; case FIELD_PROP_BOOL1: bCodeURL = *(sal_Bool*)rAny.getValue(); break; default: DBG_ERROR("illegal property"); } return TRUE; } <commit_msg>INTEGRATION: CWS changefileheader (1.11.34); FILE MERGED 2008/04/01 15:57:06 thb 1.11.34.3: #i85898# Stripping all external header guards 2008/04/01 12:54:06 thb 1.11.34.2: #i85898# Stripping all external header guards 2008/03/31 16:54:05 rt 1.11.34.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: scrptfld.cxx,v $ * $Revision: 1.12 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <docufld.hxx> #ifndef _UNOFLDMID_H #include <unofldmid.h> #endif #ifndef _COMCORE_HRC #include <comcore.hrc> #endif #include <tools/resid.hxx> using namespace ::com::sun::star; using ::rtl::OUString; /*-------------------------------------------------------------------- Beschreibung: ScriptField --------------------------------------------------------------------*/ SwScriptFieldType::SwScriptFieldType( SwDoc* pD ) : SwFieldType( RES_SCRIPTFLD ), pDoc( pD ) {} SwFieldType* SwScriptFieldType::Copy() const { return new SwScriptFieldType( pDoc ); } /*-------------------------------------------------------------------- Beschreibung: SwScriptField --------------------------------------------------------------------*/ SwScriptField::SwScriptField( SwScriptFieldType* pInitType, const String& rType, const String& rCode, BOOL bURL ) : SwField( pInitType ), sType( rType ), sCode( rCode ), bCodeURL( bURL ) { } String SwScriptField::GetDescription() const { return SW_RES(STR_SCRIPT); } String SwScriptField::Expand() const { return aEmptyStr; } SwField* SwScriptField::Copy() const { return new SwScriptField( (SwScriptFieldType*)GetTyp(), sType, sCode, bCodeURL ); } /*-------------------------------------------------------------------- Beschreibung: Type setzen --------------------------------------------------------------------*/ void SwScriptField::SetPar1( const String& rStr ) { sType = rStr; } const String& SwScriptField::GetPar1() const { return sType; } /*-------------------------------------------------------------------- Beschreibung: Code setzen --------------------------------------------------------------------*/ void SwScriptField::SetPar2( const String& rStr ) { sCode = rStr; } String SwScriptField::GetPar2() const { return sCode; } /*-----------------05.03.98 15:00------------------- --------------------------------------------------*/ BOOL SwScriptField::QueryValue( uno::Any& rAny, USHORT nWhichId ) const { switch( nWhichId ) { case FIELD_PROP_PAR1: rAny <<= OUString( sType ); break; case FIELD_PROP_PAR2: rAny <<= OUString( sCode ); break; case FIELD_PROP_BOOL1: rAny.setValue(&bCodeURL, ::getBooleanCppuType()); break; default: DBG_ERROR("illegal property"); } return TRUE; } /*-----------------05.03.98 15:00------------------- --------------------------------------------------*/ BOOL SwScriptField::PutValue( const uno::Any& rAny, USHORT nWhichId ) { switch( nWhichId ) { case FIELD_PROP_PAR1: ::GetString( rAny, sType ); break; case FIELD_PROP_PAR2: ::GetString( rAny, sCode ); break; case FIELD_PROP_BOOL1: bCodeURL = *(sal_Bool*)rAny.getValue(); break; default: DBG_ERROR("illegal property"); } return TRUE; } <|endoftext|>
<commit_before>//************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTDataInflater.cxx /// @author Matthias Richter, Timm Steinbeck /// @date 2011-08-10 /// @brief Data inflater reading the bitstream from the AliHLTDataDeflater /// @note Code original from AliHLTTPCCompModelInflater #include "AliHLTDataInflater.h" #include "AliHLTErrorGuard.h" #include <memory> #include <algorithm> #include <iostream> /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTDataInflater) AliHLTDataInflater::AliHLTDataInflater() : AliHLTLogging() , fBitDataCurrentWord(0) , fBitDataCurrentPosInWord(0) , fBitDataCurrentInput(NULL) , fBitDataCurrentInputStart(NULL) , fBitDataCurrentInputEnd(NULL) { // constructor, see header file for class documentation } AliHLTDataInflater::~AliHLTDataInflater() { // destructor Clear(); } int AliHLTDataInflater::InitBitDataInput(const AliHLTUInt8_t* input, UInt_t inputSize ) { // init inflater for reading fBitDataCurrentWord = 0; fBitDataCurrentPosInWord = 7; fBitDataCurrentInput = fBitDataCurrentInputStart = input; fBitDataCurrentInputEnd = input+inputSize; fBitDataCurrentWord = *fBitDataCurrentInput; return 0; } void AliHLTDataInflater::CloseBitDataInput() { // close inflater for reading fBitDataCurrentWord=0; fBitDataCurrentPosInWord=0; fBitDataCurrentInput=NULL; fBitDataCurrentInputStart=NULL; fBitDataCurrentInputEnd=NULL; } bool AliHLTDataInflater::InputBit( AliHLTUInt8_t & value ) { // see header file for class documenation if ( fBitDataCurrentInput>=fBitDataCurrentInputEnd ) return false; value = (fBitDataCurrentWord >> fBitDataCurrentPosInWord) & 1; if ( fBitDataCurrentPosInWord ) fBitDataCurrentPosInWord--; else { fBitDataCurrentInput++; if ( fBitDataCurrentInput<fBitDataCurrentInputEnd ) { fBitDataCurrentWord = *fBitDataCurrentInput; fBitDataCurrentPosInWord = 7; } } HLTDebug(" code 0x%08x length 1", value); return true; } bool AliHLTDataInflater::RewindBitPosition(UInt_t const & bitCount) { // Reverse the current bit position by the given number of bits. UInt_t bitDataCurrentPosInWord=fBitDataCurrentPosInWord+bitCount; if ( bitDataCurrentPosInWord > 7) { UInt_t byteShift=bitDataCurrentPosInWord/8; if (fBitDataCurrentInputStart+byteShift>fBitDataCurrentInput) { return false; } fBitDataCurrentInput-=byteShift; fBitDataCurrentWord = *fBitDataCurrentInput; fBitDataCurrentPosInWord = bitDataCurrentPosInWord%8; } return true; } void AliHLTDataInflater::Pad8Bits() { // see header file for class documenation if ( fBitDataCurrentPosInWord == 7 ) return; fBitDataCurrentInput++; if ( fBitDataCurrentInput<fBitDataCurrentInputEnd ) { fBitDataCurrentWord = *fBitDataCurrentInput; fBitDataCurrentPosInWord = 7; } } bool AliHLTDataInflater::InputBytes( AliHLTUInt8_t* data, UInt_t const & byteCount ) { // see header file for class documenation Pad8Bits(); if ( fBitDataCurrentInput+byteCount>fBitDataCurrentInputEnd ) return false; memcpy( data, fBitDataCurrentInput, byteCount ); fBitDataCurrentInput += byteCount; if ( fBitDataCurrentInput<fBitDataCurrentInputEnd ) { fBitDataCurrentWord = *fBitDataCurrentInput; fBitDataCurrentPosInWord = 7; } return true; } void AliHLTDataInflater::Clear(Option_t * /*option*/) { // internal cleanup } void AliHLTDataInflater::Print(Option_t *option) const { // print info Print(cout, option); } void AliHLTDataInflater::Print(ostream& out, Option_t */*option*/) const { // print to stream out << "AliHLTDataInflater: " << endl; } ostream& operator<<(ostream &out, const AliHLTDataInflater& me) { me.Print(out); return out; } <commit_msg>Bugfix: rewinding of bit position of the read pointer<commit_after>//************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTDataInflater.cxx /// @author Matthias Richter, Timm Steinbeck /// @date 2011-08-10 /// @brief Data inflater reading the bitstream from the AliHLTDataDeflater /// @note Code original from AliHLTTPCCompModelInflater #include "AliHLTDataInflater.h" #include "AliHLTErrorGuard.h" #include <memory> #include <algorithm> #include <iostream> /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTDataInflater) AliHLTDataInflater::AliHLTDataInflater() : AliHLTLogging() , fBitDataCurrentWord(0) , fBitDataCurrentPosInWord(0) , fBitDataCurrentInput(NULL) , fBitDataCurrentInputStart(NULL) , fBitDataCurrentInputEnd(NULL) { // constructor, see header file for class documentation } AliHLTDataInflater::~AliHLTDataInflater() { // destructor Clear(); } int AliHLTDataInflater::InitBitDataInput(const AliHLTUInt8_t* input, UInt_t inputSize ) { // init inflater for reading fBitDataCurrentWord = 0; fBitDataCurrentPosInWord = 7; fBitDataCurrentInput = fBitDataCurrentInputStart = input; fBitDataCurrentInputEnd = input+inputSize; fBitDataCurrentWord = *fBitDataCurrentInput; return 0; } void AliHLTDataInflater::CloseBitDataInput() { // close inflater for reading fBitDataCurrentWord=0; fBitDataCurrentPosInWord=0; fBitDataCurrentInput=NULL; fBitDataCurrentInputStart=NULL; fBitDataCurrentInputEnd=NULL; } bool AliHLTDataInflater::InputBit( AliHLTUInt8_t & value ) { // see header file for class documenation if ( fBitDataCurrentInput>=fBitDataCurrentInputEnd ) return false; value = (fBitDataCurrentWord >> fBitDataCurrentPosInWord) & 1; if ( fBitDataCurrentPosInWord ) fBitDataCurrentPosInWord--; else { fBitDataCurrentInput++; if ( fBitDataCurrentInput<fBitDataCurrentInputEnd ) { fBitDataCurrentWord = *fBitDataCurrentInput; fBitDataCurrentPosInWord = 7; } } HLTDebug(" code 0x%08x length 1", value); return true; } bool AliHLTDataInflater::RewindBitPosition(UInt_t const & bitCount) { // Reverse the current bit position by the given number of bits. UInt_t bitDataCurrentPosInWord=fBitDataCurrentPosInWord+bitCount; if ( bitDataCurrentPosInWord > 7) { UInt_t byteShift=bitDataCurrentPosInWord/8; if (fBitDataCurrentInputStart+byteShift>fBitDataCurrentInput) { return false; } fBitDataCurrentInput-=byteShift; fBitDataCurrentWord = *fBitDataCurrentInput; } fBitDataCurrentPosInWord = bitDataCurrentPosInWord%8; return true; } void AliHLTDataInflater::Pad8Bits() { // see header file for class documenation if ( fBitDataCurrentPosInWord == 7 ) return; fBitDataCurrentInput++; if ( fBitDataCurrentInput<fBitDataCurrentInputEnd ) { fBitDataCurrentWord = *fBitDataCurrentInput; fBitDataCurrentPosInWord = 7; } } bool AliHLTDataInflater::InputBytes( AliHLTUInt8_t* data, UInt_t const & byteCount ) { // see header file for class documenation Pad8Bits(); if ( fBitDataCurrentInput+byteCount>fBitDataCurrentInputEnd ) return false; memcpy( data, fBitDataCurrentInput, byteCount ); fBitDataCurrentInput += byteCount; if ( fBitDataCurrentInput<fBitDataCurrentInputEnd ) { fBitDataCurrentWord = *fBitDataCurrentInput; fBitDataCurrentPosInWord = 7; } return true; } void AliHLTDataInflater::Clear(Option_t * /*option*/) { // internal cleanup } void AliHLTDataInflater::Print(Option_t *option) const { // print info Print(cout, option); } void AliHLTDataInflater::Print(ostream& out, Option_t */*option*/) const { // print to stream out << "AliHLTDataInflater: " << endl; } ostream& operator<<(ostream &out, const AliHLTDataInflater& me) { me.Print(out); return out; } <|endoftext|>
<commit_before>/* Copyright 2011-2015 David Robillard <http://drobilla.net> Copyright 2015 Rui Nuno Capela <rncbc@rncbc.org> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <QWidget> #include <QTimerEvent> #include <QCloseEvent> #undef signals #include "./suil_config.h" #include "./suil_internal.h" extern "C" { typedef struct { QWidget* host_widget; QWidget* parent; } SuilX11InQt5Wrapper; class SuilQX11Widget : public QWidget { public: SuilQX11Widget(QWidget* parent, Qt::WindowFlags wflags) : QWidget(parent, wflags) , _instance(NULL) , _idle_iface(NULL) , _ui_timer(0) {} void start_idle(SuilInstance* instance, const LV2UI_Idle_Interface* idle_iface) { _instance = instance; _idle_iface = idle_iface; if (_idle_iface && _ui_timer == 0) { _ui_timer = this->startTimer(30); } } protected: void timerEvent(QTimerEvent* event) override { if (event->timerId() == _ui_timer && _idle_iface) { _idle_iface->idle(_instance->handle); } QWidget::timerEvent(event); } void closeEvent(QCloseEvent* event) override { if (_ui_timer && _idle_iface) { this->killTimer(_ui_timer); _ui_timer = 0; } QWidget::closeEvent(event); } private: SuilInstance* _instance; const LV2UI_Idle_Interface* _idle_iface; int _ui_timer; }; static void wrapper_free(SuilWrapper* wrapper) { SuilX11InQt5Wrapper* impl = (SuilX11InQt5Wrapper*)wrapper->impl; if (impl->host_widget) { delete impl->host_widget; } free(impl); } static int wrapper_wrap(SuilWrapper* wrapper, SuilInstance* instance) { SuilX11InQt5Wrapper* const impl = (SuilX11InQt5Wrapper*)wrapper->impl; SuilQX11Widget* const ew = (SuilQX11Widget*)impl->parent; if (instance->descriptor->extension_data) { const LV2UI_Idle_Interface* idle_iface = (const LV2UI_Idle_Interface*) instance->descriptor->extension_data(LV2_UI__idleInterface); ew->start_idle(instance, idle_iface); } impl->host_widget = ew; instance->host_widget = impl->host_widget; return 0; } static int wrapper_resize(LV2UI_Feature_Handle handle, int width, int height) { QWidget* const ew = (QWidget*)handle; ew->resize(width, height); return 0; } SUIL_LIB_EXPORT SuilWrapper* suil_wrapper_new(SuilHost* host, const char* host_type_uri, const char* ui_type_uri, LV2_Feature*** features, unsigned n_features) { SuilX11InQt5Wrapper* const impl = (SuilX11InQt5Wrapper*) calloc(1, sizeof(SuilX11InQt5Wrapper)); SuilWrapper* wrapper = (SuilWrapper*)malloc(sizeof(SuilWrapper)); wrapper->wrap = wrapper_wrap; wrapper->free = wrapper_free; QWidget* const ew = new SuilQX11Widget(NULL, Qt::Window); impl->parent = ew; wrapper->impl = impl; wrapper->resize.handle = ew; wrapper->resize.ui_resize = wrapper_resize; void* parent_id = (void*)(intptr_t)ew->winId(); suil_add_feature(features, &n_features, LV2_UI__parent, parent_id); suil_add_feature(features, &n_features, LV2_UI__resize, &wrapper->resize); suil_add_feature(features, &n_features, LV2_UI__idleInterface, NULL); return wrapper; } } // extern "C" <commit_msg>Clean up includes<commit_after>/* Copyright 2011-2015 David Robillard <http://drobilla.net> Copyright 2015 Rui Nuno Capela <rncbc@rncbc.org> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <QCloseEvent> #include <QTimerEvent> #include <QWidget> #undef signals #include "./suil_config.h" #include "./suil_internal.h" extern "C" { typedef struct { QWidget* host_widget; QWidget* parent; } SuilX11InQt5Wrapper; class SuilQX11Widget : public QWidget { public: SuilQX11Widget(QWidget* parent, Qt::WindowFlags wflags) : QWidget(parent, wflags) , _instance(NULL) , _idle_iface(NULL) , _ui_timer(0) {} void start_idle(SuilInstance* instance, const LV2UI_Idle_Interface* idle_iface) { _instance = instance; _idle_iface = idle_iface; if (_idle_iface && _ui_timer == 0) { _ui_timer = this->startTimer(30); } } protected: void timerEvent(QTimerEvent* event) override { if (event->timerId() == _ui_timer && _idle_iface) { _idle_iface->idle(_instance->handle); } QWidget::timerEvent(event); } void closeEvent(QCloseEvent* event) override { if (_ui_timer && _idle_iface) { this->killTimer(_ui_timer); _ui_timer = 0; } QWidget::closeEvent(event); } private: SuilInstance* _instance; const LV2UI_Idle_Interface* _idle_iface; int _ui_timer; }; static void wrapper_free(SuilWrapper* wrapper) { SuilX11InQt5Wrapper* impl = (SuilX11InQt5Wrapper*)wrapper->impl; if (impl->host_widget) { delete impl->host_widget; } free(impl); } static int wrapper_wrap(SuilWrapper* wrapper, SuilInstance* instance) { SuilX11InQt5Wrapper* const impl = (SuilX11InQt5Wrapper*)wrapper->impl; SuilQX11Widget* const ew = (SuilQX11Widget*)impl->parent; if (instance->descriptor->extension_data) { const LV2UI_Idle_Interface* idle_iface = (const LV2UI_Idle_Interface*) instance->descriptor->extension_data(LV2_UI__idleInterface); ew->start_idle(instance, idle_iface); } impl->host_widget = ew; instance->host_widget = impl->host_widget; return 0; } static int wrapper_resize(LV2UI_Feature_Handle handle, int width, int height) { QWidget* const ew = (QWidget*)handle; ew->resize(width, height); return 0; } SUIL_LIB_EXPORT SuilWrapper* suil_wrapper_new(SuilHost* host, const char* host_type_uri, const char* ui_type_uri, LV2_Feature*** features, unsigned n_features) { SuilX11InQt5Wrapper* const impl = (SuilX11InQt5Wrapper*) calloc(1, sizeof(SuilX11InQt5Wrapper)); SuilWrapper* wrapper = (SuilWrapper*)malloc(sizeof(SuilWrapper)); wrapper->wrap = wrapper_wrap; wrapper->free = wrapper_free; QWidget* const ew = new SuilQX11Widget(NULL, Qt::Window); impl->parent = ew; wrapper->impl = impl; wrapper->resize.handle = ew; wrapper->resize.ui_resize = wrapper_resize; void* parent_id = (void*)(intptr_t)ew->winId(); suil_add_feature(features, &n_features, LV2_UI__parent, parent_id); suil_add_feature(features, &n_features, LV2_UI__resize, &wrapper->resize); suil_add_feature(features, &n_features, LV2_UI__idleInterface, NULL); return wrapper; } } // extern "C" <|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 <gmock/gmock.h> #include <gtest/gtest.h> #include <cstdint> #include <queue> #include <vector> #include "breakpoint.pb.h" #include "constants.h" #include "cor.h" #include "cordebug.h" #include "dbg_object.h" #include "i_eval_coordinator_mock.h" #include "variable_wrapper.h" #include "winerror.h" using google::cloud::diagnostics::debug::Variable; using google_cloud_debugger::DbgObject; using google_cloud_debugger::IEvalCoordinator; using google_cloud_debugger::VariableWrapper; using std::queue; using std::shared_ptr; using std::string; using std::vector; using ::testing::_; using ::testing::DoAll; using ::testing::Mock; using ::testing::Return; using ::testing::SetArgPointee; namespace google_cloud_debugger_test { // Helper class that implements DbgObject. // This class returns no members. class DbgObjectValue : public DbgObject { public: DbgObjectValue(ICorDebugType *debug_type, int depth) : DbgObject(debug_type, depth) {} virtual void Initialize(ICorDebugValue *debug_value, BOOL is_null) override {} virtual HRESULT PopulateType(Variable *variable) override { variable->set_type(type_); return S_OK; } virtual HRESULT PopulateValue(Variable *variable) override { variable->set_value(value_); return S_OK; } virtual HRESULT PopulateMembers(Variable *variable_proto, std::vector<VariableWrapper> *members, IEvalCoordinator *eval_coordinator) override { return S_FALSE; } // Type of the object. std::string type_; // Value of the object. std::string value_; }; // Helper class that implements DbgObject. // This class returns members but no value. class DbgObjectMembers : public DbgObject { public: DbgObjectMembers(ICorDebugType *debug_type, int depth) : DbgObject(debug_type, depth) {} virtual void Initialize(ICorDebugValue *debug_value, BOOL is_null) override {} virtual HRESULT PopulateType(Variable *variable) override { variable->set_type(type_); return S_OK; } virtual HRESULT PopulateValue(Variable *variable) override { return S_FALSE; } // virtual HRESULT PopulateMembers(Variable *variable_proto, std::vector<VariableWrapper> *members, IEvalCoordinator *eval_coordinator) override { members->insert(members->begin(), members_.begin(), members_.end()); return S_OK; } // Type of the object. std::string type_; // Members of the object. vector<VariableWrapper> members_; }; // Test Fixture for DbgClass. // Contains various ICorDebug mock objects needed. class VariableWrapperTest : public ::testing::Test { protected: void SetUp() { value_object_->value_ = value_object_value_; value_object_->type_ = value_object_type_; value_object_2_->value_ = value_object_2_value_; value_object_2_->type_ = value_object_2_type_; value_object_3_->value_ = value_object_3_value_; value_object_3_->type_ = value_object_3_type_; member_object_->type_ = member_object_type_; member_object_2_->type_ = member_object_2_type_; } // DbgObject that returns value. shared_ptr<DbgObjectValue> value_object_ = shared_ptr<DbgObjectValue>(new DbgObjectValue(nullptr, 0)); // Variable Proto that accompanies value_object_. Variable value_object_proto_; // Value of the value_object_. string value_object_value_ = "Value"; // Type of the value_object_. string value_object_type_ = "Type"; // DbgObject that returns value. shared_ptr<DbgObjectValue> value_object_2_ = shared_ptr<DbgObjectValue>(new DbgObjectValue(nullptr, 0)); // Variable Proto that accompanies value_object_2. Variable value_object_2_proto_; // Value of the value_object_2_. string value_object_2_value_ = "Value2"; // Type of the value_object_2_. string value_object_2_type_ = "Type2"; // DbgObject that returns value. shared_ptr<DbgObjectValue> value_object_3_ = shared_ptr<DbgObjectValue>(new DbgObjectValue(nullptr, 0)); // Variable Proto that accompanies value_object_3_. Variable value_object_3_proto_; // Value of the value_object_3_. string value_object_3_value_ = "Value3"; // Type of the value_object_3_. string value_object_3_type_ = "Type3"; // DbgObject that returns members. shared_ptr<DbgObjectMembers> member_object_ = shared_ptr<DbgObjectMembers>(new DbgObjectMembers(nullptr, 0)); // Variable Proto that accompanies member_object_. Variable member_object_proto_; // Type of the member_object_. string member_object_type_ = "Type4"; // DbgObject that returns members. shared_ptr<DbgObjectMembers> member_object_2_ = shared_ptr<DbgObjectMembers>(new DbgObjectMembers(nullptr, 0)); // Variable Proto that accompanies member_object_2_. Variable member_object_2_proto_; // Type of the member_object_2_. string member_object_2_type_ = "Type5"; IEvalCoordinatorMock eval_coordinator_; }; // Tests the PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateValue) { VariableWrapper wrapper(&value_object_proto_, value_object_); HRESULT hr = wrapper.PopulateValue(); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(value_object_proto_.value(), value_object_value_); VariableWrapper wrapper_2(&member_object_proto_, member_object_); // This should return S_FALSE because variable_value_2 returns S_FALSE // when PopulateValue is called. EXPECT_EQ(wrapper_2.PopulateValue(), S_FALSE); } // Tests the error cases for PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateValueError) { VariableWrapper wrapper(nullptr, value_object_); EXPECT_EQ(wrapper.PopulateValue(), E_INVALIDARG); VariableWrapper wrapper_2(&value_object_proto_, nullptr); EXPECT_EQ(wrapper_2.PopulateValue(), E_INVALIDARG); } // Tests the PopulateType function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateType) { VariableWrapper wrapper(&value_object_proto_, value_object_); HRESULT hr = wrapper.PopulateType(); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(value_object_proto_.type(), value_object_type_); } // Tests the error cases for PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateTypeError) { VariableWrapper wrapper(nullptr, value_object_); EXPECT_EQ(wrapper.PopulateType(), E_INVALIDARG); VariableWrapper wrapper_2(&value_object_proto_, nullptr); EXPECT_EQ(wrapper_2.PopulateType(), E_INVALIDARG); } // Tests the error cases for PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateMembers) { member_object_->members_.push_back( VariableWrapper(&value_object_proto_, value_object_)); member_object_->members_.push_back( VariableWrapper(&value_object_2_proto_, value_object_2_)); VariableWrapper member_wrapper(&member_object_proto_, member_object_); vector<VariableWrapper> members; HRESULT hr = member_wrapper.PopulateMembers(&members, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(members.size(), 2); EXPECT_EQ(members[0].GetVariableProto(), &value_object_proto_); EXPECT_EQ(members[1].GetVariableProto(), &value_object_2_proto_); } // Tests the error cases for PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateMemberseError) { VariableWrapper wrapper(&member_object_proto_, member_object_); vector<VariableWrapper> members; EXPECT_EQ(wrapper.PopulateMembers(nullptr, &eval_coordinator_), E_INVALIDARG); EXPECT_EQ(wrapper.PopulateMembers(&members, nullptr), E_INVALIDARG); } // Tests PerformBFS method when there is only 1 item. TEST_F(VariableWrapperTest, TestBFSOneItem) { VariableWrapper wrapper(&value_object_proto_, value_object_); queue<VariableWrapper> bfs_queue; bfs_queue.push(wrapper); HRESULT hr = VariableWrapper::PerformBFS(&bfs_queue, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; // BFS should fill up the proto with both value and type. EXPECT_EQ(value_object_proto_.value(), value_object_value_); EXPECT_EQ(value_object_proto_.type(), value_object_type_); } // Tests PerformBFS method when there is 1 item with 2 children. TEST_F(VariableWrapperTest, TestBFSTwoChildren) { member_object_->members_.push_back( VariableWrapper(&value_object_proto_, value_object_)); member_object_->members_.push_back( VariableWrapper(&value_object_2_proto_, value_object_2_)); VariableWrapper member_wrapper(&member_object_proto_, member_object_); queue<VariableWrapper> bfs_queue; bfs_queue.push(member_wrapper); HRESULT hr = VariableWrapper::PerformBFS(&bfs_queue, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; // BFS should fill up the proto with correct type. EXPECT_EQ(member_object_proto_.type(), member_object_type_); // Checks that the children are filled up with correct information. // BFS should fill up the proto with both value and type. EXPECT_EQ(value_object_proto_.value(), value_object_value_); EXPECT_EQ(value_object_proto_.type(), value_object_type_); EXPECT_EQ(value_object_2_proto_.value(), value_object_2_value_); EXPECT_EQ(value_object_2_proto_.type(), value_object_2_type_); } // Tests PerformBFS method when there is 1 item with 2 children // and 1 of the children has another 2 children. We will, however, // sets the BFS level so that the last 2 children won't be evaluated. TEST_F(VariableWrapperTest, TestBFSTwoLevels) { member_object_->members_.push_back( VariableWrapper(&value_object_proto_, value_object_)); member_object_->members_.push_back( VariableWrapper(&member_object_2_proto_, member_object_2_)); member_object_2_->members_.push_back( VariableWrapper(&value_object_2_proto_, value_object_2_)); member_object_2_->members_.push_back( VariableWrapper(&value_object_3_proto_, value_object_3_)); VariableWrapper member_wrapper(&member_object_proto_, member_object_, google_cloud_debugger::kDefaultObjectEvalDepth - 2); queue<VariableWrapper> bfs_queue; bfs_queue.push(member_wrapper); HRESULT hr = VariableWrapper::PerformBFS(&bfs_queue, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; // BFS should fill up the proto with correct type. EXPECT_EQ(member_object_proto_.type(), member_object_type_); // Checks that the children are filled up with correct information. // BFS should fill up the proto with both value and type. EXPECT_EQ(value_object_proto_.value(), value_object_value_); EXPECT_EQ(value_object_proto_.type(), value_object_type_); EXPECT_EQ(member_object_2_proto_.type(), member_object_2_type_); // The other children should have errors set. EXPECT_TRUE(value_object_2_proto_.status().iserror(), true); EXPECT_EQ(value_object_2_proto_.status().message(), "Object evaluation limit reached"); EXPECT_TRUE(value_object_3_proto_.status().iserror(), true); EXPECT_EQ(value_object_3_proto_.status().message(), "Object evaluation limit reached"); } } // namespace google_cloud_debugger_test <commit_msg>Fix variable wrapper tests<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 <gmock/gmock.h> #include <gtest/gtest.h> #include <cstdint> #include <queue> #include <vector> #include "breakpoint.pb.h" #include "constants.h" #include "cor.h" #include "cordebug.h" #include "dbg_object.h" #include "i_eval_coordinator_mock.h" #include "variable_wrapper.h" #include "winerror.h" using google::cloud::diagnostics::debug::Variable; using google_cloud_debugger::DbgObject; using google_cloud_debugger::IEvalCoordinator; using google_cloud_debugger::VariableWrapper; using std::queue; using std::shared_ptr; using std::string; using std::vector; using ::testing::_; using ::testing::DoAll; using ::testing::Mock; using ::testing::Return; using ::testing::SetArgPointee; namespace google_cloud_debugger_test { // Helper class that implements DbgObject. // This class returns no members. class DbgObjectValue : public DbgObject { public: DbgObjectValue(ICorDebugType *debug_type, int depth) : DbgObject(debug_type, depth) {} virtual void Initialize(ICorDebugValue *debug_value, BOOL is_null) override {} virtual HRESULT PopulateType(Variable *variable) override { variable->set_type(type_); return S_OK; } virtual HRESULT PopulateValue(Variable *variable) override { variable->set_value(value_); return S_OK; } virtual HRESULT PopulateMembers(Variable *variable_proto, std::vector<VariableWrapper> *members, IEvalCoordinator *eval_coordinator) override { return S_FALSE; } // Type of the object. std::string type_; // Value of the object. std::string value_; }; // Helper class that implements DbgObject. // This class returns members but no value. class DbgObjectMembers : public DbgObject { public: DbgObjectMembers(ICorDebugType *debug_type, int depth) : DbgObject(debug_type, depth) {} virtual void Initialize(ICorDebugValue *debug_value, BOOL is_null) override {} virtual HRESULT PopulateType(Variable *variable) override { variable->set_type(type_); return S_OK; } virtual HRESULT PopulateValue(Variable *variable) override { return S_FALSE; } // virtual HRESULT PopulateMembers(Variable *variable_proto, std::vector<VariableWrapper> *members, IEvalCoordinator *eval_coordinator) override { members->insert(members->begin(), members_.begin(), members_.end()); return S_OK; } // Type of the object. std::string type_; // Members of the object. vector<VariableWrapper> members_; }; // Test Fixture for DbgClass. // Contains various ICorDebug mock objects needed. class VariableWrapperTest : public ::testing::Test { protected: void SetUp() { value_object_->value_ = value_object_value_; value_object_->type_ = value_object_type_; value_object_2_->value_ = value_object_2_value_; value_object_2_->type_ = value_object_2_type_; value_object_3_->value_ = value_object_3_value_; value_object_3_->type_ = value_object_3_type_; member_object_->type_ = member_object_type_; member_object_2_->type_ = member_object_2_type_; } // DbgObject that returns value. shared_ptr<DbgObjectValue> value_object_ = shared_ptr<DbgObjectValue>(new DbgObjectValue(nullptr, 0)); // Variable Proto that accompanies value_object_. Variable value_object_proto_; // Value of the value_object_. string value_object_value_ = "Value"; // Type of the value_object_. string value_object_type_ = "Type"; // DbgObject that returns value. shared_ptr<DbgObjectValue> value_object_2_ = shared_ptr<DbgObjectValue>(new DbgObjectValue(nullptr, 0)); // Variable Proto that accompanies value_object_2. Variable value_object_2_proto_; // Value of the value_object_2_. string value_object_2_value_ = "Value2"; // Type of the value_object_2_. string value_object_2_type_ = "Type2"; // DbgObject that returns value. shared_ptr<DbgObjectValue> value_object_3_ = shared_ptr<DbgObjectValue>(new DbgObjectValue(nullptr, 0)); // Variable Proto that accompanies value_object_3_. Variable value_object_3_proto_; // Value of the value_object_3_. string value_object_3_value_ = "Value3"; // Type of the value_object_3_. string value_object_3_type_ = "Type3"; // DbgObject that returns members. shared_ptr<DbgObjectMembers> member_object_ = shared_ptr<DbgObjectMembers>(new DbgObjectMembers(nullptr, 0)); // Variable Proto that accompanies member_object_. Variable member_object_proto_; // Type of the member_object_. string member_object_type_ = "Type4"; // DbgObject that returns members. shared_ptr<DbgObjectMembers> member_object_2_ = shared_ptr<DbgObjectMembers>(new DbgObjectMembers(nullptr, 0)); // Variable Proto that accompanies member_object_2_. Variable member_object_2_proto_; // Type of the member_object_2_. string member_object_2_type_ = "Type5"; IEvalCoordinatorMock eval_coordinator_; }; // Tests the PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateValue) { VariableWrapper wrapper(&value_object_proto_, value_object_); HRESULT hr = wrapper.PopulateValue(); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(value_object_proto_.value(), value_object_value_); VariableWrapper wrapper_2(&member_object_proto_, member_object_); // This should return S_FALSE because variable_value_2 returns S_FALSE // when PopulateValue is called. EXPECT_EQ(wrapper_2.PopulateValue(), S_FALSE); } // Tests the error cases for PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateValueError) { VariableWrapper wrapper(nullptr, value_object_); EXPECT_EQ(wrapper.PopulateValue(), E_INVALIDARG); VariableWrapper wrapper_2(&value_object_proto_, nullptr); EXPECT_EQ(wrapper_2.PopulateValue(), E_INVALIDARG); } // Tests the PopulateType function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateType) { VariableWrapper wrapper(&value_object_proto_, value_object_); HRESULT hr = wrapper.PopulateType(); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(value_object_proto_.type(), value_object_type_); } // Tests the error cases for PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateTypeError) { VariableWrapper wrapper(nullptr, value_object_); EXPECT_EQ(wrapper.PopulateType(), E_INVALIDARG); VariableWrapper wrapper_2(&value_object_proto_, nullptr); EXPECT_EQ(wrapper_2.PopulateType(), E_INVALIDARG); } // Tests the error cases for PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateMembers) { member_object_->members_.push_back( VariableWrapper(&value_object_proto_, value_object_)); member_object_->members_.push_back( VariableWrapper(&value_object_2_proto_, value_object_2_)); VariableWrapper member_wrapper(&member_object_proto_, member_object_); vector<VariableWrapper> members; HRESULT hr = member_wrapper.PopulateMembers(&members, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(members.size(), 2); EXPECT_EQ(members[0].GetVariableProto(), &value_object_proto_); EXPECT_EQ(members[1].GetVariableProto(), &value_object_2_proto_); } // Tests the error cases for PopulateValue function of VariableWrapper. TEST_F(VariableWrapperTest, TestPopulateMemberseError) { VariableWrapper wrapper(&member_object_proto_, member_object_); vector<VariableWrapper> members; EXPECT_EQ(wrapper.PopulateMembers(nullptr, &eval_coordinator_), E_INVALIDARG); EXPECT_EQ(wrapper.PopulateMembers(&members, nullptr), E_INVALIDARG); } // Tests PerformBFS method when there is only 1 item. TEST_F(VariableWrapperTest, TestBFSOneItem) { VariableWrapper wrapper(&value_object_proto_, value_object_); queue<VariableWrapper> bfs_queue; bfs_queue.push(wrapper); HRESULT hr = VariableWrapper::PerformBFS(&bfs_queue, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; // BFS should fill up the proto with both value and type. EXPECT_EQ(value_object_proto_.value(), value_object_value_); EXPECT_EQ(value_object_proto_.type(), value_object_type_); } // Tests PerformBFS method when there is 1 item with 2 children. TEST_F(VariableWrapperTest, TestBFSTwoChildren) { member_object_->members_.push_back( VariableWrapper(&value_object_proto_, value_object_)); member_object_->members_.push_back( VariableWrapper(&value_object_2_proto_, value_object_2_)); VariableWrapper member_wrapper(&member_object_proto_, member_object_); queue<VariableWrapper> bfs_queue; bfs_queue.push(member_wrapper); HRESULT hr = VariableWrapper::PerformBFS(&bfs_queue, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; // BFS should fill up the proto with correct type. EXPECT_EQ(member_object_proto_.type(), member_object_type_); // Checks that the children are filled up with correct information. // BFS should fill up the proto with both value and type. EXPECT_EQ(value_object_proto_.value(), value_object_value_); EXPECT_EQ(value_object_proto_.type(), value_object_type_); EXPECT_EQ(value_object_2_proto_.value(), value_object_2_value_); EXPECT_EQ(value_object_2_proto_.type(), value_object_2_type_); } // Tests PerformBFS method when there is 1 item with 2 children // and 1 of the children has another 2 children. We will, however, // sets the BFS level so that the last 2 children won't be evaluated. TEST_F(VariableWrapperTest, TestBFSTwoLevels) { member_object_->members_.push_back( VariableWrapper(&value_object_proto_, value_object_)); member_object_->members_.push_back( VariableWrapper(&member_object_2_proto_, member_object_2_)); member_object_2_->members_.push_back( VariableWrapper(&value_object_2_proto_, value_object_2_)); member_object_2_->members_.push_back( VariableWrapper(&value_object_3_proto_, value_object_3_)); VariableWrapper member_wrapper(&member_object_proto_, member_object_, google_cloud_debugger::kDefaultObjectEvalDepth - 2); queue<VariableWrapper> bfs_queue; bfs_queue.push(member_wrapper); HRESULT hr = VariableWrapper::PerformBFS(&bfs_queue, &eval_coordinator_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; // BFS should fill up the proto with correct type. EXPECT_EQ(member_object_proto_.type(), member_object_type_); // Checks that the children are filled up with correct information. // BFS should fill up the proto with both value and type. EXPECT_EQ(value_object_proto_.value(), value_object_value_); EXPECT_EQ(value_object_proto_.type(), value_object_type_); EXPECT_EQ(member_object_2_proto_.type(), member_object_2_type_); // The other children should have errors set. EXPECT_TRUE(value_object_2_proto_.status().iserror()); EXPECT_EQ(value_object_2_proto_.status().message(), "Object evaluation limit reached"); EXPECT_TRUE(value_object_3_proto_.status().iserror()); EXPECT_EQ(value_object_3_proto_.status().message(), "Object evaluation limit reached"); } } // namespace google_cloud_debugger_test <|endoftext|>
<commit_before><commit_msg>typos<commit_after><|endoftext|>
<commit_before>#include "zmq.h" #include <iostream> #include "AliHLTDataTypes.h" #include "AliHLTComponent.h" #include "AliHLTMessage.h" #include "TClass.h" #include "TCanvas.h" #include "TMap.h" #include "TPRegexp.h" #include "TObjString.h" #include "TDirectory.h" #include "TList.h" #include "AliZMQhelpers.h" #include "TMessage.h" #include "TSystem.h" #include "TApplication.h" #include "TH1.h" #include "TH1F.h" #include <time.h> #include <string> #include <map> #include "TFile.h" #include "TSystem.h" #include "TStyle.h" #include "signal.h" class MySignalHandler; //this is meant to become a class, hence the structure with global vars etc. //Also the code is rather flat - it is a bit of a playground to test ideas. //TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling //zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide //easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...) //methods int ProcessOptionString(TString arguments); int UpdatePad(TObject*); int DumpToFile(TObject* object); void* run(void* arg); //configuration vars Bool_t fVerbose = kFALSE; TString fZMQconfigIN = "PULL>tcp://localhost:60211"; int fZMQsocketModeIN=-1; TString fZMQsubscriptionIN = ""; TString fFilter = ""; TString fFileName=""; TFile* fFile=NULL; int fPollInterval = 0; int fPollTimeout = 1000; //1s Bool_t fSort = kTRUE; //internal state void* fZMQcontext = NULL; //ze zmq context void* fZMQin = NULL; //the in socket - entry point for the data to be merged. TApplication* gApp; TCanvas* fCanvas; TObjArray fDrawables; TString fStatus = ""; Int_t fRunNumber = 0; TPRegexp* fSelectionRegexp = NULL; TPRegexp* fUnSelectionRegexp = NULL; TString fDrawOptions; Bool_t fScaleLogX = kFALSE; Bool_t fScaleLogY = kFALSE; Bool_t fScaleLogZ = kFALSE; Bool_t fResetOnRequest = kFALSE; Int_t fHistStats = 0; Bool_t fAllowResetAtSOR = kTRUE; ULong64_t iterations=0; const char* fUSAGE = "ZMQhstViewer: Draw() all ROOT drawables in a message\n" "options: \n" " -in : data in\n" " -sleep : how long to sleep in between requests for data in s (if applicable)\n" " -timeout : how long to wait for the server to reply (s)\n" " -Verbose : be verbose\n" " -select : only show selected histograms (by regexp)\n" " -unselect : as select, only inverted\n" " -drawoptions : what draw option to use\n" " -file : dump input to file and exit\n" " -log[xyz] : use log scale on [xyz] dimension\n" " -histstats : histogram stat box options (default 0)\n" " -AllowResetAtSOR : 0/1 to reset at change of run\n" ; //_______________________________________________________________________________________ class MySignalHandler : public TSignalHandler { public: MySignalHandler(ESignals sig) : TSignalHandler(sig) {} Bool_t Notify() { Printf("signal received, exiting"); fgTerminationSignaled = true; return TSignalHandler::Notify(); } static bool TerminationSignaled() { return fgTerminationSignaled; } static bool fgTerminationSignaled; }; bool MySignalHandler::fgTerminationSignaled = false; void sig_handler(int signo) { if (signo == SIGINT) printf("received SIGINT\n"); MySignalHandler::fgTerminationSignaled=true; } //_______________________________________________________________________________________ void* run(void* arg) { //main loop while(!MySignalHandler::TerminationSignaled()) { errno=0; //send a request if we are using REQ if (fZMQsocketModeIN==ZMQ_REQ) { string request; if (fSelectionRegexp || fUnSelectionRegexp) { if (fSelectionRegexp) request += " select="+fSelectionRegexp->GetPattern(); if (fUnSelectionRegexp) request += " unselect="+fUnSelectionRegexp->GetPattern(); if (fResetOnRequest) request += " ResetOnRequest"; alizmq_msg_send("CONFIG", request, fZMQin, ZMQ_SNDMORE); } if (fVerbose) Printf("sending request CONFIG %s", request.c_str()); alizmq_msg_send("", "", fZMQin, 0); } //wait for the data zmq_pollitem_t sockets[] = { { fZMQin, 0, ZMQ_POLLIN, 0 }, }; int rc = zmq_poll(sockets, 1, (fZMQsocketModeIN==ZMQ_REQ)?fPollTimeout:-1); if (rc==-1 && errno==ETERM) { Printf("jumping out of main loop"); break; } if (!(sockets[0].revents & ZMQ_POLLIN)) { //server died Printf("connection timed out, server %s died?", fZMQconfigIN.Data()); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data()); if (fZMQsocketModeIN < 0) return NULL; continue; } else { //get all data (topic+body), possibly many of them aliZMQmsg message; alizmq_msg_recv(&message, fZMQin, 0); for (aliZMQmsg::iterator i=message.begin(); i!=message.end(); ++i) { if (alizmq_msg_iter_check(i, "INFO")==0) { //check if we have a runnumber in the string string info; alizmq_msg_iter_data(i,info); if (fVerbose) Printf("processing INFO %s", info.c_str()); fCanvas->SetTitle(info.c_str()); size_t runTagPos = info.find("run"); if (runTagPos != std::string::npos) { size_t runStartPos = info.find("=",runTagPos); size_t runEndPos = info.find(" "); string runString = info.substr(runStartPos+1,runEndPos-runStartPos-1); if (fVerbose) printf("received run=%s\n",runString.c_str()); int runnumber = atoi(runString.c_str()); if (runnumber!=fRunNumber && fAllowResetAtSOR) { if (fVerbose) printf("Run changed, resetting!\n"); fDrawables.Delete(); fCanvas->Clear(); gSystem->ProcessEvents(); } fRunNumber = runnumber; } continue; } TObject* object; alizmq_msg_iter_data(i, object); if (object) UpdatePad(object); if (!fFileName.IsNull()) { if (object) DumpToFile(object); } } alizmq_msg_close(&message); }//socket 0 gSystem->ProcessEvents(); usleep(fPollInterval); }//main loop return NULL; } //_______________________________________________________________________________________ int main(int argc, char** argv) { //process args int noptions = ProcessOptionString(AliOptionParser::GetFullArgString(argc,argv)); if (noptions<=0) { printf("%s",fUSAGE); return 1; } TH1::AddDirectory(kFALSE); TDirectory::AddDirectory(kFALSE); gApp = new TApplication("viewer", &argc, argv); gApp->SetReturnFromRun(true); //gApp->Run(); gStyle->SetOptStat(fHistStats); fCanvas = new TCanvas(); gSystem->ProcessEvents(); int mainReturnCode=0; //init stuff //globally enable schema evolution for serializing ROOT objects TMessage::EnableSchemaEvolutionForAll(kTRUE); //ZMQ init fZMQcontext = zmq_ctx_new(); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, 2); if (fZMQsocketModeIN < 0) return 1; gSystem->ResetSignal(kSigPipe); gSystem->ResetSignal(kSigQuit); gSystem->ResetSignal(kSigInterrupt); gSystem->ResetSignal(kSigTermination); //gSystem->AddSignalHandler(new MySignalHandler(kSigPipe)); //gSystem->AddSignalHandler(new MySignalHandler(kSigQuit)); //gSystem->AddSignalHandler(new MySignalHandler(kSigInterrupt)); //gSystem->AddSignalHandler(new MySignalHandler(kSigTermination)); if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); run(NULL); Printf("exiting..."); if (fFile) fFile->Close(); delete fFile; fFile=0; //destroy ZMQ sockets int linger=0; zmq_setsockopt(fZMQin, ZMQ_LINGER, &linger, sizeof(linger)); zmq_close(fZMQin); zmq_ctx_term(fZMQcontext); return mainReturnCode; } //______________________________________________________________________________ int DumpToFile(TObject* object) { Option_t* fileMode="RECREATE"; if (!fFile) fFile = new TFile(fFileName,fileMode); if (fVerbose) Printf("writing object %s to %s",object->GetName(), fFileName.Data()); int rc = object->Write(object->GetName(),TObject::kOverwrite); MySignalHandler::fgTerminationSignaled=true; return rc; } //______________________________________________________________________________ int UpdatePad(TObject* object) { if (!object) return -1; const char* name = object->GetName(); TObject* drawable = fDrawables.FindObject(name); int padIndex = fDrawables.IndexOf(drawable); if (fVerbose) Printf("in: %s (%s)", name, object->ClassName()); Bool_t selected = kTRUE; Bool_t unselected = kFALSE; if (fSelectionRegexp) selected = fSelectionRegexp->Match(name); if (fUnSelectionRegexp) unselected = fUnSelectionRegexp->Match(name); if (!selected || unselected) { delete object; return 0; } if (drawable) { //only redraw the one thing if (fVerbose) Printf(" redrawing %s in pad %i", name, padIndex); fCanvas->cd(padIndex+1); gPad->GetListOfPrimitives()->Remove(drawable); gPad->Clear(); fDrawables.RemoveAt(padIndex); delete drawable; fDrawables.AddAt(object, padIndex); object->Draw(fDrawOptions); gPad->Modified(kTRUE); } else { if (fVerbose) Printf(" new object %s", name); //add the new object to the collection, restructure the canvas //and redraw everything fDrawables.AddLast(object); if (fSort) { TObjArray sortedTitles(fDrawables.GetEntries()); for (int i=0; i<fDrawables.GetEntries(); i++) { sortedTitles.AddAt(new TNamed(fDrawables[i]->GetTitle(),fDrawables[i]->GetName()),i); } sortedTitles.Sort(); TObjArray sortedDrawables(fDrawables.GetEntries()); for (int i=0; i<fDrawables.GetEntries(); i++) { const char* name = sortedTitles[i]->GetTitle(); TObject* tmp = fDrawables.FindObject(name); int index = fDrawables.IndexOf(tmp); sortedDrawables.AddAt(fDrawables[index],i); } for (int i=0; i<sortedDrawables.GetEntries(); i++) { fDrawables.AddAt(sortedDrawables[i],i); } sortedTitles.Delete(); } //after we clear the canvas, the pads are gone, clear the pad cache as well fCanvas->Clear(); fCanvas->DivideSquare(fDrawables.GetLast()+1); //redraw all objects at their old places and the new one as last for (int i=0; i<fDrawables.GetLast()+1; i++) { TObject* obj = fDrawables[i]; fCanvas->cd(i+1); if (fScaleLogX) gPad->SetLogx(); if (fScaleLogY) gPad->SetLogy(); if (fScaleLogZ) gPad->SetLogz(); if (fVerbose) Printf(" drawing %s in pad %i", obj->GetName(), i); if (obj) obj->Draw(fDrawOptions); } } gSystem->ProcessEvents(); fCanvas->Update(); return 0; } //______________________________________________________________________________ int ProcessOptionString(TString arguments) { //process passed options aliStringVec* options = AliOptionParser::TokenizeOptionString(arguments); int nOptions = 0; for (aliStringVec::iterator i=options->begin(); i!=options->end(); ++i) { //Printf(" %s : %s", i->first.data(), i->second.data()); const TString& option = i->first; const TString& value = i->second; if (option.EqualTo("PollInterval") || option.EqualTo("sleep")) { fPollInterval = round(value.Atof()*1e6); } else if (option.EqualTo("PollTimeout") || option.EqualTo("timeout")) { fPollTimeout = round(value.Atof()*1e3); } else if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in") ) { fZMQconfigIN = value; } else if (option.EqualTo("Verbose")) { fVerbose=kTRUE; } else if (option.EqualTo("select")) { delete fSelectionRegexp; fSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("unselect")) { delete fUnSelectionRegexp; fUnSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("ResetOnRequest")) { fResetOnRequest = kTRUE; } else if (option.EqualTo("drawoptions")) { fDrawOptions = value; } else if (option.EqualTo("logx")) { fScaleLogX=kTRUE; } else if (option.EqualTo("logy")) { fScaleLogY=kTRUE; } else if (option.EqualTo("logz")) { fScaleLogZ=kTRUE; } else if (option.EqualTo("file")) { fFileName = value; } else if (option.EqualTo("sort")) { fSort=value.Contains(0)?kFALSE:kTRUE; } else if (option.EqualTo("histstats")) { fHistStats = value.Atoi(); } else if (option.EqualTo("AllowResetAtSOR")) { fAllowResetAtSOR = (option.Contains("0")||option.Contains("no"))?kFALSE:kTRUE; } else { nOptions=-1; break; } nOptions++; } delete options; //tidy up return nOptions; } <commit_msg>increase default poll timeout to 100s<commit_after>#include "zmq.h" #include <iostream> #include "AliHLTDataTypes.h" #include "AliHLTComponent.h" #include "AliHLTMessage.h" #include "TClass.h" #include "TCanvas.h" #include "TMap.h" #include "TPRegexp.h" #include "TObjString.h" #include "TDirectory.h" #include "TList.h" #include "AliZMQhelpers.h" #include "TMessage.h" #include "TSystem.h" #include "TApplication.h" #include "TH1.h" #include "TH1F.h" #include <time.h> #include <string> #include <map> #include "TFile.h" #include "TSystem.h" #include "TStyle.h" #include "signal.h" class MySignalHandler; //this is meant to become a class, hence the structure with global vars etc. //Also the code is rather flat - it is a bit of a playground to test ideas. //TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling //zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide //easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...) //methods int ProcessOptionString(TString arguments); int UpdatePad(TObject*); int DumpToFile(TObject* object); void* run(void* arg); //configuration vars Bool_t fVerbose = kFALSE; TString fZMQconfigIN = "PULL>tcp://localhost:60211"; int fZMQsocketModeIN=-1; TString fZMQsubscriptionIN = ""; TString fFilter = ""; TString fFileName=""; TFile* fFile=NULL; int fPollInterval = 0; int fPollTimeout = 100000; //100s Bool_t fSort = kTRUE; //internal state void* fZMQcontext = NULL; //ze zmq context void* fZMQin = NULL; //the in socket - entry point for the data to be merged. TApplication* gApp; TCanvas* fCanvas; TObjArray fDrawables; TString fStatus = ""; Int_t fRunNumber = 0; TPRegexp* fSelectionRegexp = NULL; TPRegexp* fUnSelectionRegexp = NULL; TString fDrawOptions; Bool_t fScaleLogX = kFALSE; Bool_t fScaleLogY = kFALSE; Bool_t fScaleLogZ = kFALSE; Bool_t fResetOnRequest = kFALSE; Int_t fHistStats = 0; Bool_t fAllowResetAtSOR = kTRUE; ULong64_t iterations=0; const char* fUSAGE = "ZMQhstViewer: Draw() all ROOT drawables in a message\n" "options: \n" " -in : data in\n" " -sleep : how long to sleep in between requests for data in s (if applicable)\n" " -timeout : how long to wait for the server to reply (s)\n" " -Verbose : be verbose\n" " -select : only show selected histograms (by regexp)\n" " -unselect : as select, only inverted\n" " -drawoptions : what draw option to use\n" " -file : dump input to file and exit\n" " -log[xyz] : use log scale on [xyz] dimension\n" " -histstats : histogram stat box options (default 0)\n" " -AllowResetAtSOR : 0/1 to reset at change of run\n" ; //_______________________________________________________________________________________ class MySignalHandler : public TSignalHandler { public: MySignalHandler(ESignals sig) : TSignalHandler(sig) {} Bool_t Notify() { Printf("signal received, exiting"); fgTerminationSignaled = true; return TSignalHandler::Notify(); } static bool TerminationSignaled() { return fgTerminationSignaled; } static bool fgTerminationSignaled; }; bool MySignalHandler::fgTerminationSignaled = false; void sig_handler(int signo) { if (signo == SIGINT) printf("received SIGINT\n"); MySignalHandler::fgTerminationSignaled=true; } //_______________________________________________________________________________________ void* run(void* arg) { //main loop while(!MySignalHandler::TerminationSignaled()) { errno=0; //send a request if we are using REQ if (fZMQsocketModeIN==ZMQ_REQ) { string request; if (fSelectionRegexp || fUnSelectionRegexp) { if (fSelectionRegexp) request += " select="+fSelectionRegexp->GetPattern(); if (fUnSelectionRegexp) request += " unselect="+fUnSelectionRegexp->GetPattern(); if (fResetOnRequest) request += " ResetOnRequest"; alizmq_msg_send("CONFIG", request, fZMQin, ZMQ_SNDMORE); } if (fVerbose) Printf("sending request CONFIG %s", request.c_str()); alizmq_msg_send("", "", fZMQin, 0); } //wait for the data zmq_pollitem_t sockets[] = { { fZMQin, 0, ZMQ_POLLIN, 0 }, }; int rc = zmq_poll(sockets, 1, (fZMQsocketModeIN==ZMQ_REQ)?fPollTimeout:-1); if (rc==-1 && errno==ETERM) { Printf("jumping out of main loop"); break; } if (!(sockets[0].revents & ZMQ_POLLIN)) { //server died Printf("connection timed out, server %s died?", fZMQconfigIN.Data()); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data()); if (fZMQsocketModeIN < 0) return NULL; continue; } else { //get all data (topic+body), possibly many of them aliZMQmsg message; alizmq_msg_recv(&message, fZMQin, 0); for (aliZMQmsg::iterator i=message.begin(); i!=message.end(); ++i) { if (alizmq_msg_iter_check(i, "INFO")==0) { //check if we have a runnumber in the string string info; alizmq_msg_iter_data(i,info); if (fVerbose) Printf("processing INFO %s", info.c_str()); fCanvas->SetTitle(info.c_str()); size_t runTagPos = info.find("run"); if (runTagPos != std::string::npos) { size_t runStartPos = info.find("=",runTagPos); size_t runEndPos = info.find(" "); string runString = info.substr(runStartPos+1,runEndPos-runStartPos-1); if (fVerbose) printf("received run=%s\n",runString.c_str()); int runnumber = atoi(runString.c_str()); if (runnumber!=fRunNumber && fAllowResetAtSOR) { if (fVerbose) printf("Run changed, resetting!\n"); fDrawables.Delete(); fCanvas->Clear(); gSystem->ProcessEvents(); } fRunNumber = runnumber; } continue; } TObject* object; alizmq_msg_iter_data(i, object); if (object) UpdatePad(object); if (!fFileName.IsNull()) { if (object) DumpToFile(object); } } alizmq_msg_close(&message); }//socket 0 gSystem->ProcessEvents(); usleep(fPollInterval); }//main loop return NULL; } //_______________________________________________________________________________________ int main(int argc, char** argv) { //process args int noptions = ProcessOptionString(AliOptionParser::GetFullArgString(argc,argv)); if (noptions<=0) { printf("%s",fUSAGE); return 1; } TH1::AddDirectory(kFALSE); TDirectory::AddDirectory(kFALSE); gApp = new TApplication("viewer", &argc, argv); gApp->SetReturnFromRun(true); //gApp->Run(); gStyle->SetOptStat(fHistStats); fCanvas = new TCanvas(); gSystem->ProcessEvents(); int mainReturnCode=0; //init stuff //globally enable schema evolution for serializing ROOT objects TMessage::EnableSchemaEvolutionForAll(kTRUE); //ZMQ init fZMQcontext = zmq_ctx_new(); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, 2); if (fZMQsocketModeIN < 0) return 1; gSystem->ResetSignal(kSigPipe); gSystem->ResetSignal(kSigQuit); gSystem->ResetSignal(kSigInterrupt); gSystem->ResetSignal(kSigTermination); //gSystem->AddSignalHandler(new MySignalHandler(kSigPipe)); //gSystem->AddSignalHandler(new MySignalHandler(kSigQuit)); //gSystem->AddSignalHandler(new MySignalHandler(kSigInterrupt)); //gSystem->AddSignalHandler(new MySignalHandler(kSigTermination)); if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); run(NULL); Printf("exiting..."); if (fFile) fFile->Close(); delete fFile; fFile=0; //destroy ZMQ sockets int linger=0; zmq_setsockopt(fZMQin, ZMQ_LINGER, &linger, sizeof(linger)); zmq_close(fZMQin); zmq_ctx_term(fZMQcontext); return mainReturnCode; } //______________________________________________________________________________ int DumpToFile(TObject* object) { Option_t* fileMode="RECREATE"; if (!fFile) fFile = new TFile(fFileName,fileMode); if (fVerbose) Printf("writing object %s to %s",object->GetName(), fFileName.Data()); int rc = object->Write(object->GetName(),TObject::kOverwrite); MySignalHandler::fgTerminationSignaled=true; return rc; } //______________________________________________________________________________ int UpdatePad(TObject* object) { if (!object) return -1; const char* name = object->GetName(); TObject* drawable = fDrawables.FindObject(name); int padIndex = fDrawables.IndexOf(drawable); if (fVerbose) Printf("in: %s (%s)", name, object->ClassName()); Bool_t selected = kTRUE; Bool_t unselected = kFALSE; if (fSelectionRegexp) selected = fSelectionRegexp->Match(name); if (fUnSelectionRegexp) unselected = fUnSelectionRegexp->Match(name); if (!selected || unselected) { delete object; return 0; } if (drawable) { //only redraw the one thing if (fVerbose) Printf(" redrawing %s in pad %i", name, padIndex); fCanvas->cd(padIndex+1); gPad->GetListOfPrimitives()->Remove(drawable); gPad->Clear(); fDrawables.RemoveAt(padIndex); delete drawable; fDrawables.AddAt(object, padIndex); object->Draw(fDrawOptions); gPad->Modified(kTRUE); } else { if (fVerbose) Printf(" new object %s", name); //add the new object to the collection, restructure the canvas //and redraw everything fDrawables.AddLast(object); if (fSort) { TObjArray sortedTitles(fDrawables.GetEntries()); for (int i=0; i<fDrawables.GetEntries(); i++) { sortedTitles.AddAt(new TNamed(fDrawables[i]->GetTitle(),fDrawables[i]->GetName()),i); } sortedTitles.Sort(); TObjArray sortedDrawables(fDrawables.GetEntries()); for (int i=0; i<fDrawables.GetEntries(); i++) { const char* name = sortedTitles[i]->GetTitle(); TObject* tmp = fDrawables.FindObject(name); int index = fDrawables.IndexOf(tmp); sortedDrawables.AddAt(fDrawables[index],i); } for (int i=0; i<sortedDrawables.GetEntries(); i++) { fDrawables.AddAt(sortedDrawables[i],i); } sortedTitles.Delete(); } //after we clear the canvas, the pads are gone, clear the pad cache as well fCanvas->Clear(); fCanvas->DivideSquare(fDrawables.GetLast()+1); //redraw all objects at their old places and the new one as last for (int i=0; i<fDrawables.GetLast()+1; i++) { TObject* obj = fDrawables[i]; fCanvas->cd(i+1); if (fScaleLogX) gPad->SetLogx(); if (fScaleLogY) gPad->SetLogy(); if (fScaleLogZ) gPad->SetLogz(); if (fVerbose) Printf(" drawing %s in pad %i", obj->GetName(), i); if (obj) obj->Draw(fDrawOptions); } } gSystem->ProcessEvents(); fCanvas->Update(); return 0; } //______________________________________________________________________________ int ProcessOptionString(TString arguments) { //process passed options aliStringVec* options = AliOptionParser::TokenizeOptionString(arguments); int nOptions = 0; for (aliStringVec::iterator i=options->begin(); i!=options->end(); ++i) { //Printf(" %s : %s", i->first.data(), i->second.data()); const TString& option = i->first; const TString& value = i->second; if (option.EqualTo("PollInterval") || option.EqualTo("sleep")) { fPollInterval = round(value.Atof()*1e6); } else if (option.EqualTo("PollTimeout") || option.EqualTo("timeout")) { fPollTimeout = round(value.Atof()*1e3); } else if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in") ) { fZMQconfigIN = value; } else if (option.EqualTo("Verbose")) { fVerbose=kTRUE; } else if (option.EqualTo("select")) { delete fSelectionRegexp; fSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("unselect")) { delete fUnSelectionRegexp; fUnSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("ResetOnRequest")) { fResetOnRequest = kTRUE; } else if (option.EqualTo("drawoptions")) { fDrawOptions = value; } else if (option.EqualTo("logx")) { fScaleLogX=kTRUE; } else if (option.EqualTo("logy")) { fScaleLogY=kTRUE; } else if (option.EqualTo("logz")) { fScaleLogZ=kTRUE; } else if (option.EqualTo("file")) { fFileName = value; } else if (option.EqualTo("sort")) { fSort=value.Contains(0)?kFALSE:kTRUE; } else if (option.EqualTo("histstats")) { fHistStats = value.Atoi(); } else if (option.EqualTo("AllowResetAtSOR")) { fAllowResetAtSOR = (option.Contains("0")||option.Contains("no"))?kFALSE:kTRUE; } else { nOptions=-1; break; } nOptions++; } delete options; //tidy up return nOptions; } <|endoftext|>
<commit_before>#include <MeshSim.h> #include <SimPartitionedMesh.h> #include <SimUtil.h> #include <apf.h> #include <gmi_mesh.h> #include <gmi_sim.h> #include <apfMDS.h> #include <apfMesh2.h> #include <PCU.h> int main(int argc, char** argv) { assert(argc==4); MPI_Init(&argc,&argv); PCU_Comm_Init(); gmi_register_sim(); gmi_register_mesh(); Sim_readLicenseFile(NULL); SimPartitionedMesh_start(&argc,&argv); SimModel_start(); apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]); apf::writeVtkFiles(argv[3], m); m->destroyNative(); apf::destroyMesh(m); PCU_Comm_Free(); MPI_Finalize(); } <commit_msg>render does not need SimPartitionedMesh<commit_after>#include <MeshSim.h> #include <SimUtil.h> #include <apf.h> #include <gmi_mesh.h> #include <gmi_sim.h> #include <apfMDS.h> #include <apfMesh2.h> #include <PCU.h> int main(int argc, char** argv) { assert(argc==4); MPI_Init(&argc,&argv); PCU_Comm_Init(); gmi_register_sim(); gmi_register_mesh(); Sim_readLicenseFile(NULL); SimModel_start(); apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]); apf::writeVtkFiles(argv[3], m); m->destroyNative(); apf::destroyMesh(m); PCU_Comm_Free(); MPI_Finalize(); } <|endoftext|>
<commit_before><commit_msg>Fix default OADB container in case of pp 13 TeV<commit_after><|endoftext|>
<commit_before><commit_msg>remove empty DumpHints() [loplugin:unreffun]<commit_after><|endoftext|>
<commit_before>#include "SmallFS.h" #include <string.h> #ifdef __linux__ #include <fcntl.h> #include <unistd.h> #include <endian.h> #include <stdio.h> #include <strings.h> #define BE32(x) be32toh(x) #else #include "Arduino.h" #include "zfdevice.h" #define BE32(x) x #endif #undef SMALLFSDEBUG #ifdef HAVE_ZFDEVICE static void zf_register_smallfs(); #endif int SmallFS_class::begin() { #ifdef __linux__ fsstart = 0; fd = ::open("smallfs.dat",O_RDONLY); if (fd<0) { perror("Cannot open smallfs.dat"); return -1; } #else struct boot_t *b = (struct boot_t*)bootloaderdata; fsstart = b->spiend; /* Check for >1.9 bootloader */ if (b->signature==0xb00110ad ) { can_load_sketches=1; } #endif offset = 0xffffffff; read(fsstart, &hdr,sizeof(hdr)); #ifdef SMALLFSDEBUG unsigned debug; Serial.print("Read magic "); Serial.println(hdr.magic); Serial.print("SPI end "); Serial.println(fsstart); Serial.print("Bdata at "); Serial.println((unsigned)b); // Test read read(fsstart - 8, &debug,sizeof(debug)); Serial.print("DD1 "); Serial.println(debug); read(&debug,sizeof(debug)); Serial.print("DD2 "); Serial.println(debug); read(&debug,sizeof(debug)); Serial.print("DD3 "); Serial.println(debug); #endif /* if(SMALLFS_MAGIC==BE32(hdr.magic)) return 0; return -1; */ #ifdef HAVE_ZFDEVICE zf_register_smallfs(); #endif return hdr.magic - SMALLFS_MAGIC; } void SmallFS_class::seek_if_needed(unsigned address) { register_t spibasedata=&SPIDATA; if (address!=offset) { offset = address; spi_disable(); spi_enable(); #ifdef SMALLFSDEBUG Serial.print("Seeking to "); Serial.println(address); #endif /* spiwrite(spibasedata,0x0B); spiwrite(spibasedata,address>>16); spiwrite(spibasedata,address>>8); spiwrite(spibasedata,address); spiwrite(spibasedata,0); spiwrite(spibasedata,0); // Read ahead */ address+=0x0B000000; spiwrite(spibasedata+2,address>>16); /* 16-bit write */ address<<=16; spiwrite(spibasedata+6,address); /* 32-bit Includes read-ahead */ } } unsigned SmallFS_class::readByte(unsigned address) { seek_if_needed(address); unsigned v = spiread(); // Already cached spiwrite(0); offset++; return v; } void SmallFS_class::read(unsigned address, void *target, unsigned size) { #ifdef __linux__ if (fd>=0) { ::read(fd,target,size); } #else seek_if_needed(address); unsigned char *p=(unsigned char*)target; while (size--) { unsigned v = spiread(); // Already cached spiwrite(0); *p++=v; offset++; } #endif } SmallFSEntry SmallFS_class::getFirstEntry() { unsigned o = fsstart + sizeof(struct smallfs_header); if (BE32(hdr.numfiles)==0) return SmallFSEntry(); return SmallFSEntry(o,0); } bool SmallFSEntry::hasNext() const { return (m_index+1)<SmallFS_class::getCount(); } bool SmallFSEntry::equals(const char *name){ struct smallfs_entry e; char buf[256]; SmallFS_class::read(m_offset, &e,sizeof(struct smallfs_entry)); SmallFS_class::read( m_offset + sizeof(struct smallfs_entry), buf, e.namesize); buf[e.namesize] = '\0'; return (strcmp(name,buf)==0); } bool SmallFSEntry::endsWith(const char *name) { struct smallfs_entry e; char buf[256]; SmallFS_class::read(m_offset, &e,sizeof(struct smallfs_entry)); SmallFS_class::read( m_offset + sizeof(struct smallfs_entry), buf, e.namesize); buf[e.namesize] = '\0'; unsigned l = strlen(name); if (l>e.namesize) return false; char *p = buf + e.namesize - l; return (strcmp(name,p)==0); } void SmallFSEntry::getName(char *name) { struct smallfs_entry e; SmallFS_class::read( m_offset, &e,sizeof(struct smallfs_entry)); SmallFS_class::read( m_offset + sizeof(struct smallfs_entry), name, e.namesize); name[e.namesize] = '\0'; } bool SmallFSEntry::startsWith(const char *name) { struct smallfs_entry e; char buf[256]; SmallFS_class::read( m_offset, &e,sizeof(struct smallfs_entry)); SmallFS_class::read( m_offset + sizeof(struct smallfs_entry), buf, e.namesize); buf[e.namesize] = '\0'; return (strncmp(name,buf,strlen(name))==0); } SmallFSFile SmallFSEntry::open() { return SmallFS_class::openByOffset(m_offset); }; SmallFSEntry &SmallFSEntry::operator++(int) { if (hasNext()) { struct smallfs_entry e; m_index++; /* Recompute offset */ SmallFS_class::read(m_offset, &e,sizeof(struct smallfs_entry)); m_offset+=sizeof(struct smallfs_entry); m_offset+=e.namesize; } return *this; } SmallFSFile SmallFS_class::openByOffset(unsigned offset) { struct smallfs_entry e; read(offset, &e,sizeof(struct smallfs_entry)); seek_if_needed(BE32(e.offset) + fsstart); return SmallFSFile(BE32(e.offset) + fsstart, BE32(e.size)); } SmallFSFile SmallFS_class::open(const char *name) { /* Start at root offset */ unsigned o = fsstart + sizeof(struct smallfs_header); unsigned char buf[256]; struct smallfs_entry e; int c; for (c=BE32(hdr.numfiles); c; c--) { read(o, &e,sizeof(struct smallfs_entry)); o+=sizeof(struct smallfs_entry); read(o, buf,e.namesize); o+=e.namesize; buf[e.namesize] = '\0'; /* Compare */ if (strcmp((const char*)buf,name)==0) { // Seek and readahead seek_if_needed(BE32(e.offset) + fsstart); return SmallFSFile(BE32(e.offset) + fsstart, BE32(e.size)); } } // Reset offset. offset=(unsigned)-1; return SmallFSFile(); } int SmallFSFile::read(void *buf, int s) { if (!valid()) return -1; if (seekpos==filesize) return 0; /* EOF */ if (s + seekpos > filesize) { s = filesize-seekpos; } SmallFS.read(seekpos + flashoffset, buf,s); seekpos+=s; return s; } void *SmallFSFile::readIntoMemory() { void *ret = malloc( getSize() ); if (NULL==ret) return NULL; read(ret, getSize()); return ret; } int SmallFSFile::readCallback(int s, void (*callback)(unsigned char, void*), void *data) { unsigned char c; int save_s; if (!valid()) return -1; if (seekpos==filesize) return 0; /* EOF */ if (s + seekpos > filesize) { s = filesize-seekpos; } #ifdef SMALLFSDEBUG Serial.print("Will read "); Serial.print(s); Serial.print(" bytes from file at offset "); Serial.print(flashoffset); Serial.print(" seekpos is "); Serial.println(seekpos); #endif //SmallFS.spi_enable(); //SmallFS.startread( seekpos + flashoffset ); save_s = s; unsigned tpos = seekpos + flashoffset; seekpos += s; while (s--) { c=SmallFS.readByte(tpos++); callback(c,data); } return save_s; } void SmallFSFile::seek(int pos, int whence) { int newpos; if (whence==SEEK_SET) newpos = pos; else if (whence==SEEK_CUR) newpos = seekpos + pos; else newpos = filesize + pos; if (newpos>filesize) newpos=filesize; if (newpos<0) newpos=0; seekpos=newpos; SmallFS.seek(seekpos + flashoffset); } void SmallFS_class::loadSketch(const char *name) { unsigned *lc = (unsigned*)0x38; void (*load_sketch)(unsigned offset, unsigned size); if (!can_load_sketches) return; SmallFSFile f = open(name); if (f.valid()) { load_sketch = ( void(*)(unsigned,unsigned) )*lc; #ifdef SMALLFSDEBUG Serial.print("Loading sketch at "); Serial.print(f.getOffset()); Serial.print(" size "); Serial.println(f.getSize()); #endif load_sketch(f.getOffset(), f.getSize()); } } SmallFS_class SmallFS; bool SmallFS_class::can_load_sketches = 0; struct smallfs_header SmallFS_class::hdr; unsigned SmallFS_class::fsstart=0; unsigned SmallFS_class::offset=0; #ifdef HAVE_ZFDEVICE /* ZPUino File Device support */ static void *zf_smallfs_open(const char *path) { SmallFSFile f = SmallFS.open(path); if (f.valid()) { return new SmallFSFile(f); } return NULL; } static ssize_t zf_smallfs_read(void *ptr, void *dest, size_t size) { SmallFSFile *f = static_cast<SmallFSFile*>(ptr); return f->read(dest, size); } static struct zfops zf_smallfs_ops = { &zf_smallfs_open, NULL, &zf_smallfs_read, NULL, NULL, }; void zf_register_smallfs() { zfRegisterFileBackend("smallfs", &zf_smallfs_ops); } #endif <commit_msg>Implement lseek()<commit_after>#include "SmallFS.h" #include <string.h> #ifdef __linux__ #include <fcntl.h> #include <unistd.h> #include <endian.h> #include <stdio.h> #include <strings.h> #define BE32(x) be32toh(x) #else #include "Arduino.h" #include "zfdevice.h" #define BE32(x) x #endif #undef SMALLFSDEBUG #ifdef HAVE_ZFDEVICE static void zf_register_smallfs(); #endif int SmallFS_class::begin() { #ifdef __linux__ fsstart = 0; fd = ::open("smallfs.dat",O_RDONLY); if (fd<0) { perror("Cannot open smallfs.dat"); return -1; } #else struct boot_t *b = (struct boot_t*)bootloaderdata; fsstart = b->spiend; /* Check for >1.9 bootloader */ if (b->signature==0xb00110ad ) { can_load_sketches=1; } #endif offset = 0xffffffff; read(fsstart, &hdr,sizeof(hdr)); #ifdef SMALLFSDEBUG unsigned debug; Serial.print("Read magic "); Serial.println(hdr.magic); Serial.print("SPI end "); Serial.println(fsstart); Serial.print("Bdata at "); Serial.println((unsigned)b); // Test read read(fsstart - 8, &debug,sizeof(debug)); Serial.print("DD1 "); Serial.println(debug); read(&debug,sizeof(debug)); Serial.print("DD2 "); Serial.println(debug); read(&debug,sizeof(debug)); Serial.print("DD3 "); Serial.println(debug); #endif /* if(SMALLFS_MAGIC==BE32(hdr.magic)) return 0; return -1; */ #ifdef HAVE_ZFDEVICE zf_register_smallfs(); #endif return hdr.magic - SMALLFS_MAGIC; } void SmallFS_class::seek_if_needed(unsigned address) { register_t spibasedata=&SPIDATA; if (address!=offset) { offset = address; spi_disable(); spi_enable(); #ifdef SMALLFSDEBUG Serial.print("Seeking to "); Serial.println(address); #endif /* spiwrite(spibasedata,0x0B); spiwrite(spibasedata,address>>16); spiwrite(spibasedata,address>>8); spiwrite(spibasedata,address); spiwrite(spibasedata,0); spiwrite(spibasedata,0); // Read ahead */ address+=0x0B000000; spiwrite(spibasedata+2,address>>16); /* 16-bit write */ address<<=16; spiwrite(spibasedata+6,address); /* 32-bit Includes read-ahead */ } } unsigned SmallFS_class::readByte(unsigned address) { seek_if_needed(address); unsigned v = spiread(); // Already cached spiwrite(0); offset++; return v; } void SmallFS_class::read(unsigned address, void *target, unsigned size) { #ifdef __linux__ if (fd>=0) { ::read(fd,target,size); } #else seek_if_needed(address); unsigned char *p=(unsigned char*)target; while (size--) { unsigned v = spiread(); // Already cached spiwrite(0); *p++=v; offset++; } #endif } SmallFSEntry SmallFS_class::getFirstEntry() { unsigned o = fsstart + sizeof(struct smallfs_header); if (BE32(hdr.numfiles)==0) return SmallFSEntry(); return SmallFSEntry(o,0); } bool SmallFSEntry::hasNext() const { return (m_index+1)<SmallFS_class::getCount(); } bool SmallFSEntry::equals(const char *name){ struct smallfs_entry e; char buf[256]; SmallFS_class::read(m_offset, &e,sizeof(struct smallfs_entry)); SmallFS_class::read( m_offset + sizeof(struct smallfs_entry), buf, e.namesize); buf[e.namesize] = '\0'; return (strcmp(name,buf)==0); } bool SmallFSEntry::endsWith(const char *name) { struct smallfs_entry e; char buf[256]; SmallFS_class::read(m_offset, &e,sizeof(struct smallfs_entry)); SmallFS_class::read( m_offset + sizeof(struct smallfs_entry), buf, e.namesize); buf[e.namesize] = '\0'; unsigned l = strlen(name); if (l>e.namesize) return false; char *p = buf + e.namesize - l; return (strcmp(name,p)==0); } void SmallFSEntry::getName(char *name) { struct smallfs_entry e; SmallFS_class::read( m_offset, &e,sizeof(struct smallfs_entry)); SmallFS_class::read( m_offset + sizeof(struct smallfs_entry), name, e.namesize); name[e.namesize] = '\0'; } bool SmallFSEntry::startsWith(const char *name) { struct smallfs_entry e; char buf[256]; SmallFS_class::read( m_offset, &e,sizeof(struct smallfs_entry)); SmallFS_class::read( m_offset + sizeof(struct smallfs_entry), buf, e.namesize); buf[e.namesize] = '\0'; return (strncmp(name,buf,strlen(name))==0); } SmallFSFile SmallFSEntry::open() { return SmallFS_class::openByOffset(m_offset); }; SmallFSEntry &SmallFSEntry::operator++(int) { if (hasNext()) { struct smallfs_entry e; m_index++; /* Recompute offset */ SmallFS_class::read(m_offset, &e,sizeof(struct smallfs_entry)); m_offset+=sizeof(struct smallfs_entry); m_offset+=e.namesize; } return *this; } SmallFSFile SmallFS_class::openByOffset(unsigned offset) { struct smallfs_entry e; read(offset, &e,sizeof(struct smallfs_entry)); seek_if_needed(BE32(e.offset) + fsstart); return SmallFSFile(BE32(e.offset) + fsstart, BE32(e.size)); } SmallFSFile SmallFS_class::open(const char *name) { /* Start at root offset */ unsigned o = fsstart + sizeof(struct smallfs_header); unsigned char buf[256]; struct smallfs_entry e; int c; for (c=BE32(hdr.numfiles); c; c--) { read(o, &e,sizeof(struct smallfs_entry)); o+=sizeof(struct smallfs_entry); read(o, buf,e.namesize); o+=e.namesize; buf[e.namesize] = '\0'; /* Compare */ if (strcmp((const char*)buf,name)==0) { // Seek and readahead seek_if_needed(BE32(e.offset) + fsstart); return SmallFSFile(BE32(e.offset) + fsstart, BE32(e.size)); } } // Reset offset. offset=(unsigned)-1; return SmallFSFile(); } int SmallFSFile::read(void *buf, int s) { if (!valid()) return -1; if (seekpos==filesize) return 0; /* EOF */ if (s + seekpos > filesize) { s = filesize-seekpos; } SmallFS.read(seekpos + flashoffset, buf,s); seekpos+=s; return s; } void *SmallFSFile::readIntoMemory() { void *ret = malloc( getSize() ); if (NULL==ret) return NULL; read(ret, getSize()); return ret; } int SmallFSFile::readCallback(int s, void (*callback)(unsigned char, void*), void *data) { unsigned char c; int save_s; if (!valid()) return -1; if (seekpos==filesize) return 0; /* EOF */ if (s + seekpos > filesize) { s = filesize-seekpos; } #ifdef SMALLFSDEBUG Serial.print("Will read "); Serial.print(s); Serial.print(" bytes from file at offset "); Serial.print(flashoffset); Serial.print(" seekpos is "); Serial.println(seekpos); #endif //SmallFS.spi_enable(); //SmallFS.startread( seekpos + flashoffset ); save_s = s; unsigned tpos = seekpos + flashoffset; seekpos += s; while (s--) { c=SmallFS.readByte(tpos++); callback(c,data); } return save_s; } void SmallFSFile::seek(int pos, int whence) { int newpos; if (whence==SEEK_SET) newpos = pos; else if (whence==SEEK_CUR) newpos = seekpos + pos; else newpos = filesize + pos; if (newpos>filesize) newpos=filesize; if (newpos<0) newpos=0; seekpos=newpos; SmallFS.seek(seekpos + flashoffset); } void SmallFS_class::loadSketch(const char *name) { unsigned *lc = (unsigned*)0x38; void (*load_sketch)(unsigned offset, unsigned size); if (!can_load_sketches) return; SmallFSFile f = open(name); if (f.valid()) { load_sketch = ( void(*)(unsigned,unsigned) )*lc; #ifdef SMALLFSDEBUG Serial.print("Loading sketch at "); Serial.print(f.getOffset()); Serial.print(" size "); Serial.println(f.getSize()); #endif load_sketch(f.getOffset(), f.getSize()); } } SmallFS_class SmallFS; bool SmallFS_class::can_load_sketches = 0; struct smallfs_header SmallFS_class::hdr; unsigned SmallFS_class::fsstart=0; unsigned SmallFS_class::offset=0; #ifdef HAVE_ZFDEVICE /* ZPUino File Device support */ static void *zf_smallfs_open(const char *path) { SmallFSFile f = SmallFS.open(path); if (f.valid()) { return new SmallFSFile(f); } return NULL; } static ssize_t zf_smallfs_read(void *ptr, void *dest, size_t size) { SmallFSFile *f = static_cast<SmallFSFile*>(ptr); return f->read(dest, size); } static ssize_t zf_smallfs_seek(void *ptr, int pos, int whence) { SmallFSFile *f = static_cast<SmallFSFile*>(ptr); return f->seek(pos, whence); } static struct zfops zf_smallfs_ops = { &zf_smallfs_open, NULL, &zf_smallfs_read, NULL, &zf_smallfs_seek, NULL }; void zf_register_smallfs() { zfRegisterFileBackend("smallfs", &zf_smallfs_ops); } #endif <|endoftext|>
<commit_before>#include"j1Collision.h" #include"j1App.h" #include"j1Player.h" #include"j1Render.h" j1Collision::j1Collision() { //for (uint i = 0; i < colliders.size(); ++i) //colliders[i] = nullptr; matrix[collider_link][collider_zelda] = true; matrix[collider_zelda][collider_link] = true; matrix[collider_button][collider_link] = true; matrix[collider_link][collider_button] = true; matrix[collider_link][collider_change_height] = true; matrix[collider_change_height][collider_link] = true; matrix[collider_zelda][collider_change_height] = true; matrix[collider_change_height][collider_zelda] = true; } // Destructor j1Collision::~j1Collision() {} bool j1Collision::Start() { // CHANGE THIS /*matrix_colliders.push_back(App->player->Link->allow_collision); matrix_colliders.push_back(App->player->Zelda->allow_collision); matrix_colliders.push_back(App->player->Zelda->allow_collision); matrix_colliders.push_back(App->player->Zelda->allow_collision); matrix_colliders.push_back(App->player->Zelda->allow_collision); matrix_colliders.push_back(App->player->Zelda->allow_collision);*/ return true; } bool j1Collision::PreUpdate() { // Remove all colliders scheduled for deletion for (uint i = 0; i < colliders.size(); ++i) { if (colliders[i] != nullptr && colliders[i]->to_delete == true) { delete colliders[i]; colliders[i] = nullptr; } } return true; } // Called before render is available bool j1Collision::Update(float dt) { Collider* c1; Collider* c2; for (uint i = 0; i < MAX_COLLIDERS; ++i) { // skip empty colliders if (colliders[i] == nullptr) continue; c1 = colliders[i]; // avoid checking collisions already checked for (uint k = i + 1; k < colliders.size(); ++k) { // skip empty colliders if (colliders[k] == nullptr) continue; c2 = colliders[k]; if (c1->CheckCollision(c2->rect) == true) { if (matrix[c1->type][c2->type] && c1->callback) { c1->callback->OnCollision(c1, c2); //App->render->Blit(App->player->graphics, App->player->PreviousPos.x, App->player->PreviousPos.y-1, &(App->player->current_animation->GetCurrentFrame())); } if (matrix[c2->type][c1->type] && c2->callback) { c2->callback->OnCollision(c2, c1); } } } } DebugDraw(); return true; } void j1Collision::DebugDraw() { if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) debug = !debug; if (debug == false) return; Uint8 alpha = 80; for (uint i = 0; i < colliders.size(); ++i) { if (colliders[i] == nullptr) continue; switch (colliders[i]->type) { case collider_link: // green App->render->DrawQuad(colliders[i]->rect, 12, 198, 0, alpha); break; case collider_zelda: // pink App->render->DrawQuad(colliders[i]->rect, 245, 25, 219, alpha); break; case collider_chest: App->render->DrawQuad(colliders[i]->rect, 255, 255, 255, 255); break; case collider_button: App->render->DrawQuad(colliders[i]->rect, 150, 65, 255, 255); break; } } } // Called before quitting bool j1Collision::CleanUp() { LOG("Freeing all colliders"); for (uint i = 0; i < colliders.size(); ++i) { if (colliders[i] != nullptr) { delete colliders[i]; colliders[i] = nullptr; } } return true; } Collider* j1Collision::AddCollider(SDL_Rect rect, COLLIDER_TYPE type,Entity* parent, j1Module* callback) { Collider* ret = nullptr; ret = new Collider(rect, type, parent, callback); colliders.push_back(ret); return ret; } bool j1Collision::EraseCollider(Collider* collider) { if (collider != nullptr) { // we still search for it in case we received a dangling pointer for (uint i = 0; i < colliders.size(); ++i) { if (colliders[i] == collider) { collider->to_delete = true; break; } } } return false; } // ----------------------------------------------------- bool Collider::CheckCollision(const SDL_Rect& r) const { return (rect.x < r.x + r.w && rect.x + rect.w > r.x && rect.y < r.y + r.h && rect.h + rect.y > r.y); }<commit_msg>Draw quad added<commit_after>#include"j1Collision.h" #include"j1App.h" #include"j1Player.h" #include"j1Render.h" j1Collision::j1Collision() { //for (uint i = 0; i < colliders.size(); ++i) //colliders[i] = nullptr; matrix[collider_link][collider_zelda] = true; matrix[collider_zelda][collider_link] = true; matrix[collider_button][collider_link] = true; matrix[collider_link][collider_button] = true; matrix[collider_link][collider_change_height] = true; matrix[collider_change_height][collider_link] = true; matrix[collider_zelda][collider_change_height] = true; matrix[collider_change_height][collider_zelda] = true; } // Destructor j1Collision::~j1Collision() {} bool j1Collision::Start() { return true; } bool j1Collision::PreUpdate() { // Remove all colliders scheduled for deletion for (uint i = 0; i < colliders.size(); ++i) { if (colliders[i] != nullptr && colliders[i]->to_delete == true) { delete colliders[i]; colliders[i] = nullptr; } } return true; } // Called before render is available bool j1Collision::Update(float dt) { Collider* c1; Collider* c2; for (uint i = 0; i < MAX_COLLIDERS; ++i) { // skip empty colliders if (colliders[i] == nullptr) continue; c1 = colliders[i]; // avoid checking collisions already checked for (uint k = i + 1; k < colliders.size(); ++k) { // skip empty colliders if (colliders[k] == nullptr) continue; c2 = colliders[k]; if (c1->CheckCollision(c2->rect) == true) { if (matrix[c1->type][c2->type] && c1->callback) { c1->callback->OnCollision(c1, c2); //App->render->Blit(App->player->graphics, App->player->PreviousPos.x, App->player->PreviousPos.y-1, &(App->player->current_animation->GetCurrentFrame())); } if (matrix[c2->type][c1->type] && c2->callback) { c2->callback->OnCollision(c2, c1); } } } } DebugDraw(); return true; } void j1Collision::DebugDraw() { if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN) debug = !debug; if (debug == false) return; Uint8 alpha = 80; for (uint i = 0; i < colliders.size(); ++i) { if (colliders[i] == nullptr) continue; switch (colliders[i]->type) { case collider_link: // green App->render->DrawQuad(colliders[i]->rect, 12, 198, 0, alpha); break; case collider_zelda: // pink App->render->DrawQuad(colliders[i]->rect, 245, 25, 219, alpha); break; case collider_chest: App->render->DrawQuad(colliders[i]->rect, 255, 255, 255, 255); break; case collider_button: App->render->DrawQuad(colliders[i]->rect, 150, 65, 255, 255); break; case collider_change_height: App->render->DrawQuad(colliders[i]->rect, 255, 255, 255, 255); break; } } } // Called before quitting bool j1Collision::CleanUp() { LOG("Freeing all colliders"); for (uint i = 0; i < colliders.size(); ++i) { if (colliders[i] != nullptr) { delete colliders[i]; colliders[i] = nullptr; } } return true; } Collider* j1Collision::AddCollider(SDL_Rect rect, COLLIDER_TYPE type,Entity* parent, j1Module* callback) { Collider* ret = nullptr; ret = new Collider(rect, type, parent, callback); colliders.push_back(ret); return ret; } bool j1Collision::EraseCollider(Collider* collider) { if (collider != nullptr) { // we still search for it in case we received a dangling pointer for (uint i = 0; i < colliders.size(); ++i) { if (colliders[i] == collider) { collider->to_delete = true; break; } } } return false; } // ----------------------------------------------------- bool Collider::CheckCollision(const SDL_Rect& r) const { return (rect.x < r.x + r.w && rect.x + rect.w > r.x && rect.y < r.y + r.h && rect.h + rect.y > r.y); }<|endoftext|>
<commit_before>/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/probe/CoreProbes.h" #include "bindings/core/v8/V8BindingForCore.h" #include "core/CoreProbeSink.h" #include "core/events/Event.h" #include "core/events/EventTarget.h" #include "core/inspector/InspectorCSSAgent.h" #include "core/inspector/InspectorDOMDebuggerAgent.h" #include "core/inspector/InspectorNetworkAgent.h" #include "core/inspector/InspectorPageAgent.h" #include "core/inspector/InspectorSession.h" #include "core/inspector/InspectorTraceEvents.h" #include "core/inspector/MainThreadDebugger.h" #include "core/inspector/ThreadDebugger.h" #include "core/page/Page.h" #include "core/workers/WorkerGlobalScope.h" #include "platform/instrumentation/tracing/TraceEvent.h" #include "platform/loader/fetch/FetchInitiatorInfo.h" namespace blink { namespace probe { void ctxDesc( ExecutionContext *c, char *b ) { b[ 0 ] = c->IsDocument() ? 'A' : 'a'; b[ 1 ] = c->IsWorkerOrWorkletGlobalScope() ? 'B' : 'b'; b[ 2 ] = c->IsWorkerGlobalScope() ? 'C' : 'c'; b[ 3 ] = c->IsWorkletGlobalScope() ? 'D' : 'd'; b[ 4 ] = c->IsMainThreadWorkletGlobalScope() ? 'E' : 'e'; b[ 5 ] = c->IsDedicatedWorkerGlobalScope() ? 'F' : 'f'; b[ 6 ] = c->IsSharedWorkerGlobalScope() ? 'G' : 'g'; b[ 7 ] = c->IsServiceWorkerGlobalScope() ? 'H' : 'h'; b[ 8 ] = c->IsCompositorWorkerGlobalScope() ? 'I' : 'i'; b[ 9 ] = c->IsAnimationWorkletGlobalScope() ? 'J' : 'j'; b[ 10 ] = c->IsAudioWorkletGlobalScope() ? 'K' : 'k'; b[ 11 ] = c->IsPaintWorkletGlobalScope() ? 'L' : 'l'; b[ 12 ] = c->IsThreadedWorkletGlobalScope() ? 'M' : 'm'; b[ 13 ] = c->IsJSExecutionForbidden() ? 'N' : 'n'; b[ 14 ] = c->IsContextThread() ? 'O' : 'o'; b[ 15 ] = 0; } // printf -> fprintf // - fopen // - temp names // - process id in the file name // more info // chrome extension for start/stop // timestamp FILE * file_hack( void ) { static FILE * f = NULL; static pid = 0; if( !f || pid != getpid() ) { f = fopen( "/tmp/blah.txt", "w" ); } return f; } AsyncTask::AsyncTask(ExecutionContext* context, void* task, const char* step, bool enabled) : debugger_(enabled ? ThreadDebugger::From(ToIsolate(context)) : nullptr), task_(task), recurring_(step) { if (recurring_) { TRACE_EVENT_FLOW_STEP0("devtools.timeline.async", "AsyncTask", TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task)), step ? step : ""); } else { TRACE_EVENT_FLOW_END0("devtools.timeline.async", "AsyncTask", TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task))); } char d[ 16 ]; ctxDesc( context, d ); printf( "{ \"micro\": 0, \"phase\": 2, \"ctx\": \"%s\", \"task_ptr\": %p, \"ctx_ptr\": %p, " "\"step\": \"%s\" }\n", d, task, context, step ? step : "" ); if (debugger_) debugger_->AsyncTaskStarted(task_); } AsyncTask::~AsyncTask() { printf( "{ \"micro\": 0, \"phase\": 3, \"task_ptr\": %p, \"recurring\": %s }\n", task_, recurring_ ? "yes" : "no" ); if( !recurring_ ) printf( "{ \"micro\": 0, \"phase\": 3, \"task_ptr\": %p }\n", task_ ); if (debugger_) { debugger_->AsyncTaskFinished(task_); if (!recurring_) debugger_->AsyncTaskCanceled(task_); } } void AsyncTaskScheduled(ExecutionContext* context, const String& name, void* task) { TRACE_EVENT_FLOW_BEGIN1("devtools.timeline.async", "AsyncTask", TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task)), "data", InspectorAsyncTask::Data(name)); if (ThreadDebugger* debugger = ThreadDebugger::From(ToIsolate(context))) debugger->AsyncTaskScheduled(name, task, true); } void AsyncTaskScheduledBreakable(ExecutionContext* context, const char* name, void* task) { AsyncTaskScheduled(context, name, task); breakableLocation(context, name); } void AsyncTaskCanceled(ExecutionContext* context, void* task) { if (ThreadDebugger* debugger = ThreadDebugger::From(ToIsolate(context))) debugger->AsyncTaskCanceled(task); TRACE_EVENT_FLOW_END0("devtools.timeline.async", "AsyncTask", TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task))); } void AsyncTaskCanceledBreakable(ExecutionContext* context, const char* name, void* task) { AsyncTaskCanceled(context, task); breakableLocation(context, name); } void AllAsyncTasksCanceled(ExecutionContext* context) { if (ThreadDebugger* debugger = ThreadDebugger::From(ToIsolate(context))) debugger->AllAsyncTasksCanceled(); } void DidReceiveResourceResponseButCanceled(LocalFrame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, Resource* resource) { didReceiveResourceResponse(frame->GetDocument(), identifier, loader, r, resource); } void CanceledAfterReceivedResourceResponse(LocalFrame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, Resource* resource) { DidReceiveResourceResponseButCanceled(frame, loader, identifier, r, resource); } void ContinueWithPolicyIgnore(LocalFrame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, Resource* resource) { DidReceiveResourceResponseButCanceled(frame, loader, identifier, r, resource); } } // namespace probe } // namespace blink <commit_msg>static<commit_after>/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/probe/CoreProbes.h" #include "bindings/core/v8/V8BindingForCore.h" #include "core/CoreProbeSink.h" #include "core/events/Event.h" #include "core/events/EventTarget.h" #include "core/inspector/InspectorCSSAgent.h" #include "core/inspector/InspectorDOMDebuggerAgent.h" #include "core/inspector/InspectorNetworkAgent.h" #include "core/inspector/InspectorPageAgent.h" #include "core/inspector/InspectorSession.h" #include "core/inspector/InspectorTraceEvents.h" #include "core/inspector/MainThreadDebugger.h" #include "core/inspector/ThreadDebugger.h" #include "core/page/Page.h" #include "core/workers/WorkerGlobalScope.h" #include "platform/instrumentation/tracing/TraceEvent.h" #include "platform/loader/fetch/FetchInitiatorInfo.h" namespace blink { namespace probe { void ctxDesc( ExecutionContext *c, char *b ) { b[ 0 ] = c->IsDocument() ? 'A' : 'a'; b[ 1 ] = c->IsWorkerOrWorkletGlobalScope() ? 'B' : 'b'; b[ 2 ] = c->IsWorkerGlobalScope() ? 'C' : 'c'; b[ 3 ] = c->IsWorkletGlobalScope() ? 'D' : 'd'; b[ 4 ] = c->IsMainThreadWorkletGlobalScope() ? 'E' : 'e'; b[ 5 ] = c->IsDedicatedWorkerGlobalScope() ? 'F' : 'f'; b[ 6 ] = c->IsSharedWorkerGlobalScope() ? 'G' : 'g'; b[ 7 ] = c->IsServiceWorkerGlobalScope() ? 'H' : 'h'; b[ 8 ] = c->IsCompositorWorkerGlobalScope() ? 'I' : 'i'; b[ 9 ] = c->IsAnimationWorkletGlobalScope() ? 'J' : 'j'; b[ 10 ] = c->IsAudioWorkletGlobalScope() ? 'K' : 'k'; b[ 11 ] = c->IsPaintWorkletGlobalScope() ? 'L' : 'l'; b[ 12 ] = c->IsThreadedWorkletGlobalScope() ? 'M' : 'm'; b[ 13 ] = c->IsJSExecutionForbidden() ? 'N' : 'n'; b[ 14 ] = c->IsContextThread() ? 'O' : 'o'; b[ 15 ] = 0; } // printf -> fprintf // - fopen // - temp names // - process id in the file name // more info // chrome extension for start/stop // timestamp FILE * file_hack( void ) { static FILE * f = NULL; static pid_t pid = 0; if( !f || pid != getpid() ) { pid = getpid(); /* include pid in file name */ f = fopen( "/tmp/blah.txt", "w" ); } return f; } AsyncTask::AsyncTask(ExecutionContext* context, void* task, const char* step, bool enabled) : debugger_(enabled ? ThreadDebugger::From(ToIsolate(context)) : nullptr), task_(task), recurring_(step) { if (recurring_) { TRACE_EVENT_FLOW_STEP0("devtools.timeline.async", "AsyncTask", TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task)), step ? step : ""); } else { TRACE_EVENT_FLOW_END0("devtools.timeline.async", "AsyncTask", TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task))); } char d[ 16 ]; ctxDesc( context, d ); printf( "{ \"micro\": 0, \"phase\": 2, \"ctx\": \"%s\", \"task_ptr\": %p, \"ctx_ptr\": %p, " "\"step\": \"%s\" }\n", d, task, context, step ? step : "" ); if (debugger_) debugger_->AsyncTaskStarted(task_); } AsyncTask::~AsyncTask() { printf( "{ \"micro\": 0, \"phase\": 3, \"task_ptr\": %p, \"recurring\": %s }\n", task_, recurring_ ? "yes" : "no" ); if( !recurring_ ) printf( "{ \"micro\": 0, \"phase\": 3, \"task_ptr\": %p }\n", task_ ); if (debugger_) { debugger_->AsyncTaskFinished(task_); if (!recurring_) debugger_->AsyncTaskCanceled(task_); } } void AsyncTaskScheduled(ExecutionContext* context, const String& name, void* task) { TRACE_EVENT_FLOW_BEGIN1("devtools.timeline.async", "AsyncTask", TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task)), "data", InspectorAsyncTask::Data(name)); if (ThreadDebugger* debugger = ThreadDebugger::From(ToIsolate(context))) debugger->AsyncTaskScheduled(name, task, true); } void AsyncTaskScheduledBreakable(ExecutionContext* context, const char* name, void* task) { AsyncTaskScheduled(context, name, task); breakableLocation(context, name); } void AsyncTaskCanceled(ExecutionContext* context, void* task) { if (ThreadDebugger* debugger = ThreadDebugger::From(ToIsolate(context))) debugger->AsyncTaskCanceled(task); TRACE_EVENT_FLOW_END0("devtools.timeline.async", "AsyncTask", TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task))); } void AsyncTaskCanceledBreakable(ExecutionContext* context, const char* name, void* task) { AsyncTaskCanceled(context, task); breakableLocation(context, name); } void AllAsyncTasksCanceled(ExecutionContext* context) { if (ThreadDebugger* debugger = ThreadDebugger::From(ToIsolate(context))) debugger->AllAsyncTasksCanceled(); } void DidReceiveResourceResponseButCanceled(LocalFrame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, Resource* resource) { didReceiveResourceResponse(frame->GetDocument(), identifier, loader, r, resource); } void CanceledAfterReceivedResourceResponse(LocalFrame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, Resource* resource) { DidReceiveResourceResponseButCanceled(frame, loader, identifier, r, resource); } void ContinueWithPolicyIgnore(LocalFrame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, Resource* resource) { DidReceiveResourceResponseButCanceled(frame, loader, identifier, r, resource); } } // namespace probe } // namespace blink <|endoftext|>
<commit_before>/*! Registry Settings Handler Copyright 2012 Astea Solutions AD Licensed under the New BSD license. You may not use this file except in compliance with this License. You may obtain a copy of the License at https://github.com/gpii/windows/LICENSE.txt */ #include <Windows.h> #include <iostream> #include <exception> #include "json/json.h" using namespace std; HKEY hKeyFromString(string input) { //TODO Cover all possible HKEY values if ("HKEY_LOCAL_MACHINE" == input) return HKEY_LOCAL_MACHINE; else if ("HKEY_CURRENT_USER" == input) return HKEY_CURRENT_USER; else return NULL; } long getDwordValue (HKEY hKey, LPCWSTR path, LPCWSTR valueName) { HKEY resKey; DWORD valueData; DWORD bufferSize(sizeof(DWORD)); long codeOpen = RegOpenKeyExW(hKey, path, 0, KEY_QUERY_VALUE, &resKey); if (codeOpen != ERROR_SUCCESS) { throw 500; } long returnCode = RegQueryValueExW(resKey, valueName, NULL, NULL, (LPBYTE)&valueData, &bufferSize); RegCloseKey(hKey); if (returnCode == ERROR_SUCCESS) { return valueData; } else { throw 404; } } bool setDwordValue(HKEY hKey, LPCWSTR path, LPCWSTR valueName, DWORD valueData) { HKEY resKey; RegCreateKeyExW(hKey, path, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &resKey, NULL); DWORD bufferSize(sizeof(DWORD)); long returnCode = RegSetValueExW(resKey, valueName, 0, REG_DWORD, (const BYTE*)&valueData, bufferSize); RegCloseKey(hKey); // TODO Gracefully handle errors in setting a registry value. return (returnCode == ERROR_SUCCESS); } bool parseJson(const string jsonString, Json::Value &rootElement) { Json::Reader reader; return reader.parse(jsonString, rootElement); // TODO Gracefully handle JSON parsing errors. } wstring toWideChar(const char * str) { int length = MultiByteToWideChar(CP_UTF8, 0, str, strlen(str), 0, 0); LPWSTR wideString = SysAllocStringLen(0, length); MultiByteToWideChar(CP_UTF8, 0, str, strlen(str), wideString, length); wstring result(wideString); SysFreeString(wideString); return result; } bool updateRegistry(Json::Value &jsonRoot, Json::Value &outputRoot) { bool success = true; for (Json::ValueIterator iter = jsonRoot.begin(); iter != jsonRoot.end(); iter++) { Json::Value solutionsRoot = jsonRoot.get(iter.memberName(), Json::Value()); Json::Value solutionsOutput; for(Json::ValueIterator itr = solutionsRoot["settings"].begin() ; itr != solutionsRoot["settings"].end() ; itr++ ) { bool missingValue = false; Json::Value currentOption; const char * path = solutionsRoot["options"]["path"].asCString(); const char * valueName = itr.memberName(); long valueToSet = solutionsRoot["settings"][valueName].asUInt(); wstring updatedPath = toWideChar(path); wstring updatedValueName = toWideChar(valueName); long value = -1; try { value = getDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str()); } catch (int exCode) { currentOption["statusCode"] = exCode; currentOption["oldValue"] = Json::Value(); currentOption["newValue"] = Json::Value(); success = false; missingValue = true; } bool valueSet = setDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str(), valueToSet); if (missingValue) { currentOption["oldValue"] = Json::Value(); } else { currentOption["oldValue"] = value; } try { currentOption["newValue"] = getDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str()); } catch (int exceptionCode) { // TODO Handle gracefully. } if (!valueSet) { success = false; currentOption["newValue"] = value; } solutionsOutput[valueName] = currentOption; } outputRoot[iter.memberName()]["results"] = solutionsOutput; } return success; } int main (int argc, char *argv[]) { // argv[1] - json model if (argc < 2) { cout << "Missing argument. Usage: RegistrySettingsHandler <JsonModel>."; } Json::Value root, optionsRoot, output; parseJson(argv[1], root); bool updateSuccessful = updateRegistry(root, output); cout << root; cout << output; system("Pause"); return !updateSuccessful; }<commit_msg>Removing debug lines to allow integration as node.js plug-in.<commit_after>/*! Registry Settings Handler Copyright 2012 Astea Solutions AD Licensed under the New BSD license. You may not use this file except in compliance with this License. You may obtain a copy of the License at https://github.com/gpii/windows/LICENSE.txt */ #include <Windows.h> #include <iostream> #include <exception> #include "json/json.h" using namespace std; HKEY hKeyFromString(string input) { //TODO Cover all possible HKEY values if ("HKEY_LOCAL_MACHINE" == input) return HKEY_LOCAL_MACHINE; else if ("HKEY_CURRENT_USER" == input) return HKEY_CURRENT_USER; else return NULL; } long getDwordValue (HKEY hKey, LPCWSTR path, LPCWSTR valueName) { HKEY resKey; DWORD valueData; DWORD bufferSize(sizeof(DWORD)); long codeOpen = RegOpenKeyExW(hKey, path, 0, KEY_QUERY_VALUE, &resKey); if (codeOpen != ERROR_SUCCESS) { throw 500; } long returnCode = RegQueryValueExW(resKey, valueName, NULL, NULL, (LPBYTE)&valueData, &bufferSize); RegCloseKey(hKey); if (returnCode == ERROR_SUCCESS) { return valueData; } else { throw 404; } } bool setDwordValue(HKEY hKey, LPCWSTR path, LPCWSTR valueName, DWORD valueData) { HKEY resKey; RegCreateKeyExW(hKey, path, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &resKey, NULL); DWORD bufferSize(sizeof(DWORD)); long returnCode = RegSetValueExW(resKey, valueName, 0, REG_DWORD, (const BYTE*)&valueData, bufferSize); RegCloseKey(hKey); // TODO Gracefully handle errors in setting a registry value. return (returnCode == ERROR_SUCCESS); } bool parseJson(const string jsonString, Json::Value &rootElement) { Json::Reader reader; return reader.parse(jsonString, rootElement); // TODO Gracefully handle JSON parsing errors. } wstring toWideChar(const char * str) { int length = MultiByteToWideChar(CP_UTF8, 0, str, strlen(str), 0, 0); LPWSTR wideString = SysAllocStringLen(0, length); MultiByteToWideChar(CP_UTF8, 0, str, strlen(str), wideString, length); wstring result(wideString); SysFreeString(wideString); return result; } bool updateRegistry(Json::Value &jsonRoot, Json::Value &outputRoot) { bool success = true; for (Json::ValueIterator iter = jsonRoot.begin(); iter != jsonRoot.end(); iter++) { Json::Value solutionsRoot = jsonRoot.get(iter.memberName(), Json::Value()); Json::Value solutionsOutput; for(Json::ValueIterator itr = solutionsRoot["settings"].begin() ; itr != solutionsRoot["settings"].end() ; itr++ ) { bool missingValue = false; Json::Value currentOption; const char * path = solutionsRoot["options"]["path"].asCString(); const char * valueName = itr.memberName(); long valueToSet = solutionsRoot["settings"][valueName].asUInt(); wstring updatedPath = toWideChar(path); wstring updatedValueName = toWideChar(valueName); long value = -1; try { value = getDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str()); } catch (int exCode) { currentOption["statusCode"] = exCode; currentOption["oldValue"] = Json::Value(); currentOption["newValue"] = Json::Value(); success = false; missingValue = true; } bool valueSet = setDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str(), valueToSet); if (missingValue) { currentOption["oldValue"] = Json::Value(); } else { currentOption["oldValue"] = value; } try { currentOption["newValue"] = getDwordValue(hKeyFromString(solutionsRoot["options"]["hKey"].asCString()), updatedPath.c_str(), updatedValueName.c_str()); } catch (int exceptionCode) { // TODO Handle gracefully. } if (!valueSet) { success = false; currentOption["newValue"] = value; } solutionsOutput[valueName] = currentOption; } outputRoot[iter.memberName()]["results"] = solutionsOutput; } return success; } int main (int argc, char *argv[]) { // argv[1] - json model if (argc < 2) { cout << "Missing argument. Usage: RegistrySettingsHandler <JsonModel>."; } Json::Value root, optionsRoot, output; parseJson(argv[1], root); bool updateSuccessful = updateRegistry(root, output); cout << output; return !updateSuccessful; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: breakiterator_cjk.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:00:36 $ * * 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 * ************************************************************************/ #define BREAKITERATOR_ALL #include <breakiterator_cjk.hxx> #include <i18nutil/unicode.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { // ---------------------------------------------------- // class BreakIterator_CJK // ----------------------------------------------------; BreakIterator_CJK::BreakIterator_CJK() : dict(NULL) { cBreakIterator = "com.sun.star.i18n.BreakIterator_CJK"; } Boundary SAL_CALL BreakIterator_CJK::previousWord(const OUString& text, sal_Int32 anyPos, const lang::Locale& nLocale, sal_Int16 wordType) throw(RuntimeException) { if (dict) { result = dict->previousWord(text.getStr(), anyPos, text.getLength(), wordType); // #109813# for non-CJK, single character word, fallback to ICU breakiterator. if (result.endPos - result.startPos != 1 || getScriptType(text, result.startPos) == ScriptType::ASIAN) return result; } return BreakIterator_Unicode::previousWord(text, anyPos, nLocale, wordType); } Boundary SAL_CALL BreakIterator_CJK::nextWord(const OUString& text, sal_Int32 anyPos, const lang::Locale& nLocale, sal_Int16 wordType) throw(RuntimeException) { if (dict) { result = dict->nextWord(text.getStr(), anyPos, text.getLength(), wordType); // #109813# for non-CJK, single character word, fallback to ICU breakiterator. if (result.endPos - result.startPos != 1 || getScriptType(text, result.startPos) == ScriptType::ASIAN) return result; } return BreakIterator_Unicode::nextWord(text, anyPos, nLocale, wordType); } Boundary SAL_CALL BreakIterator_CJK::getWordBoundary( const OUString& text, sal_Int32 anyPos, const lang::Locale& nLocale, sal_Int16 wordType, sal_Bool bDirection ) throw(RuntimeException) { if (dict) { result = dict->getWordBoundary(text.getStr(), anyPos, text.getLength(), wordType, bDirection); // #109813# for non-CJK, single character word, fallback to ICU breakiterator. if (result.endPos - result.startPos != 1 || getScriptType(text, result.startPos) == ScriptType::ASIAN) return result; } return BreakIterator_Unicode::getWordBoundary(text, anyPos, nLocale, wordType, bDirection); } LineBreakResults SAL_CALL BreakIterator_CJK::getLineBreak( const OUString& Text, sal_Int32 nStartPos, const lang::Locale& rLocale, sal_Int32 nMinBreakPos, const LineBreakHyphenationOptions& hOptions, const LineBreakUserOptions& bOptions ) throw(RuntimeException) { LineBreakResults lbr; if (bOptions.allowPunctuationOutsideMargin && bOptions.forbiddenBeginCharacters.indexOf(Text[nStartPos]) != -1 && ++nStartPos == Text.getLength()) { ; // do nothing } else if (bOptions.applyForbiddenRules && 0 < nStartPos && nStartPos < Text.getLength()) { while (nStartPos > 0 && (bOptions.forbiddenBeginCharacters.indexOf(Text[nStartPos]) != -1 || bOptions.forbiddenEndCharacters.indexOf(Text[nStartPos-1]) != -1)) nStartPos--; } lbr.breakIndex = nStartPos; lbr.breakType = BreakType::WORDBOUNDARY; return lbr; } // ---------------------------------------------------- // class BreakIterator_zh // ----------------------------------------------------; BreakIterator_zh::BreakIterator_zh() { dict = new xdictionary("zh"); cBreakIterator = "com.sun.star.i18n.BreakIterator_zh"; } BreakIterator_zh::~BreakIterator_zh() { delete dict; } // ---------------------------------------------------- // class BreakIterator_ja // ----------------------------------------------------; BreakIterator_ja::BreakIterator_ja() { dict = new xdictionary("ja"); dict->setJapaneseWordBreak(); cBreakIterator = "com.sun.star.i18n.BreakIterator_ja"; } BreakIterator_ja::~BreakIterator_ja() { delete dict; } // ---------------------------------------------------- // class BreakIterator_ko // ----------------------------------------------------; BreakIterator_ko::BreakIterator_ko() { cBreakIterator = "com.sun.star.i18n.BreakIterator_ko"; } BreakIterator_ko::~BreakIterator_ko() { } } } } } <commit_msg>INTEGRATION: CWS warnings01 (1.11.14); FILE MERGED 2005/11/09 20:21:53 pl 1.11.14.1: #i53898# removed warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: breakiterator_cjk.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:41:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #define BREAKITERATOR_ALL #include <breakiterator_cjk.hxx> #include <i18nutil/unicode.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::rtl; namespace com { namespace sun { namespace star { namespace i18n { // ---------------------------------------------------- // class BreakIterator_CJK // ----------------------------------------------------; BreakIterator_CJK::BreakIterator_CJK() : dict(NULL) { cBreakIterator = "com.sun.star.i18n.BreakIterator_CJK"; } Boundary SAL_CALL BreakIterator_CJK::previousWord(const OUString& text, sal_Int32 anyPos, const lang::Locale& nLocale, sal_Int16 wordType) throw(RuntimeException) { if (dict) { result = dict->previousWord(text.getStr(), anyPos, text.getLength(), wordType); // #109813# for non-CJK, single character word, fallback to ICU breakiterator. if (result.endPos - result.startPos != 1 || getScriptType(text, result.startPos) == ScriptType::ASIAN) return result; } return BreakIterator_Unicode::previousWord(text, anyPos, nLocale, wordType); } Boundary SAL_CALL BreakIterator_CJK::nextWord(const OUString& text, sal_Int32 anyPos, const lang::Locale& nLocale, sal_Int16 wordType) throw(RuntimeException) { if (dict) { result = dict->nextWord(text.getStr(), anyPos, text.getLength(), wordType); // #109813# for non-CJK, single character word, fallback to ICU breakiterator. if (result.endPos - result.startPos != 1 || getScriptType(text, result.startPos) == ScriptType::ASIAN) return result; } return BreakIterator_Unicode::nextWord(text, anyPos, nLocale, wordType); } Boundary SAL_CALL BreakIterator_CJK::getWordBoundary( const OUString& text, sal_Int32 anyPos, const lang::Locale& nLocale, sal_Int16 wordType, sal_Bool bDirection ) throw(RuntimeException) { if (dict) { result = dict->getWordBoundary(text.getStr(), anyPos, text.getLength(), wordType, bDirection); // #109813# for non-CJK, single character word, fallback to ICU breakiterator. if (result.endPos - result.startPos != 1 || getScriptType(text, result.startPos) == ScriptType::ASIAN) return result; } return BreakIterator_Unicode::getWordBoundary(text, anyPos, nLocale, wordType, bDirection); } LineBreakResults SAL_CALL BreakIterator_CJK::getLineBreak( const OUString& Text, sal_Int32 nStartPos, const lang::Locale& /*rLocale*/, sal_Int32 /*nMinBreakPos*/, const LineBreakHyphenationOptions& /*hOptions*/, const LineBreakUserOptions& bOptions ) throw(RuntimeException) { LineBreakResults lbr; if (bOptions.allowPunctuationOutsideMargin && bOptions.forbiddenBeginCharacters.indexOf(Text[nStartPos]) != -1 && ++nStartPos == Text.getLength()) { ; // do nothing } else if (bOptions.applyForbiddenRules && 0 < nStartPos && nStartPos < Text.getLength()) { while (nStartPos > 0 && (bOptions.forbiddenBeginCharacters.indexOf(Text[nStartPos]) != -1 || bOptions.forbiddenEndCharacters.indexOf(Text[nStartPos-1]) != -1)) nStartPos--; } lbr.breakIndex = nStartPos; lbr.breakType = BreakType::WORDBOUNDARY; return lbr; } // ---------------------------------------------------- // class BreakIterator_zh // ----------------------------------------------------; BreakIterator_zh::BreakIterator_zh() { dict = new xdictionary("zh"); cBreakIterator = "com.sun.star.i18n.BreakIterator_zh"; } BreakIterator_zh::~BreakIterator_zh() { delete dict; } // ---------------------------------------------------- // class BreakIterator_ja // ----------------------------------------------------; BreakIterator_ja::BreakIterator_ja() { dict = new xdictionary("ja"); dict->setJapaneseWordBreak(); cBreakIterator = "com.sun.star.i18n.BreakIterator_ja"; } BreakIterator_ja::~BreakIterator_ja() { delete dict; } // ---------------------------------------------------- // class BreakIterator_ko // ----------------------------------------------------; BreakIterator_ko::BreakIterator_ko() { cBreakIterator = "com.sun.star.i18n.BreakIterator_ko"; } BreakIterator_ko::~BreakIterator_ko() { } } } } } <|endoftext|>
<commit_before>/* * Copyright 2018-2020, INRIA */ #ifndef __eigenpy_details_rvalue_from_python_data_hpp__ #define __eigenpy_details_rvalue_from_python_data_hpp__ #include <boost/python/converter/rvalue_from_python_data.hpp> #include <Eigen/Core> namespace boost { namespace python { namespace converter { /// \brief Template specialization of rvalue_from_python_data template<typename Derived> struct rvalue_from_python_data<Eigen::MatrixBase<Derived> const & > : rvalue_from_python_storage<Derived const & > { typedef Eigen::MatrixBase<Derived> const & T; # if (!defined(__MWERKS__) || __MWERKS__ >= 0x3000) \ && (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 245) \ && (!defined(__DECCXX_VER) || __DECCXX_VER > 60590014) \ && !defined(BOOST_PYTHON_SYNOPSIS) /* Synopsis' OpenCXX has trouble parsing this */ // This must always be a POD struct with m_data its first member. BOOST_STATIC_ASSERT(BOOST_PYTHON_OFFSETOF(rvalue_from_python_storage<T>,stage1) == 0); # endif // The usual constructor rvalue_from_python_data(rvalue_from_python_stage1_data const & _stage1) { this->stage1 = _stage1; } // This constructor just sets m_convertible -- used by // implicitly_convertible<> to perform the final step of the // conversion, where the construct() function is already known. rvalue_from_python_data(void* convertible) { this->stage1.convertible = convertible; } // Destroys any object constructed in the storage. ~rvalue_from_python_data() { if (this->stage1.convertible == this->storage.bytes) static_cast<Derived *>((void *)this->storage.bytes)->~Derived(); } }; /// \brief Template specialization of rvalue_from_python_data template<typename Derived> struct rvalue_from_python_data<Eigen::EigenBase<Derived> const & > : rvalue_from_python_storage<Derived const & > { typedef Eigen::MatrixBase<Derived> const & T; # if (!defined(__MWERKS__) || __MWERKS__ >= 0x3000) \ && (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 245) \ && (!defined(__DECCXX_VER) || __DECCXX_VER > 60590014) \ && !defined(BOOST_PYTHON_SYNOPSIS) /* Synopsis' OpenCXX has trouble parsing this */ // This must always be a POD struct with m_data its first member. BOOST_STATIC_ASSERT(BOOST_PYTHON_OFFSETOF(rvalue_from_python_storage<T>,stage1) == 0); # endif // The usual constructor rvalue_from_python_data(rvalue_from_python_stage1_data const & _stage1) { this->stage1 = _stage1; } // This constructor just sets m_convertible -- used by // implicitly_convertible<> to perform the final step of the // conversion, where the construct() function is already known. rvalue_from_python_data(void* convertible) { this->stage1.convertible = convertible; } // Destroys any object constructed in the storage. ~rvalue_from_python_data() { if (this->stage1.convertible == this->storage.bytes) static_cast<Derived *>((void *)this->storage.bytes)->~Derived(); } }; } } } // namespace boost::python::converter #endif // ifndef __eigenpy_details_rvalue_from_python_data_hpp__ <commit_msg>core: fix bug<commit_after>/* * Copyright 2018-2020, INRIA */ #ifndef __eigenpy_details_rvalue_from_python_data_hpp__ #define __eigenpy_details_rvalue_from_python_data_hpp__ #include <boost/python/converter/rvalue_from_python_data.hpp> #include <Eigen/Core> namespace boost { namespace python { namespace converter { /// \brief Template specialization of rvalue_from_python_data template<typename Derived> struct rvalue_from_python_data<Eigen::MatrixBase<Derived> const & > : rvalue_from_python_storage<Derived const & > { typedef Eigen::MatrixBase<Derived> const & T; # if (!defined(__MWERKS__) || __MWERKS__ >= 0x3000) \ && (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 245) \ && (!defined(__DECCXX_VER) || __DECCXX_VER > 60590014) \ && !defined(BOOST_PYTHON_SYNOPSIS) /* Synopsis' OpenCXX has trouble parsing this */ // This must always be a POD struct with m_data its first member. BOOST_STATIC_ASSERT(BOOST_PYTHON_OFFSETOF(rvalue_from_python_storage<T>,stage1) == 0); # endif // The usual constructor rvalue_from_python_data(rvalue_from_python_stage1_data const & _stage1) { this->stage1 = _stage1; } // This constructor just sets m_convertible -- used by // implicitly_convertible<> to perform the final step of the // conversion, where the construct() function is already known. rvalue_from_python_data(void* convertible) { this->stage1.convertible = convertible; } // Destroys any object constructed in the storage. ~rvalue_from_python_data() { if (this->stage1.convertible == this->storage.bytes) static_cast<Derived *>((void *)this->storage.bytes)->~Derived(); } }; /// \brief Template specialization of rvalue_from_python_data template<typename Derived> struct rvalue_from_python_data<Eigen::EigenBase<Derived> const & > : rvalue_from_python_storage<Derived const & > { typedef Eigen::EigenBase<Derived> const & T; # if (!defined(__MWERKS__) || __MWERKS__ >= 0x3000) \ && (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 245) \ && (!defined(__DECCXX_VER) || __DECCXX_VER > 60590014) \ && !defined(BOOST_PYTHON_SYNOPSIS) /* Synopsis' OpenCXX has trouble parsing this */ // This must always be a POD struct with m_data its first member. BOOST_STATIC_ASSERT(BOOST_PYTHON_OFFSETOF(rvalue_from_python_storage<T>,stage1) == 0); # endif // The usual constructor rvalue_from_python_data(rvalue_from_python_stage1_data const & _stage1) { this->stage1 = _stage1; } // This constructor just sets m_convertible -- used by // implicitly_convertible<> to perform the final step of the // conversion, where the construct() function is already known. rvalue_from_python_data(void* convertible) { this->stage1.convertible = convertible; } // Destroys any object constructed in the storage. ~rvalue_from_python_data() { if (this->stage1.convertible == this->storage.bytes) static_cast<Derived *>((void *)this->storage.bytes)->~Derived(); } }; } } } // namespace boost::python::converter #endif // ifndef __eigenpy_details_rvalue_from_python_data_hpp__ <|endoftext|>
<commit_before>/********************************************************************** ** Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com ** Author: Sérgio Martins <sergio.martins@kdab.com> ** ** This file may be distributed and/or modified under the terms of the ** GNU Lesser General Public License version 2.1 and version 3 as published by the ** Free Software Foundation and appearing in the file LICENSE.LGPL.txt included. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. **********************************************************************/ #include "qstringuneededheapallocations.h" #include "Utils.h" #include "StringUtils.h" #include "MethodSignatureUtils.h" #include <clang/AST/DeclCXX.h> #include <clang/AST/ExprCXX.h> #include <clang/AST/Expr.h> #include <clang/Basic/Diagnostic.h> #include <clang/Rewrite/Frontend/FixItRewriter.h> #include <clang/Lex/Lexer.h> #include <iostream> using namespace clang; using namespace std; QStringUneededHeapAllocations::QStringUneededHeapAllocations(clang::CompilerInstance &ci) : CheckBase(ci) { } void QStringUneededHeapAllocations::VisitStmt(clang::Stmt *stm) { VisitCtor(stm); VisitOperatorCall(stm); VisitFromLatin1OrUtf8(stm); VisitAssignOperatorQLatin1String(stm); } std::string QStringUneededHeapAllocations::name() const { return "qstring-uneeded-heap-allocations"; } // Returns the first occurrence of a QLatin1String(char*) CTOR call static Stmt *qlatin1CtorExpr(Stmt *stm, ConditionalOperator * &ternary) { if (stm == nullptr) return nullptr; CXXConstructExpr *constructExpr = dyn_cast<CXXConstructExpr>(stm); if (constructExpr != nullptr) { CXXConstructorDecl *ctor = constructExpr->getConstructor(); if (isOfClass(ctor, "QLatin1String") && hasCharPtrArgument(ctor, 1)) { if (Utils::containsStringLiteral(constructExpr, /*allowEmpty=*/ false, 2)) return constructExpr; } } if (ternary == nullptr) { ternary = dyn_cast<ConditionalOperator>(stm); } auto it = stm->child_begin(); auto end = stm->child_end(); for (; it != end; ++it) { auto expr = qlatin1CtorExpr(*it, ternary); if (expr != nullptr) return expr; } return nullptr; } // Returns true if there's a literal in the hierarchy, but aborts if it's parented on CallExpr // so, returns true for: QLatin1String("foo") but false for QLatin1String(indirection("foo")); // static bool containsStringLiteralNoCallExpr(Stmt *stmt) { if (stmt == nullptr) return false; StringLiteral *sl = dyn_cast<StringLiteral>(stmt); if (sl != nullptr) return true; auto it = stmt->child_begin(); auto end = stmt->child_end(); for (; it != end; ++it) { if (*it == nullptr) continue; CallExpr *callExpr = dyn_cast<CallExpr>(*it); if (callExpr) continue; if (containsStringLiteralNoCallExpr(*it)) return true; } return false; } void QStringUneededHeapAllocations::VisitCtor(Stmt *stm) { CXXConstructExpr *ctorExpr = dyn_cast<CXXConstructExpr>(stm); if (!Utils::containsStringLiteral(ctorExpr, /**allowEmpty=*/ true)) return; CXXConstructorDecl *ctorDecl = ctorExpr->getConstructor(); if (!isOfClass(ctorDecl, "QString")) return; bool isQLatin1String = false; string paramType; if (hasCharPtrArgument(ctorDecl, 1)) { paramType = "const char*"; } else if (hasArgumentOfType(ctorDecl, "class QLatin1String", 1)) { paramType = "QLatin1String"; isQLatin1String = true; } else { return; } string msg = string("QString(") + paramType + string(") being called"); if (isQLatin1String) { ConditionalOperator *ternary = nullptr; Stmt *begin = qlatin1CtorExpr(stm, ternary); if (begin == nullptr) return; vector<FixItHint> fixits = ternary == nullptr ? fixItReplaceQLatin1StringWithQStringLiteral(begin) : fixItReplaceQLatin1StringWithQStringLiteralInTernary(ternary); emitWarning(stm->getLocStart(), msg, fixits); } else { emitWarning(stm->getLocStart(), msg); } } vector<FixItHint> QStringUneededHeapAllocations::fixItReplaceQLatin1StringWithQStringLiteral(clang::Stmt *begin) { vector<FixItHint> fixits; SourceLocation rangeStart = begin->getLocStart(); SourceLocation rangeEnd = Lexer::getLocForEndOfToken(rangeStart, -1, m_ci.getSourceManager(), m_ci.getLangOpts()); fixits.push_back(FixItHint::CreateReplacement(SourceRange(rangeStart, rangeEnd), "QStringLiteral")); return fixits; } vector<FixItHint> QStringUneededHeapAllocations::fixItReplaceQLatin1StringWithQStringLiteralInTernary(clang::ConditionalOperator *ternary) { vector<CXXConstructExpr*> constructExprs; Utils::getChilds2<CXXConstructExpr>(ternary, constructExprs, 1); // depth = 1, only the two immediate expressions vector<FixItHint> fixits; fixits.reserve(2); if (constructExprs.size() != 2) { llvm::errs() << "Weird ternary operator with " << constructExprs.size() << " at " << ternary->getLocStart().printToString(m_ci.getSourceManager()) << "\n"; assert(false); return fixits; } for (int i = 0; i < 2; ++i) { SourceLocation rangeStart = constructExprs[i]->getLocStart(); SourceLocation rangeEnd = Lexer::getLocForEndOfToken(rangeStart, -1, m_ci.getSourceManager(), m_ci.getLangOpts()); fixits.push_back(FixItHint::CreateReplacement(SourceRange(rangeStart, rangeEnd), "QStringLiteral")); } return fixits;} void QStringUneededHeapAllocations::VisitOperatorCall(Stmt *stm) { CXXOperatorCallExpr *operatorCall = dyn_cast<CXXOperatorCallExpr>(stm); if (operatorCall == nullptr) return; std::vector<StringLiteral*> stringLiterals; Utils::getChilds2<StringLiteral>(operatorCall, stringLiterals); // We're only after string literals, str.contains(some_method_returning_const_char_is_fine()) if (stringLiterals.empty()) return; FunctionDecl *funcDecl = operatorCall->getDirectCallee(); if (funcDecl == nullptr) return; CXXMethodDecl *methodDecl = dyn_cast<CXXMethodDecl>(funcDecl); if (!isOfClass(methodDecl, "QString")) return; if (!hasCharPtrArgument(methodDecl)) return; string msg = string("QString(const char*) being called"); emitWarning(stm->getLocStart(), msg); } void QStringUneededHeapAllocations::VisitFromLatin1OrUtf8(Stmt *stmt) { CallExpr *callExpr = dyn_cast<CallExpr>(stmt); if (callExpr == nullptr) return; FunctionDecl *functionDecl = callExpr->getDirectCallee(); if (functionDecl == nullptr) return; CXXMethodDecl *methodDecl = dyn_cast<CXXMethodDecl>(functionDecl); if (methodDecl == nullptr) return; std::string functionName = functionDecl->getNameAsString(); if (functionName != "fromLatin1" && functionName != "fromUtf8") return; if (methodDecl->getParent()->getNameAsString() != "QString") return; if (!Utils::callHasDefaultArguments(callExpr) || !hasCharPtrArgument(functionDecl, 2)) // QString::fromLatin1("foo", 1) is ok return; if (!containsStringLiteralNoCallExpr(callExpr)) return; if (functionName == "fromLatin1") { emitWarning(stmt->getLocStart(), string("QString::fromLatin1() being passed a literal")); } else { emitWarning(stmt->getLocStart(), string("QString::fromUtf8() being passed a literal")); } } void QStringUneededHeapAllocations::VisitAssignOperatorQLatin1String(Stmt *stmt) { CXXOperatorCallExpr *callExpr = dyn_cast<CXXOperatorCallExpr>(stmt); if (callExpr == nullptr) return; FunctionDecl *functionDecl = callExpr->getDirectCallee(); if (functionDecl == nullptr) return; CXXMethodDecl *methodDecl = dyn_cast<CXXMethodDecl>(functionDecl); if (!isOfClass(methodDecl, "QString") || functionDecl->getNameAsString() != "operator=" || !hasArgumentOfType(functionDecl, "class QLatin1String", 1)) return; if (!containsStringLiteralNoCallExpr(stmt)) return; ConditionalOperator *ternary = nullptr; Stmt *begin = qlatin1CtorExpr(stmt, ternary); if (begin == nullptr) return; vector<FixItHint> fixits = ternary == nullptr ? fixItReplaceQLatin1StringWithQStringLiteral(begin) : fixItReplaceQLatin1StringWithQStringLiteralInTernary(ternary); emitWarning(stmt->getLocStart(), string("QString::operator=(QLatin1String(\"literal\")"), fixits); } <commit_msg>qstring-uneeded-heap-allocations: cleanup++<commit_after>/********************************************************************** ** Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com ** Author: Sérgio Martins <sergio.martins@kdab.com> ** ** This file may be distributed and/or modified under the terms of the ** GNU Lesser General Public License version 2.1 and version 3 as published by the ** Free Software Foundation and appearing in the file LICENSE.LGPL.txt included. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. **********************************************************************/ #include "qstringuneededheapallocations.h" #include "Utils.h" #include "StringUtils.h" #include "MethodSignatureUtils.h" #include <clang/AST/DeclCXX.h> #include <clang/AST/ExprCXX.h> #include <clang/AST/Expr.h> #include <clang/Basic/Diagnostic.h> #include <clang/Rewrite/Frontend/FixItRewriter.h> #include <clang/Lex/Lexer.h> #include <iostream> using namespace clang; using namespace std; QStringUneededHeapAllocations::QStringUneededHeapAllocations(clang::CompilerInstance &ci) : CheckBase(ci) { } void QStringUneededHeapAllocations::VisitStmt(clang::Stmt *stm) { VisitCtor(stm); VisitOperatorCall(stm); VisitFromLatin1OrUtf8(stm); VisitAssignOperatorQLatin1String(stm); } std::string QStringUneededHeapAllocations::name() const { return "qstring-uneeded-heap-allocations"; } // Returns the first occurrence of a QLatin1String(char*) CTOR call static Stmt *qlatin1CtorExpr(Stmt *stm, ConditionalOperator * &ternary) { if (stm == nullptr) return nullptr; CXXConstructExpr *constructExpr = dyn_cast<CXXConstructExpr>(stm); if (constructExpr != nullptr) { CXXConstructorDecl *ctor = constructExpr->getConstructor(); if (isOfClass(ctor, "QLatin1String") && hasCharPtrArgument(ctor, 1)) { if (Utils::containsStringLiteral(constructExpr, /*allowEmpty=*/ false, 2)) return constructExpr; } } if (ternary == nullptr) { ternary = dyn_cast<ConditionalOperator>(stm); } auto it = stm->child_begin(); auto end = stm->child_end(); for (; it != end; ++it) { auto expr = qlatin1CtorExpr(*it, ternary); if (expr != nullptr) return expr; } return nullptr; } // Returns true if there's a literal in the hierarchy, but aborts if it's parented on CallExpr // so, returns true for: QLatin1String("foo") but false for QLatin1String(indirection("foo")); // static bool containsStringLiteralNoCallExpr(Stmt *stmt) { if (stmt == nullptr) return false; StringLiteral *sl = dyn_cast<StringLiteral>(stmt); if (sl != nullptr) return true; auto it = stmt->child_begin(); auto end = stmt->child_end(); for (; it != end; ++it) { if (*it == nullptr) continue; CallExpr *callExpr = dyn_cast<CallExpr>(*it); if (callExpr) continue; if (containsStringLiteralNoCallExpr(*it)) return true; } return false; } void QStringUneededHeapAllocations::VisitCtor(Stmt *stm) { CXXConstructExpr *ctorExpr = dyn_cast<CXXConstructExpr>(stm); if (!Utils::containsStringLiteral(ctorExpr, /**allowEmpty=*/ true)) return; CXXConstructorDecl *ctorDecl = ctorExpr->getConstructor(); if (!isOfClass(ctorDecl, "QString")) return; bool isQLatin1String = false; string paramType; if (hasCharPtrArgument(ctorDecl, 1)) { paramType = "const char*"; } else if (hasArgumentOfType(ctorDecl, "class QLatin1String", 1)) { paramType = "QLatin1String"; isQLatin1String = true; } else { return; } string msg = string("QString(") + paramType + string(") being called"); if (isQLatin1String) { ConditionalOperator *ternary = nullptr; Stmt *begin = qlatin1CtorExpr(stm, ternary); if (begin == nullptr) return; vector<FixItHint> fixits = ternary == nullptr ? fixItReplaceQLatin1StringWithQStringLiteral(begin) : fixItReplaceQLatin1StringWithQStringLiteralInTernary(ternary); emitWarning(stm->getLocStart(), msg, fixits); } else { emitWarning(stm->getLocStart(), msg); } } vector<FixItHint> QStringUneededHeapAllocations::fixItReplaceQLatin1StringWithQStringLiteral(clang::Stmt *begin) { vector<FixItHint> fixits; SourceLocation rangeStart = begin->getLocStart(); SourceLocation rangeEnd = Lexer::getLocForEndOfToken(rangeStart, -1, m_ci.getSourceManager(), m_ci.getLangOpts()); fixits.push_back(FixItHint::CreateReplacement(SourceRange(rangeStart, rangeEnd), "QStringLiteral")); return fixits; } vector<FixItHint> QStringUneededHeapAllocations::fixItReplaceQLatin1StringWithQStringLiteralInTernary(clang::ConditionalOperator *ternary) { vector<CXXConstructExpr*> constructExprs; Utils::getChilds2<CXXConstructExpr>(ternary, constructExprs, 1); // depth = 1, only the two immediate expressions vector<FixItHint> fixits; fixits.reserve(2); if (constructExprs.size() != 2) { llvm::errs() << "Weird ternary operator with " << constructExprs.size() << " at " << ternary->getLocStart().printToString(m_ci.getSourceManager()) << "\n"; assert(false); return fixits; } for (int i = 0; i < 2; ++i) { SourceLocation rangeStart = constructExprs[i]->getLocStart(); SourceLocation rangeEnd = Lexer::getLocForEndOfToken(rangeStart, -1, m_ci.getSourceManager(), m_ci.getLangOpts()); fixits.push_back(FixItHint::CreateReplacement(SourceRange(rangeStart, rangeEnd), "QStringLiteral")); } return fixits;} void QStringUneededHeapAllocations::VisitOperatorCall(Stmt *stm) { CXXOperatorCallExpr *operatorCall = dyn_cast<CXXOperatorCallExpr>(stm); if (operatorCall == nullptr) return; std::vector<StringLiteral*> stringLiterals; Utils::getChilds2<StringLiteral>(operatorCall, stringLiterals); // We're only after string literals, str.contains(some_method_returning_const_char_is_fine()) if (stringLiterals.empty()) return; FunctionDecl *funcDecl = operatorCall->getDirectCallee(); if (funcDecl == nullptr) return; CXXMethodDecl *methodDecl = dyn_cast<CXXMethodDecl>(funcDecl); if (!isOfClass(methodDecl, "QString")) return; if (!hasCharPtrArgument(methodDecl)) return; string msg = string("QString(const char*) being called"); emitWarning(stm->getLocStart(), msg); } void QStringUneededHeapAllocations::VisitFromLatin1OrUtf8(Stmt *stmt) { CallExpr *callExpr = dyn_cast<CallExpr>(stmt); if (callExpr == nullptr) return; FunctionDecl *functionDecl = callExpr->getDirectCallee(); if (functionDecl == nullptr) return; CXXMethodDecl *methodDecl = dyn_cast<CXXMethodDecl>(functionDecl); if (methodDecl == nullptr) return; std::string functionName = functionDecl->getNameAsString(); if (functionName != "fromLatin1" && functionName != "fromUtf8") return; if (!isOfClass(methodDecl, "QString")) return; if (!Utils::callHasDefaultArguments(callExpr) || !hasCharPtrArgument(functionDecl, 2)) // QString::fromLatin1("foo", 1) is ok return; if (!containsStringLiteralNoCallExpr(callExpr)) return; if (functionName == "fromLatin1") { emitWarning(stmt->getLocStart(), string("QString::fromLatin1() being passed a literal")); } else { emitWarning(stmt->getLocStart(), string("QString::fromUtf8() being passed a literal")); } } void QStringUneededHeapAllocations::VisitAssignOperatorQLatin1String(Stmt *stmt) { CXXOperatorCallExpr *callExpr = dyn_cast<CXXOperatorCallExpr>(stmt); if (callExpr == nullptr) return; FunctionDecl *functionDecl = callExpr->getDirectCallee(); if (functionDecl == nullptr) return; CXXMethodDecl *methodDecl = dyn_cast<CXXMethodDecl>(functionDecl); if (!isOfClass(methodDecl, "QString") || functionDecl->getNameAsString() != "operator=" || !hasArgumentOfType(functionDecl, "class QLatin1String", 1)) return; if (!containsStringLiteralNoCallExpr(stmt)) return; ConditionalOperator *ternary = nullptr; Stmt *begin = qlatin1CtorExpr(stmt, ternary); if (begin == nullptr) return; vector<FixItHint> fixits = ternary == nullptr ? fixItReplaceQLatin1StringWithQStringLiteral(begin) : fixItReplaceQLatin1StringWithQStringLiteralInTernary(ternary); emitWarning(stmt->getLocStart(), string("QString::operator=(QLatin1String(\"literal\")"), fixits); } <|endoftext|>
<commit_before>#include "Updater.h" #include "Arduino.h" #include "eboot_command.h" #include "interrupts.h" #include "esp8266_peri.h" //#define DEBUG_UPDATER Serial extern "C" { #include "c_types.h" #include "spi_flash.h" #include "user_interface.h" } extern "C" uint32_t _SPIFFS_start; UpdaterClass::UpdaterClass() : _async(false) , _error(0) , _buffer(0) , _bufferLen(0) , _size(0) , _startAddress(0) , _currentAddress(0) , _command(U_FLASH) { } void UpdaterClass::_reset() { if (_buffer) delete[] _buffer; _buffer = 0; _bufferLen = 0; _startAddress = 0; _currentAddress = 0; _size = 0; _command = U_FLASH; } bool UpdaterClass::begin(size_t size, int command) { if(_size > 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println(F("[begin] already running")); #endif return false; } /* Check boot mode; if boot mode is 1 (UART download mode), we will not be able to reset into normal mode once update is done. Fail early to avoid frustration. https://github.com/esp8266/Arduino/issues/1017#issuecomment-200605576 */ int boot_mode = (GPI >> 16) & 0xf; if (boot_mode == 1) { _setError(UPDATE_ERROR_BOOTSTRAP); return false; } #ifdef DEBUG_UPDATER if (command == U_SPIFFS) { DEBUG_UPDATER.println(F("[begin] Update SPIFFS.")); } #endif if(size == 0) { _setError(UPDATE_ERROR_SIZE); return false; } if(!ESP.checkFlashConfig(false)) { _setError(UPDATE_ERROR_FLASH_CONFIG); return false; } _reset(); clearError(); // _error = 0 wifi_set_sleep_type(NONE_SLEEP_T); uint32_t updateStartAddress = 0; if (command == U_FLASH) { //size of current sketch rounded to a sector uint32_t currentSketchSize = (ESP.getSketchSize() + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address of the end of the space available for sketch and update uint32_t updateEndAddress = (uint32_t)&_SPIFFS_start - 0x40200000; //size of the update rounded to a sector uint32_t roundedSize = (size + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address where we will start writing the update updateStartAddress = updateEndAddress - roundedSize; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("[begin] roundedSize: 0x%08X (%d)\n", roundedSize, roundedSize); DEBUG_UPDATER.printf("[begin] updateEndAddress: 0x%08X (%d)\n", updateEndAddress, updateEndAddress); DEBUG_UPDATER.printf("[begin] currentSketchSize: 0x%08X (%d)\n", currentSketchSize, currentSketchSize); #endif //make sure that the size of both sketches is less than the total space (updateEndAddress) if(updateStartAddress < currentSketchSize) { _setError(UPDATE_ERROR_SPACE); return false; } } else if (command == U_SPIFFS) { updateStartAddress = (uint32_t)&_SPIFFS_start - 0x40200000; } else { // unknown command #ifdef DEBUG_UPDATER DEBUG_UPDATER.println(F("[begin] Unknown update command.")); #endif return false; } //initialize _startAddress = updateStartAddress; _currentAddress = _startAddress; _size = size; if (ESP.getFreeHeap() > 2 * FLASH_SECTOR_SIZE) { _bufferSize = FLASH_SECTOR_SIZE; } else { _bufferSize = 256; } _buffer = new uint8_t[_bufferSize]; _command = command; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("[begin] _startAddress: 0x%08X (%d)\n", _startAddress, _startAddress); DEBUG_UPDATER.printf("[begin] _currentAddress: 0x%08X (%d)\n", _currentAddress, _currentAddress); DEBUG_UPDATER.printf("[begin] _size: 0x%08X (%d)\n", _size, _size); #endif _md5.begin(); return true; } bool UpdaterClass::setMD5(const char * expected_md5){ if(strlen(expected_md5) != 32) { return false; } _target_md5 = expected_md5; return true; } bool UpdaterClass::end(bool evenIfRemaining){ if(_size == 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println(F("no update")); #endif return false; } if(hasError() || (!isFinished() && !evenIfRemaining)){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("premature end: res:%u, pos:%u/%u\n", getError(), progress(), _size); #endif _reset(); return false; } if(evenIfRemaining) { if(_bufferLen > 0) { _writeBuffer(); } _size = progress(); } _md5.calculate(); if(_target_md5.length()) { if(_target_md5 != _md5.toString()){ _setError(UPDATE_ERROR_MD5); _reset(); return false; } #ifdef DEBUG_UPDATER else DEBUG_UPDATER.printf("MD5 Success: %s\n", _target_md5.c_str()); #endif } if(!_verifyEnd()) { _reset(); return false; } if (_command == U_FLASH) { eboot_command ebcmd; ebcmd.action = ACTION_COPY_RAW; ebcmd.args[0] = _startAddress; ebcmd.args[1] = 0x00000; ebcmd.args[2] = _size; eboot_command_write(&ebcmd); #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("Staged: address:0x%08X, size:0x%08X\n", _startAddress, _size); } else if (_command == U_SPIFFS) { DEBUG_UPDATER.printf("SPIFFS: address:0x%08X, size:0x%08X\n", _startAddress, _size); #endif } _reset(); return true; } bool UpdaterClass::_writeBuffer(){ bool eraseResult = true, writeResult = true; if (_currentAddress % FLASH_SECTOR_SIZE == 0) { if(!_async) yield(); eraseResult = ESP.flashEraseSector(_currentAddress/FLASH_SECTOR_SIZE); } if (eraseResult) { if(!_async) yield(); writeResult = ESP.flashWrite(_currentAddress, (uint32_t*) _buffer, _bufferLen); } else { // if erase was unsuccessful _currentAddress = (_startAddress + _size); _setError(UPDATE_ERROR_ERASE); return false; } if (!writeResult) { _currentAddress = (_startAddress + _size); _setError(UPDATE_ERROR_WRITE); return false; } _md5.add(_buffer, _bufferLen); _currentAddress += _bufferLen; _bufferLen = 0; return true; } size_t UpdaterClass::write(uint8_t *data, size_t len) { if(hasError() || !isRunning()) return 0; if(len > remaining()){ //len = remaining(); //fail instead _setError(UPDATE_ERROR_SPACE); return 0; } size_t left = len; while((_bufferLen + left) > _bufferSize) { size_t toBuff = _bufferSize - _bufferLen; memcpy(_buffer + _bufferLen, data + (len - left), toBuff); _bufferLen += toBuff; if(!_writeBuffer()){ return len - left; } left -= toBuff; if(!_async) yield(); } //lets see whats left memcpy(_buffer + _bufferLen, data + (len - left), left); _bufferLen += left; if(_bufferLen == remaining()){ //we are at the end of the update, so should write what's left to flash if(!_writeBuffer()){ return len - left; } } return len; } bool UpdaterClass::_verifyHeader(uint8_t data) { if(_command == U_FLASH) { // check for valid first magic byte (is always 0xE9) if(data != 0xE9) { _currentAddress = (_startAddress + _size); _setError(UPDATE_ERROR_MAGIC_BYTE); return false; } return true; } else if(_command == U_SPIFFS) { // no check of SPIFFS possible with first byte. return true; } return false; } bool UpdaterClass::_verifyEnd() { if(_command == U_FLASH) { uint8_t buf[4]; if(!ESP.flashRead(_startAddress, (uint32_t *) &buf[0], 4)) { _currentAddress = (_startAddress); _setError(UPDATE_ERROR_READ); return false; } // check for valid first magic byte if(buf[0] != 0xE9) { _currentAddress = (_startAddress); _setError(UPDATE_ERROR_MAGIC_BYTE); return false; } uint32_t bin_flash_size = ESP.magicFlashChipSize((buf[3] & 0xf0) >> 4); // check if new bin fits to SPI flash if(bin_flash_size > ESP.getFlashChipRealSize()) { _currentAddress = (_startAddress); _setError(UPDATE_ERROR_NEW_FLASH_CONFIG); return false; } return true; } else if(_command == U_SPIFFS) { // SPIFFS is already over written checks make no sense any more. return true; } return false; } size_t UpdaterClass::writeStream(Stream &data) { size_t written = 0; size_t toRead = 0; if(hasError() || !isRunning()) return 0; if(!_verifyHeader(data.peek())) { #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif _reset(); return 0; } while(remaining()) { toRead = data.readBytes(_buffer + _bufferLen, (_bufferSize - _bufferLen)); if(toRead == 0) { //Timeout delay(100); toRead = data.readBytes(_buffer + _bufferLen, (_bufferSize - _bufferLen)); if(toRead == 0) { //Timeout _currentAddress = (_startAddress + _size); _setError(UPDATE_ERROR_STREAM); _reset(); return written; } } _bufferLen += toRead; if((_bufferLen == remaining() || _bufferLen == _bufferSize) && !_writeBuffer()) return written; written += toRead; yield(); } return written; } void UpdaterClass::_setError(int error){ _error = error; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif } void UpdaterClass::printError(Print &out){ out.printf_P(PSTR("ERROR[%u]: "), _error); if(_error == UPDATE_ERROR_OK){ out.println(F("No Error")); } else if(_error == UPDATE_ERROR_WRITE){ out.println(F("Flash Write Failed")); } else if(_error == UPDATE_ERROR_ERASE){ out.println(F("Flash Erase Failed")); } else if(_error == UPDATE_ERROR_READ){ out.println(F("Flash Read Failed")); } else if(_error == UPDATE_ERROR_SPACE){ out.println(F("Not Enough Space")); } else if(_error == UPDATE_ERROR_SIZE){ out.println(F("Bad Size Given")); } else if(_error == UPDATE_ERROR_STREAM){ out.println(F("Stream Read Timeout")); } else if(_error == UPDATE_ERROR_MD5){ //out.println(F("MD5 Check Failed")); out.printf("MD5 Failed: expected:%s, calculated:%s\n", _target_md5.c_str(), _md5.toString().c_str()); } else if(_error == UPDATE_ERROR_FLASH_CONFIG){ out.printf_P(PSTR("Flash config wrong real: %d IDE: %d\n"), ESP.getFlashChipRealSize(), ESP.getFlashChipSize()); } else if(_error == UPDATE_ERROR_NEW_FLASH_CONFIG){ out.printf_P(PSTR("new Flash config wrong real: %d\n"), ESP.getFlashChipRealSize()); } else if(_error == UPDATE_ERROR_MAGIC_BYTE){ out.println(F("Magic byte is wrong, not 0xE9")); } else if (_error == UPDATE_ERROR_BOOTSTRAP){ out.println(F("Invalid bootstrapping state, reset ESP8266 before updating")); } else { out.println(F("UNKNOWN")); } } UpdaterClass Update;<commit_msg>Resolve updater size check bug (#4550)<commit_after>#include "Updater.h" #include "Arduino.h" #include "eboot_command.h" #include "interrupts.h" #include "esp8266_peri.h" //#define DEBUG_UPDATER Serial extern "C" { #include "c_types.h" #include "spi_flash.h" #include "user_interface.h" } extern "C" uint32_t _SPIFFS_start; UpdaterClass::UpdaterClass() : _async(false) , _error(0) , _buffer(0) , _bufferLen(0) , _size(0) , _startAddress(0) , _currentAddress(0) , _command(U_FLASH) { } void UpdaterClass::_reset() { if (_buffer) delete[] _buffer; _buffer = 0; _bufferLen = 0; _startAddress = 0; _currentAddress = 0; _size = 0; _command = U_FLASH; } bool UpdaterClass::begin(size_t size, int command) { if(_size > 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println(F("[begin] already running")); #endif return false; } /* Check boot mode; if boot mode is 1 (UART download mode), we will not be able to reset into normal mode once update is done. Fail early to avoid frustration. https://github.com/esp8266/Arduino/issues/1017#issuecomment-200605576 */ int boot_mode = (GPI >> 16) & 0xf; if (boot_mode == 1) { _setError(UPDATE_ERROR_BOOTSTRAP); return false; } #ifdef DEBUG_UPDATER if (command == U_SPIFFS) { DEBUG_UPDATER.println(F("[begin] Update SPIFFS.")); } #endif if(size == 0) { _setError(UPDATE_ERROR_SIZE); return false; } if(!ESP.checkFlashConfig(false)) { _setError(UPDATE_ERROR_FLASH_CONFIG); return false; } _reset(); clearError(); // _error = 0 wifi_set_sleep_type(NONE_SLEEP_T); uint32_t updateStartAddress = 0; if (command == U_FLASH) { //size of current sketch rounded to a sector uint32_t currentSketchSize = (ESP.getSketchSize() + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address of the end of the space available for sketch and update uint32_t updateEndAddress = (uint32_t)&_SPIFFS_start - 0x40200000; //size of the update rounded to a sector uint32_t roundedSize = (size + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address where we will start writing the update updateStartAddress = (updateEndAddress > roundedSize)? (updateEndAddress - roundedSize) : 0; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("[begin] roundedSize: 0x%08X (%d)\n", roundedSize, roundedSize); DEBUG_UPDATER.printf("[begin] updateEndAddress: 0x%08X (%d)\n", updateEndAddress, updateEndAddress); DEBUG_UPDATER.printf("[begin] currentSketchSize: 0x%08X (%d)\n", currentSketchSize, currentSketchSize); #endif //make sure that the size of both sketches is less than the total space (updateEndAddress) if(updateStartAddress < currentSketchSize) { _setError(UPDATE_ERROR_SPACE); return false; } } else if (command == U_SPIFFS) { updateStartAddress = (uint32_t)&_SPIFFS_start - 0x40200000; } else { // unknown command #ifdef DEBUG_UPDATER DEBUG_UPDATER.println(F("[begin] Unknown update command.")); #endif return false; } //initialize _startAddress = updateStartAddress; _currentAddress = _startAddress; _size = size; if (ESP.getFreeHeap() > 2 * FLASH_SECTOR_SIZE) { _bufferSize = FLASH_SECTOR_SIZE; } else { _bufferSize = 256; } _buffer = new uint8_t[_bufferSize]; _command = command; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("[begin] _startAddress: 0x%08X (%d)\n", _startAddress, _startAddress); DEBUG_UPDATER.printf("[begin] _currentAddress: 0x%08X (%d)\n", _currentAddress, _currentAddress); DEBUG_UPDATER.printf("[begin] _size: 0x%08X (%d)\n", _size, _size); #endif _md5.begin(); return true; } bool UpdaterClass::setMD5(const char * expected_md5){ if(strlen(expected_md5) != 32) { return false; } _target_md5 = expected_md5; return true; } bool UpdaterClass::end(bool evenIfRemaining){ if(_size == 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println(F("no update")); #endif return false; } if(hasError() || (!isFinished() && !evenIfRemaining)){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("premature end: res:%u, pos:%u/%u\n", getError(), progress(), _size); #endif _reset(); return false; } if(evenIfRemaining) { if(_bufferLen > 0) { _writeBuffer(); } _size = progress(); } _md5.calculate(); if(_target_md5.length()) { if(_target_md5 != _md5.toString()){ _setError(UPDATE_ERROR_MD5); _reset(); return false; } #ifdef DEBUG_UPDATER else DEBUG_UPDATER.printf("MD5 Success: %s\n", _target_md5.c_str()); #endif } if(!_verifyEnd()) { _reset(); return false; } if (_command == U_FLASH) { eboot_command ebcmd; ebcmd.action = ACTION_COPY_RAW; ebcmd.args[0] = _startAddress; ebcmd.args[1] = 0x00000; ebcmd.args[2] = _size; eboot_command_write(&ebcmd); #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("Staged: address:0x%08X, size:0x%08X\n", _startAddress, _size); } else if (_command == U_SPIFFS) { DEBUG_UPDATER.printf("SPIFFS: address:0x%08X, size:0x%08X\n", _startAddress, _size); #endif } _reset(); return true; } bool UpdaterClass::_writeBuffer(){ bool eraseResult = true, writeResult = true; if (_currentAddress % FLASH_SECTOR_SIZE == 0) { if(!_async) yield(); eraseResult = ESP.flashEraseSector(_currentAddress/FLASH_SECTOR_SIZE); } if (eraseResult) { if(!_async) yield(); writeResult = ESP.flashWrite(_currentAddress, (uint32_t*) _buffer, _bufferLen); } else { // if erase was unsuccessful _currentAddress = (_startAddress + _size); _setError(UPDATE_ERROR_ERASE); return false; } if (!writeResult) { _currentAddress = (_startAddress + _size); _setError(UPDATE_ERROR_WRITE); return false; } _md5.add(_buffer, _bufferLen); _currentAddress += _bufferLen; _bufferLen = 0; return true; } size_t UpdaterClass::write(uint8_t *data, size_t len) { if(hasError() || !isRunning()) return 0; if(len > remaining()){ //len = remaining(); //fail instead _setError(UPDATE_ERROR_SPACE); return 0; } size_t left = len; while((_bufferLen + left) > _bufferSize) { size_t toBuff = _bufferSize - _bufferLen; memcpy(_buffer + _bufferLen, data + (len - left), toBuff); _bufferLen += toBuff; if(!_writeBuffer()){ return len - left; } left -= toBuff; if(!_async) yield(); } //lets see whats left memcpy(_buffer + _bufferLen, data + (len - left), left); _bufferLen += left; if(_bufferLen == remaining()){ //we are at the end of the update, so should write what's left to flash if(!_writeBuffer()){ return len - left; } } return len; } bool UpdaterClass::_verifyHeader(uint8_t data) { if(_command == U_FLASH) { // check for valid first magic byte (is always 0xE9) if(data != 0xE9) { _currentAddress = (_startAddress + _size); _setError(UPDATE_ERROR_MAGIC_BYTE); return false; } return true; } else if(_command == U_SPIFFS) { // no check of SPIFFS possible with first byte. return true; } return false; } bool UpdaterClass::_verifyEnd() { if(_command == U_FLASH) { uint8_t buf[4]; if(!ESP.flashRead(_startAddress, (uint32_t *) &buf[0], 4)) { _currentAddress = (_startAddress); _setError(UPDATE_ERROR_READ); return false; } // check for valid first magic byte if(buf[0] != 0xE9) { _currentAddress = (_startAddress); _setError(UPDATE_ERROR_MAGIC_BYTE); return false; } uint32_t bin_flash_size = ESP.magicFlashChipSize((buf[3] & 0xf0) >> 4); // check if new bin fits to SPI flash if(bin_flash_size > ESP.getFlashChipRealSize()) { _currentAddress = (_startAddress); _setError(UPDATE_ERROR_NEW_FLASH_CONFIG); return false; } return true; } else if(_command == U_SPIFFS) { // SPIFFS is already over written checks make no sense any more. return true; } return false; } size_t UpdaterClass::writeStream(Stream &data) { size_t written = 0; size_t toRead = 0; if(hasError() || !isRunning()) return 0; if(!_verifyHeader(data.peek())) { #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif _reset(); return 0; } while(remaining()) { toRead = data.readBytes(_buffer + _bufferLen, (_bufferSize - _bufferLen)); if(toRead == 0) { //Timeout delay(100); toRead = data.readBytes(_buffer + _bufferLen, (_bufferSize - _bufferLen)); if(toRead == 0) { //Timeout _currentAddress = (_startAddress + _size); _setError(UPDATE_ERROR_STREAM); _reset(); return written; } } _bufferLen += toRead; if((_bufferLen == remaining() || _bufferLen == _bufferSize) && !_writeBuffer()) return written; written += toRead; yield(); } return written; } void UpdaterClass::_setError(int error){ _error = error; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif } void UpdaterClass::printError(Print &out){ out.printf_P(PSTR("ERROR[%u]: "), _error); if(_error == UPDATE_ERROR_OK){ out.println(F("No Error")); } else if(_error == UPDATE_ERROR_WRITE){ out.println(F("Flash Write Failed")); } else if(_error == UPDATE_ERROR_ERASE){ out.println(F("Flash Erase Failed")); } else if(_error == UPDATE_ERROR_READ){ out.println(F("Flash Read Failed")); } else if(_error == UPDATE_ERROR_SPACE){ out.println(F("Not Enough Space")); } else if(_error == UPDATE_ERROR_SIZE){ out.println(F("Bad Size Given")); } else if(_error == UPDATE_ERROR_STREAM){ out.println(F("Stream Read Timeout")); } else if(_error == UPDATE_ERROR_MD5){ //out.println(F("MD5 Check Failed")); out.printf("MD5 Failed: expected:%s, calculated:%s\n", _target_md5.c_str(), _md5.toString().c_str()); } else if(_error == UPDATE_ERROR_FLASH_CONFIG){ out.printf_P(PSTR("Flash config wrong real: %d IDE: %d\n"), ESP.getFlashChipRealSize(), ESP.getFlashChipSize()); } else if(_error == UPDATE_ERROR_NEW_FLASH_CONFIG){ out.printf_P(PSTR("new Flash config wrong real: %d\n"), ESP.getFlashChipRealSize()); } else if(_error == UPDATE_ERROR_MAGIC_BYTE){ out.println(F("Magic byte is wrong, not 0xE9")); } else if (_error == UPDATE_ERROR_BOOTSTRAP){ out.println(F("Invalid bootstrapping state, reset ESP8266 before updating")); } else { out.println(F("UNKNOWN")); } } UpdaterClass Update; <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QDebug> #include <QHBoxLayout> #include <QPushButton> #include <QStyle> // CTK includes #include "ctkDirectoryButton.h" //----------------------------------------------------------------------------- class ctkDirectoryButtonPrivate: public ctkPrivate<ctkDirectoryButton> { public: ctkDirectoryButtonPrivate(); void init(); QDir Directory; QPushButton* PushButton; QString DialogCaption; #if QT_VERSION >= 0x040700 QFileDialog::Options DialogOptions; #else ctkDirectoryButton::Options DialogOptions; #endif // TODO expose DisplayAbsolutePath into the API bool DisplayAbsolutePath; }; //----------------------------------------------------------------------------- ctkDirectoryButtonPrivate::ctkDirectoryButtonPrivate() { #if QT_VERSION >= 0x040700 this->DialogOptions = QFileDialog::ShowDirsOnly; #else this->DialogOptions = ctkDirectoryButton::ShowDirsOnly; #endif this->DisplayAbsolutePath = true; } //----------------------------------------------------------------------------- void ctkDirectoryButtonPrivate::init() { CTK_P(ctkDirectoryButton); this->PushButton = new QPushButton(p); QObject::connect(this->PushButton, SIGNAL(clicked()), p, SLOT(browse())); QHBoxLayout* l = new QHBoxLayout(p); l->addWidget(this->PushButton); l->setContentsMargins(0,0,0,0); p->setLayout(l); } //----------------------------------------------------------------------------- ctkDirectoryButton::ctkDirectoryButton(QWidget * parentWidget) :QWidget(parentWidget) { CTK_INIT_PRIVATE(ctkDirectoryButton); CTK_D(ctkDirectoryButton); d->init(); d->PushButton->setText(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); d->PushButton->setIcon(this->style()->standardIcon(QStyle::SP_DirIcon)); } //----------------------------------------------------------------------------- ctkDirectoryButton::ctkDirectoryButton(const QString& dir, QWidget * parentWidget) :QWidget(parentWidget) { CTK_INIT_PRIVATE(ctkDirectoryButton); CTK_D(ctkDirectoryButton); d->init(); d->Directory = QDir(dir); d->PushButton->setText(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); d->PushButton->setIcon(this->style()->standardIcon(QStyle::SP_DirIcon)); } //----------------------------------------------------------------------------- ctkDirectoryButton::ctkDirectoryButton( const QIcon & icon, const QString& dir, QWidget * parentWidget) :QWidget(parentWidget) { CTK_INIT_PRIVATE(ctkDirectoryButton); CTK_D(ctkDirectoryButton); d->init(); d->Directory = QDir(dir); d->PushButton->setText(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); d->PushButton->setIcon(icon); } //----------------------------------------------------------------------------- void ctkDirectoryButton::setDirectory(const QString& dir) { CTK_D(ctkDirectoryButton); QDir newDirectory(dir); if (d->Directory == newDirectory) { emit directorySelected(d->DisplayAbsolutePath ? newDirectory.absolutePath() : newDirectory.path()); return; } d->Directory = newDirectory; d->PushButton->setText(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); emit directorySelected(d->DisplayAbsolutePath ? newDirectory.absolutePath() : newDirectory.path()); emit directoryChanged(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); } //----------------------------------------------------------------------------- QString ctkDirectoryButton::directory()const { CTK_D(const ctkDirectoryButton); return d->Directory.path(); } //----------------------------------------------------------------------------- void ctkDirectoryButton::setCaption(const QString& caption) { CTK_D(ctkDirectoryButton); d->DialogCaption = caption; } //----------------------------------------------------------------------------- const QString& ctkDirectoryButton::caption()const { CTK_D(const ctkDirectoryButton); return d->DialogCaption; } //----------------------------------------------------------------------------- #if QT_VERSION >= 0x040700 void ctkDirectoryButton::setOptions(const QFileDialog::Options& dialogOptions) #else void ctkDirectoryButton::setOptions(const Options& dialogOptions) #endif { CTK_D(ctkDirectoryButton); d->DialogOptions = dialogOptions; } //----------------------------------------------------------------------------- #if QT_VERSION >= 0x040700 const QFileDialog::Options& ctkDirectoryButton::options()const #else const ctkDirectoryButton::Options& ctkDirectoryButton::options()const #endif { CTK_D(const ctkDirectoryButton); return d->DialogOptions; } //----------------------------------------------------------------------------- void ctkDirectoryButton::browse() { CTK_D(ctkDirectoryButton); QString dir = QFileDialog::getExistingDirectory( this, d->DialogCaption.isEmpty() ? this->toolTip() : d->DialogCaption, d->Directory.path(), #if QT_VERSION >= 0x040700 d->DialogOptions); #else QFlags<QFileDialog::Option>(int(d->DialogOptions))); #endif // An empty directory means that the user cancelled the dialog. if (dir.isEmpty()) { return; } this->setDirectory(dir); } <commit_msg>BUG: Set sizepolicy to ctkDirectoryButton<commit_after>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware 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.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QDebug> #include <QHBoxLayout> #include <QPushButton> #include <QStyle> // CTK includes #include "ctkDirectoryButton.h" //----------------------------------------------------------------------------- class ctkDirectoryButtonPrivate: public ctkPrivate<ctkDirectoryButton> { public: ctkDirectoryButtonPrivate(); void init(); QDir Directory; QPushButton* PushButton; QString DialogCaption; #if QT_VERSION >= 0x040700 QFileDialog::Options DialogOptions; #else ctkDirectoryButton::Options DialogOptions; #endif // TODO expose DisplayAbsolutePath into the API bool DisplayAbsolutePath; }; //----------------------------------------------------------------------------- ctkDirectoryButtonPrivate::ctkDirectoryButtonPrivate() { #if QT_VERSION >= 0x040700 this->DialogOptions = QFileDialog::ShowDirsOnly; #else this->DialogOptions = ctkDirectoryButton::ShowDirsOnly; #endif this->DisplayAbsolutePath = true; } //----------------------------------------------------------------------------- void ctkDirectoryButtonPrivate::init() { CTK_P(ctkDirectoryButton); this->PushButton = new QPushButton(p); QObject::connect(this->PushButton, SIGNAL(clicked()), p, SLOT(browse())); QHBoxLayout* l = new QHBoxLayout(p); l->addWidget(this->PushButton); l->setContentsMargins(0,0,0,0); p->setLayout(l); p->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed, QSizePolicy::ButtonBox)); } //----------------------------------------------------------------------------- ctkDirectoryButton::ctkDirectoryButton(QWidget * parentWidget) :QWidget(parentWidget) { CTK_INIT_PRIVATE(ctkDirectoryButton); CTK_D(ctkDirectoryButton); d->init(); d->PushButton->setText(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); d->PushButton->setIcon(this->style()->standardIcon(QStyle::SP_DirIcon)); } //----------------------------------------------------------------------------- ctkDirectoryButton::ctkDirectoryButton(const QString& dir, QWidget * parentWidget) :QWidget(parentWidget) { CTK_INIT_PRIVATE(ctkDirectoryButton); CTK_D(ctkDirectoryButton); d->init(); d->Directory = QDir(dir); d->PushButton->setText(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); d->PushButton->setIcon(this->style()->standardIcon(QStyle::SP_DirIcon)); } //----------------------------------------------------------------------------- ctkDirectoryButton::ctkDirectoryButton( const QIcon & icon, const QString& dir, QWidget * parentWidget) :QWidget(parentWidget) { CTK_INIT_PRIVATE(ctkDirectoryButton); CTK_D(ctkDirectoryButton); d->init(); d->Directory = QDir(dir); d->PushButton->setText(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); d->PushButton->setIcon(icon); } //----------------------------------------------------------------------------- void ctkDirectoryButton::setDirectory(const QString& dir) { CTK_D(ctkDirectoryButton); QDir newDirectory(dir); if (d->Directory == newDirectory) { emit directorySelected(d->DisplayAbsolutePath ? newDirectory.absolutePath() : newDirectory.path()); return; } d->Directory = newDirectory; d->PushButton->setText(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); emit directorySelected(d->DisplayAbsolutePath ? newDirectory.absolutePath() : newDirectory.path()); emit directoryChanged(d->DisplayAbsolutePath ? d->Directory.absolutePath() : d->Directory.path()); } //----------------------------------------------------------------------------- QString ctkDirectoryButton::directory()const { CTK_D(const ctkDirectoryButton); return d->Directory.path(); } //----------------------------------------------------------------------------- void ctkDirectoryButton::setCaption(const QString& caption) { CTK_D(ctkDirectoryButton); d->DialogCaption = caption; } //----------------------------------------------------------------------------- const QString& ctkDirectoryButton::caption()const { CTK_D(const ctkDirectoryButton); return d->DialogCaption; } //----------------------------------------------------------------------------- #if QT_VERSION >= 0x040700 void ctkDirectoryButton::setOptions(const QFileDialog::Options& dialogOptions) #else void ctkDirectoryButton::setOptions(const Options& dialogOptions) #endif { CTK_D(ctkDirectoryButton); d->DialogOptions = dialogOptions; } //----------------------------------------------------------------------------- #if QT_VERSION >= 0x040700 const QFileDialog::Options& ctkDirectoryButton::options()const #else const ctkDirectoryButton::Options& ctkDirectoryButton::options()const #endif { CTK_D(const ctkDirectoryButton); return d->DialogOptions; } //----------------------------------------------------------------------------- void ctkDirectoryButton::browse() { CTK_D(ctkDirectoryButton); QString dir = QFileDialog::getExistingDirectory( this, d->DialogCaption.isEmpty() ? this->toolTip() : d->DialogCaption, d->Directory.path(), #if QT_VERSION >= 0x040700 d->DialogOptions); #else QFlags<QFileDialog::Option>(int(d->DialogOptions))); #endif // An empty directory means that the user cancelled the dialog. if (dir.isEmpty()) { return; } this->setDirectory(dir); } <|endoftext|>
<commit_before>#include "pch.h" #include "utils.h" #ifndef _WIN32 web::http::client::http_client::~http_client() noexcept {} #endif static pplx::task<bool> _do_while_iteration(std::function<pplx::task<bool>(void)> func) { pplx::task_completion_event<bool> ev; func().then([=](bool task_completed) { ev.set(task_completed); }); return pplx::create_task(ev); } static pplx::task<bool> _do_while_impl(std::function<pplx::task<bool>(void)> func) { return _do_while_iteration(func).then([=](bool continue_next_iteration) -> pplx::task<bool> { return ((continue_next_iteration == true) ? _do_while_impl(func) : pplx::task_from_result(false)); }); } pplx::task<void> async_do_while(std::function<pplx::task<bool>(void)> func) { return _do_while_impl(func).then([](bool) { }); } std::string utf16_to_utf8(const std::wstring& w) { return std::wstring_convert< std::codecvt_utf8_utf16<wchar_t>, wchar_t>{}.to_bytes(w); } std::wstring utf8_to_utf16(const std::string& n) { return std::wstring_convert< std::codecvt_utf8_utf16<wchar_t>, wchar_t>{}.from_bytes(n); } <commit_msg>Removed the redef of ~http_client()<commit_after>#include "pch.h" #include "utils.h" static pplx::task<bool> _do_while_iteration(std::function<pplx::task<bool>(void)> func) { pplx::task_completion_event<bool> ev; func().then([=](bool task_completed) { ev.set(task_completed); }); return pplx::create_task(ev); } static pplx::task<bool> _do_while_impl(std::function<pplx::task<bool>(void)> func) { return _do_while_iteration(func).then([=](bool continue_next_iteration) -> pplx::task<bool> { return ((continue_next_iteration == true) ? _do_while_impl(func) : pplx::task_from_result(false)); }); } pplx::task<void> async_do_while(std::function<pplx::task<bool>(void)> func) { return _do_while_impl(func).then([](bool) { }); } std::string utf16_to_utf8(const std::wstring& w) { return std::wstring_convert< std::codecvt_utf8_utf16<wchar_t>, wchar_t>{}.to_bytes(w); } std::wstring utf8_to_utf16(const std::string& n) { return std::wstring_convert< std::codecvt_utf8_utf16<wchar_t>, wchar_t>{}.from_bytes(n); } <|endoftext|>
<commit_before>#include <list.h> #include <move.h> #include "yatf/include/yatf.h" using namespace yacppl; TEST(list, can_create_empty_list) { list<int> list; REQUIRE(list.size() == 0); } TEST(list, can_add_front_item) { list<int> list; list.push_front(2); REQUIRE(list.size() == 1); REQUIRE(list.front() == 2); } TEST(list, can_add_two_front_items) { list<int> list; list.push_front(2); list.push_front(1); REQUIRE(list.size() == 2); REQUIRE(list.front() == 1); REQUIRE(list.back() == 2); } TEST(list, can_add_back_item) { list<int> list; list.push_back(4); REQUIRE(list.size() == 1); REQUIRE(list.back() == 4); } TEST(list, can_add_back_two_items) { list<int> list; list.push_back(8); list.push_back(3); REQUIRE(list.size() == 2); REQUIRE(list.front() == 8); REQUIRE(list.back() == 3); } TEST(list, can_be_initialized_with_initializer_list) { list<int> list{2, 5, 6, 88, 4}; REQUIRE(list.size() == 5); REQUIRE(list.front() == 2); REQUIRE(list.back() == 4); int result[5]; int i = 0; for (auto &it : list) result[i++] = it; REQUIRE(result[0] == 2); REQUIRE(result[1] == 5); REQUIRE(result[2] == 6); REQUIRE(result[3] == 88); REQUIRE(result[4] == 4); } TEST(list, can_access_elements) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); int result[3]; int i = 0; for (const auto &it : list) result[i++] = it; REQUIRE(result[0] == 1); REQUIRE(result[1] == 2); REQUIRE(result[2] == 3); } TEST(list, can_pop_back) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); REQUIRE(list.front() == 1); list.pop_back(); REQUIRE(list.size() == 2); REQUIRE(list.back() == 2); REQUIRE(list.front() == 1); } TEST(list, can_pop_front) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); REQUIRE(list.front() == 10); list.pop_front(); REQUIRE(list.size() == 3); REQUIRE(list.back() == 3); REQUIRE(list.front() == 1); } TEST(list, can_be_resized) { list<int> list; list.resize(20); REQUIRE(list.size() == 20); for (auto &it : list) it = 38; REQUIRE(list.front() == 38); REQUIRE(list.back() == 38); list.resize(2); REQUIRE(list.front() == 38); REQUIRE(list.back() == 38); REQUIRE(list.size() == 2); } TEST(list, can_increment_iterator) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); auto it = list.begin(); REQUIRE(*it == 10); it++; REQUIRE(*it == 1); ++it; REQUIRE(*it == 2); it = list.begin(); *it = 34; REQUIRE(*it == 34); REQUIRE(list.front() == 34); } TEST(list, can_decrement_iterator) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); auto it = list.end(); it--; REQUIRE(*it == 3); --it; REQUIRE(*it == 2); } TEST(list, can_increment_and_decrement_iterator) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); auto it = list.begin(); REQUIRE(*it == 10); it++; REQUIRE(*it == 1); it--; REQUIRE(*it == 10); } TEST(list, can_compare_iterators) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); auto it1 = list.begin(); auto it2 = it1; REQUIRE(it1 == it2); it2++; REQUIRE(it1 != it2); } TEST(list, can_be_constructed_by_copy) { list<int> list1; list1.push_back(3); list1.push_front(2); list1.push_front(1); list1.push_front(10); list<int> list2(list1); REQUIRE(list1.front() == 10); REQUIRE(list2.front() == 10); REQUIRE(list2.back() == 3); } TEST(list, can_be_assigned) { list<int> list1; list1.push_back(3); list1.push_front(2); list1.push_front(1); list1.push_front(10); list<int> list2; list2.push_back(99); list2.push_back(120); list2 = list1; REQUIRE(list1.size() == 4); REQUIRE(list2.size() == 4); REQUIRE(list1.front() == 10); REQUIRE(list2.front() == 10); REQUIRE(list2.back() == 3); } TEST(list, can_be_constructed_by_move) { list<int> list1; list1.push_back(3); list1.push_front(2); list1.push_front(1); list1.push_front(10); list<int> list2(move(list1)); int result[4]; int i = 0; for (const auto &it : list2) result[i++] = it; REQUIRE(list1.size() == 0); REQUIRE(list2.size() == 4); REQUIRE(list2.front() == 10); REQUIRE(list2.back() == 3); REQUIRE(result[0] == 10); REQUIRE(result[1] == 1); REQUIRE(result[2] == 2); REQUIRE(result[3] == 3); } TEST(list, can_be_moved) { list<int> list1; list1.push_back(3); list1.push_front(2); list1.push_front(1); list1.push_front(10); list<int> list2; list2.push_back(4); list2.push_back(54); list2 = move(list1); int result[4]; int i = 0; for (const auto &it : list2) result[i++] = it; REQUIRE(list1.size() == 0); REQUIRE(list2.size() == 4); REQUIRE(list2.front() == 10); REQUIRE(list2.back() == 3); REQUIRE(result[0] == 10); REQUIRE(result[1] == 1); REQUIRE(result[2] == 2); REQUIRE(result[3] == 3); } TEST(list, can_erase_single_element) { list<int> list; list.push_front(43); list.push_front(-59); list.push_back(23); auto it = list.begin(); ++it; REQUIRE(list.front() == -59); REQUIRE(list.back() == 23); list.erase(it); REQUIRE(list.size() == 2); REQUIRE(list.front() == -59); REQUIRE(list.back() == 23); list.erase(list.begin()); REQUIRE(list.size() == 1); REQUIRE(list.front() == 23); REQUIRE(list.back() == 23); list.erase(list.end()--); REQUIRE(list.size() == 0); } TEST(list, can_erase_elements) { list<int> list; list.push_front(43); list.push_front(-59); list.push_back(23); list.push_back(13); list.erase(++list.begin(), list.end()); REQUIRE(list.size() == 1); REQUIRE(list.front() == -59); REQUIRE(list.back() == -59); list.erase(list.begin(), list.end()); REQUIRE(list.size() == 0); } <commit_msg>Update list tests<commit_after>#include <list.h> #include <move.h> #include "yatf/include/yatf.h" using namespace yacppl; TEST(list, can_create_empty_list) { list<int> list; REQUIRE(list.size() == 0); } TEST(list, can_add_front_item) { list<int> list; list.push_front(2); REQUIRE(list.size() == 1); REQUIRE_EQ(list.front(), 2); } TEST(list, can_add_two_front_items) { list<int> list; list.push_front(2); list.push_front(1); REQUIRE(list.size() == 2); REQUIRE_EQ(list.front(), 1); REQUIRE_EQ(list.back(), 2); } TEST(list, can_add_back_item) { list<int> list; list.push_back(4); REQUIRE(list.size() == 1); REQUIRE_EQ(list.back(), 4); } TEST(list, can_add_back_two_items) { list<int> list; list.push_back(8); list.push_back(3); REQUIRE(list.size() == 2); REQUIRE_EQ(list.front(), 8); REQUIRE_EQ(list.back(), 3); } TEST(list, can_be_initialized_with_initializer_list) { list<int> list{2, 5, 6, 88, 4}; REQUIRE(list.size() == 5); REQUIRE_EQ(list.front(), 2); REQUIRE_EQ(list.back(), 4); int result[5]; int i = 0; for (auto &it : list) result[i++] = it; REQUIRE_EQ(result[0], 2); REQUIRE_EQ(result[1], 5); REQUIRE_EQ(result[2], 6); REQUIRE_EQ(result[3], 88); REQUIRE_EQ(result[4], 4); } TEST(list, can_access_elements) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); int result[3]; int i = 0; for (const auto &it : list) result[i++] = it; REQUIRE_EQ(result[0], 1); REQUIRE_EQ(result[1], 2); REQUIRE_EQ(result[2], 3); } TEST(list, can_pop_back) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); REQUIRE_EQ(list.front(), 1); list.pop_back(); REQUIRE(list.size() == 2); REQUIRE_EQ(list.back(), 2); REQUIRE_EQ(list.front(), 1); } TEST(list, can_pop_front) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); REQUIRE_EQ(list.front(), 10); list.pop_front(); REQUIRE(list.size() == 3); REQUIRE_EQ(list.back(), 3); REQUIRE_EQ(list.front(), 1); } TEST(list, can_be_resized) { list<int> list; list.resize(20); REQUIRE(list.size() == 20); for (auto &it : list) it = 38; REQUIRE_EQ(list.front(), 38); REQUIRE_EQ(list.back(), 38); list.resize(2); REQUIRE_EQ(list.front(), 38); REQUIRE_EQ(list.back(), 38); REQUIRE(list.size() == 2); } TEST(list, can_increment_iterator) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); auto it = list.begin(); REQUIRE_EQ(*it, 10); it++; REQUIRE_EQ(*it, 1); ++it; REQUIRE_EQ(*it, 2); it = list.begin(); *it = 34; REQUIRE_EQ(*it, 34); REQUIRE_EQ(list.front(), 34); } TEST(list, can_decrement_iterator) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); auto it = list.end(); it--; REQUIRE_EQ(*it, 3); --it; REQUIRE_EQ(*it, 2); } TEST(list, can_increment_and_decrement_iterator) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); auto it = list.begin(); REQUIRE_EQ(*it, 10); it++; REQUIRE_EQ(*it, 1); it--; REQUIRE_EQ(*it, 10); } TEST(list, can_compare_iterators) { list<int> list; list.push_back(3); list.push_front(2); list.push_front(1); list.push_front(10); auto it1 = list.begin(); auto it2 = it1; REQUIRE_EQ(it1 == it2, true); it2++; REQUIRE_EQ(it1 != it2, true); } TEST(list, can_be_constructed_by_copy) { list<int> list1; list1.push_back(3); list1.push_front(2); list1.push_front(1); list1.push_front(10); list<int> list2(list1); REQUIRE_EQ(list1.front(), 10); REQUIRE_EQ(list2.front(), 10); REQUIRE_EQ(list2.back(), 3); } TEST(list, can_be_assigned) { list<int> list1; list1.push_back(3); list1.push_front(2); list1.push_front(1); list1.push_front(10); list<int> list2; list2.push_back(99); list2.push_back(120); list2 = list1; REQUIRE(list1.size() == 4); REQUIRE(list2.size() == 4); REQUIRE_EQ(list1.front(), 10); REQUIRE_EQ(list2.front(), 10); REQUIRE_EQ(list2.back(), 3); } TEST(list, can_be_constructed_by_move) { list<int> list1; list1.push_back(3); list1.push_front(2); list1.push_front(1); list1.push_front(10); list<int> list2(move(list1)); int result[4]; int i = 0; for (const auto &it : list2) result[i++] = it; REQUIRE(list1.size() == 0); REQUIRE(list2.size() == 4); REQUIRE_EQ(list2.front(), 10); REQUIRE_EQ(list2.back(), 3); REQUIRE_EQ(result[0], 10); REQUIRE_EQ(result[1], 1); REQUIRE_EQ(result[2], 2); REQUIRE_EQ(result[3], 3); } TEST(list, can_be_moved) { list<int> list1; list1.push_back(3); list1.push_front(2); list1.push_front(1); list1.push_front(10); list<int> list2; list2.push_back(4); list2.push_back(54); list2 = move(list1); int result[4]; int i = 0; for (const auto &it : list2) result[i++] = it; REQUIRE(list1.size() == 0); REQUIRE(list2.size() == 4); REQUIRE_EQ(list2.front(), 10); REQUIRE_EQ(list2.back(), 3); REQUIRE_EQ(result[0], 10); REQUIRE_EQ(result[1], 1); REQUIRE_EQ(result[2], 2); REQUIRE_EQ(result[3], 3); } TEST(list, can_erase_single_element) { list<int> list; list.push_front(43); list.push_front(-59); list.push_back(23); auto it = list.begin(); ++it; REQUIRE_EQ(list.front(), -59); REQUIRE_EQ(list.back(), 23); list.erase(it); REQUIRE(list.size() == 2); REQUIRE_EQ(list.front(), -59); REQUIRE_EQ(list.back(), 23); list.erase(list.begin()); REQUIRE(list.size() == 1); REQUIRE_EQ(list.front(), 23); REQUIRE_EQ(list.back(), 23); list.erase(list.end()--); REQUIRE(list.size() == 0); } TEST(list, can_erase_elements) { list<int> list; list.push_front(43); list.push_front(-59); list.push_back(23); list.push_back(13); list.erase(++list.begin(), list.end()); REQUIRE(list.size() == 1); REQUIRE_EQ(list.front(), -59); REQUIRE_EQ(list.back(), -59); list.erase(list.begin(), list.end()); REQUIRE(list.size() == 0); } <|endoftext|>
<commit_before>#include "Updater.h" #include "Arduino.h" #include "eboot_command.h" #include "interrupts.h" //#define DEBUG_UPDATER Serial extern "C" { #include "c_types.h" #include "spi_flash.h" } extern "C" uint32_t _SPIFFS_start; UpdaterClass::UpdaterClass() : _error(0) , _buffer(0) , _bufferLen(0) , _size(0) , _startAddress(0) , _currentAddress(0) , _command(U_FLASH) { } void UpdaterClass::_reset() { if (_buffer) delete[] _buffer; _buffer = 0; _bufferLen = 0; _startAddress = 0; _currentAddress = 0; _size = 0; _command = U_FLASH; } bool UpdaterClass::begin(size_t size, int command) { if(_size > 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("already running"); #endif return false; } #ifdef DEBUG_UPDATER if (command == U_SPIFFS) { DEBUG_UPDATER.println("Update SPIFFS."); } #endif if(size == 0) { _error = UPDATE_ERROR_SIZE; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } _reset(); _error = 0; uint32_t updateStartAddress = 0; if (command == U_FLASH) { //size of current sketch rounded to a sector uint32_t currentSketchSize = (ESP.getSketchSize() + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address of the end of the space available for sketch and update uint32_t updateEndAddress = (uint32_t)&_SPIFFS_start - 0x40200000; //size of the update rounded to a sector uint32_t roundedSize = (size + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address where we will start writing the update updateStartAddress = updateEndAddress - roundedSize; //make sure that the size of both sketches is less than the total space (updateEndAddress) if(updateStartAddress < currentSketchSize) { _error = UPDATE_ERROR_SPACE; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } } else if (command == U_SPIFFS) { updateStartAddress = (uint32_t)&_SPIFFS_start - 0x40200000; } else { // unknown command #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("Unknown update command."); #endif return false; } //initialize _startAddress = updateStartAddress; _currentAddress = _startAddress; _size = size; _buffer = new uint8_t[FLASH_SECTOR_SIZE]; _command = command; _md5.begin(); return true; } void UpdaterClass::setMD5(const char * expected_md5){ if(strlen(expected_md5) != 32) return; _target_md5 = expected_md5; } bool UpdaterClass::end(bool evenIfRemaining){ if(_size == 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("no update"); #endif return false; } if(hasError() || (!isFinished() && !evenIfRemaining)){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("premature end: res:%u, pos:%u/%u\n", getError(), progress(), _size); #endif _reset(); return false; } if(evenIfRemaining) { if(_bufferLen > 0) { _writeBuffer(); } _size = progress(); } _md5.calculate(); if(_target_md5.length()) { if(_target_md5 != _md5.toString()){ _error = UPDATE_ERROR_MD5; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("MD5 Failed: expected:%s, calculated:%s\n", _target_md5.c_str(), _md5.toString().c_str()); #endif return false; } #ifdef DEBUG_UPDATER else DEBUG_UPDATER.printf("MD5 Success: %s\n", _target_md5.c_str()); #endif } if (_command == U_FLASH) { eboot_command ebcmd; ebcmd.action = ACTION_COPY_RAW; ebcmd.args[0] = _startAddress; ebcmd.args[1] = 0x00000; ebcmd.args[2] = _size; eboot_command_write(&ebcmd); #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("Staged: address:0x%08X, size:0x%08X\n", _startAddress, _size); } else if (_command == U_SPIFFS) { DEBUG_UPDATER.printf("SPIFFS: address:0x%08X, size:0x%08X\n", _startAddress, _size); #endif } _reset(); return true; } bool UpdaterClass::_writeBuffer(){ yield(); bool result = ESP.flashEraseSector(_currentAddress/FLASH_SECTOR_SIZE) && ESP.flashWrite(_currentAddress, (uint32_t*) _buffer, _bufferLen); if (!result) { _error = UPDATE_ERROR_WRITE; _currentAddress = (_startAddress + _size); #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } _md5.add(_buffer, _bufferLen); _currentAddress += _bufferLen; _bufferLen = 0; return true; } size_t UpdaterClass::write(uint8_t *data, size_t len) { size_t left = len; if(hasError() || !isRunning()) return 0; if(len > remaining()) len = remaining(); while((_bufferLen + left) > FLASH_SECTOR_SIZE) { size_t toBuff = FLASH_SECTOR_SIZE - _bufferLen; memcpy(_buffer + _bufferLen, data + (len - left), toBuff); _bufferLen += toBuff; if(!_writeBuffer()){ return len - left; } left -= toBuff; yield(); } //lets see whats left memcpy(_buffer + _bufferLen, data + (len - left), left); _bufferLen += left; if(_bufferLen == remaining()){ //we are at the end of the update, so should write what's left to flash if(!_writeBuffer()){ return len - left; } } return len; } size_t UpdaterClass::writeStream(Stream &data) { size_t written = 0; size_t toRead = 0; if(hasError() || !isRunning()) return 0; while(remaining()) { toRead = FLASH_SECTOR_SIZE - _bufferLen; toRead = data.readBytes(_buffer + _bufferLen, toRead); if(toRead == 0){ //Timeout _error = UPDATE_ERROR_STREAM; _currentAddress = (_startAddress + _size); #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return written; } _bufferLen += toRead; if((_bufferLen == remaining() || _bufferLen == FLASH_SECTOR_SIZE) && !_writeBuffer()) return written; written += toRead; yield(); } return written; } void UpdaterClass::printError(Stream &out){ out.printf("ERROR[%u]: ", _error); if(_error == UPDATE_ERROR_OK){ out.println("No Error"); } else if(_error == UPDATE_ERROR_WRITE){ out.println("Flash Write Failed"); } else if(_error == UPDATE_ERROR_ERASE){ out.println("Flash Erase Failed"); } else if(_error == UPDATE_ERROR_SPACE){ out.println("Not Enough Space"); } else if(_error == UPDATE_ERROR_SIZE){ out.println("Bad Size Given"); } else if(_error == UPDATE_ERROR_STREAM){ out.println("Stream Read Timeout"); } else if(_error == UPDATE_ERROR_MD5){ out.println("MD5 Check Failed"); } else { out.println("UNKNOWN"); } } UpdaterClass Update; <commit_msg>Disable sleep mode before doing OTA (#1005)<commit_after>#include "Updater.h" #include "Arduino.h" #include "eboot_command.h" #include "interrupts.h" //#define DEBUG_UPDATER Serial extern "C" { #include "c_types.h" #include "spi_flash.h" #include "user_interface.h" } extern "C" uint32_t _SPIFFS_start; UpdaterClass::UpdaterClass() : _error(0) , _buffer(0) , _bufferLen(0) , _size(0) , _startAddress(0) , _currentAddress(0) , _command(U_FLASH) { } void UpdaterClass::_reset() { if (_buffer) delete[] _buffer; _buffer = 0; _bufferLen = 0; _startAddress = 0; _currentAddress = 0; _size = 0; _command = U_FLASH; } bool UpdaterClass::begin(size_t size, int command) { if(_size > 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("already running"); #endif return false; } #ifdef DEBUG_UPDATER if (command == U_SPIFFS) { DEBUG_UPDATER.println("Update SPIFFS."); } #endif if(size == 0) { _error = UPDATE_ERROR_SIZE; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } _reset(); _error = 0; wifi_set_sleep_type(NONE_SLEEP_T); uint32_t updateStartAddress = 0; if (command == U_FLASH) { //size of current sketch rounded to a sector uint32_t currentSketchSize = (ESP.getSketchSize() + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address of the end of the space available for sketch and update uint32_t updateEndAddress = (uint32_t)&_SPIFFS_start - 0x40200000; //size of the update rounded to a sector uint32_t roundedSize = (size + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1)); //address where we will start writing the update updateStartAddress = updateEndAddress - roundedSize; //make sure that the size of both sketches is less than the total space (updateEndAddress) if(updateStartAddress < currentSketchSize) { _error = UPDATE_ERROR_SPACE; #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } } else if (command == U_SPIFFS) { updateStartAddress = (uint32_t)&_SPIFFS_start - 0x40200000; } else { // unknown command #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("Unknown update command."); #endif return false; } //initialize _startAddress = updateStartAddress; _currentAddress = _startAddress; _size = size; _buffer = new uint8_t[FLASH_SECTOR_SIZE]; _command = command; _md5.begin(); return true; } void UpdaterClass::setMD5(const char * expected_md5){ if(strlen(expected_md5) != 32) return; _target_md5 = expected_md5; } bool UpdaterClass::end(bool evenIfRemaining){ if(_size == 0){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.println("no update"); #endif return false; } if(hasError() || (!isFinished() && !evenIfRemaining)){ #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("premature end: res:%u, pos:%u/%u\n", getError(), progress(), _size); #endif _reset(); return false; } if(evenIfRemaining) { if(_bufferLen > 0) { _writeBuffer(); } _size = progress(); } _md5.calculate(); if(_target_md5.length()) { if(_target_md5 != _md5.toString()){ _error = UPDATE_ERROR_MD5; #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("MD5 Failed: expected:%s, calculated:%s\n", _target_md5.c_str(), _md5.toString().c_str()); #endif return false; } #ifdef DEBUG_UPDATER else DEBUG_UPDATER.printf("MD5 Success: %s\n", _target_md5.c_str()); #endif } if (_command == U_FLASH) { eboot_command ebcmd; ebcmd.action = ACTION_COPY_RAW; ebcmd.args[0] = _startAddress; ebcmd.args[1] = 0x00000; ebcmd.args[2] = _size; eboot_command_write(&ebcmd); #ifdef DEBUG_UPDATER DEBUG_UPDATER.printf("Staged: address:0x%08X, size:0x%08X\n", _startAddress, _size); } else if (_command == U_SPIFFS) { DEBUG_UPDATER.printf("SPIFFS: address:0x%08X, size:0x%08X\n", _startAddress, _size); #endif } _reset(); return true; } bool UpdaterClass::_writeBuffer(){ yield(); bool result = ESP.flashEraseSector(_currentAddress/FLASH_SECTOR_SIZE) && ESP.flashWrite(_currentAddress, (uint32_t*) _buffer, _bufferLen); if (!result) { _error = UPDATE_ERROR_WRITE; _currentAddress = (_startAddress + _size); #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return false; } _md5.add(_buffer, _bufferLen); _currentAddress += _bufferLen; _bufferLen = 0; return true; } size_t UpdaterClass::write(uint8_t *data, size_t len) { size_t left = len; if(hasError() || !isRunning()) return 0; if(len > remaining()) len = remaining(); while((_bufferLen + left) > FLASH_SECTOR_SIZE) { size_t toBuff = FLASH_SECTOR_SIZE - _bufferLen; memcpy(_buffer + _bufferLen, data + (len - left), toBuff); _bufferLen += toBuff; if(!_writeBuffer()){ return len - left; } left -= toBuff; yield(); } //lets see whats left memcpy(_buffer + _bufferLen, data + (len - left), left); _bufferLen += left; if(_bufferLen == remaining()){ //we are at the end of the update, so should write what's left to flash if(!_writeBuffer()){ return len - left; } } return len; } size_t UpdaterClass::writeStream(Stream &data) { size_t written = 0; size_t toRead = 0; if(hasError() || !isRunning()) return 0; while(remaining()) { toRead = FLASH_SECTOR_SIZE - _bufferLen; toRead = data.readBytes(_buffer + _bufferLen, toRead); if(toRead == 0){ //Timeout _error = UPDATE_ERROR_STREAM; _currentAddress = (_startAddress + _size); #ifdef DEBUG_UPDATER printError(DEBUG_UPDATER); #endif return written; } _bufferLen += toRead; if((_bufferLen == remaining() || _bufferLen == FLASH_SECTOR_SIZE) && !_writeBuffer()) return written; written += toRead; yield(); } return written; } void UpdaterClass::printError(Stream &out){ out.printf("ERROR[%u]: ", _error); if(_error == UPDATE_ERROR_OK){ out.println("No Error"); } else if(_error == UPDATE_ERROR_WRITE){ out.println("Flash Write Failed"); } else if(_error == UPDATE_ERROR_ERASE){ out.println("Flash Erase Failed"); } else if(_error == UPDATE_ERROR_SPACE){ out.println("Not Enough Space"); } else if(_error == UPDATE_ERROR_SIZE){ out.println("Bad Size Given"); } else if(_error == UPDATE_ERROR_STREAM){ out.println("Stream Read Timeout"); } else if(_error == UPDATE_ERROR_MD5){ out.println("MD5 Check Failed"); } else { out.println("UNKNOWN"); } } UpdaterClass Update; <|endoftext|>
<commit_before>/* This file is part of the Vc library. Copyright (C) 2009-2012 Matthias Kretz <kretz@kde.org> Vc 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. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include "unittest.h" #include <iostream> using namespace Vc; template<typename T> static constexpr T min(T a, T b) { return a < b ? a : b; } template<typename Vec> constexpr unsigned long alignmentMask() { return Vec::Size == 1 ? ( // on 32bit the maximal alignment is 4 Bytes, even for 8-Byte doubles. min(sizeof(void*), sizeof(typename Vec::EntryType)) - 1 ) : ( // AVX::VectorAlignment is too large min<size_t>(sizeof(Vec), VectorAlignment) - 1 ); } template<typename Vec> void checkAlignment() { unsigned char i = 1; Vec a[10]; unsigned long mask = alignmentMask<Vec>(); for (i = 0; i < 10; ++i) { VERIFY((reinterpret_cast<size_t>(&a[i]) & mask) == 0) << "a = " << a << ", mask = " << mask; } const char *data = reinterpret_cast<const char *>(&a[0]); for (i = 0; i < 10; ++i) { VERIFY(&data[i * sizeof(Vec)] == reinterpret_cast<const char *>(&a[i])); } } void *hack_to_put_b_on_the_stack = 0; template<typename Vec> void checkMemoryAlignment() { typedef typename Vec::EntryType T; const T *b = 0; Vc::Memory<Vec, 10> a; b = a; hack_to_put_b_on_the_stack = &b; size_t mask = memory_alignment<Vec>::value - 1; for (int i = 0; i < 10; ++i) { VERIFY((reinterpret_cast<size_t>(&b[i * Vec::Size]) & mask) == 0) << "b = " << b << ", mask = " << mask; } } template<typename Vec> void loadArray() { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; enum loadArrayEnum { count = 256 * 1024 / sizeof(T) }; Vc::Memory<Vec, count> array; for (int i = 0; i < count; ++i) { array[i] = i; } const I indexesFromZero(IndexesFromZero); const Vec offsets(indexesFromZero); for (int i = 0; i < count; i += Vec::Size) { const T *const addr = &array[i]; Vec ii(i); ii += offsets; Vec a(addr); COMPARE(a, ii); Vec b = Vec::Zero(); b.load(addr); COMPARE(b, ii); } // check that Vc allows construction from objects that auto-convert to T* Vec tmp0(array); tmp0.load(array); } enum Enum { loadArrayShortCount = 32 * 1024, streamingLoadCount = 1024 }; template<typename Vec> void loadArrayShort() { typedef typename Vec::EntryType T; Vc::Memory<Vec, loadArrayShortCount> array; for (int i = 0; i < loadArrayShortCount; ++i) { array[i] = i; } const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero()); for (int i = 0; i < loadArrayShortCount; i += Vec::Size) { const T *const addr = &array[i]; Vec ii(i); ii += offsets; Vec a(addr); COMPARE(a, ii); Vec b = Vec::Zero(); b.load(addr); COMPARE(b, ii); } } template<typename Vec> void streamingLoad() { typedef typename Vec::EntryType T; Vc::Memory<Vec, streamingLoadCount> data; data[0] = static_cast<T>(-streamingLoadCount/2); for (int i = 1; i < streamingLoadCount; ++i) { data[i] = data[i - 1]; ++data[i]; } Vec ref = data.firstVector(); for (size_t i = 0; i < streamingLoadCount - Vec::Size; ++i, ++ref) { Vec v1, v2; if (0 == i % Vec::Size) { v1 = Vec(&data[i], Vc::Streaming); v2.load (&data[i], Vc::Streaming); } else { v1 = Vec(&data[i], Vc::Streaming | Vc::Unaligned); v2.load (&data[i], Vc::Unaligned | Vc::Streaming); } COMPARE(v1, ref) << ", i = " << i; COMPARE(v2, ref) << ", i = " << i; } } template<typename T> struct TypeInfo; template<> struct TypeInfo<double > { static const char *string() { return "double"; } }; template<> struct TypeInfo<float > { static const char *string() { return "float"; } }; template<> struct TypeInfo<int > { static const char *string() { return "int"; } }; template<> struct TypeInfo<unsigned int > { static const char *string() { return "uint"; } }; template<> struct TypeInfo<short > { static const char *string() { return "short"; } }; template<> struct TypeInfo<unsigned short> { static const char *string() { return "ushort"; } }; template<> struct TypeInfo<signed char > { static const char *string() { return "schar"; } }; template<> struct TypeInfo<unsigned char > { static const char *string() { return "uchar"; } }; template<> struct TypeInfo<double_v > { static const char *string() { return "double_v"; } }; template<> struct TypeInfo<float_v > { static const char *string() { return "float_v"; } }; template<> struct TypeInfo<int_v > { static const char *string() { return "int_v"; } }; template<> struct TypeInfo<uint_v > { static const char *string() { return "uint_v"; } }; template<> struct TypeInfo<short_v > { static const char *string() { return "short_v"; } }; template<> struct TypeInfo<ushort_v > { static const char *string() { return "ushort_v"; } }; template<typename T, typename Current = void> struct SupportedConversions { typedef void Next; }; template<> struct SupportedConversions<float, void> { typedef double Next; }; template<> struct SupportedConversions<float, double> { typedef int Next; }; template<> struct SupportedConversions<float, int> { typedef unsigned int Next; }; template<> struct SupportedConversions<float, unsigned int> { typedef short Next; }; template<> struct SupportedConversions<float, short> { typedef unsigned short Next; }; template<> struct SupportedConversions<float, unsigned short> { typedef signed char Next; }; template<> struct SupportedConversions<float, signed char> { typedef unsigned char Next; }; template<> struct SupportedConversions<float, unsigned char> { typedef void Next; }; template<> struct SupportedConversions<int , void > { typedef unsigned int Next; }; template<> struct SupportedConversions<int , unsigned int > { typedef short Next; }; template<> struct SupportedConversions<int , short > { typedef unsigned short Next; }; template<> struct SupportedConversions<int , unsigned short> { typedef signed char Next; }; template<> struct SupportedConversions<int , signed char > { typedef unsigned char Next; }; template<> struct SupportedConversions<int , unsigned char > { typedef void Next; }; template<> struct SupportedConversions<unsigned int, void > { typedef unsigned short Next; }; template<> struct SupportedConversions<unsigned int, unsigned short> { typedef unsigned char Next; }; template<> struct SupportedConversions<unsigned int, unsigned char > { typedef void Next; }; template<> struct SupportedConversions<unsigned short, void > { typedef unsigned char Next; }; template<> struct SupportedConversions<unsigned short, unsigned char > { typedef void Next; }; template<> struct SupportedConversions< short, void > { typedef unsigned char Next; }; template<> struct SupportedConversions< short, unsigned char > { typedef signed char Next; }; template<> struct SupportedConversions< short, signed char > { typedef void Next; }; template<typename Vec, typename MemT> struct LoadCvt { static void test() { typedef typename Vec::EntryType VecT; MemT *data = Vc::malloc<MemT, Vc::AlignOnCacheline>(128); for (size_t i = 0; i < 128; ++i) { data[i] = static_cast<MemT>(i - 64); } for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) { Vec v; if (i % (2 * Vec::Size) == 0) { v = Vec(&data[i]); } else if (i % Vec::Size == 0) { v = Vec(&data[i], Vc::Aligned); } else { v = Vec(&data[i], Vc::Unaligned); } for (size_t j = 0; j < Vec::Size; ++j) { COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string(); } } for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) { Vec v; if (i % (2 * Vec::Size) == 0) { v.load(&data[i]); } else if (i % Vec::Size == 0) { v.load(&data[i], Vc::Aligned); } else { v.load(&data[i], Vc::Unaligned); } for (size_t j = 0; j < Vec::Size; ++j) { COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string(); } } for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) { Vec v; if (i % (2 * Vec::Size) == 0) { v = Vec(&data[i], Vc::Streaming); } else if (i % Vec::Size == 0) { v = Vec(&data[i], Vc::Streaming | Vc::Aligned); } else { v = Vec(&data[i], Vc::Streaming | Vc::Unaligned); } for (size_t j = 0; j < Vec::Size; ++j) { COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string(); } } ADD_PASS() << "loadCvt: load " << TypeInfo<MemT>::string() << "* as " << TypeInfo<Vec>::string(); LoadCvt<Vec, typename SupportedConversions<VecT, MemT>::Next>::test(); } }; template<typename Vec> struct LoadCvt<Vec, void> { static void test() {} }; template<typename Vec> void loadCvt() { typedef typename Vec::EntryType T; LoadCvt<Vec, typename SupportedConversions<T>::Next>::test(); } void testmain() { runTest(checkAlignment<int_v>); runTest(checkAlignment<uint_v>); runTest(checkAlignment<float_v>); runTest(checkAlignment<double_v>); runTest(checkAlignment<short_v>); runTest(checkAlignment<ushort_v>); testAllTypes(checkMemoryAlignment); runTest(loadArray<int_v>); runTest(loadArray<uint_v>); runTest(loadArray<float_v>); runTest(loadArray<double_v>); runTest(loadArrayShort<short_v>); runTest(loadArrayShort<ushort_v>); testAllTypes(streamingLoad); testAllTypes(loadCvt); } <commit_msg>mark loads that I want aligned accordingly<commit_after>/* This file is part of the Vc library. Copyright (C) 2009-2012 Matthias Kretz <kretz@kde.org> Vc 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. Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>. */ #include "unittest.h" #include <iostream> using namespace Vc; template<typename T> static constexpr T min(T a, T b) { return a < b ? a : b; } template<typename Vec> constexpr unsigned long alignmentMask() { return Vec::Size == 1 ? ( // on 32bit the maximal alignment is 4 Bytes, even for 8-Byte doubles. min(sizeof(void*), sizeof(typename Vec::EntryType)) - 1 ) : ( // AVX::VectorAlignment is too large min<size_t>(sizeof(Vec), VectorAlignment) - 1 ); } template<typename Vec> void checkAlignment() { unsigned char i = 1; Vec a[10]; unsigned long mask = alignmentMask<Vec>(); for (i = 0; i < 10; ++i) { VERIFY((reinterpret_cast<size_t>(&a[i]) & mask) == 0) << "a = " << a << ", mask = " << mask; } const char *data = reinterpret_cast<const char *>(&a[0]); for (i = 0; i < 10; ++i) { VERIFY(&data[i * sizeof(Vec)] == reinterpret_cast<const char *>(&a[i])); } } void *hack_to_put_b_on_the_stack = 0; template<typename Vec> void checkMemoryAlignment() { typedef typename Vec::EntryType T; const T *b = 0; Vc::Memory<Vec, 10> a; b = a; hack_to_put_b_on_the_stack = &b; size_t mask = memory_alignment<Vec>::value - 1; for (int i = 0; i < 10; ++i) { VERIFY((reinterpret_cast<size_t>(&b[i * Vec::Size]) & mask) == 0) << "b = " << b << ", mask = " << mask; } } template<typename Vec> void loadArray() { typedef typename Vec::EntryType T; typedef typename Vec::IndexType I; enum loadArrayEnum { count = 256 * 1024 / sizeof(T) }; Vc::Memory<Vec, count> array; for (int i = 0; i < count; ++i) { array[i] = i; } const I indexesFromZero(IndexesFromZero); const Vec offsets(indexesFromZero); for (int i = 0; i < count; i += Vec::Size) { const T *const addr = &array[i]; Vec ii(i); ii += offsets; Vec a(addr, Vc::Aligned); COMPARE(a, ii); Vec b = Vec::Zero(); b.load(addr, Vc::Aligned); COMPARE(b, ii); } // check that Vc allows construction from objects that auto-convert to T* Vec tmp0(array, Vc::Aligned); tmp0.load(array, Vc::Aligned); } enum Enum { loadArrayShortCount = 32 * 1024, streamingLoadCount = 1024 }; template<typename Vec> void loadArrayShort() { typedef typename Vec::EntryType T; Vc::Memory<Vec, loadArrayShortCount> array; for (int i = 0; i < loadArrayShortCount; ++i) { array[i] = i; } const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero()); for (int i = 0; i < loadArrayShortCount; i += Vec::Size) { const T *const addr = &array[i]; Vec ii(i); ii += offsets; Vec a(addr, Vc::Aligned); COMPARE(a, ii); Vec b = Vec::Zero(); b.load(addr, Vc::Aligned); COMPARE(b, ii); } } template<typename Vec> void streamingLoad() { typedef typename Vec::EntryType T; Vc::Memory<Vec, streamingLoadCount> data; data[0] = static_cast<T>(-streamingLoadCount/2); for (int i = 1; i < streamingLoadCount; ++i) { data[i] = data[i - 1]; ++data[i]; } Vec ref = data.firstVector(); for (size_t i = 0; i < streamingLoadCount - Vec::Size; ++i, ++ref) { Vec v1, v2; if (0 == i % Vec::Size) { v1 = Vec(&data[i], Vc::Aligned | Vc::Streaming); v2.load (&data[i], Vc::Aligned | Vc::Streaming); } else { v1 = Vec(&data[i], Vc::Streaming | Vc::Unaligned); v2.load (&data[i], Vc::Unaligned | Vc::Streaming); } COMPARE(v1, ref) << ", i = " << i; COMPARE(v2, ref) << ", i = " << i; } } template<typename T> struct TypeInfo; template<> struct TypeInfo<double > { static const char *string() { return "double"; } }; template<> struct TypeInfo<float > { static const char *string() { return "float"; } }; template<> struct TypeInfo<int > { static const char *string() { return "int"; } }; template<> struct TypeInfo<unsigned int > { static const char *string() { return "uint"; } }; template<> struct TypeInfo<short > { static const char *string() { return "short"; } }; template<> struct TypeInfo<unsigned short> { static const char *string() { return "ushort"; } }; template<> struct TypeInfo<signed char > { static const char *string() { return "schar"; } }; template<> struct TypeInfo<unsigned char > { static const char *string() { return "uchar"; } }; template<> struct TypeInfo<double_v > { static const char *string() { return "double_v"; } }; template<> struct TypeInfo<float_v > { static const char *string() { return "float_v"; } }; template<> struct TypeInfo<int_v > { static const char *string() { return "int_v"; } }; template<> struct TypeInfo<uint_v > { static const char *string() { return "uint_v"; } }; template<> struct TypeInfo<short_v > { static const char *string() { return "short_v"; } }; template<> struct TypeInfo<ushort_v > { static const char *string() { return "ushort_v"; } }; template<typename T, typename Current = void> struct SupportedConversions { typedef void Next; }; template<> struct SupportedConversions<float, void> { typedef double Next; }; template<> struct SupportedConversions<float, double> { typedef int Next; }; template<> struct SupportedConversions<float, int> { typedef unsigned int Next; }; template<> struct SupportedConversions<float, unsigned int> { typedef short Next; }; template<> struct SupportedConversions<float, short> { typedef unsigned short Next; }; template<> struct SupportedConversions<float, unsigned short> { typedef signed char Next; }; template<> struct SupportedConversions<float, signed char> { typedef unsigned char Next; }; template<> struct SupportedConversions<float, unsigned char> { typedef void Next; }; template<> struct SupportedConversions<int , void > { typedef unsigned int Next; }; template<> struct SupportedConversions<int , unsigned int > { typedef short Next; }; template<> struct SupportedConversions<int , short > { typedef unsigned short Next; }; template<> struct SupportedConversions<int , unsigned short> { typedef signed char Next; }; template<> struct SupportedConversions<int , signed char > { typedef unsigned char Next; }; template<> struct SupportedConversions<int , unsigned char > { typedef void Next; }; template<> struct SupportedConversions<unsigned int, void > { typedef unsigned short Next; }; template<> struct SupportedConversions<unsigned int, unsigned short> { typedef unsigned char Next; }; template<> struct SupportedConversions<unsigned int, unsigned char > { typedef void Next; }; template<> struct SupportedConversions<unsigned short, void > { typedef unsigned char Next; }; template<> struct SupportedConversions<unsigned short, unsigned char > { typedef void Next; }; template<> struct SupportedConversions< short, void > { typedef unsigned char Next; }; template<> struct SupportedConversions< short, unsigned char > { typedef signed char Next; }; template<> struct SupportedConversions< short, signed char > { typedef void Next; }; template<typename Vec, typename MemT> struct LoadCvt { static void test() { typedef typename Vec::EntryType VecT; MemT *data = Vc::malloc<MemT, Vc::AlignOnCacheline>(128); for (size_t i = 0; i < 128; ++i) { data[i] = static_cast<MemT>(i - 64); } for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) { Vec v; if (i % (2 * Vec::Size) == 0) { v = Vec(&data[i]); } else if (i % Vec::Size == 0) { v = Vec(&data[i], Vc::Aligned); } else { v = Vec(&data[i], Vc::Unaligned); } for (size_t j = 0; j < Vec::Size; ++j) { COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string(); } } for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) { Vec v; if (i % (2 * Vec::Size) == 0) { v.load(&data[i]); } else if (i % Vec::Size == 0) { v.load(&data[i], Vc::Aligned); } else { v.load(&data[i], Vc::Unaligned); } for (size_t j = 0; j < Vec::Size; ++j) { COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string(); } } for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) { Vec v; if (i % (2 * Vec::Size) == 0) { v = Vec(&data[i], Vc::Streaming); } else if (i % Vec::Size == 0) { v = Vec(&data[i], Vc::Streaming | Vc::Aligned); } else { v = Vec(&data[i], Vc::Streaming | Vc::Unaligned); } for (size_t j = 0; j < Vec::Size; ++j) { COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string(); } } ADD_PASS() << "loadCvt: load " << TypeInfo<MemT>::string() << "* as " << TypeInfo<Vec>::string(); LoadCvt<Vec, typename SupportedConversions<VecT, MemT>::Next>::test(); } }; template<typename Vec> struct LoadCvt<Vec, void> { static void test() {} }; template<typename Vec> void loadCvt() { typedef typename Vec::EntryType T; LoadCvt<Vec, typename SupportedConversions<T>::Next>::test(); } void testmain() { runTest(checkAlignment<int_v>); runTest(checkAlignment<uint_v>); runTest(checkAlignment<float_v>); runTest(checkAlignment<double_v>); runTest(checkAlignment<short_v>); runTest(checkAlignment<ushort_v>); testAllTypes(checkMemoryAlignment); runTest(loadArray<int_v>); runTest(loadArray<uint_v>); runTest(loadArray<float_v>); runTest(loadArray<double_v>); runTest(loadArrayShort<short_v>); runTest(loadArrayShort<ushort_v>); testAllTypes(streamingLoad); testAllTypes(loadCvt); } <|endoftext|>
<commit_before>//===- Args.cpp -----------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Common/Args.h" #include "lld/Common/ErrorHandler.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Option/ArgList.h" using namespace llvm; using namespace lld; int lld::args::getInteger(opt::InputArgList &Args, unsigned Key, int Default) { int V = Default; if (auto *Arg = Args.getLastArg(Key)) { StringRef S = Arg->getValue(); if (!to_integer(S, V, 10)) error(Arg->getSpelling() + ": number expected, but got '" + S + "'"); } return V; } std::vector<StringRef> lld::args::getStrings(opt::InputArgList &Args, int Id) { std::vector<StringRef> V; for (auto *Arg : Args.filtered(Id)) V.push_back(Arg->getValue()); return V; } uint64_t lld::args::getZOptionValue(opt::InputArgList &Args, int Id, StringRef Key, uint64_t Default) { for (auto *Arg : Args.filtered(Id)) { std::pair<StringRef, StringRef> KV = StringRef(Arg->getValue()).split('='); if (KV.first == Key) { uint64_t Result = Default; if (!to_integer(KV.second, Result)) error("invalid " + Key + ": " + KV.second); return Result; } } return Default; } std::vector<StringRef> lld::args::getLines(MemoryBufferRef MB) { SmallVector<StringRef, 0> Arr; MB.getBuffer().split(Arr, '\n'); std::vector<StringRef> Ret; for (StringRef S : Arr) { S = S.trim(); if (!S.empty() && S[0] != '#') Ret.push_back(S); } return Ret; } <commit_msg>Fix formatting.<commit_after>//===- Args.cpp -----------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lld/Common/Args.h" #include "lld/Common/ErrorHandler.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Option/ArgList.h" using namespace llvm; using namespace lld; int lld::args::getInteger(opt::InputArgList &Args, unsigned Key, int Default) { int V = Default; if (auto *Arg = Args.getLastArg(Key)) { StringRef S = Arg->getValue(); if (!to_integer(S, V, 10)) error(Arg->getSpelling() + ": number expected, but got '" + S + "'"); } return V; } std::vector<StringRef> lld::args::getStrings(opt::InputArgList &Args, int Id) { std::vector<StringRef> V; for (auto *Arg : Args.filtered(Id)) V.push_back(Arg->getValue()); return V; } uint64_t lld::args::getZOptionValue(opt::InputArgList &Args, int Id, StringRef Key, uint64_t Default) { for (auto *Arg : Args.filtered(Id)) { std::pair<StringRef, StringRef> KV = StringRef(Arg->getValue()).split('='); if (KV.first == Key) { uint64_t Result = Default; if (!to_integer(KV.second, Result)) error("invalid " + Key + ": " + KV.second); return Result; } } return Default; } std::vector<StringRef> lld::args::getLines(MemoryBufferRef MB) { SmallVector<StringRef, 0> Arr; MB.getBuffer().split(Arr, '\n'); std::vector<StringRef> Ret; for (StringRef S : Arr) { S = S.trim(); if (!S.empty() && S[0] != '#') Ret.push_back(S); } return Ret; } <|endoftext|>
<commit_before><commit_msg>Fix the opacity of titlebars on the NTP page. We were accidentally setting the opacity to 1/255.<commit_after><|endoftext|>
<commit_before>/*! @file @author Albert Semenov @date 02/2008 */ /* This file is part of MyGUI. MyGUI 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. MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #include "MyGUI_Precompiled.h" #include "MyGUI_LayerNode.h" #include "MyGUI_ILayerItem.h" #include "MyGUI_ITexture.h" #include "MyGUI_ISubWidget.h" #include "MyGUI_ISubWidgetText.h" namespace MyGUI { LayerNode::LayerNode(ILayer* _layer, ILayerNode* _parent) : mParent(_parent), mLayer(_layer), mOutOfDate(false) { } LayerNode::~LayerNode() { for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { delete (*iter); } mFirstRenderItems.clear(); for (VectorRenderItem::iterator iter=mSecondRenderItems.begin(); iter!=mSecondRenderItems.end(); ++iter) { delete (*iter); } mSecondRenderItems.clear(); // удаляем дочерние узлы for (VectorILayerNode::iterator iter = mChildItems.begin(); iter!=mChildItems.end(); ++iter) { delete (*iter); } mChildItems.clear(); } ILayerNode* LayerNode::createChildItemNode() { LayerNode* layer = new LayerNode(mLayer, this); mChildItems.push_back(layer); return layer; } void LayerNode::destroyChildItemNode(ILayerNode* _node) { for (VectorILayerNode::iterator iter=mChildItems.begin(); iter!=mChildItems.end(); ++iter) { if ((*iter) == _node) { delete _node; mChildItems.erase(iter); return; } } MYGUI_EXCEPT("item node not found"); } void LayerNode::upChildItemNode(ILayerNode* _item) { for (VectorILayerNode::iterator iter=mChildItems.begin(); iter!=mChildItems.end(); ++iter) { if ((*iter) == _item) { mChildItems.erase(iter); mChildItems.push_back(_item); return; } } MYGUI_EXCEPT("item node not found"); } void LayerNode::renderToTarget(IRenderTarget* _target, bool _update) { // проверяем на сжатие пустот bool need_compression = false; for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { if ((*iter)->getCompression()) { need_compression = true; break; } } if (need_compression) updateCompression(); // сначала отрисовываем свое for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { (*iter)->renderToTarget(_target, _update); } for (VectorRenderItem::iterator iter=mSecondRenderItems.begin(); iter!=mSecondRenderItems.end(); ++iter) { (*iter)->renderToTarget(_target, _update); } // теперь отрисовываем дочерние узлы for (VectorILayerNode::iterator iter = mChildItems.begin(); iter!=mChildItems.end(); ++iter) { (*iter)->renderToTarget(_target, _update); } mOutOfDate = false; } ILayerItem* LayerNode::getLayerItemByPoint(int _left, int _top) { // сначала пикаем детей for (VectorILayerNode::iterator iter = mChildItems.begin(); iter!=mChildItems.end(); ++iter) { ILayerItem * item = (*iter)->getLayerItemByPoint(_left, _top); if (nullptr != item) return item; } for (VectorLayerItem::iterator iter=mLayerItems.begin(); iter!=mLayerItems.end(); ++iter) { ILayerItem * item = (*iter)->getLayerItemByPoint(_left, _top); if (nullptr != item) return item; } return nullptr; } RenderItem* LayerNode::addToRenderItem(ITexture* _texture, ISubWidget* _item) { bool first = _item->castType<ISubWidgetText>(false) == nullptr; // для первичной очереди нужен порядок if (first) { if (mFirstRenderItems.empty()) { // создаем новый буфер RenderItem * item = new RenderItem(); item->setTexture(_texture); mFirstRenderItems.push_back(item); return item; } // если последний буфер пустой, то мона не создавать if (mFirstRenderItems.back()->getNeedVertexCount() == 0) { // пустых может быть сколько угодно, нужен самый первый из пустых for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { if ((*iter)->getNeedVertexCount() == 0) { // а теперь внимание, если перед пустым наш, то его и юзаем if (iter != mFirstRenderItems.begin()) { VectorRenderItem::iterator prev = iter - 1; if ((*prev)->getTexture() == _texture) { return (*prev); } } (*iter)->setTexture(_texture); return (*iter); } } } // та же текстура if (mFirstRenderItems.back()->getTexture() == _texture) { return mFirstRenderItems.back(); } // создаем новый буфер RenderItem * item = new RenderItem(); item->setTexture(_texture); mFirstRenderItems.push_back(item); return item; } // для второй очереди порядок неважен for (VectorRenderItem::iterator iter=mSecondRenderItems.begin(); iter!=mSecondRenderItems.end(); ++iter) { // либо такая же текстура, либо пустой буфер if ((*iter)->getTexture() == _texture) { return (*iter); } else if ((*iter)->getNeedVertexCount() == 0) { (*iter)->setTexture(_texture); return (*iter); } } // не найденно создадим новый RenderItem * item = new RenderItem(); item->setTexture(_texture); mSecondRenderItems.push_back(item); return mSecondRenderItems.back(); } void LayerNode::attachLayerItem(ILayerItem* _item) { mLayerItems.push_back(_item); _item->attachItemToNode(mLayer, this); } void LayerNode::detachLayerItem(ILayerItem* _item) { for (VectorLayerItem::iterator iter=mLayerItems.begin(); iter!=mLayerItems.end(); ++iter) { if ((*iter) == _item) { (*iter) = mLayerItems.back(); mLayerItems.pop_back(); return; } } MYGUI_EXCEPT("layer item not found"); } void LayerNode::outOfDate(RenderItem* _item) { mOutOfDate = true; if (_item) _item->outOfDate(); } EnumeratorILayerNode LayerNode::getEnumerator() { return EnumeratorILayerNode(mChildItems); } void LayerNode::updateCompression() { // буферы освобождаются по одному всегда if (mFirstRenderItems.size() > 1) { // пытаемся поднять пустой буфер выше полных VectorRenderItem::iterator iter1 = mFirstRenderItems.begin(); VectorRenderItem::iterator iter2 = iter1 + 1; while (iter2 != mFirstRenderItems.end()) { if ((*iter1)->getNeedVertexCount() == 0) { RenderItem * tmp = (*iter1); (*iter1) = (*iter2); (*iter2) = tmp; } iter1 = iter2; ++iter2; } } } void LayerNode::dumpStatisticToLog(size_t _level) { static const char* spacer = " "; std::string offset(" ", _level); MYGUI_LOG(Info, offset << " - Node batch_count='" << mFirstRenderItems.size() + mSecondRenderItems.size() << spacer); for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { MYGUI_LOG(Info, offset << " * Batch texture='" << ((*iter)->getTexture() == nullptr ? "nullptr" : (*iter)->getTexture()->getName()) << "' vertex_count='" << (*iter)->getVertexCount() << "'" << spacer); } for (VectorRenderItem::iterator iter=mSecondRenderItems.begin(); iter!=mSecondRenderItems.end(); ++iter) { MYGUI_LOG(Info, offset << " * Batch texture='" << ((*iter)->getTexture() == nullptr ? "nullptr" : (*iter)->getTexture()->getName()) << "' vertex_count='" << (*iter)->getVertexCount() << "'" << spacer); } for (VectorILayerNode::iterator iter = mChildItems.begin(); iter!=mChildItems.end(); ++iter) { (*iter)->dumpStatisticToLog(_level + 1); } } } // namespace MyGUI <commit_msg>fix child texture visibility<commit_after>/*! @file @author Albert Semenov @date 02/2008 */ /* This file is part of MyGUI. MyGUI 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. MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>. */ #include "MyGUI_Precompiled.h" #include "MyGUI_LayerNode.h" #include "MyGUI_ILayerItem.h" #include "MyGUI_ITexture.h" #include "MyGUI_ISubWidget.h" #include "MyGUI_ISubWidgetText.h" namespace MyGUI { LayerNode::LayerNode(ILayer* _layer, ILayerNode* _parent) : mParent(_parent), mLayer(_layer), mOutOfDate(false) { } LayerNode::~LayerNode() { for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { delete (*iter); } mFirstRenderItems.clear(); for (VectorRenderItem::iterator iter=mSecondRenderItems.begin(); iter!=mSecondRenderItems.end(); ++iter) { delete (*iter); } mSecondRenderItems.clear(); // удаляем дочерние узлы for (VectorILayerNode::iterator iter = mChildItems.begin(); iter!=mChildItems.end(); ++iter) { delete (*iter); } mChildItems.clear(); } ILayerNode* LayerNode::createChildItemNode() { LayerNode* layer = new LayerNode(mLayer, this); mChildItems.push_back(layer); return layer; } void LayerNode::destroyChildItemNode(ILayerNode* _node) { for (VectorILayerNode::iterator iter=mChildItems.begin(); iter!=mChildItems.end(); ++iter) { if ((*iter) == _node) { delete _node; mChildItems.erase(iter); return; } } MYGUI_EXCEPT("item node not found"); } void LayerNode::upChildItemNode(ILayerNode* _item) { for (VectorILayerNode::iterator iter=mChildItems.begin(); iter!=mChildItems.end(); ++iter) { if ((*iter) == _item) { mChildItems.erase(iter); mChildItems.push_back(_item); return; } } MYGUI_EXCEPT("item node not found"); } void LayerNode::renderToTarget(IRenderTarget* _target, bool _update) { // проверяем на сжатие пустот bool need_compression = false; for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { if ((*iter)->getCompression()) { need_compression = true; break; } } if (need_compression) updateCompression(); // сначала отрисовываем свое for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { (*iter)->renderToTarget(_target, _update); } for (VectorRenderItem::iterator iter=mSecondRenderItems.begin(); iter!=mSecondRenderItems.end(); ++iter) { (*iter)->renderToTarget(_target, _update); } // теперь отрисовываем дочерние узлы for (VectorILayerNode::iterator iter = mChildItems.begin(); iter!=mChildItems.end(); ++iter) { (*iter)->renderToTarget(_target, _update); } mOutOfDate = false; } ILayerItem* LayerNode::getLayerItemByPoint(int _left, int _top) { // сначала пикаем детей for (VectorILayerNode::iterator iter = mChildItems.begin(); iter!=mChildItems.end(); ++iter) { ILayerItem * item = (*iter)->getLayerItemByPoint(_left, _top); if (nullptr != item) return item; } for (VectorLayerItem::iterator iter=mLayerItems.begin(); iter!=mLayerItems.end(); ++iter) { ILayerItem * item = (*iter)->getLayerItemByPoint(_left, _top); if (nullptr != item) return item; } return nullptr; } RenderItem* LayerNode::addToRenderItem(ITexture* _texture, ISubWidget* _item) { bool first = _item->castType<ISubWidgetText>(false) == nullptr; // для первичной очереди нужен порядок if (first) { if (mFirstRenderItems.empty()) { // создаем новый буфер RenderItem * item = new RenderItem(); item->setTexture(_texture); mFirstRenderItems.push_back(item); return item; } // если последний буфер пустой, то мона не создавать if (mFirstRenderItems.back()->getNeedVertexCount() == 0) { // пустых может быть сколько угодно, нужен самый первый из пустых for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { if ((*iter)->getNeedVertexCount() == 0) { // а теперь внимание, если перед пустым наш, то его и юзаем // косячит, иногда дети рисуются под отцами /*if (iter != mFirstRenderItems.begin()) { VectorRenderItem::iterator prev = iter - 1; if ((*prev)->getTexture() == _texture) { return (*prev); } }*/ (*iter)->setTexture(_texture); return (*iter); } } } // та же текстура if (mFirstRenderItems.back()->getTexture() == _texture) { return mFirstRenderItems.back(); } // создаем новый буфер RenderItem * item = new RenderItem(); item->setTexture(_texture); mFirstRenderItems.push_back(item); return item; } // для второй очереди порядок неважен for (VectorRenderItem::iterator iter=mSecondRenderItems.begin(); iter!=mSecondRenderItems.end(); ++iter) { // либо такая же текстура, либо пустой буфер if ((*iter)->getTexture() == _texture) { return (*iter); } else if ((*iter)->getNeedVertexCount() == 0) { (*iter)->setTexture(_texture); return (*iter); } } // не найденно создадим новый RenderItem * item = new RenderItem(); item->setTexture(_texture); mSecondRenderItems.push_back(item); return mSecondRenderItems.back(); } void LayerNode::attachLayerItem(ILayerItem* _item) { mLayerItems.push_back(_item); _item->attachItemToNode(mLayer, this); } void LayerNode::detachLayerItem(ILayerItem* _item) { for (VectorLayerItem::iterator iter=mLayerItems.begin(); iter!=mLayerItems.end(); ++iter) { if ((*iter) == _item) { (*iter) = mLayerItems.back(); mLayerItems.pop_back(); return; } } MYGUI_EXCEPT("layer item not found"); } void LayerNode::outOfDate(RenderItem* _item) { mOutOfDate = true; if (_item) _item->outOfDate(); } EnumeratorILayerNode LayerNode::getEnumerator() { return EnumeratorILayerNode(mChildItems); } void LayerNode::updateCompression() { // буферы освобождаются по одному всегда if (mFirstRenderItems.size() > 1) { // пытаемся поднять пустой буфер выше полных VectorRenderItem::iterator iter1 = mFirstRenderItems.begin(); VectorRenderItem::iterator iter2 = iter1 + 1; while (iter2 != mFirstRenderItems.end()) { if ((*iter1)->getNeedVertexCount() == 0) { RenderItem * tmp = (*iter1); (*iter1) = (*iter2); (*iter2) = tmp; } iter1 = iter2; ++iter2; } } } void LayerNode::dumpStatisticToLog(size_t _level) { static const char* spacer = " "; std::string offset(" ", _level); MYGUI_LOG(Info, offset << " - Node batch_count='" << mFirstRenderItems.size() + mSecondRenderItems.size() << spacer); for (VectorRenderItem::iterator iter=mFirstRenderItems.begin(); iter!=mFirstRenderItems.end(); ++iter) { MYGUI_LOG(Info, offset << " * Batch texture='" << ((*iter)->getTexture() == nullptr ? "nullptr" : (*iter)->getTexture()->getName()) << "' vertex_count='" << (*iter)->getVertexCount() << "'" << spacer); } for (VectorRenderItem::iterator iter=mSecondRenderItems.begin(); iter!=mSecondRenderItems.end(); ++iter) { MYGUI_LOG(Info, offset << " * Batch texture='" << ((*iter)->getTexture() == nullptr ? "nullptr" : (*iter)->getTexture()->getName()) << "' vertex_count='" << (*iter)->getVertexCount() << "'" << spacer); } for (VectorILayerNode::iterator iter = mChildItems.begin(); iter!=mChildItems.end(); ++iter) { (*iter)->dumpStatisticToLog(_level + 1); } } } // namespace MyGUI <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fontlb.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2006-12-20 14:10:16 $ * * 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 SVX_FONTLB_HXX #define SVX_FONTLB_HXX #ifndef _SVTABBOX_HXX #include <svtools/svtabbx.hxx> #endif #ifndef _SV_VIRDEV_HXX #include <vcl/virdev.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif // ============================================================================ /** A list box string item which stores its text and font. */ class SvLBoxFontString : public SvLBoxString { private: Font maFont; /// The font used by this item. bool mbUseColor; /// true = use font color, false = default listbox color. public: SvLBoxFontString(); SvLBoxFontString( SvLBoxEntry* pEntry, sal_uInt16 nFlags, const XubString& rString, const Font& rFont, const Color* pColor = NULL ); virtual ~SvLBoxFontString(); /** Creates a new empty list box item. */ virtual SvLBoxItem* Create() const; void InitViewData( SvLBox*,SvLBoxEntry*,SvViewDataItem* ); /** Paints this entry to the specified position, using the own font settings. */ void Paint( const Point& rPos, SvLBox& rDev, sal_uInt16 nFlags, SvLBoxEntry* pEntry ); }; // ============================================================================ /** A list box supporting formatted string entries. */ class SVX_DLLPUBLIC SvxFontListBox : public SvTabListBox { private: Font maStdFont; /// Used for entries without specific font. // The following members are used to store additional parameters for InitEntry(). Font maEntryFont; /// Current entry font used in InitEntry(). const Color* mpEntryColor; /// Current entry color used in InitEntry(). bool mbUseFont; /// true = Use maEntryFont/mpEntryColor in InitEntry(). public: SvxFontListBox( Window* pParent, const ResId& rResId ); /** Inserts a list entry and sets the font used for this entry. @param pColor The font color. NULL = use default listbox text color. */ void InsertFontEntry( const String& rString, const Font& rFont, const Color* pColor = NULL ); /** Selects/deselects an entry specified by its position in the list box. */ void SelectEntryPos( sal_uInt16 nPos, bool bSelect = true ); /** Removes a selection. */ void SetNoSelection(); /** Returns the position of the entry currently selected or LIST_ENTRY_NOTFOUND. */ sal_uInt32 GetSelectEntryPos() const; /** Returns the text of the selected entry or an empty string. */ XubString GetSelectEntry() const; protected: /** Initializes a new SvLBoxFontString entry. @descr Uses current value of maEntryFont to set the entry font (if mbUseFont is true). */ virtual void InitEntry( SvLBoxEntry* pEntry, const XubString& rEntryText, const Image& rCollImg, const Image& rExpImg, SvLBoxButtonKind eButtonKind ); }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.602); FILE MERGED 2008/04/01 15:49:14 thb 1.5.602.3: #i85898# Stripping all external header guards 2008/04/01 12:46:20 thb 1.5.602.2: #i85898# Stripping all external header guards 2008/03/31 14:17:55 rt 1.5.602.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fontlb.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SVX_FONTLB_HXX #define SVX_FONTLB_HXX #ifndef _SVTABBOX_HXX #include <svtools/svtabbx.hxx> #endif #include <vcl/virdev.hxx> #include "svx/svxdllapi.h" // ============================================================================ /** A list box string item which stores its text and font. */ class SvLBoxFontString : public SvLBoxString { private: Font maFont; /// The font used by this item. bool mbUseColor; /// true = use font color, false = default listbox color. public: SvLBoxFontString(); SvLBoxFontString( SvLBoxEntry* pEntry, sal_uInt16 nFlags, const XubString& rString, const Font& rFont, const Color* pColor = NULL ); virtual ~SvLBoxFontString(); /** Creates a new empty list box item. */ virtual SvLBoxItem* Create() const; void InitViewData( SvLBox*,SvLBoxEntry*,SvViewDataItem* ); /** Paints this entry to the specified position, using the own font settings. */ void Paint( const Point& rPos, SvLBox& rDev, sal_uInt16 nFlags, SvLBoxEntry* pEntry ); }; // ============================================================================ /** A list box supporting formatted string entries. */ class SVX_DLLPUBLIC SvxFontListBox : public SvTabListBox { private: Font maStdFont; /// Used for entries without specific font. // The following members are used to store additional parameters for InitEntry(). Font maEntryFont; /// Current entry font used in InitEntry(). const Color* mpEntryColor; /// Current entry color used in InitEntry(). bool mbUseFont; /// true = Use maEntryFont/mpEntryColor in InitEntry(). public: SvxFontListBox( Window* pParent, const ResId& rResId ); /** Inserts a list entry and sets the font used for this entry. @param pColor The font color. NULL = use default listbox text color. */ void InsertFontEntry( const String& rString, const Font& rFont, const Color* pColor = NULL ); /** Selects/deselects an entry specified by its position in the list box. */ void SelectEntryPos( sal_uInt16 nPos, bool bSelect = true ); /** Removes a selection. */ void SetNoSelection(); /** Returns the position of the entry currently selected or LIST_ENTRY_NOTFOUND. */ sal_uInt32 GetSelectEntryPos() const; /** Returns the text of the selected entry or an empty string. */ XubString GetSelectEntry() const; protected: /** Initializes a new SvLBoxFontString entry. @descr Uses current value of maEntryFont to set the entry font (if mbUseFont is true). */ virtual void InitEntry( SvLBoxEntry* pEntry, const XubString& rEntryText, const Image& rCollImg, const Image& rExpImg, SvLBoxButtonKind eButtonKind ); }; // ============================================================================ #endif <|endoftext|>
<commit_before>/* This file is part of Bohrium and Copyright (c) 2012 the Bohrium team: http://bohrium.bitbucket.org Bohrium 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. Bohrium 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 Lesser General Public License along with bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include "bh/bh.hpp" #include "util/timing.hpp" #include "util/argparse.hpp" using namespace std; using namespace bh; using namespace argparse; template <typename T> multi_array<T>& cnd(multi_array<T>& x) { multi_array<T> l, k, w; multi_array<bh_bool> mask; T a1 = 0.31938153, a2 =-0.356563782, a3 = 1.781477937, a4 =-1.821255978, a5 = 1.330274429, pp = 2.5066282746310002; // sqrt(2.0*PI) l = abs(x); k = 1.0 / (1.0 + 0.2316419 * l); w = 1.0 - 1.0 / pp * exp(-1.0*l*l/2.0) * \ (a1*k + \ a2*(pow(k,(T)2)) + \ a3*(pow(k,(T)3)) + \ a4*(pow(k,(T)4)) + \ a5*(pow(k,(T)5))); mask = x < 0.0; return w * as<T>(!mask) + (1.0-w)* as<T>(mask); } template <typename T> T* pricing(size_t samples, size_t iterations, char flag, T x, T d_t, T r, T v) { multi_array<T> d1, d2, res, s; T* p = (T*)malloc(sizeof(T)*samples); // Intermediate results T t = d_t; // Initial delta s = random<T>((int64_t)samples)*4.0 +58.0; // Model between 58-62 for(size_t i=0; i<iterations; i++) { d1 = (log(s/x) + (r+v*v/2.0)*t) / (v*sqrt(t)); d2 = d1-v*sqrt(t); if (flag == 'c') { res = s * cnd(d1) - x * exp(-r * t) * cnd(d2); } else { res = x * exp(-r*t) * cnd(-1.0*d2) - s*cnd(-1.0*d1); } t += d_t; // Increment delta p[i] = scalar(sum(res)) / (T)samples; // Result from timestep } return p; } int main(int argc, char* argv[]) { const char usage[] = "usage: ./black_scholes --size=1000*10 [--verbose]"; if (2>argc) { cout << usage << endl; return 1; } arguments_t args; // Parse command-line if (!parse_args(argc, argv, args)) { cout << "Err: Invalid argument(s)." << endl; cout << usage << endl; return 1; } if (2 > args.size.size()) { cout << "Err: Not enough arguments." << endl; cout << usage << endl; return 1; } if (2 < args.size.size()) { cout << "Err: Too many arguments." << endl; cout << usage << endl; return 1; } bh_intp start = _bh_timing(); double* prices = pricing<double>( // Do the computations... args.size[0], args.size[1], 'c', 65.0, 1.0 / 365.0, 0.08, 0.3 ); stop(); // Output timing cout << "{elapsed-time: "<< (_bh_timing()-start)/1000000.0 <<""; if (args.verbose) { // and values. cout << ", \"output\": ["; for(size_t i=0; i<args.size[1]; i++) { cout << prices[i]; if (args.size[1]-1!=i) { cout << ", "; } } cout << "]" << endl; } cout << "}" << endl; free(prices); // Cleanup return 0; } <commit_msg>cppb/benchmarks: Fixed an indexing error in cpp/black_scholes.<commit_after>/* This file is part of Bohrium and Copyright (c) 2012 the Bohrium team: http://bohrium.bitbucket.org Bohrium 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. Bohrium 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 Lesser General Public License along with bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include "bh/bh.hpp" #include "util/timing.hpp" #include "util/argparse.hpp" using namespace std; using namespace bh; using namespace argparse; template <typename T> multi_array<T>& cnd(multi_array<T>& x) { multi_array<T> l, k, w; multi_array<bh_bool> mask; T a1 = 0.31938153, a2 =-0.356563782, a3 = 1.781477937, a4 =-1.821255978, a5 = 1.330274429, pp = 2.5066282746310002; // sqrt(2.0*PI) l = abs(x); k = 1.0 / (1.0 + 0.2316419 * l); w = 1.0 - 1.0 / pp * exp(-1.0*l*l/2.0) * \ (a1*k + \ a2*(pow(k,(T)2)) + \ a3*(pow(k,(T)3)) + \ a4*(pow(k,(T)4)) + \ a5*(pow(k,(T)5))); mask = x < 0.0; return w * as<T>(!mask) + (1.0-w)* as<T>(mask); } template <typename T> T* pricing(size_t samples, size_t iterations, char flag, T x, T d_t, T r, T v) { multi_array<T> d1, d2, res, s; T* p = (T*)malloc(sizeof(T)*iterations); // Intermediate results T t = d_t; // Initial delta s = random<T>((int64_t)samples)*4.0 +58.0; // Model between 58-62 for(size_t i=0; i<iterations; i++) { d1 = (log(s/x) + (r+v*v/2.0)*t) / (v*sqrt(t)); d2 = d1-v*sqrt(t); if (flag == 'c') { res = s * cnd(d1) - x * exp(-r * t) * cnd(d2); } else { res = x * exp(-r*t) * cnd(-1.0*d2) - s*cnd(-1.0*d1); } t += d_t; // Increment delta p[i] = scalar(sum(res)) / (T)samples; // Result from timestep } return p; } int main(int argc, char* argv[]) { const char usage[] = "usage: ./black_scholes --size=1000*10 [--verbose]"; if (2>argc) { cout << usage << endl; return 1; } arguments_t args; // Parse command-line if (!parse_args(argc, argv, args)) { cout << "Err: Invalid argument(s)." << endl; cout << usage << endl; return 1; } if (2 > args.size.size()) { cout << "Err: Not enough arguments." << endl; cout << usage << endl; return 1; } if (2 < args.size.size()) { cout << "Err: Too many arguments." << endl; cout << usage << endl; return 1; } bh_intp start = _bh_timing(); double* prices = pricing<double>( // Do the computations... args.size[0], args.size[1], 'c', 65.0, 1.0 / 365.0, 0.08, 0.3 ); stop(); // Output timing cout << "{elapsed-time: "<< (_bh_timing()-start)/1000000.0 <<""; if (args.verbose) { // and values. cout << ", \"output\": ["; for(size_t i=0; i<args.size[1]; i++) { cout << prices[i]; if (args.size[1]-1!=i) { cout << ", "; } } cout << "]" << endl; } cout << "}" << endl; free(prices); // Cleanup return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: breakit.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: jp $ $Date: 2000-11-20 09:33:11 $ * * 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 _BREAKIT_HXX #define _BREAKIT_HXX #ifndef _LANG_HXX //autogen #include <tools/lang.hxx> #endif /************************************************************************* * class SwBreakIt *************************************************************************/ #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_TEXT_XBREAKITERATOR_HPP_ #include <com/sun/star/text/XBreakIterator.hpp> #endif class SwBreakIt { public: com::sun::star::uno::Reference < com::sun::star::text::XBreakIterator > xBreak; private: com::sun::star::lang::Locale* pLocale; LanguageType aLast; com::sun::star::lang::Locale& _GetLocale( const LanguageType aLang ); public: SwBreakIt(); ~SwBreakIt() { delete pLocale; } com::sun::star::lang::Locale& GetLocale( const LanguageType aLang ) { if( aLast == aLang ) return *pLocale; return _GetLocale( aLang ); } }; extern SwBreakIt* pBreakIt; #endif <commit_msg>BreakIterator moved to i18n<commit_after>/************************************************************************* * * $RCSfile: breakit.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: jp $ $Date: 2000-11-20 15:00:30 $ * * 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 _BREAKIT_HXX #define _BREAKIT_HXX #ifndef _LANG_HXX //autogen #include <tools/lang.hxx> #endif /************************************************************************* * class SwBreakIt *************************************************************************/ #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_I18N_XBREAKITERATOR_HPP_ #include <com/sun/star/i18n/XBreakIterator.hpp> #endif class SwBreakIt { public: com::sun::star::uno::Reference < com::sun::star::i18n::XBreakIterator > xBreak; private: com::sun::star::lang::Locale* pLocale; LanguageType aLast; com::sun::star::lang::Locale& _GetLocale( const LanguageType aLang ); public: SwBreakIt(); ~SwBreakIt() { delete pLocale; } com::sun::star::lang::Locale& GetLocale( const LanguageType aLang ) { if( aLast == aLang ) return *pLocale; return _GetLocale( aLang ); } }; extern SwBreakIt* pBreakIt; #endif <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include "loader_talk.h" #include <errno.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <cassert> #include <cstdlib> #include "loader.h" #include "logging.h" #include "platform.h" #include "util/posix.h" using namespace std; // NOLINT namespace loader { namespace loader_talk { bool spawned_ = false; string *socket_path_ = NULL; int socket_fd_ = -1; pthread_t thread_talk_; bool Init(const string &socket_path) { spawned_ = false; socket_path_ = new string(socket_path); socket_fd_ = MakeSocket(*socket_path_, 0600); if (socket_fd_ == -1) return false; if (listen(socket_fd_, 1) == -1) { LogCvmfs(kLogCvmfs, kLogDebug, "listening on socket failed (%d)", errno); return false; } unlink((socket_path + ".paused.crashed").c_str()); unlink((socket_path + ".paused").c_str()); return true; } static void *MainTalk(void *data __attribute__((unused))) { struct sockaddr_un remote; socklen_t socket_size = sizeof(remote); int con_fd = -1; while (true) { if (con_fd >= 0) { shutdown(con_fd, SHUT_RDWR); close(con_fd); } if ((con_fd = accept(socket_fd_, (struct sockaddr *)&remote, &socket_size)) < 0) { break; } char command; if (recv(con_fd, &command, 1, 0) > 0) { if ((command != 'R') && (command != 'S')) { SendMsg2Socket(con_fd, "unknown command\n"); continue; } SetLogMicroSyslog(*usyslog_path_); LogCvmfs(kLogCvmfs, kLogSyslog, "reloading Fuse module"); int retval = Reload(con_fd, command == 'S'); SendMsg2Socket(con_fd, "~"); (void)send(con_fd, &retval, sizeof(retval), MSG_NOSIGNAL); if (retval != kFailOk) { LogCvmfs(kLogCvmfs, kLogSyslogErr, "reloading Fuse module failed " "(%d - %s)", retval, Code2Ascii(static_cast<Failures>(retval))); abort(); } SetLogMicroSyslog(""); } } return NULL; } void Spawn() { int retval; retval = pthread_create(&thread_talk_, NULL, MainTalk, NULL); assert(retval == 0); spawned_ = true; } void Fini() { unlink(socket_path_->c_str()); shutdown(socket_fd_, SHUT_RDWR); close(socket_fd_); if (spawned_) pthread_join(thread_talk_, NULL); delete socket_path_; socket_path_ = NULL; spawned_ = false; socket_fd_ = -1; } /** * Connects to a loader socket and triggers the reload */ int MainReload(const std::string &socket_path, const bool stop_and_go) { LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "Connecting to CernVM-FS loader... "); int socket_fd = ConnectSocket(socket_path); if (socket_fd < 0) { LogCvmfs(kLogCvmfs, kLogStdout, "failed!"); return 100; } LogCvmfs(kLogCvmfs, kLogStdout, "done"); const char command = stop_and_go ? 'S' : 'R'; WritePipe(socket_fd, &command, 1); char buf; int retval; while ((retval = read(socket_fd, &buf, 1)) == 1) { if (buf == '~') break; LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "%c", buf); } if (retval != 1) { LogCvmfs(kLogCvmfs, kLogStderr, "Reload CRASHED! " "CernVM-FS mountpoints unusuable."); return 101; } int result = 102; retval = read(socket_fd, &result, sizeof(result)); if ((retval != 0) || (result != kFailOk)) { LogCvmfs(kLogCvmfs, kLogStderr, "Reload FAILED! " "CernVM-FS mountpoints unusuable."); } return result; } } // namespace loader_talk } // namespace loader <commit_msg>fix wrong error message in cvmfs_config reload<commit_after>/** * This file is part of the CernVM File System. */ #include "cvmfs_config.h" #include "loader_talk.h" #include <errno.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <cassert> #include <cstdlib> #include "loader.h" #include "logging.h" #include "platform.h" #include "util/posix.h" using namespace std; // NOLINT namespace loader { namespace loader_talk { bool spawned_ = false; string *socket_path_ = NULL; int socket_fd_ = -1; pthread_t thread_talk_; bool Init(const string &socket_path) { spawned_ = false; socket_path_ = new string(socket_path); socket_fd_ = MakeSocket(*socket_path_, 0600); if (socket_fd_ == -1) return false; if (listen(socket_fd_, 1) == -1) { LogCvmfs(kLogCvmfs, kLogDebug, "listening on socket failed (%d)", errno); return false; } unlink((socket_path + ".paused.crashed").c_str()); unlink((socket_path + ".paused").c_str()); return true; } static void *MainTalk(void *data __attribute__((unused))) { struct sockaddr_un remote; socklen_t socket_size = sizeof(remote); int con_fd = -1; while (true) { if (con_fd >= 0) { shutdown(con_fd, SHUT_RDWR); close(con_fd); } if ((con_fd = accept(socket_fd_, (struct sockaddr *)&remote, &socket_size)) < 0) { break; } char command; if (recv(con_fd, &command, 1, 0) > 0) { if ((command != 'R') && (command != 'S')) { SendMsg2Socket(con_fd, "unknown command\n"); continue; } SetLogMicroSyslog(*usyslog_path_); LogCvmfs(kLogCvmfs, kLogSyslog, "reloading Fuse module"); int retval = Reload(con_fd, command == 'S'); SendMsg2Socket(con_fd, "~"); (void)send(con_fd, &retval, sizeof(retval), MSG_NOSIGNAL); if (retval != kFailOk) { LogCvmfs(kLogCvmfs, kLogSyslogErr, "reloading Fuse module failed " "(%d - %s)", retval, Code2Ascii(static_cast<Failures>(retval))); abort(); } SetLogMicroSyslog(""); } } return NULL; } void Spawn() { int retval; retval = pthread_create(&thread_talk_, NULL, MainTalk, NULL); assert(retval == 0); spawned_ = true; } void Fini() { unlink(socket_path_->c_str()); shutdown(socket_fd_, SHUT_RDWR); close(socket_fd_); if (spawned_) pthread_join(thread_talk_, NULL); delete socket_path_; socket_path_ = NULL; spawned_ = false; socket_fd_ = -1; } /** * Connects to a loader socket and triggers the reload */ int MainReload(const std::string &socket_path, const bool stop_and_go) { LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "Connecting to CernVM-FS loader... "); int socket_fd = ConnectSocket(socket_path); if (socket_fd < 0) { LogCvmfs(kLogCvmfs, kLogStdout, "failed!"); return 100; } LogCvmfs(kLogCvmfs, kLogStdout, "done"); const char command = stop_and_go ? 'S' : 'R'; WritePipe(socket_fd, &command, 1); char buf; int retval; while ((retval = read(socket_fd, &buf, 1)) == 1) { if (buf == '~') break; LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "%c", buf); } if (retval != 1) { LogCvmfs(kLogCvmfs, kLogStderr, "Reload CRASHED! " "CernVM-FS mountpoints unusuable."); return 101; } int result = 102; (void) read(socket_fd, &result, sizeof(result)); if (result != kFailOk) { LogCvmfs(kLogCvmfs, kLogStderr, "Reload FAILED! " "CernVM-FS mountpoints unusuable."); } return result; } } // namespace loader_talk } // namespace loader <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Achim Brandt //////////////////////////////////////////////////////////////////////////////// #include "Thread.h" #include <errno.h> #include <signal.h> #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/ConditionLocker.h" #include "Basics/Exceptions.h" #include "Logger/Logger.h" #include <chrono> #include <thread> using namespace arangodb; using namespace arangodb::application_features; using namespace arangodb::basics; /// @brief local thread number static thread_local uint64_t LOCAL_THREAD_NUMBER = 0; static thread_local char const* LOCAL_THREAD_NAME = nullptr; #if !defined(ARANGODB_HAVE_GETTID) && !defined(_WIN32) namespace { std::atomic<uint64_t> NEXT_THREAD_ID(1); } #endif /// @brief static started with access to the private variables void Thread::startThread(void* arg) { #if defined(ARANGODB_HAVE_GETTID) LOCAL_THREAD_NUMBER = (uint64_t)gettid(); #elif defined(_WIN32) LOCAL_THREAD_NUMBER = (uint64_t)GetCurrentThreadId(); #else LOCAL_THREAD_NUMBER = NEXT_THREAD_ID.fetch_add(1, std::memory_order_seq_cst); #endif TRI_ASSERT(arg != nullptr); Thread* ptr = static_cast<Thread*>(arg); TRI_ASSERT(ptr != nullptr); ptr->_threadNumber = LOCAL_THREAD_NUMBER; LOCAL_THREAD_NAME = ptr->name().c_str(); // make sure we drop our reference when we are finished! auto guard = scopeGuard([ptr]() { LOCAL_THREAD_NAME = nullptr; ptr->_state.store(ThreadState::STOPPED); ptr->releaseRef(); }); ThreadState expected = ThreadState::STARTING; bool res = ptr->_state.compare_exchange_strong(expected, ThreadState::STARTED); if (!res) { TRI_ASSERT(expected == ThreadState::STOPPING); // we are already shutting down -> don't bother calling run! return; } try { ptr->runMe(); } catch (std::exception const& ex) { LOG_TOPIC(WARN, Logger::THREADS) << "caught exception in thread '" << ptr->_name << "': " << ex.what(); ptr->crashNotification(ex); throw; } } /// @brief returns the process id TRI_pid_t Thread::currentProcessId() { #ifdef _WIN32 return _getpid(); #else return getpid(); #endif } /// @brief returns the thread process id uint64_t Thread::currentThreadNumber() { return LOCAL_THREAD_NUMBER; } /// @brief returns the name of the current thread, if set /// note that this function may return a nullptr char const* Thread::currentThreadName() { return LOCAL_THREAD_NAME; } /// @brief returns the thread id TRI_tid_t Thread::currentThreadId() { #ifdef TRI_HAVE_WIN32_THREADS return GetCurrentThreadId(); #else #ifdef TRI_HAVE_POSIX_THREADS return pthread_self(); #else #error "Thread::currentThreadId not implemented" #endif #endif } std::string Thread::stringify(ThreadState state) { switch (state) { case ThreadState::CREATED: return "created"; case ThreadState::STARTING: return "starting"; case ThreadState::STARTED: return "started"; case ThreadState::STOPPING: return "stopping"; case ThreadState::STOPPED: return "stopped"; } return "unknown"; } /// @brief constructs a thread Thread::Thread(std::string const& name, bool deleteOnExit) : _deleteOnExit(deleteOnExit), _threadStructInitialized(false), _refs(0), _name(name), _thread(), _threadNumber(0), _finishedCondition(nullptr), _state(ThreadState::CREATED) { TRI_InitThread(&_thread); } /// @brief deletes the thread Thread::~Thread() { TRI_ASSERT(_refs.load() == 0); auto state = _state.load(); LOG_TOPIC(TRACE, Logger::THREADS) << "delete(" << _name << "), state: " << stringify(state); if (state != ThreadState::STOPPED) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "thread '" << _name << "' is not stopped but " << stringify(state) << ". shutting down hard"; FATAL_ERROR_ABORT(); } } /// @brief flags the thread as stopping void Thread::beginShutdown() { LOG_TOPIC(TRACE, Logger::THREADS) << "beginShutdown(" << _name << ") in state " << stringify(_state.load()); ThreadState state = _state.load(); while (state == ThreadState::CREATED) { _state.compare_exchange_weak(state, ThreadState::STOPPED); } while (state != ThreadState::STOPPING && state != ThreadState::STOPPED) { _state.compare_exchange_weak(state, ThreadState::STOPPING); } LOG_TOPIC(TRACE, Logger::THREADS) << "beginShutdown(" << _name << ") reached state " << stringify(_state.load()); } /// @brief MUST be called from the destructor of the MOST DERIVED class void Thread::shutdown() { LOG_TOPIC(TRACE, Logger::THREADS) << "shutdown(" << _name << ")"; beginShutdown(); if (_threadStructInitialized) { if (TRI_IsSelfThread(&_thread)) { // we must ignore any errors here, but TRI_DetachThread will log them TRI_DetachThread(&_thread); } else { // we must ignore any errors here, but TRI_JoinThread will log them TRI_JoinThread(&_thread); } } TRI_ASSERT(_refs.load() == 0); TRI_ASSERT(_state.load() == ThreadState::STOPPED); } /// @brief checks if the current thread was asked to stop bool Thread::isStopping() const { auto state = _state.load(std::memory_order_relaxed); return state == ThreadState::STOPPING || state == ThreadState::STOPPED; } /// @brief starts the thread bool Thread::start(ConditionVariable* finishedCondition) { if (!isSystem() && !ApplicationServer::isPrepared()) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "trying to start a thread '" << _name << "' before prepare has finished, current state: " << (ApplicationServer::server == nullptr ? -1 : (int)ApplicationServer::server->state()); FATAL_ERROR_ABORT(); } _finishedCondition = finishedCondition; ThreadState state = _state.load(); if (state != ThreadState::CREATED) { LOG_TOPIC(FATAL, Logger::THREADS) << "called started on an already started thread, thread is in state " << stringify(state); FATAL_ERROR_ABORT(); } ThreadState expected = ThreadState::CREATED; if (!_state.compare_exchange_strong(expected, ThreadState::STARTING)) { // This should never happen! If it does, it means we have multiple calls to start(). LOG_TOPIC(WARN, Logger::THREADS) << "failed to set thread to state 'starting'; thread is in unexpected state " << stringify(expected); FATAL_ERROR_ABORT(); } // we count two references - one for the current thread and one for the thread that // we are trying to start. _refs.fetch_add(2); TRI_ASSERT(_refs.load() == 2); TRI_ASSERT(_threadStructInitialized == false); TRI_InitThread(&_thread); bool ok = TRI_StartThread(&_thread, _name.c_str(), &startThread, this); if (!ok) { // could not start the thread -> decrement ref for the foreign thread _refs.fetch_sub(1); _state.store(ThreadState::STOPPED); LOG_TOPIC(ERR, Logger::THREADS) << "could not start thread '" << _name << "': " << TRI_last_error(); } _threadStructInitialized = true; releaseRef(); return ok; } void Thread::markAsStopped() { // TODO - marked as stopped before accessing finishedCondition? _state.store(ThreadState::STOPPED); if (_finishedCondition != nullptr) { CONDITION_LOCKER(locker, *_finishedCondition); locker.broadcast(); } } void Thread::runMe() { // make sure the thread is marked as stopped under all circumstances TRI_DEFER(markAsStopped()); try { run(); } catch (std::exception const& ex) { if (!isSilent()) { LOG_TOPIC(ERR, Logger::THREADS) << "exception caught in thread '" << _name << "': " << ex.what(); Logger::flush(); } throw; } catch (...) { if (!isSilent()) { LOG_TOPIC(ERR, Logger::THREADS) << "unknown exception caught in thread '" << _name << "'"; Logger::flush(); } throw; } } void Thread::releaseRef() { auto refs = _refs.fetch_sub(1) - 1; TRI_ASSERT(refs >= 0); if (refs == 0 && _deleteOnExit) { LOCAL_THREAD_NAME = nullptr; delete this; } } <commit_msg>show thread name in fatal error messages<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler /// @author Achim Brandt //////////////////////////////////////////////////////////////////////////////// #include "Thread.h" #include <errno.h> #include <signal.h> #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/ConditionLocker.h" #include "Basics/Exceptions.h" #include "Logger/Logger.h" #include <chrono> #include <thread> using namespace arangodb; using namespace arangodb::application_features; using namespace arangodb::basics; /// @brief local thread number static thread_local uint64_t LOCAL_THREAD_NUMBER = 0; static thread_local char const* LOCAL_THREAD_NAME = nullptr; #if !defined(ARANGODB_HAVE_GETTID) && !defined(_WIN32) namespace { std::atomic<uint64_t> NEXT_THREAD_ID(1); } #endif /// @brief static started with access to the private variables void Thread::startThread(void* arg) { #if defined(ARANGODB_HAVE_GETTID) LOCAL_THREAD_NUMBER = (uint64_t)gettid(); #elif defined(_WIN32) LOCAL_THREAD_NUMBER = (uint64_t)GetCurrentThreadId(); #else LOCAL_THREAD_NUMBER = NEXT_THREAD_ID.fetch_add(1, std::memory_order_seq_cst); #endif TRI_ASSERT(arg != nullptr); Thread* ptr = static_cast<Thread*>(arg); TRI_ASSERT(ptr != nullptr); ptr->_threadNumber = LOCAL_THREAD_NUMBER; LOCAL_THREAD_NAME = ptr->name().c_str(); // make sure we drop our reference when we are finished! auto guard = scopeGuard([ptr]() { LOCAL_THREAD_NAME = nullptr; ptr->_state.store(ThreadState::STOPPED); ptr->releaseRef(); }); ThreadState expected = ThreadState::STARTING; bool res = ptr->_state.compare_exchange_strong(expected, ThreadState::STARTED); if (!res) { TRI_ASSERT(expected == ThreadState::STOPPING); // we are already shutting down -> don't bother calling run! return; } try { ptr->runMe(); } catch (std::exception const& ex) { LOG_TOPIC(WARN, Logger::THREADS) << "caught exception in thread '" << ptr->_name << "': " << ex.what(); ptr->crashNotification(ex); throw; } } /// @brief returns the process id TRI_pid_t Thread::currentProcessId() { #ifdef _WIN32 return _getpid(); #else return getpid(); #endif } /// @brief returns the thread process id uint64_t Thread::currentThreadNumber() { return LOCAL_THREAD_NUMBER; } /// @brief returns the name of the current thread, if set /// note that this function may return a nullptr char const* Thread::currentThreadName() { return LOCAL_THREAD_NAME; } /// @brief returns the thread id TRI_tid_t Thread::currentThreadId() { #ifdef TRI_HAVE_WIN32_THREADS return GetCurrentThreadId(); #else #ifdef TRI_HAVE_POSIX_THREADS return pthread_self(); #else #error "Thread::currentThreadId not implemented" #endif #endif } std::string Thread::stringify(ThreadState state) { switch (state) { case ThreadState::CREATED: return "created"; case ThreadState::STARTING: return "starting"; case ThreadState::STARTED: return "started"; case ThreadState::STOPPING: return "stopping"; case ThreadState::STOPPED: return "stopped"; } return "unknown"; } /// @brief constructs a thread Thread::Thread(std::string const& name, bool deleteOnExit) : _deleteOnExit(deleteOnExit), _threadStructInitialized(false), _refs(0), _name(name), _thread(), _threadNumber(0), _finishedCondition(nullptr), _state(ThreadState::CREATED) { TRI_InitThread(&_thread); } /// @brief deletes the thread Thread::~Thread() { TRI_ASSERT(_refs.load() == 0); auto state = _state.load(); LOG_TOPIC(TRACE, Logger::THREADS) << "delete(" << _name << "), state: " << stringify(state); if (state != ThreadState::STOPPED) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "thread '" << _name << "' is not stopped but " << stringify(state) << ". shutting down hard"; FATAL_ERROR_ABORT(); } } /// @brief flags the thread as stopping void Thread::beginShutdown() { LOG_TOPIC(TRACE, Logger::THREADS) << "beginShutdown(" << _name << ") in state " << stringify(_state.load()); ThreadState state = _state.load(); while (state == ThreadState::CREATED) { _state.compare_exchange_weak(state, ThreadState::STOPPED); } while (state != ThreadState::STOPPING && state != ThreadState::STOPPED) { _state.compare_exchange_weak(state, ThreadState::STOPPING); } LOG_TOPIC(TRACE, Logger::THREADS) << "beginShutdown(" << _name << ") reached state " << stringify(_state.load()); } /// @brief MUST be called from the destructor of the MOST DERIVED class void Thread::shutdown() { LOG_TOPIC(TRACE, Logger::THREADS) << "shutdown(" << _name << ")"; beginShutdown(); if (_threadStructInitialized) { if (TRI_IsSelfThread(&_thread)) { // we must ignore any errors here, but TRI_DetachThread will log them TRI_DetachThread(&_thread); } else { // we must ignore any errors here, but TRI_JoinThread will log them TRI_JoinThread(&_thread); } } TRI_ASSERT(_refs.load() == 0); TRI_ASSERT(_state.load() == ThreadState::STOPPED); } /// @brief checks if the current thread was asked to stop bool Thread::isStopping() const { auto state = _state.load(std::memory_order_relaxed); return state == ThreadState::STOPPING || state == ThreadState::STOPPED; } /// @brief starts the thread bool Thread::start(ConditionVariable* finishedCondition) { if (!isSystem() && !ApplicationServer::isPrepared()) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "trying to start a thread '" << _name << "' before prepare has finished, current state: " << (ApplicationServer::server == nullptr ? -1 : (int)ApplicationServer::server->state()); FATAL_ERROR_ABORT(); } _finishedCondition = finishedCondition; ThreadState state = _state.load(); if (state != ThreadState::CREATED) { LOG_TOPIC(FATAL, Logger::THREADS) << "called started on an already started thread '" << _name << "', thread is in state " << stringify(state); FATAL_ERROR_ABORT(); } ThreadState expected = ThreadState::CREATED; if (!_state.compare_exchange_strong(expected, ThreadState::STARTING)) { // This should never happen! If it does, it means we have multiple calls to start(). LOG_TOPIC(WARN, Logger::THREADS) << "failed to set thread '" << _name << "' to state 'starting'; thread is in unexpected state " << stringify(expected); FATAL_ERROR_ABORT(); } // we count two references - one for the current thread and one for the thread that // we are trying to start. _refs.fetch_add(2); TRI_ASSERT(_refs.load() == 2); TRI_ASSERT(_threadStructInitialized == false); TRI_InitThread(&_thread); bool ok = TRI_StartThread(&_thread, _name.c_str(), &startThread, this); if (!ok) { // could not start the thread -> decrement ref for the foreign thread _refs.fetch_sub(1); _state.store(ThreadState::STOPPED); LOG_TOPIC(ERR, Logger::THREADS) << "could not start thread '" << _name << "': " << TRI_last_error(); } _threadStructInitialized = true; releaseRef(); return ok; } void Thread::markAsStopped() { // TODO - marked as stopped before accessing finishedCondition? _state.store(ThreadState::STOPPED); if (_finishedCondition != nullptr) { CONDITION_LOCKER(locker, *_finishedCondition); locker.broadcast(); } } void Thread::runMe() { // make sure the thread is marked as stopped under all circumstances TRI_DEFER(markAsStopped()); try { run(); } catch (std::exception const& ex) { if (!isSilent()) { LOG_TOPIC(ERR, Logger::THREADS) << "exception caught in thread '" << _name << "': " << ex.what(); Logger::flush(); } throw; } catch (...) { if (!isSilent()) { LOG_TOPIC(ERR, Logger::THREADS) << "unknown exception caught in thread '" << _name << "'"; Logger::flush(); } throw; } } void Thread::releaseRef() { auto refs = _refs.fetch_sub(1) - 1; TRI_ASSERT(refs >= 0); if (refs == 0 && _deleteOnExit) { LOCAL_THREAD_NAME = nullptr; delete this; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ndhints.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2007-04-25 08:55:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _NDHINTS_HXX #define _NDHINTS_HXX #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #ifndef _SVMEMPOOL_HXX //autogen #include <tools/mempool.hxx> #endif #include "numrule.hxx" class SwTxtNode; class SwRegHistory; // steht im RolBck.hxx class SwTxtAttr; /* * Ableitung der Klasse SwpHints ueber den Umweg ueber SwpHts, da * lediglich die Klasse SwTxtNode Attribute einfuegen und * loeschen koennen soll. Anderen Klassen wie den Frames steht * lediglich ein lesender Zugriff ueber den Index-Operator zur * Verfuegung. * Groesse beim Anlegen gleich 1, weil nur dann ein Array erzeug wird, wenn * auch ein Hint eingefuegt wird. */ /************************************************************************* * class SwpHtStart/End *************************************************************************/ SV_DECL_PTRARR_SORT(SwpHtStart,SwTxtAttr*,1,1) SV_DECL_PTRARR_SORT(SwpHtEnd,SwTxtAttr*,1,1) /************************************************************************* * class SwpHintsArr *************************************************************************/ // Das neue Hintsarray: class SwpHintsArr : private SwpHtStart { protected: SwpHtEnd aHtEnd; public: void Insert( const SwTxtAttr *pHt ); void DeleteAtPos( const USHORT nPosInStart ); BOOL Resort(); SwTxtAttr *Cut( const USHORT nPosInStart ); inline const SwTxtAttr *GetStart( const USHORT nPos ) const { return (*this)[nPos]; } inline const SwTxtAttr *GetEnd( const USHORT nPos ) const { return aHtEnd[nPos]; } inline SwTxtAttr *GetStart( const USHORT nPos ) { return GetHt(nPos); } inline SwTxtAttr *GetEnd( const USHORT nPos ) { return aHtEnd[nPos]; } inline USHORT GetEndCount() const { return aHtEnd.Count(); } inline USHORT GetStartCount() const { return Count(); } inline USHORT GetStartOf( const SwTxtAttr *pHt ) const; inline USHORT GetPos( const SwTxtAttr *pHt ) const // OS: in svmem.hxx wird fuer TCPP GetPos ohne const gerufen #ifdef TCPP { return SwpHtStart::GetPos( (SwTxtAttr *)pHt ); } #else { return SwpHtStart::GetPos( pHt ); } #endif inline SwTxtAttr *GetHt( const USHORT nIdx ) { return SwpHtStart::operator[](nIdx); } inline const SwTxtAttr *operator[]( const USHORT nIdx )const { return SwpHtStart::operator[](nIdx); } inline USHORT Count() const { return SwpHtStart::Count(); } #ifndef PRODUCT BOOL Check() const; #endif }; /************************************************************************* * class SwpHints *************************************************************************/ // Die public-Schnittstelle zum Node hin class SwpHints: public SwpHintsArr { private: SwRegHistory* pHistory; // Numerierung BOOL bHasHiddenParaField :1; // HiddenParaFld BOOL bFntChg :1; // Fontwechsel BOOL bFtn :1; // Fussnoten BOOL bInSplitNode: 1; // TRUE: der Node ist im Split und die Frames // werden verschoben! BOOL bDDEFlds : 1; // es sind DDE-Felder am TextNode vorhanden BOOL bCalcHiddenParaField : 1; // bHasHiddenParaField ist invalid, CalcHiddenParaField() rufen // Haelt ein neues Attribut in pHistory fest. void NoteInHistory( SwTxtAttr *pAttr, const BOOL bNew = FALSE ); void CalcFlags( ); // die Delete Methoden duerfen nur vom TextNode gerufen werden !! // Dieser sorgt dafuer, das bei Attributen ohne Ende auch das // entsp. Zeichen entfernt wird !! friend class SwTxtNode; void DeleteAtPos( const USHORT nPos ); // Ist der Hint schon bekannt, dann suche die Position und loesche ihn. // Ist er nicht im Array, so gibt es ein ASSERT !! void Delete( SwTxtAttr* pTxtHt ); inline void SetCalcHiddenParaField(){ bCalcHiddenParaField = TRUE; } inline void SetHiddenParaField( const BOOL bNew ) { bHasHiddenParaField = bNew; } inline BOOL HasHiddenParaField() const { if( bCalcHiddenParaField ) ((SwpHints*)this)->CalcHiddenParaField(); return bHasHiddenParaField; } void BuildPortions( SwTxtNode& rNode, SwTxtAttr& rNewHint, USHORT nMode ); bool MergePortions( SwTxtNode& rNode ); public: inline BOOL CanBeDeleted() const { return !Count(); } // damit das SwDoc::Undo ueber alle Attributaenderungen informiert // wird, gibt es hier einen Pointer auf die History. Nur wenn dieser // != 0 ist, muessen alle Attributaenderungen "gemeldet" werden. void Register( SwRegHistory* pHist ) { pHistory = pHist; } void DeRegister() { Register(0); } void Insert( SwTxtAttr* pHt, SwTxtNode &rNode, USHORT nMode = 0 ); inline BOOL HasFtn() const { return bFtn; } inline BOOL IsInSplitNode() const { return bInSplitNode; } // Konstruktor (wird im nur einmal benutzt!) SwpHints() { pHistory = 0; bFntChg = TRUE; bDDEFlds = bFtn = bInSplitNode = bCalcHiddenParaField = bHasHiddenParaField = FALSE; } // Berechnung von bHasHiddenParaField, return-Wert TRUE bei Aenderung BOOL CalcHiddenParaField(); DECL_FIXEDMEMPOOL_NEWDEL(SwpHints) }; // Ausgabeoperator fuer die Texthints SvStream &operator<<(SvStream &aS, const SwpHints &rHints); //$ ostream /************************************************************************* * Inline-Implementationen *************************************************************************/ inline USHORT SwpHintsArr::GetStartOf( const SwTxtAttr *pHt ) const { USHORT nPos; if( !Seek_Entry( pHt, &nPos ) ) nPos = USHRT_MAX; return nPos; } inline SwTxtAttr *SwpHintsArr::Cut( const USHORT nPosInStart ) { SwTxtAttr *pHt = GetHt(nPosInStart); DeleteAtPos( nPosInStart ); return pHt; } #endif <commit_msg>INTEGRATION: CWS sw8u10bf04 (1.10.318); FILE MERGED 2007/12/20 12:06:55 ama 1.10.318.1: Fix #i83619#: A new footnote corrupts the reghistory<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ndhints.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2008-01-29 08:36:29 $ * * 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 _NDHINTS_HXX #define _NDHINTS_HXX #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #ifndef _SVMEMPOOL_HXX //autogen #include <tools/mempool.hxx> #endif #include "numrule.hxx" class SwTxtNode; class SwRegHistory; // steht im RolBck.hxx class SwTxtAttr; /* * Ableitung der Klasse SwpHints ueber den Umweg ueber SwpHts, da * lediglich die Klasse SwTxtNode Attribute einfuegen und * loeschen koennen soll. Anderen Klassen wie den Frames steht * lediglich ein lesender Zugriff ueber den Index-Operator zur * Verfuegung. * Groesse beim Anlegen gleich 1, weil nur dann ein Array erzeug wird, wenn * auch ein Hint eingefuegt wird. */ /************************************************************************* * class SwpHtStart/End *************************************************************************/ SV_DECL_PTRARR_SORT(SwpHtStart,SwTxtAttr*,1,1) SV_DECL_PTRARR_SORT(SwpHtEnd,SwTxtAttr*,1,1) /************************************************************************* * class SwpHintsArr *************************************************************************/ // Das neue Hintsarray: class SwpHintsArr : private SwpHtStart { protected: SwpHtEnd aHtEnd; public: void Insert( const SwTxtAttr *pHt ); void DeleteAtPos( const USHORT nPosInStart ); BOOL Resort(); SwTxtAttr *Cut( const USHORT nPosInStart ); inline const SwTxtAttr *GetStart( const USHORT nPos ) const { return (*this)[nPos]; } inline const SwTxtAttr *GetEnd( const USHORT nPos ) const { return aHtEnd[nPos]; } inline SwTxtAttr *GetStart( const USHORT nPos ) { return GetHt(nPos); } inline SwTxtAttr *GetEnd( const USHORT nPos ) { return aHtEnd[nPos]; } inline USHORT GetEndCount() const { return aHtEnd.Count(); } inline USHORT GetStartCount() const { return Count(); } inline USHORT GetStartOf( const SwTxtAttr *pHt ) const; inline USHORT GetPos( const SwTxtAttr *pHt ) const // OS: in svmem.hxx wird fuer TCPP GetPos ohne const gerufen #ifdef TCPP { return SwpHtStart::GetPos( (SwTxtAttr *)pHt ); } #else { return SwpHtStart::GetPos( pHt ); } #endif inline SwTxtAttr *GetHt( const USHORT nIdx ) { return SwpHtStart::operator[](nIdx); } inline const SwTxtAttr *operator[]( const USHORT nIdx )const { return SwpHtStart::operator[](nIdx); } inline USHORT Count() const { return SwpHtStart::Count(); } #ifndef PRODUCT BOOL Check() const; #endif }; /************************************************************************* * class SwpHints *************************************************************************/ // Die public-Schnittstelle zum Node hin class SwpHints: public SwpHintsArr { private: SwRegHistory* pHistory; // Numerierung BOOL bHasHiddenParaField :1; // HiddenParaFld BOOL bFntChg :1; // Fontwechsel BOOL bFtn :1; // Fussnoten BOOL bInSplitNode: 1; // TRUE: der Node ist im Split und die Frames // werden verschoben! BOOL bDDEFlds : 1; // es sind DDE-Felder am TextNode vorhanden BOOL bCalcHiddenParaField : 1; // bHasHiddenParaField ist invalid, CalcHiddenParaField() rufen // Haelt ein neues Attribut in pHistory fest. void NoteInHistory( SwTxtAttr *pAttr, const BOOL bNew = FALSE ); void CalcFlags( ); // die Delete Methoden duerfen nur vom TextNode gerufen werden !! // Dieser sorgt dafuer, das bei Attributen ohne Ende auch das // entsp. Zeichen entfernt wird !! friend class SwTxtNode; void DeleteAtPos( const USHORT nPos ); // Ist der Hint schon bekannt, dann suche die Position und loesche ihn. // Ist er nicht im Array, so gibt es ein ASSERT !! void Delete( SwTxtAttr* pTxtHt ); inline void SetCalcHiddenParaField(){ bCalcHiddenParaField = TRUE; } inline void SetHiddenParaField( const BOOL bNew ) { bHasHiddenParaField = bNew; } inline BOOL HasHiddenParaField() const { if( bCalcHiddenParaField ) ((SwpHints*)this)->CalcHiddenParaField(); return bHasHiddenParaField; } void BuildPortions( SwTxtNode& rNode, SwTxtAttr& rNewHint, USHORT nMode ); bool MergePortions( SwTxtNode& rNode ); public: inline BOOL CanBeDeleted() const { return !Count(); } // damit das SwDoc::Undo ueber alle Attributaenderungen informiert // wird, gibt es hier einen Pointer auf die History. Nur wenn dieser // != 0 ist, muessen alle Attributaenderungen "gemeldet" werden. void Register( SwRegHistory* pHist ) { pHistory = pHist; } void DeRegister() { Register(0); } SwRegHistory* getHistory() const { return pHistory; } void Insert( SwTxtAttr* pHt, SwTxtNode &rNode, USHORT nMode = 0 ); inline BOOL HasFtn() const { return bFtn; } inline BOOL IsInSplitNode() const { return bInSplitNode; } // Konstruktor (wird im nur einmal benutzt!) SwpHints() { pHistory = 0; bFntChg = TRUE; bDDEFlds = bFtn = bInSplitNode = bCalcHiddenParaField = bHasHiddenParaField = FALSE; } // Berechnung von bHasHiddenParaField, return-Wert TRUE bei Aenderung BOOL CalcHiddenParaField(); DECL_FIXEDMEMPOOL_NEWDEL(SwpHints) }; // Ausgabeoperator fuer die Texthints SvStream &operator<<(SvStream &aS, const SwpHints &rHints); //$ ostream /************************************************************************* * Inline-Implementationen *************************************************************************/ inline USHORT SwpHintsArr::GetStartOf( const SwTxtAttr *pHt ) const { USHORT nPos; if( !Seek_Entry( pHt, &nPos ) ) nPos = USHRT_MAX; return nPos; } inline SwTxtAttr *SwpHintsArr::Cut( const USHORT nPosInStart ) { SwTxtAttr *pHt = GetHt(nPosInStart); DeleteAtPos( nPosInStart ); return pHt; } #endif <|endoftext|>
<commit_before>#include <ctime> #include <iostream> #include <cassert> #include "enforcer/setup_cmd.h" #include "shared/duration.h" #include "shared/file.h" #include "shared/str.h" #include "daemon/engine.h" #include "daemon/orm.h" #include "policy/update_kasp_task.h" #include "policy/kasp.pb.h" #include "keystate/update_keyzones_task.h" #include "keystate/keystate.pb.h" #include "hsmkey/update_hsmkeys_task.h" #include "hsmkey/hsmkey_gen_task.h" #include "hsmkey/hsmkey.pb.h" #include "protobuf-orm/pb-orm.h" static const char *module_str = "setup_cmd"; /** * Print help for the 'setup' command * */ void help_setup_cmd(int sockfd) { ods_printf(sockfd, "setup delete existing database files and then perform:\n" " update kasp - to import kasp.xml\n" " update zonelist - to import zonelist.xml\n" ); } static bool create_database_tables(int sockfd, OrmConn conn) { bool ok = true; if (!OrmCreateTable(conn, ods::hsmkey::HsmKey::descriptor() )) { ods_log_error_and_printf(sockfd, module_str, "creating HsmKey tables failed"); ok = false; } if (!OrmCreateTable(conn, ods::kasp::Policy::descriptor())) { ods_log_error_and_printf(sockfd,module_str, "creating Policy tables failed"); ok = false; } if (!OrmCreateTable(conn, ods::keystate::EnforcerZone::descriptor())) { ods_log_error_and_printf(sockfd,module_str, "creating EnforcerZone tabled failed"); ok = false; } return ok; } static bool drop_database_tables(int sockfd, OrmConn conn, engineconfig_type* config) { bool ok = true; if (!OrmDropTable(conn, ods::hsmkey::HsmKey::descriptor())) { ods_log_error_and_printf(sockfd, module_str, "dropping HsmKey tables failed"); ok = false; } if (!OrmDropTable(conn, ods::kasp::Policy::descriptor())) { ods_log_error_and_printf(sockfd, module_str, "dropping Policy tables failed"); ok = false; } if (!OrmDropTable(conn, ods::keystate::EnforcerZone::descriptor())) { ods_log_error_and_printf(sockfd, module_str, "dropping EnforcerZone tables failed"); return; } if (!config->db_host && config->datastore) { // SQLite because 'db_host' is not assigned a value, but 'datastore' is. // Try to remove the SQLite database file too. if (unlink(config->datastore)==-1 && errno!=ENOENT) { ods_log_error_and_printf(sockfd, module_str, "unlink of \"%s\" failed: %s (%d)", config->datastore,strerror(errno),errno); ok = false; } } return ok; } static void flush_all_tasks(int sockfd, engine_type* engine) { ods_log_debug("[%s] flushing all tasks...", module_str); ods_printf(sockfd,"flushing all tasks...\n"); ods_log_assert(engine); ods_log_assert(engine->taskq); lock_basic_lock(&engine->taskq->schedule_lock); /* [LOCK] schedule */ schedule_flush(engine->taskq, TASK_NONE); /* [UNLOCK] schedule */ lock_basic_unlock(&engine->taskq->schedule_lock); engine_wakeup_workers(engine); } /** * Handle the 'setup' command. * */ int handled_setup_cmd(int sockfd, engine_type* engine, const char *cmd, ssize_t n) { const char *scmd = "setup"; cmd = ods_check_command(cmd,n,scmd); if (!cmd) return 0; // not handled ods_log_debug("[%s] %s command", module_str, scmd); // check that we are using a compatible protobuf version. GOOGLE_PROTOBUF_VERIFY_VERSION; time_t tstart = time(NULL); OrmConnRef conn; if (!ods_orm_connect(sockfd, engine->config, conn)) return; // errors have already been reported. if (!drop_database_tables(sockfd,conn,engine->config)) return; // errors have already been reported. if (!create_database_tables(sockfd, conn)) return; // errors have already been reported. perform_update_kasp(sockfd, engine->config); perform_update_keyzones(sockfd, engine->config); perform_update_hsmkeys(sockfd, engine->config, 0 /* automatic */); perform_hsmkey_gen(sockfd, engine->config, 0 /* automatic */, engine->config->automatic_keygen_duration); flush_all_tasks(sockfd, engine); ods_printf(sockfd, "%s completed in %ld seconds.\n",scmd,time(NULL)-tstart); return 1; } <commit_msg>Fix return errors<commit_after>#include <ctime> #include <iostream> #include <cassert> #include "enforcer/setup_cmd.h" #include "shared/duration.h" #include "shared/file.h" #include "shared/str.h" #include "daemon/engine.h" #include "daemon/orm.h" #include "policy/update_kasp_task.h" #include "policy/kasp.pb.h" #include "keystate/update_keyzones_task.h" #include "keystate/keystate.pb.h" #include "hsmkey/update_hsmkeys_task.h" #include "hsmkey/hsmkey_gen_task.h" #include "hsmkey/hsmkey.pb.h" #include "protobuf-orm/pb-orm.h" static const char *module_str = "setup_cmd"; /** * Print help for the 'setup' command * */ void help_setup_cmd(int sockfd) { ods_printf(sockfd, "setup delete existing database files and then perform:\n" " update kasp - to import kasp.xml\n" " update zonelist - to import zonelist.xml\n" ); } static bool create_database_tables(int sockfd, OrmConn conn) { bool ok = true; if (!OrmCreateTable(conn, ods::hsmkey::HsmKey::descriptor() )) { ods_log_error_and_printf(sockfd, module_str, "creating HsmKey tables failed"); ok = false; } if (!OrmCreateTable(conn, ods::kasp::Policy::descriptor())) { ods_log_error_and_printf(sockfd,module_str, "creating Policy tables failed"); ok = false; } if (!OrmCreateTable(conn, ods::keystate::EnforcerZone::descriptor())) { ods_log_error_and_printf(sockfd,module_str, "creating EnforcerZone tabled failed"); ok = false; } return ok; } static bool drop_database_tables(int sockfd, OrmConn conn, engineconfig_type* config) { bool ok = true; if (!OrmDropTable(conn, ods::hsmkey::HsmKey::descriptor())) { ods_log_error_and_printf(sockfd, module_str, "dropping HsmKey tables failed"); ok = false; } if (!OrmDropTable(conn, ods::kasp::Policy::descriptor())) { ods_log_error_and_printf(sockfd, module_str, "dropping Policy tables failed"); ok = false; } if (!OrmDropTable(conn, ods::keystate::EnforcerZone::descriptor())) { ods_log_error_and_printf(sockfd, module_str, "dropping EnforcerZone tables failed"); ok = false; } if (!config->db_host && config->datastore) { // SQLite because 'db_host' is not assigned a value, but 'datastore' is. // Try to remove the SQLite database file too. if (unlink(config->datastore)==-1 && errno!=ENOENT) { ods_log_error_and_printf(sockfd, module_str, "unlink of \"%s\" failed: %s (%d)", config->datastore,strerror(errno),errno); ok = false; } } return ok; } static void flush_all_tasks(int sockfd, engine_type* engine) { ods_log_debug("[%s] flushing all tasks...", module_str); ods_printf(sockfd,"flushing all tasks...\n"); ods_log_assert(engine); ods_log_assert(engine->taskq); lock_basic_lock(&engine->taskq->schedule_lock); /* [LOCK] schedule */ schedule_flush(engine->taskq, TASK_NONE); /* [UNLOCK] schedule */ lock_basic_unlock(&engine->taskq->schedule_lock); engine_wakeup_workers(engine); } /** * Handle the 'setup' command. * */ int handled_setup_cmd(int sockfd, engine_type* engine, const char *cmd, ssize_t n) { const char *scmd = "setup"; cmd = ods_check_command(cmd,n,scmd); if (!cmd) return 0; // not handled ods_log_debug("[%s] %s command", module_str, scmd); // check that we are using a compatible protobuf version. GOOGLE_PROTOBUF_VERIFY_VERSION; time_t tstart = time(NULL); OrmConnRef conn; if (!ods_orm_connect(sockfd, engine->config, conn)) return 1; // errors have already been reported. if (!drop_database_tables(sockfd,conn,engine->config)) return 1; // errors have already been reported. if (!create_database_tables(sockfd, conn)) return 1; // errors have already been reported. perform_update_kasp(sockfd, engine->config); perform_update_keyzones(sockfd, engine->config); perform_update_hsmkeys(sockfd, engine->config, 0 /* automatic */); perform_hsmkey_gen(sockfd, engine->config, 0 /* automatic */, engine->config->automatic_keygen_duration); flush_all_tasks(sockfd, engine); ods_printf(sockfd, "%s completed in %ld seconds.\n",scmd,time(NULL)-tstart); return 1; } <|endoftext|>
<commit_before><commit_msg>WaE: overriding destructor declaration not explicitly marked 'virtual'<commit_after><|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #ifndef CQL3_UPDATE_PARAMETERS_HH #define CQL3_UPDATE_PARAMETERS_HH #include "database.hh" #include "exceptions/exceptions.hh" namespace cql3 { /** * A simple container that simplify passing parameters for collections methods. */ class update_parameters final { public: using prefetched_rows_type = std::experimental::optional< std::unordered_map<partition_key, row, partition_key::hashing, partition_key::equality>>; private: const gc_clock::duration _ttl; const prefetched_rows_type _prefetched; // For operation that require a read-before-write public: const api::timestamp_type _timestamp; const gc_clock::time_point _local_deletion_time; const schema_ptr _schema; const query_options& _options; update_parameters(const schema_ptr schema_, const query_options& options, api::timestamp_type timestamp, gc_clock::duration ttl, prefetched_rows_type prefetched) : _ttl(ttl) , _prefetched(std::move(prefetched)) , _timestamp(timestamp) , _local_deletion_time(gc_clock::now()) , _schema(std::move(schema_)) , _options(options) { // We use MIN_VALUE internally to mean the absence of of timestamp (in Selection, in sstable stats, ...), so exclude // it to avoid potential confusion. if (timestamp < api::min_timestamp || timestamp > api::max_timestamp) { throw exceptions::invalid_request_exception(sprint("Out of bound timestamp, must be in [%d, %d]", api::min_timestamp, api::max_timestamp)); } } atomic_cell make_dead_cell() const { return atomic_cell::make_dead(_timestamp, _local_deletion_time); } atomic_cell make_cell(bytes_view value) const { auto ttl = _ttl; if (ttl.count() <= 0) { ttl = _schema->default_time_to_live; } return atomic_cell::make_live(_timestamp, ttl.count() > 0 ? ttl_opt{_local_deletion_time + ttl} : ttl_opt{}, value); }; #if 0 public Cell makeCounter(CellName name, long delta) throws InvalidRequestException { QueryProcessor.validateCellName(name, metadata.comparator); return new BufferCounterUpdateCell(name, delta, FBUtilities.timestampMicros()); } #endif tombstone make_tombstone() const { return {_timestamp, _local_deletion_time}; } #if 0 public RangeTombstone makeRangeTombstone(ColumnSlice slice) throws InvalidRequestException { QueryProcessor.validateComposite(slice.start, metadata.comparator); QueryProcessor.validateComposite(slice.finish, metadata.comparator); return new RangeTombstone(slice.start, slice.finish, timestamp, localDeletionTime); } public RangeTombstone makeTombstoneForOverwrite(ColumnSlice slice) throws InvalidRequestException { QueryProcessor.validateComposite(slice.start, metadata.comparator); QueryProcessor.validateComposite(slice.finish, metadata.comparator); return new RangeTombstone(slice.start, slice.finish, timestamp - 1, localDeletionTime); } public List<Cell> getPrefetchedList(ByteBuffer rowKey, ColumnIdentifier cql3ColumnName) { if (prefetchedLists == null) return Collections.emptyList(); CQL3Row row = prefetchedLists.get(rowKey); return row == null ? Collections.<Cell>emptyList() : row.getMultiCellColumn(cql3ColumnName); } #endif }; } #endif <commit_msg>cql3: fix update_parameters prefetched rows type<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #ifndef CQL3_UPDATE_PARAMETERS_HH #define CQL3_UPDATE_PARAMETERS_HH #include "database.hh" #include "exceptions/exceptions.hh" namespace cql3 { /** * A simple container that simplify passing parameters for collections methods. */ class update_parameters final { public: struct prefetch_data { query::partition_slice slice; query::result result; }; // Note: value (mutation) only required to contain the rows we are interested in using prefetched_rows_type = std::experimental::optional<prefetch_data>; private: const gc_clock::duration _ttl; const prefetched_rows_type _prefetched; // For operation that require a read-before-write public: const api::timestamp_type _timestamp; const gc_clock::time_point _local_deletion_time; const schema_ptr _schema; const query_options& _options; update_parameters(const schema_ptr schema_, const query_options& options, api::timestamp_type timestamp, gc_clock::duration ttl, prefetched_rows_type prefetched) : _ttl(ttl) , _prefetched(std::move(prefetched)) , _timestamp(timestamp) , _local_deletion_time(gc_clock::now()) , _schema(std::move(schema_)) , _options(options) { // We use MIN_VALUE internally to mean the absence of of timestamp (in Selection, in sstable stats, ...), so exclude // it to avoid potential confusion. if (timestamp < api::min_timestamp || timestamp > api::max_timestamp) { throw exceptions::invalid_request_exception(sprint("Out of bound timestamp, must be in [%d, %d]", api::min_timestamp, api::max_timestamp)); } } atomic_cell make_dead_cell() const { return atomic_cell::make_dead(_timestamp, _local_deletion_time); } atomic_cell make_cell(bytes_view value) const { auto ttl = _ttl; if (ttl.count() <= 0) { ttl = _schema->default_time_to_live; } return atomic_cell::make_live(_timestamp, ttl.count() > 0 ? ttl_opt{_local_deletion_time + ttl} : ttl_opt{}, value); }; #if 0 public Cell makeCounter(CellName name, long delta) throws InvalidRequestException { QueryProcessor.validateCellName(name, metadata.comparator); return new BufferCounterUpdateCell(name, delta, FBUtilities.timestampMicros()); } #endif tombstone make_tombstone() const { return {_timestamp, _local_deletion_time}; } #if 0 public RangeTombstone makeRangeTombstone(ColumnSlice slice) throws InvalidRequestException { QueryProcessor.validateComposite(slice.start, metadata.comparator); QueryProcessor.validateComposite(slice.finish, metadata.comparator); return new RangeTombstone(slice.start, slice.finish, timestamp, localDeletionTime); } public RangeTombstone makeTombstoneForOverwrite(ColumnSlice slice) throws InvalidRequestException { QueryProcessor.validateComposite(slice.start, metadata.comparator); QueryProcessor.validateComposite(slice.finish, metadata.comparator); return new RangeTombstone(slice.start, slice.finish, timestamp - 1, localDeletionTime); } public List<Cell> getPrefetchedList(ByteBuffer rowKey, ColumnIdentifier cql3ColumnName) { if (prefetchedLists == null) return Collections.emptyList(); CQL3Row row = prefetchedLists.get(rowKey); return row == null ? Collections.<Cell>emptyList() : row.getMultiCellColumn(cql3ColumnName); } #endif }; } #endif <|endoftext|>
<commit_before>#include <sys/types.h> #include <dirent.h> #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <string> #include <stdio.h> using namespace cv; using namespace std; int main(void) { DIR *dirp = opendir("."); struct dirent *dp; while (dirp) { if ((dp = readdir(dirp)) != NULL) { if (strstr(dp->d_name, ".png") || strstr(dp->d_name, ".png") ){ Mat frame = imread(dp->d_name); string str(dp->d_name); //cerr << str << endl; //cerr << str.rfind('.') << endl; str = str.substr(0, str.rfind('.')); cerr << str + "_g.png" << endl; // Save grayscale equalized version Mat frameGray; cvtColor( frame, frameGray, CV_BGR2GRAY ); equalizeHist( frameGray, frameGray ); imwrite(str + "_g.png", frameGray); } } } closedir(dirp); } <commit_msg>Fixed infinite loop<commit_after>#include <sys/types.h> #include <dirent.h> #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <string> #include <stdio.h> using namespace cv; using namespace std; int main(void) { DIR *dirp = opendir("."); struct dirent *dp; while (dirp) { if ((dp = readdir(dirp)) != NULL) { if (strstr(dp->d_name, ".png") || strstr(dp->d_name, ".jpg") ){ if (strstr(dp->d_name, "_g.png") || strstr(dp->d_name, "_g.jpg")) continue; Mat frame = imread(dp->d_name); string str(dp->d_name); //cerr << str << endl; //cerr << str.rfind('.') << endl; str = str.substr(0, str.rfind('.')); cerr << str + "_g.png" << endl; // Save grayscale equalized version Mat frameGray; cvtColor( frame, frameGray, CV_BGR2GRAY ); equalizeHist( frameGray, frameGray ); imwrite(str + "_g.png", frameGray); } } } closedir(dirp); } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "QOgreUIView.h" #include <QPaintEvent> #ifndef Q_WS_WIN #include <QX11Info> #endif namespace OgreRenderer { QOgreUIView::QOgreUIView () : QGraphicsView(), win_(0), view_(0) { Initialize_(); } QOgreUIView::QOgreUIView (QGraphicsScene *scene) : QGraphicsView(scene), win_(0), view_(0) { Initialize_(); } QOgreUIView::~QOgreUIView () { } void QOgreUIView::Initialize_() { setMinimumSize (150,100); setUpdatesEnabled (false); // reduces flicker and overpaint setFocusPolicy (Qt::StrongFocus); setViewportUpdateMode (QGraphicsView::FullViewportUpdate); setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff); } void QOgreUIView::SetWorldView(QOgreWorldView *view) { view_ = view; QObject::connect(scene(), SIGNAL( changed (const QList<QRectF> &) ), this, SLOT( SceneChange() )); } void QOgreUIView::InitializeWorldView(int width, int height) { if (view_) view_->InitializeOverlay(width, height); } Ogre::RenderWindow *QOgreUIView::CreateRenderWindow (const std::string &name, int width, int height, int left, int top, bool fullscreen) { bool stealparent ((parentWidget())? true : false); QWidget *nativewin ((stealparent)? parentWidget() : this); Ogre::NameValuePairList params; Ogre::String winhandle; #ifdef Q_WS_WIN // According to Ogre Docs // positive integer for W32 (HWND handle) winhandle = Ogre::StringConverter::toString ((unsigned int) (nativewin-> winId ())); //Add the external window handle parameters to the existing params set. params["externalWindowHandle"] = winhandle; #endif #ifdef Q_WS_X11 // GLX - According to Ogre Docs: // poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*) QX11Info info = x11Info (); winhandle = Ogre::StringConverter::toString ((unsigned long) (info.display ())); winhandle += ":"; winhandle += Ogre::StringConverter::toString ((unsigned int) (info.screen ())); winhandle += ":"; winhandle += Ogre::StringConverter::toString ((unsigned long) nativewin-> winId()); //Add the external window handle parameters to the existing params set. params["parentWindowHandle"] = winhandle; #endif // Window position to params if (left != -1) params["left"] = Core::ToString(left); if (top != -1) params["top"] = Core::ToString(top); win_ = Ogre::Root::getSingletonPtr()-> createRenderWindow(name, width, height, fullscreen, &params); return win_; } void QOgreUIView::resizeEvent(QResizeEvent *e) { QGraphicsView::resizeEvent(e); // Resize render window and UI texture to match this if (view_) { view_->ResizeWindow(width(), height()); view_->ResizeOverlay(viewport()->width(), viewport()->height()); } if (scene()) scene()->setSceneRect(viewport()->rect()); } void QOgreUIView::SceneChange() { setDirty(true); } } <commit_msg>Fixes 200 memory leaks. <commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "QOgreUIView.h" #include <QPaintEvent> #ifndef Q_WS_WIN #include <QX11Info> #endif namespace OgreRenderer { QOgreUIView::QOgreUIView () : QGraphicsView(), win_(0), view_(0) { Initialize_(); } QOgreUIView::QOgreUIView (QGraphicsScene *scene) : QGraphicsView(scene), win_(0), view_(0) { Initialize_(); } QOgreUIView::~QOgreUIView () { if ( this->scene() != 0 ) delete this->scene(); } void QOgreUIView::Initialize_() { setMinimumSize (150,100); setUpdatesEnabled (false); // reduces flicker and overpaint setFocusPolicy (Qt::StrongFocus); setViewportUpdateMode (QGraphicsView::FullViewportUpdate); setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff); } void QOgreUIView::SetWorldView(QOgreWorldView *view) { view_ = view; QObject::connect(scene(), SIGNAL( changed (const QList<QRectF> &) ), this, SLOT( SceneChange() )); } void QOgreUIView::InitializeWorldView(int width, int height) { if (view_) view_->InitializeOverlay(width, height); } Ogre::RenderWindow *QOgreUIView::CreateRenderWindow (const std::string &name, int width, int height, int left, int top, bool fullscreen) { bool stealparent ((parentWidget())? true : false); QWidget *nativewin ((stealparent)? parentWidget() : this); Ogre::NameValuePairList params; Ogre::String winhandle; #ifdef Q_WS_WIN // According to Ogre Docs // positive integer for W32 (HWND handle) winhandle = Ogre::StringConverter::toString ((unsigned int) (nativewin-> winId ())); //Add the external window handle parameters to the existing params set. params["externalWindowHandle"] = winhandle; #endif #ifdef Q_WS_X11 // GLX - According to Ogre Docs: // poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*) QX11Info info = x11Info (); winhandle = Ogre::StringConverter::toString ((unsigned long) (info.display ())); winhandle += ":"; winhandle += Ogre::StringConverter::toString ((unsigned int) (info.screen ())); winhandle += ":"; winhandle += Ogre::StringConverter::toString ((unsigned long) nativewin-> winId()); //Add the external window handle parameters to the existing params set. params["parentWindowHandle"] = winhandle; #endif // Window position to params if (left != -1) params["left"] = Core::ToString(left); if (top != -1) params["top"] = Core::ToString(top); win_ = Ogre::Root::getSingletonPtr()-> createRenderWindow(name, width, height, fullscreen, &params); return win_; } void QOgreUIView::resizeEvent(QResizeEvent *e) { QGraphicsView::resizeEvent(e); // Resize render window and UI texture to match this if (view_) { view_->ResizeWindow(width(), height()); view_->ResizeOverlay(viewport()->width(), viewport()->height()); } if (scene()) scene()->setSceneRect(viewport()->rect()); } void QOgreUIView::SceneChange() { setDirty(true); } } <|endoftext|>
<commit_before>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ lineLength = 25; // length of drawn lines reverseDrawing = false; // boolean to flip the drawing method (toggle with mouse) ellipse_color = ofColor(0); // color of drawn ellipses line_color = ofColor(0, 125); // color of drawn lines fbo_color = ofColor(0); ofFbo fbo; fbo.allocate(ofGetWidth(), ofGetHeight(), GL_RGBA); fbo.begin(); ofTrueTypeFont ttf; ttf.loadFont(OF_TTF_SANS, 350); string s = "TYPE"; // Center string code from: // https://github.com/armadillu/ofxCenteredTrueTypeFont/blob/master/src/ofxCenteredTrueTypeFont.h ofRectangle r = ttf.getStringBoundingBox(s, 0, 0); ofVec2f offset = ofVec2f(floor(-r.x - r.width * 0.5f), floor(-r.y - r.height * 0.5f)); ofSetColor(fbo_color); ttf.drawString(s, fbo.getWidth() / 2 + offset.x, fbo.getHeight() / 2 + offset.y); fbo.end(); fbo.readToPixels(pix); // the ofPixels class has a convenient getColor() method ofBackground(255); ofSetLineWidth(0.5); ofEnableAntiAliasing(); ofEnableSmoothing(); ofSetFrameRate(60); // cap frameRate otherwise it goes too fast } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ // determine grid dimensions based on the mouse position and calculate resulting grid settings int gridHorizontal = (int)ofMap(mouseX, 0, ofGetWidth(), 30, 200); // number of horizontal grid cells (based on mouseX) int gridVertical = (int)ofMap(mouseY, 0, ofGetHeight(), 15, 100); // number of vertical grid cells (based on mouseY) float w = (float)ofGetWidth() / gridHorizontal; float h = (float)ofGetHeight() / gridVertical; float r = MIN(w, h); // draw shapes to the screen for(int y = 0; y < gridVertical; y++){ for(int x = 0; x < gridHorizontal; x++){ float e_x = x * w; float e_y = y * h; ofColor c = pix.getColor((int)e_x, (int)e_y); // get fbo color at this coordinate bool textDrawn = (c == fbo_color); // is the color equal to fbo_color (aka is there text here) // use the reverseDrawing boolean to flip the textDrawn boolean // thus in fact flipping the resulting displayed shapes if(reverseDrawing ? !textDrawn : textDrawn){ ofFill(); ofSetColor(ellipse_color); ofEllipse(e_x, e_y, r, r); } else{ ofNoFill(); ofSetColor(line_color); ofLine(e_x, e_y, e_x + lineLength, e_y + lineLength); } } } } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ reverseDrawing = !reverseDrawing; // toggle boolean for drawing method } <commit_msg>Update InsideOutsideText example<commit_after>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ lineLength = 25; // length of drawn lines reverseDrawing = false; // boolean to flip the drawing method (toggle with mouse) ellipse_color = ofColor(0); // color of drawn ellipses line_color = ofColor(0, 125); // color of drawn lines fbo_color = ofColor(0); ofBackground(255); ofSetLineWidth(0.5); ofEnableAntiAliasing(); ofEnableSmoothing(); ofSetFrameRate(60); ofTrueTypeFont ttf; ttf.loadFont(OF_TTF_SANS, 350); string s = "TYPE"; ofFbo fbo; fbo.allocate(ofGetWidth(), ofGetHeight(), GL_RGBA); pix.allocate(ofGetWidth(), ofGetHeight(), OF_PIXELS_RGBA); fbo.begin(); // Center string code from: // https://github.com/armadillu/ofxCenteredTrueTypeFont/blob/master/src/ofxCenteredTrueTypeFont.h ofRectangle r = ttf.getStringBoundingBox(s, 0, 0); ofVec2f offset = ofVec2f(floor(-r.x - r.width * 0.5f), floor(-r.y - r.height * 0.5f)); ofSetColor(fbo_color); ttf.drawString(s, fbo.getWidth() / 2 + offset.x, fbo.getHeight() / 2 + offset.y); fbo.end(); fbo.readToPixels(pix); // the ofPixels class has a convenient getColor() method } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ // determine grid dimensions based on the mouse position and calculate resulting grid settings int gridHorizontal = (int)ofMap(mouseX, 0, ofGetWidth(), 30, 200); // number of horizontal grid cells (based on mouseX) int gridVertical = (int)ofMap(mouseY, 0, ofGetHeight(), 15, 100); // number of vertical grid cells (based on mouseY) float w = (float)ofGetWidth() / gridHorizontal; float h = (float)ofGetHeight() / gridVertical; float r = MIN(w, h); // draw shapes to the screen for(int y = 0; y < gridVertical; y++){ for(int x = 0; x < gridHorizontal; x++){ float e_x = x * w; float e_y = y * h; ofColor c = pix.getColor((int)e_x, (int)e_y); // get fbo color at this coordinate bool textDrawn = (c == fbo_color); // is the color equal to fbo_color (aka is there text here) // use the reverseDrawing boolean to flip the textDrawn boolean // thus in fact flipping the resulting displayed shapes if(reverseDrawing ? !textDrawn : textDrawn){ ofFill(); ofSetColor(ellipse_color); ofEllipse(e_x, e_y, r, r); } else{ ofNoFill(); ofSetColor(line_color); ofLine(e_x, e_y, e_x + lineLength, e_y + lineLength); } } } } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ reverseDrawing = !reverseDrawing; // toggle boolean for drawing method } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Daniel C. Dillon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define CATCH_CONFIG_MAIN #include "catch.hpp" #include <iostream> #include "../include/cpuaff/cpuaff.hpp" #if defined(CPUAFF_PCI_SUPPORTED) TEST_CASE("pci_device_manager", "[pci_device_manager]") { cpuaff::pci_device_manager manager; if (manager.has_pci_devices()) { cpuaff::pci_device_set devices; cpuaff::pci_device device; REQUIRE(manager.get_pci_devices(devices)); REQUIRE(!devices.empty()); device = *devices.begin(); REQUIRE( manager.get_pci_device_for_address(device, device.address())); REQUIRE(manager.get_pci_device_for_address(device, device.address().get())); REQUIRE(manager.get_pci_devices_by_spec(devices, device.spec())); REQUIRE(manager.get_pci_devices_by_numa(devices, device.numa())); REQUIRE( manager.get_pci_devices_by_vendor(devices, device.vendor())); } } #endif TEST_CASE("affinity_manager", "[affinity_manager]") { cpuaff::affinity_manager manager; SECTION("affinity_manager member functions") { REQUIRE(manager.has_cpus()); cpuaff::cpu cpu; cpuaff::cpu_set cpus; REQUIRE(manager.get_cpu_from_index(cpu, 0)); REQUIRE(manager.get_cpu_from_id(cpu, cpu.id())); REQUIRE(manager.get_cpu_from_id(cpu, cpu.id().get())); REQUIRE(manager.get_cpu_from_spec( cpu, cpuaff::cpu_spec(cpu.socket(), cpu.core(), cpu.processing_unit()))); REQUIRE(manager.get_cpus(cpus)); REQUIRE(manager.get_cpus_by_numa(cpus, cpu.numa())); REQUIRE(manager.get_cpus_by_socket(cpus, cpu.socket())); REQUIRE(manager.get_cpus_by_core(cpus, cpu.core())); REQUIRE( manager.get_cpus_by_processing_unit(cpus, cpu.processing_unit())); REQUIRE(manager.get_cpus_by_socket_and_core( cpus, cpu.socket(), cpu.core())); REQUIRE(manager.get_affinity(cpus)); REQUIRE(cpus.size() > 0); cpuaff::cpu_set new_affinity; new_affinity.insert(cpu); REQUIRE(manager.set_affinity(new_affinity)); REQUIRE(manager.get_affinity(cpus)); if (cpus.size() == new_affinity.size()) { cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); cpuaff::cpu_set::iterator j = new_affinity.begin(); cpuaff::cpu_set::iterator jend = new_affinity.end(); for (; i != iend && j != jend; ++i, ++j) { REQUIRE((*i) == (*j)); } } REQUIRE(manager.get_cpus(new_affinity)); REQUIRE(manager.set_affinity(new_affinity)); REQUIRE(manager.get_affinity(cpus)); if (cpus.size() == new_affinity.size()) { cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); cpuaff::cpu_set::iterator j = new_affinity.begin(); cpuaff::cpu_set::iterator jend = new_affinity.end(); for (; i != iend && j != jend; ++i, ++j) { REQUIRE((*i) == (*j)); } } REQUIRE(manager.pin(cpu)); REQUIRE(manager.get_affinity(cpus)); } } TEST_CASE("affinity_stack", "[affinity_stack]") { SECTION("affinity_stack member functions") { cpuaff::affinity_manager manager; REQUIRE(manager.has_cpus()); cpuaff::affinity_stack stack(manager); cpuaff::cpu_set original_affinity; cpuaff::cpu_set new_affinity; cpuaff::cpu_set cpus; REQUIRE(stack.get_affinity(original_affinity)); REQUIRE(original_affinity.size() > 0); REQUIRE(stack.push_affinity()); REQUIRE(stack.get_affinity(cpus)); REQUIRE(cpus.size() == original_affinity.size()); if (cpus.size() == original_affinity.size()) { cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); cpuaff::cpu_set::iterator j = original_affinity.begin(); cpuaff::cpu_set::iterator jend = original_affinity.end(); for (; i != iend && j != jend; ++i, ++j) { REQUIRE((*i) == (*j)); } } new_affinity.insert(*original_affinity.begin()); REQUIRE(stack.set_affinity(new_affinity)); REQUIRE(stack.get_affinity(cpus)); REQUIRE(stack.pop_affinity()); REQUIRE(stack.get_affinity(cpus)); if (cpus.size() == original_affinity.size()) { cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); cpuaff::cpu_set::iterator j = original_affinity.begin(); cpuaff::cpu_set::iterator jend = original_affinity.end(); for (; i != iend && j != jend; ++i, ++j) { REQUIRE((*i) == (*j)); } } } } TEST_CASE("round_robin_allocator", "[round_robin_allocator]") { SECTION("round_robin_allocator member functions") { cpuaff::affinity_manager manager; REQUIRE(manager.has_cpus()); cpuaff::round_robin_allocator allocator; cpuaff::cpu_set cpus; cpuaff::cpu_set allocated_cpus; cpuaff::cpu cpu; REQUIRE(manager.get_cpus(cpus)); REQUIRE(allocator.initialize(cpus)); for (int i = 0; i < cpus.size() * 2; ++i) { cpu = allocator.allocate(); bool test = cpu.socket() >= 0 && cpu.core() >= 0 && cpu.processing_unit() >= 0; REQUIRE(test); } REQUIRE(allocator.allocate(allocated_cpus, 4)); bool test = allocated_cpus.size() == 4 || (allocated_cpus.size() < 4 && allocated_cpus.size() == cpus.size()); REQUIRE(test); } } TEST_CASE("native_cpu_mapper", "[native_cpu_mapper]") { SECTION("native_cpu_mapper member functions") { cpuaff::affinity_manager manager; REQUIRE(manager.has_cpus()); cpuaff::native_cpu_mapper mapper; if (mapper.initialize(manager)) { cpuaff::cpu_set cpus; manager.get_cpus(cpus); cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); for (; i != iend; ++i) { cpuaff::native_cpu_mapper::native_cpu_wrapper_type native; cpuaff::cpu cpu; REQUIRE(mapper.get_native_from_cpu(native, *i)); REQUIRE(mapper.get_cpu_from_native(cpu, native)); REQUIRE(mapper.get_cpu_from_native(cpu, native.get())); } } } } <commit_msg>code formatting<commit_after>/* Copyright (c) 2015, Daniel C. Dillon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define CATCH_CONFIG_MAIN #include "catch.hpp" #include <iostream> #include "../include/cpuaff/cpuaff.hpp" #if defined(CPUAFF_PCI_SUPPORTED) TEST_CASE("pci_device_manager", "[pci_device_manager]") { cpuaff::pci_device_manager manager; if (manager.has_pci_devices()) { cpuaff::pci_device_set devices; cpuaff::pci_device device; REQUIRE(manager.get_pci_devices(devices)); REQUIRE(!devices.empty()); device = *devices.begin(); REQUIRE(manager.get_pci_device_for_address(device, device.address())); REQUIRE( manager.get_pci_device_for_address(device, device.address().get())); REQUIRE(manager.get_pci_devices_by_spec(devices, device.spec())); REQUIRE(manager.get_pci_devices_by_numa(devices, device.numa())); REQUIRE(manager.get_pci_devices_by_vendor(devices, device.vendor())); } } #endif TEST_CASE("affinity_manager", "[affinity_manager]") { cpuaff::affinity_manager manager; SECTION("affinity_manager member functions") { REQUIRE(manager.has_cpus()); cpuaff::cpu cpu; cpuaff::cpu_set cpus; REQUIRE(manager.get_cpu_from_index(cpu, 0)); REQUIRE(manager.get_cpu_from_id(cpu, cpu.id())); REQUIRE(manager.get_cpu_from_id(cpu, cpu.id().get())); REQUIRE(manager.get_cpu_from_spec( cpu, cpuaff::cpu_spec(cpu.socket(), cpu.core(), cpu.processing_unit()))); REQUIRE(manager.get_cpus(cpus)); REQUIRE(manager.get_cpus_by_numa(cpus, cpu.numa())); REQUIRE(manager.get_cpus_by_socket(cpus, cpu.socket())); REQUIRE(manager.get_cpus_by_core(cpus, cpu.core())); REQUIRE( manager.get_cpus_by_processing_unit(cpus, cpu.processing_unit())); REQUIRE(manager.get_cpus_by_socket_and_core( cpus, cpu.socket(), cpu.core())); REQUIRE(manager.get_affinity(cpus)); REQUIRE(cpus.size() > 0); cpuaff::cpu_set new_affinity; new_affinity.insert(cpu); REQUIRE(manager.set_affinity(new_affinity)); REQUIRE(manager.get_affinity(cpus)); if (cpus.size() == new_affinity.size()) { cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); cpuaff::cpu_set::iterator j = new_affinity.begin(); cpuaff::cpu_set::iterator jend = new_affinity.end(); for (; i != iend && j != jend; ++i, ++j) { REQUIRE((*i) == (*j)); } } REQUIRE(manager.get_cpus(new_affinity)); REQUIRE(manager.set_affinity(new_affinity)); REQUIRE(manager.get_affinity(cpus)); if (cpus.size() == new_affinity.size()) { cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); cpuaff::cpu_set::iterator j = new_affinity.begin(); cpuaff::cpu_set::iterator jend = new_affinity.end(); for (; i != iend && j != jend; ++i, ++j) { REQUIRE((*i) == (*j)); } } REQUIRE(manager.pin(cpu)); REQUIRE(manager.get_affinity(cpus)); } } TEST_CASE("affinity_stack", "[affinity_stack]") { SECTION("affinity_stack member functions") { cpuaff::affinity_manager manager; REQUIRE(manager.has_cpus()); cpuaff::affinity_stack stack(manager); cpuaff::cpu_set original_affinity; cpuaff::cpu_set new_affinity; cpuaff::cpu_set cpus; REQUIRE(stack.get_affinity(original_affinity)); REQUIRE(original_affinity.size() > 0); REQUIRE(stack.push_affinity()); REQUIRE(stack.get_affinity(cpus)); REQUIRE(cpus.size() == original_affinity.size()); if (cpus.size() == original_affinity.size()) { cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); cpuaff::cpu_set::iterator j = original_affinity.begin(); cpuaff::cpu_set::iterator jend = original_affinity.end(); for (; i != iend && j != jend; ++i, ++j) { REQUIRE((*i) == (*j)); } } new_affinity.insert(*original_affinity.begin()); REQUIRE(stack.set_affinity(new_affinity)); REQUIRE(stack.get_affinity(cpus)); REQUIRE(stack.pop_affinity()); REQUIRE(stack.get_affinity(cpus)); if (cpus.size() == original_affinity.size()) { cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); cpuaff::cpu_set::iterator j = original_affinity.begin(); cpuaff::cpu_set::iterator jend = original_affinity.end(); for (; i != iend && j != jend; ++i, ++j) { REQUIRE((*i) == (*j)); } } } } TEST_CASE("round_robin_allocator", "[round_robin_allocator]") { SECTION("round_robin_allocator member functions") { cpuaff::affinity_manager manager; REQUIRE(manager.has_cpus()); cpuaff::round_robin_allocator allocator; cpuaff::cpu_set cpus; cpuaff::cpu_set allocated_cpus; cpuaff::cpu cpu; REQUIRE(manager.get_cpus(cpus)); REQUIRE(allocator.initialize(cpus)); for (int i = 0; i < cpus.size() * 2; ++i) { cpu = allocator.allocate(); bool test = cpu.socket() >= 0 && cpu.core() >= 0 && cpu.processing_unit() >= 0; REQUIRE(test); } REQUIRE(allocator.allocate(allocated_cpus, 4)); bool test = allocated_cpus.size() == 4 || (allocated_cpus.size() < 4 && allocated_cpus.size() == cpus.size()); REQUIRE(test); } } TEST_CASE("native_cpu_mapper", "[native_cpu_mapper]") { SECTION("native_cpu_mapper member functions") { cpuaff::affinity_manager manager; REQUIRE(manager.has_cpus()); cpuaff::native_cpu_mapper mapper; if (mapper.initialize(manager)) { cpuaff::cpu_set cpus; manager.get_cpus(cpus); cpuaff::cpu_set::iterator i = cpus.begin(); cpuaff::cpu_set::iterator iend = cpus.end(); for (; i != iend; ++i) { cpuaff::native_cpu_mapper::native_cpu_wrapper_type native; cpuaff::cpu cpu; REQUIRE(mapper.get_native_from_cpu(native, *i)); REQUIRE(mapper.get_cpu_from_native(cpu, native)); REQUIRE(mapper.get_cpu_from_native(cpu, native.get())); } } } } <|endoftext|>
<commit_before>/******************************************************************************* * E.S.O. - ACS project * * "@(#) $Id: maciContainerLogLevel.cpp,v 1.7 2008/07/14 13:41:20 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * bgustafs 2002-04-15 corrected shutdown action * msekoran 2001/12/23 created */ /** @file maciContainerSetLogLevel.cpp * maciContainerSetLogLevel is used to set container log levels runtime. * @htmlonly * <br><br> * @endhtmlonly * @param container This is simply the name of the container in the CDB that we want to stop. * @htmlonly * <br><hr> * @endhtmlonly */ #include <vltPort.h> #include <acsutil.h> #include <logging.h> #include <maciHelper.h> #include <maciContainerImpl.h> using namespace maci; void printUsageAndExit(int argc, char *argv[]) { ACE_OS::printf("\n\tusage: %s <container name wildcard> {set,get,list,refresh} [<loggerName | \"default\"> <minLogLevel> <minLogLevelLocal>] [<ORB options>]\nWith log level values {2-6,8-11,99=OFF}\n", argv[0]); exit(-1); } // Only integer values for certain levels are defined, e.g. DEBUG = 3. // No illegal levels should be sent to the LoggingConfigurable processes (containers, manager, ...) int isLogLevelValid(int logLevel) { return ( (logLevel >= 2 && logLevel <= 11 && logLevel != 7) || logLevel==99 ); } int main (int argc, char *argv[]) { if (argc < 3) printUsageAndExit(argc, argv); char * command = argv[2]; #define SET 1 #define GET 2 #define LIST 3 #define REFRESH 4 int cmd; if (ACE_OS::strcmp(command, "set") == 0) cmd = SET; else if (ACE_OS::strcmp(command, "get") == 0) cmd = GET; else if (ACE_OS::strcmp(command, "list") == 0) cmd = LIST; else if (ACE_OS::strcmp(command, "refresh") == 0) cmd = REFRESH; else { ACE_OS::printf("Invalid command, must be one of {set,get,list,refresh}.\n"); printUsageAndExit(argc, argv); } if (cmd == SET && argc < 4) { // if only 4 then default is set ACE_OS::printf("Not enough parameters.\n"); printUsageAndExit(argc, argv); } if (cmd == GET && argc < 4) { ACE_OS::printf("Not enough parameters.\n"); printUsageAndExit(argc, argv); } LoggingProxy * logger = new LoggingProxy(0, 0, 31); if (logger) { LoggingProxy::init(logger); LoggingProxy::ProcessName(argv[0]); LoggingProxy::ThreadName("main"); } else ACS_SHORT_LOG((LM_INFO, "Failed to initialize logging.")); try { // Initialize the ORB. CORBA::ORB_var orb = CORBA::ORB_init (argc, argv, "TAO" ); maci::Manager_var mgr = MACIHelper::resolveManager(orb.ptr(), argc, argv, 0, 0); if (CORBA::is_nil(mgr.ptr())) { ACS_SHORT_LOG((LM_ERROR, "Failed to resolve Manager reference.")); return -1; } maci::HandleSeq handles; handles.length(0); // a little hack to manager (this clas should implement administrator interface, etc..) maci::Handle h = 0x05000000; maci::ContainerInfoSeq_var containers = mgr->get_container_info(h, handles, argv[1]); if (!containers.ptr() || containers->length()==0) { ACS_SHORT_LOG((LM_INFO, "No containers matching name %s found.", argv[1])); return -1; } for (CORBA::ULong i = 0; i < containers->length(); i++) { try { ACS_SHORT_LOG((LM_INFO, "Container: %s", containers[i].name.in())); if (cmd == LIST) { ACS_SHORT_LOG((LM_INFO, "\tLogger names:")); maci::stringSeq_var loggerNames = containers[i].reference->get_logger_names(); for (CORBA::ULong j = 0; j < loggerNames->length(); j++) ACS_SHORT_LOG((LM_INFO, "\t\t%s", loggerNames[j].in())); } else if (cmd == REFRESH) { ACS_SHORT_LOG((LM_INFO, "\tRefreshing logging config.")); containers[i].reference->refresh_logging_config(); } else if (cmd == GET) { char * loggerName = argv[3]; LoggingConfigurable::LogLevels logLevels; if (ACE_OS::strcmp(loggerName, "default") == 0) logLevels = containers[i].reference->get_default_logLevels(); else logLevels = containers[i].reference->get_logLevels(loggerName); ACS_SHORT_LOG((LM_INFO, "\tLog levels for logger '%s':", loggerName)); ACS_SHORT_LOG((LM_INFO, "\t\tuseDefault : %s", logLevels.useDefault ? "true" : "false")); ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevel : %d", logLevels.minLogLevel)); ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevelLocal: %d", logLevels.minLogLevelLocal)); } else if (cmd == SET) { char * loggerName = argv[3]; LoggingConfigurable::LogLevels logLevels; logLevels.useDefault = argc < 6; if (!logLevels.useDefault) { logLevels.minLogLevel = atoi(argv[4]); logLevels.minLogLevelLocal = atoi(argv[5]); if (!isLogLevelValid(logLevels.minLogLevel) || !isLogLevelValid(logLevels.minLogLevelLocal)) { printUsageAndExit(argc, argv); } } else { logLevels.minLogLevel = 0; logLevels.minLogLevelLocal = 0; } ACS_SHORT_LOG((LM_INFO, "\tSetting levels for logger '%s':", loggerName)); ACS_SHORT_LOG((LM_INFO, "\t\tuseDefault : %s", logLevels.useDefault ? "true" : "false")); //if (!logLevels.useDefault) { ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevel : %d", logLevels.minLogLevel)); ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevelLocal: %d", logLevels.minLogLevelLocal)); } if (ACE_OS::strcmp(loggerName, "default") == 0) containers[i].reference->set_default_logLevels(logLevels); else containers[i].reference->set_logLevels(loggerName, logLevels); } ACS_SHORT_LOG((LM_INFO, "\t... done.")); } catch( CORBA::Exception &ex ) { ACS_SHORT_LOG((LM_INFO, "... failed!")); ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, ACE_TEXT ("Exception caught while calling remote method.")); } } ACS_SHORT_LOG((LM_INFO, "Done all.")); } catch( CORBA::Exception &ex ) { ACS_SHORT_LOG((LM_INFO, "Failed.")); ACE_PRINT_EXCEPTION (ex, ACE_TEXT ("Caught unexpected exception:")); return -1; } return 0; } <commit_msg>Updated maciContainerLogLevel to use the new log level schema defined (now levels start from 1)<commit_after>/******************************************************************************* * E.S.O. - ACS project * * "@(#) $Id: maciContainerLogLevel.cpp,v 1.8 2010/03/30 21:34:55 javarias Exp $" * * who when what * -------- -------- ---------------------------------------------- * bgustafs 2002-04-15 corrected shutdown action * msekoran 2001/12/23 created */ /** @file maciContainerSetLogLevel.cpp * maciContainerSetLogLevel is used to set container log levels runtime. * @htmlonly * <br><br> * @endhtmlonly * @param container This is simply the name of the container in the CDB that we want to stop. * @htmlonly * <br><hr> * @endhtmlonly */ #include <vltPort.h> #include <acsutil.h> #include <logging.h> #include <maciHelper.h> #include <maciContainerImpl.h> using namespace maci; void printUsageAndExit(int argc, char *argv[]) { ACE_OS::printf("\n\tusage: %s <container name wildcard> {set,get,list,refresh} [<loggerName | \"default\"> <minLogLevel> <minLogLevelLocal>] [<ORB options>]\nWith log level values {1-6,8-11,99=OFF}\n", argv[0]); exit(-1); } // Only integer values for certain levels are defined, e.g. DEBUG = 3. // No illegal levels should be sent to the LoggingConfigurable processes (containers, manager, ...) int isLogLevelValid(int logLevel) { return ( (logLevel >= 1 && logLevel <= 11 && logLevel != 7) || logLevel==99 ); } int main (int argc, char *argv[]) { if (argc < 3) printUsageAndExit(argc, argv); char * command = argv[2]; #define SET 1 #define GET 2 #define LIST 3 #define REFRESH 4 int cmd; if (ACE_OS::strcmp(command, "set") == 0) cmd = SET; else if (ACE_OS::strcmp(command, "get") == 0) cmd = GET; else if (ACE_OS::strcmp(command, "list") == 0) cmd = LIST; else if (ACE_OS::strcmp(command, "refresh") == 0) cmd = REFRESH; else { ACE_OS::printf("Invalid command, must be one of {set,get,list,refresh}.\n"); printUsageAndExit(argc, argv); } if (cmd == SET && argc < 4) { // if only 4 then default is set ACE_OS::printf("Not enough parameters.\n"); printUsageAndExit(argc, argv); } if (cmd == GET && argc < 4) { ACE_OS::printf("Not enough parameters.\n"); printUsageAndExit(argc, argv); } LoggingProxy * logger = new LoggingProxy(0, 0, 31); if (logger) { LoggingProxy::init(logger); LoggingProxy::ProcessName(argv[0]); LoggingProxy::ThreadName("main"); } else ACS_SHORT_LOG((LM_INFO, "Failed to initialize logging.")); try { // Initialize the ORB. CORBA::ORB_var orb = CORBA::ORB_init (argc, argv, "TAO" ); maci::Manager_var mgr = MACIHelper::resolveManager(orb.ptr(), argc, argv, 0, 0); if (CORBA::is_nil(mgr.ptr())) { ACS_SHORT_LOG((LM_ERROR, "Failed to resolve Manager reference.")); return -1; } maci::HandleSeq handles; handles.length(0); // a little hack to manager (this clas should implement administrator interface, etc..) maci::Handle h = 0x05000000; maci::ContainerInfoSeq_var containers = mgr->get_container_info(h, handles, argv[1]); if (!containers.ptr() || containers->length()==0) { ACS_SHORT_LOG((LM_INFO, "No containers matching name %s found.", argv[1])); return -1; } for (CORBA::ULong i = 0; i < containers->length(); i++) { try { ACS_SHORT_LOG((LM_INFO, "Container: %s", containers[i].name.in())); if (cmd == LIST) { ACS_SHORT_LOG((LM_INFO, "\tLogger names:")); maci::stringSeq_var loggerNames = containers[i].reference->get_logger_names(); for (CORBA::ULong j = 0; j < loggerNames->length(); j++) ACS_SHORT_LOG((LM_INFO, "\t\t%s", loggerNames[j].in())); } else if (cmd == REFRESH) { ACS_SHORT_LOG((LM_INFO, "\tRefreshing logging config.")); containers[i].reference->refresh_logging_config(); } else if (cmd == GET) { char * loggerName = argv[3]; LoggingConfigurable::LogLevels logLevels; if (ACE_OS::strcmp(loggerName, "default") == 0) logLevels = containers[i].reference->get_default_logLevels(); else logLevels = containers[i].reference->get_logLevels(loggerName); ACS_SHORT_LOG((LM_INFO, "\tLog levels for logger '%s':", loggerName)); ACS_SHORT_LOG((LM_INFO, "\t\tuseDefault : %s", logLevels.useDefault ? "true" : "false")); ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevel : %d", logLevels.minLogLevel)); ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevelLocal: %d", logLevels.minLogLevelLocal)); } else if (cmd == SET) { char * loggerName = argv[3]; LoggingConfigurable::LogLevels logLevels; logLevels.useDefault = argc < 6; if (!logLevels.useDefault) { logLevels.minLogLevel = atoi(argv[4]); logLevels.minLogLevelLocal = atoi(argv[5]); if (!isLogLevelValid(logLevels.minLogLevel) || !isLogLevelValid(logLevels.minLogLevelLocal)) { printUsageAndExit(argc, argv); } } else { logLevels.minLogLevel = 0; logLevels.minLogLevelLocal = 0; } ACS_SHORT_LOG((LM_INFO, "\tSetting levels for logger '%s':", loggerName)); ACS_SHORT_LOG((LM_INFO, "\t\tuseDefault : %s", logLevels.useDefault ? "true" : "false")); //if (!logLevels.useDefault) { ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevel : %d", logLevels.minLogLevel)); ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevelLocal: %d", logLevels.minLogLevelLocal)); } if (ACE_OS::strcmp(loggerName, "default") == 0) containers[i].reference->set_default_logLevels(logLevels); else containers[i].reference->set_logLevels(loggerName, logLevels); } ACS_SHORT_LOG((LM_INFO, "\t... done.")); } catch( CORBA::Exception &ex ) { ACS_SHORT_LOG((LM_INFO, "... failed!")); ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, ACE_TEXT ("Exception caught while calling remote method.")); } } ACS_SHORT_LOG((LM_INFO, "Done all.")); } catch( CORBA::Exception &ex ) { ACS_SHORT_LOG((LM_INFO, "Failed.")); ACE_PRINT_EXCEPTION (ex, ACE_TEXT ("Caught unexpected exception:")); return -1; } return 0; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #ifndef _Stroika_Foundation_Execution_Function_inl_ #define _Stroika_Foundation_Execution_Function_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Common/Compare.h" namespace Stroika::Foundation::Execution { /* ******************************************************************************** ******************************** Execution::Function *************************** ******************************************************************************** */ template <typename FUNCTION_SIGNATURE> template <typename CTOR_FUNC_SIG> inline Function<FUNCTION_SIGNATURE>::Function (const CTOR_FUNC_SIG& f) // @todo - Understand why changing this to uniform-initialization fails to compile : fFun_ (STDFUNCTION{f}) , fOrdering_{fFun_.template target<CTOR_FUNC_SIG> ()} { Assert ((fOrdering_ == nullptr) == (fFun_ == nullptr)); } template <typename FUNCTION_SIGNATURE> inline Function<FUNCTION_SIGNATURE>::Function (nullptr_t) : fFun_{} { Assert (fOrdering_ == nullptr); } template <typename FUNCTION_SIGNATURE> inline Function<FUNCTION_SIGNATURE>::operator STDFUNCTION () const { return fFun_; } template <typename FUNCTION_SIGNATURE> template <typename... Args> inline typename Function<FUNCTION_SIGNATURE>::result_type Function<FUNCTION_SIGNATURE>::operator() (Args... args) const { RequireNotNull (fFun_); return fFun_ (forward<Args> (args)...); } #if __cpp_impl_three_way_comparison >= 201907 template <typename FUNCTION_SIGNATURE> inline strong_ordering Function<FUNCTION_SIGNATURE>::operator<=> (const Function& rhs) const { return fOrdering_ <=> rhs.fOrdering_; } template <typename FUNCTION_SIGNATURE> inline bool Function<FUNCTION_SIGNATURE>::operator== (const Function& rhs) const { return fOrdering_ == rhs.fOrdering_; } #endif #if __cpp_impl_three_way_comparison < 201907 /* ******************************************************************************** ************** Function<FUNCTION_SIGNATURE> operators ************************** ******************************************************************************** */ template <typename FUNCTION_SIGNATURE> inline bool operator< (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) < 0; } template <typename FUNCTION_SIGNATURE> inline bool operator<= (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) <= 0; } template <typename FUNCTION_SIGNATURE> inline bool operator== (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) == 0; } template <typename FUNCTION_SIGNATURE> inline bool operator== (const Function<FUNCTION_SIGNATURE>& lhs, nullptr_t) { return Common::ThreeWayCompare (lhs.fOrdering_, nullptr) == 0; } template <typename FUNCTION_SIGNATURE> inline bool operator!= (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) != 0; } template <typename FUNCTION_SIGNATURE> inline bool operator!= (const Function<FUNCTION_SIGNATURE>& lhs, nullptr_t) { return Common::ThreeWayCompare (lhs.fOrdering_, nullptr) != 0; } template <typename FUNCTION_SIGNATURE> inline bool operator> (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) > 0; } template <typename FUNCTION_SIGNATURE> inline bool operator>= (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) >= 0; } #endif } #endif /*_Stroika_Foundation_Execution_Function_inl_*/ <commit_msg>cleanup/document one place to not use uniform initialization for implicit conversions<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #ifndef _Stroika_Foundation_Execution_Function_inl_ #define _Stroika_Foundation_Execution_Function_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Common/Compare.h" namespace Stroika::Foundation::Execution { /* ******************************************************************************** ******************************** Execution::Function *************************** ******************************************************************************** */ template <typename FUNCTION_SIGNATURE> template <typename CTOR_FUNC_SIG> inline Function<FUNCTION_SIGNATURE>::Function (const CTOR_FUNC_SIG& f) : fFun_{STDFUNCTION (f)} // use non-uniform-initialzation convert to STDFUNCTION so we can get implicit conversions here , fOrdering_{fFun_.template target<CTOR_FUNC_SIG> ()} { Assert ((fOrdering_ == nullptr) == (fFun_ == nullptr)); } template <typename FUNCTION_SIGNATURE> inline Function<FUNCTION_SIGNATURE>::Function (nullptr_t) : fFun_{} { Assert (fOrdering_ == nullptr); } template <typename FUNCTION_SIGNATURE> inline Function<FUNCTION_SIGNATURE>::operator STDFUNCTION () const { return fFun_; } template <typename FUNCTION_SIGNATURE> template <typename... Args> inline typename Function<FUNCTION_SIGNATURE>::result_type Function<FUNCTION_SIGNATURE>::operator() (Args... args) const { RequireNotNull (fFun_); return fFun_ (forward<Args> (args)...); } #if __cpp_impl_three_way_comparison >= 201907 template <typename FUNCTION_SIGNATURE> inline strong_ordering Function<FUNCTION_SIGNATURE>::operator<=> (const Function& rhs) const { return fOrdering_ <=> rhs.fOrdering_; } template <typename FUNCTION_SIGNATURE> inline bool Function<FUNCTION_SIGNATURE>::operator== (const Function& rhs) const { return fOrdering_ == rhs.fOrdering_; } #endif #if __cpp_impl_three_way_comparison < 201907 /* ******************************************************************************** ************** Function<FUNCTION_SIGNATURE> operators ************************** ******************************************************************************** */ template <typename FUNCTION_SIGNATURE> inline bool operator< (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) < 0; } template <typename FUNCTION_SIGNATURE> inline bool operator<= (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) <= 0; } template <typename FUNCTION_SIGNATURE> inline bool operator== (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) == 0; } template <typename FUNCTION_SIGNATURE> inline bool operator== (const Function<FUNCTION_SIGNATURE>& lhs, nullptr_t) { return Common::ThreeWayCompare (lhs.fOrdering_, nullptr) == 0; } template <typename FUNCTION_SIGNATURE> inline bool operator!= (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) != 0; } template <typename FUNCTION_SIGNATURE> inline bool operator!= (const Function<FUNCTION_SIGNATURE>& lhs, nullptr_t) { return Common::ThreeWayCompare (lhs.fOrdering_, nullptr) != 0; } template <typename FUNCTION_SIGNATURE> inline bool operator> (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) > 0; } template <typename FUNCTION_SIGNATURE> inline bool operator>= (const Function<FUNCTION_SIGNATURE>& lhs, const Function<FUNCTION_SIGNATURE>& rhs) { return Common::ThreeWayCompare (lhs.fOrdering_, rhs.fOrdering_) >= 0; } #endif } #endif /*_Stroika_Foundation_Execution_Function_inl_*/ <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file exponential_distribution.hpp * \date May 2014 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com) */ #ifndef FL__DISTRIBUTION__EXPONENTIAL_DISTRIBUTION_HPP #define FL__DISTRIBUTION__EXPONENTIAL_DISTRIBUTION_HPP #include <limits> #include <cmath> #include <fl/distribution/interface/evaluation.hpp> #include <fl/distribution/interface/standard_gaussian_mapping.hpp> namespace fl { /// \todo MISSING DOC. MISSING UTESTS /** * \ingroup distributions */ class ExponentialDistribution: public Evaluation<double, double>, public StandardGaussianMapping<double, double> { public: ExponentialDistribution(double lambda, double min = 0, double max = std::numeric_limits<double>::infinity()): lambda_(lambda), min_(min), max_(max) { exp_lambda_min_ = std::exp(-lambda_*min); exp_lambda_max_ = std::exp(-lambda_*max); } virtual ~ExponentialDistribution() { } virtual double probability(const double& input) const { if(input < min_ || input > max_) return 0; return lambda_ * std::exp(-lambda_ * input) / (exp_lambda_min_ - exp_lambda_max_); } virtual double log_probability(const double& input) const { return std::log(probability(input)); } virtual double map_standard_normal(const double& gaussian_sample) const { // map from a gaussian to a uniform distribution double uniform_sample = 0.5 * (1.0 + std::erf(gaussian_sample / std::sqrt(2.0))); // map from a uniform to an exponential distribution return -std::log(exp_lambda_min_ - (exp_lambda_min_ - exp_lambda_max_) * uniform_sample) / lambda_; } virtual double map_standard_normal(const double& gaussian_sample, const double& max) const { double exp_lambda_max = std::exp(-lambda_*max); // map from a gaussian to a uniform distribution double uniform_sample = 0.5 * (1.0 + std::erf(gaussian_sample / std::sqrt(2.0))); // map from a uniform to an exponential distribution return -std::log(exp_lambda_min_ - (exp_lambda_min_ - exp_lambda_max) * uniform_sample) / lambda_; } private: double lambda_; double min_; double max_; double exp_lambda_min_; double exp_lambda_max_; }; } #endif <commit_msg>double -> FloatingPoint<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file exponential_distribution.hpp * \date May 2014 * \author Manuel Wuthrich (manuel.wuthrich@gmail.com) */ #ifndef FL__DISTRIBUTION__EXPONENTIAL_DISTRIBUTION_HPP #define FL__DISTRIBUTION__EXPONENTIAL_DISTRIBUTION_HPP #include <limits> #include <cmath> #include <fl/util/types.hpp> #include <fl/distribution/interface/evaluation.hpp> #include <fl/distribution/interface/standard_gaussian_mapping.hpp> namespace fl { /// \todo MISSING DOC. MISSING UTESTS /** * \ingroup distributions */ class ExponentialDistribution: public Evaluation<FloatingPoint, FloatingPoint>, public StandardGaussianMapping<FloatingPoint, FloatingPoint> { public: ExponentialDistribution(FloatingPoint lambda, FloatingPoint min = 0, FloatingPoint max = std::numeric_limits<FloatingPoint>::infinity()): lambda_(lambda), min_(min), max_(max) { exp_lambda_min_ = std::exp(-lambda_*min); exp_lambda_max_ = std::exp(-lambda_*max); } virtual ~ExponentialDistribution() { } virtual FloatingPoint probability(const FloatingPoint& input) const { if(input < min_ || input > max_) return 0; return lambda_ * std::exp(-lambda_ * input) / (exp_lambda_min_ - exp_lambda_max_); } virtual FloatingPoint log_probability(const FloatingPoint& input) const { return std::log(probability(input)); } virtual FloatingPoint map_standard_normal(const FloatingPoint& gaussian_sample) const { // map from a gaussian to a uniform distribution FloatingPoint uniform_sample = 0.5 * (1.0 + std::erf(gaussian_sample / std::sqrt(2.0))); // map from a uniform to an exponential distribution return -std::log(exp_lambda_min_ - (exp_lambda_min_ - exp_lambda_max_) * uniform_sample) / lambda_; } virtual FloatingPoint map_standard_normal(const FloatingPoint& gaussian_sample, const FloatingPoint& max) const { FloatingPoint exp_lambda_max = std::exp(-lambda_*max); // map from a gaussian to a uniform distribution FloatingPoint uniform_sample = 0.5 * (1.0 + std::erf(gaussian_sample / std::sqrt(2.0))); // map from a uniform to an exponential distribution return -std::log(exp_lambda_min_ - (exp_lambda_min_ - exp_lambda_max) * uniform_sample) / lambda_; } private: FloatingPoint lambda_; FloatingPoint min_; FloatingPoint max_; FloatingPoint exp_lambda_min_; FloatingPoint exp_lambda_max_; }; } #endif <|endoftext|>
<commit_before>#include "GuiGamelistOptions.h" #include "GuiMetaDataEd.h" #include "views/gamelist/IGameListView.h" #include "views/ViewController.h" GuiGamelistOptions::GuiGamelistOptions(Window* window, SystemData* system) : GuiComponent(window), mSystem(system), mMenu(window, "OPTIONS") { addChild(&mMenu); // jump to letter char curChar = getGamelist()->getCursor()->getName()[0]; mJumpToLetterList = std::make_shared<LetterList>(mWindow, "JUMP TO LETTER", false); for(char c = 'A'; c <= 'Z'; c++) { mJumpToLetterList->add(std::string(1, c), c, c == curChar); } ComponentListRow row; row.addElement(std::make_shared<TextComponent>(mWindow, "JUMP TO LETTER", Font::get(FONT_SIZE_MEDIUM), 0x777777FF), true); row.addElement(mJumpToLetterList, false); row.input_handler = [&](InputConfig* config, Input input) { if(config->isMappedTo("a", input) && input.value) { jumpToLetter(); return true; } else if(mJumpToLetterList->input(config, input)) { return true; } return false; }; mMenu.addRow(row); // sort list by mListSort = std::make_shared<SortList>(mWindow, "SORT GAMES BY", false); for(unsigned int i = 0; i < FileSorts::SortTypes.size(); i++) { const FileData::SortType& sort = FileSorts::SortTypes.at(i); mListSort->add(sort.description, &sort, i == 0); // TODO - actually make the sort type persistent } mMenu.addWithLabel("SORT GAMES BY", mListSort); // edit game metadata row.elements.clear(); row.addElement(std::make_shared<TextComponent>(mWindow, "EDIT THIS GAME'S METADATA", Font::get(FONT_SIZE_MEDIUM), 0x777777FF), true); row.addElement(makeArrow(mWindow), false); row.makeAcceptInputHandler(std::bind(&GuiGamelistOptions::openMetaDataEd, this)); mMenu.addRow(row); // center the menu setSize((float)Renderer::getScreenWidth(), (float)Renderer::getScreenHeight()); mMenu.setPosition((mSize.x() - mMenu.getSize().x()) / 2, (mSize.y() - mMenu.getSize().y()) / 2); } GuiGamelistOptions::~GuiGamelistOptions() { // apply sort FileData* root = getGamelist()->getCursor()->getSystem()->getRootFolder(); root->sort(*mListSort->getSelected()); // will also recursively sort children // notify that the root folder was sorted getGamelist()->onFileChanged(root, FILE_SORTED); } void GuiGamelistOptions::openMetaDataEd() { // open metadata editor FileData* file = getGamelist()->getCursor(); ScraperSearchParams p; p.game = file; p.system = file->getSystem(); mWindow->pushGui(new GuiMetaDataEd(mWindow, &file->metadata, file->metadata.getMDD(), p, file->getPath().filename().string(), std::bind(&IGameListView::onFileChanged, getGamelist(), file, FILE_METADATA_CHANGED), [this, file] { boost::filesystem::remove(file->getPath()); //actually delete the file on the filesystem file->getParent()->removeChild(file); //unlink it so list repopulations triggered from onFileChanged won't see it getGamelist()->onFileChanged(file, FILE_REMOVED); //tell the view delete file; //free it })); } void GuiGamelistOptions::jumpToLetter() { char letter = mJumpToLetterList->getSelected(); IGameListView* gamelist = getGamelist(); // this is a really shitty way to get a list of files const std::vector<FileData*>& files = gamelist->getCursor()->getParent()->getChildren(); long min = 0; long max = files.size() - 1; long mid = 0; while(max >= min) { mid = ((max - min) / 2) + min; // game somehow has no first character to check if(files.at(mid)->getName().empty()) continue; char checkLetter = toupper(files.at(mid)->getName()[0]); if(checkLetter < letter) min = mid + 1; else if(checkLetter > letter) max = mid - 1; else break; //exact match found } gamelist->setCursor(files.at(mid)); delete this; } bool GuiGamelistOptions::input(InputConfig* config, Input input) { if((config->isMappedTo("b", input) || config->isMappedTo("select", input)) && input.value) { delete this; return true; } return mMenu.input(config, input); } std::vector<HelpPrompt> GuiGamelistOptions::getHelpPrompts() { auto prompts = mMenu.getHelpPrompts(); prompts.push_back(HelpPrompt("b", "close")); return prompts; } IGameListView* GuiGamelistOptions::getGamelist() { return ViewController::get()->getGameListView(mSystem).get(); } <commit_msg>Fixed non-ASCII characters never setting an initial selected value for "jump to letter."<commit_after>#include "GuiGamelistOptions.h" #include "GuiMetaDataEd.h" #include "views/gamelist/IGameListView.h" #include "views/ViewController.h" GuiGamelistOptions::GuiGamelistOptions(Window* window, SystemData* system) : GuiComponent(window), mSystem(system), mMenu(window, "OPTIONS") { addChild(&mMenu); // jump to letter char curChar = toupper(getGamelist()->getCursor()->getName()[0]); if(curChar < 'A' || curChar > 'Z') curChar = 'A'; mJumpToLetterList = std::make_shared<LetterList>(mWindow, "JUMP TO LETTER", false); for(char c = 'A'; c <= 'Z'; c++) mJumpToLetterList->add(std::string(1, c), c, c == curChar); ComponentListRow row; row.addElement(std::make_shared<TextComponent>(mWindow, "JUMP TO LETTER", Font::get(FONT_SIZE_MEDIUM), 0x777777FF), true); row.addElement(mJumpToLetterList, false); row.input_handler = [&](InputConfig* config, Input input) { if(config->isMappedTo("a", input) && input.value) { jumpToLetter(); return true; } else if(mJumpToLetterList->input(config, input)) { return true; } return false; }; mMenu.addRow(row); // sort list by mListSort = std::make_shared<SortList>(mWindow, "SORT GAMES BY", false); for(unsigned int i = 0; i < FileSorts::SortTypes.size(); i++) { const FileData::SortType& sort = FileSorts::SortTypes.at(i); mListSort->add(sort.description, &sort, i == 0); // TODO - actually make the sort type persistent } mMenu.addWithLabel("SORT GAMES BY", mListSort); // edit game metadata row.elements.clear(); row.addElement(std::make_shared<TextComponent>(mWindow, "EDIT THIS GAME'S METADATA", Font::get(FONT_SIZE_MEDIUM), 0x777777FF), true); row.addElement(makeArrow(mWindow), false); row.makeAcceptInputHandler(std::bind(&GuiGamelistOptions::openMetaDataEd, this)); mMenu.addRow(row); // center the menu setSize((float)Renderer::getScreenWidth(), (float)Renderer::getScreenHeight()); mMenu.setPosition((mSize.x() - mMenu.getSize().x()) / 2, (mSize.y() - mMenu.getSize().y()) / 2); } GuiGamelistOptions::~GuiGamelistOptions() { // apply sort FileData* root = getGamelist()->getCursor()->getSystem()->getRootFolder(); root->sort(*mListSort->getSelected()); // will also recursively sort children // notify that the root folder was sorted getGamelist()->onFileChanged(root, FILE_SORTED); } void GuiGamelistOptions::openMetaDataEd() { // open metadata editor FileData* file = getGamelist()->getCursor(); ScraperSearchParams p; p.game = file; p.system = file->getSystem(); mWindow->pushGui(new GuiMetaDataEd(mWindow, &file->metadata, file->metadata.getMDD(), p, file->getPath().filename().string(), std::bind(&IGameListView::onFileChanged, getGamelist(), file, FILE_METADATA_CHANGED), [this, file] { boost::filesystem::remove(file->getPath()); //actually delete the file on the filesystem file->getParent()->removeChild(file); //unlink it so list repopulations triggered from onFileChanged won't see it getGamelist()->onFileChanged(file, FILE_REMOVED); //tell the view delete file; //free it })); } void GuiGamelistOptions::jumpToLetter() { char letter = mJumpToLetterList->getSelected(); IGameListView* gamelist = getGamelist(); // this is a really shitty way to get a list of files const std::vector<FileData*>& files = gamelist->getCursor()->getParent()->getChildren(); long min = 0; long max = files.size() - 1; long mid = 0; while(max >= min) { mid = ((max - min) / 2) + min; // game somehow has no first character to check if(files.at(mid)->getName().empty()) continue; char checkLetter = toupper(files.at(mid)->getName()[0]); if(checkLetter < letter) min = mid + 1; else if(checkLetter > letter) max = mid - 1; else break; //exact match found } gamelist->setCursor(files.at(mid)); delete this; } bool GuiGamelistOptions::input(InputConfig* config, Input input) { if((config->isMappedTo("b", input) || config->isMappedTo("select", input)) && input.value) { delete this; return true; } return mMenu.input(config, input); } std::vector<HelpPrompt> GuiGamelistOptions::getHelpPrompts() { auto prompts = mMenu.getHelpPrompts(); prompts.push_back(HelpPrompt("b", "close")); return prompts; } IGameListView* GuiGamelistOptions::getGamelist() { return ViewController::get()->getGameListView(mSystem).get(); } <|endoftext|>
<commit_before>/* // Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #pragma once #include <systemd/sd-bus.h> #include <boost/system/error_code.hpp> #include <sdbusplus/bus.hpp> #include <sdbusplus/message.hpp> namespace sdbusplus { namespace asio { namespace detail { /* Class meant for converting a static callback, and void* userdata from sd-bus * back into a structured class to be returned to the user. */ template <typename CompletionToken> struct unpack_userdata { CompletionToken handler_; static int do_unpack(sd_bus_message* mesg, void* userdata, sd_bus_error* /*error*/) { if (userdata == nullptr) { return -EINVAL; } // Take RAII ownership of the pointer again using self_t = unpack_userdata<CompletionToken>; std::unique_ptr<self_t> context(static_cast<self_t*>(userdata)); if (mesg == nullptr) { return -EINVAL; } message_t message(mesg); auto ec = make_error_code( static_cast<boost::system::errc::errc_t>(message.get_errno())); context->handler_(ec, message); return 0; } }; struct async_send_handler { sd_bus* bus; message_t& mesg; uint64_t timeout; template <typename CompletionToken> void operator()(CompletionToken&& token) { using unpack_t = unpack_userdata<CompletionToken>; auto context = std::make_unique<unpack_t>(std::move(token)); int ec = sd_bus_call_async(bus, NULL, mesg.get(), &unpack_t::do_unpack, context.get(), timeout); if (ec < 0) { auto err = make_error_code(static_cast<boost::system::errc::errc_t>(ec)); context->handler_(err, mesg); return; } // If the call succeeded, sd-bus owns the pointer now, so release it // without freeing. context.release(); } }; } // namespace detail } // namespace asio } // namespace sdbusplus <commit_msg>Give async_send_hander a real constructor<commit_after>/* // Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #pragma once #include <systemd/sd-bus.h> #include <boost/system/error_code.hpp> #include <sdbusplus/bus.hpp> #include <sdbusplus/message.hpp> namespace sdbusplus { namespace asio { namespace detail { /* Class meant for converting a static callback, and void* userdata from sd-bus * back into a structured class to be returned to the user. */ template <typename CompletionToken> struct unpack_userdata { CompletionToken handler_; static int do_unpack(sd_bus_message* mesg, void* userdata, sd_bus_error* /*error*/) { if (userdata == nullptr) { return -EINVAL; } // Take RAII ownership of the pointer again using self_t = unpack_userdata<CompletionToken>; std::unique_ptr<self_t> context(static_cast<self_t*>(userdata)); if (mesg == nullptr) { return -EINVAL; } message_t message(mesg); auto ec = make_error_code( static_cast<boost::system::errc::errc_t>(message.get_errno())); context->handler_(ec, message); return 0; } explicit unpack_userdata(CompletionToken&& handler) : handler_(std::forward<CompletionToken>(handler)) {} }; class async_send_handler { sd_bus* bus; message_t& mesg; uint64_t timeout; public: template <typename CompletionToken> void operator()(CompletionToken&& token) { using unpack_t = unpack_userdata<CompletionToken>; auto context = std::make_unique<unpack_t>(std::move(token)); int ec = sd_bus_call_async(bus, NULL, mesg.get(), &unpack_t::do_unpack, context.get(), timeout); if (ec < 0) { auto err = make_error_code(static_cast<boost::system::errc::errc_t>(ec)); context->handler_(err, mesg); return; } // If the call succeeded, sd-bus owns the pointer now, so release it // without freeing. context.release(); } async_send_handler(sd_bus* busIn, message_t& mesgIn, uint64_t timeoutIn) : bus(busIn), mesg(mesgIn), timeout(timeoutIn) {} }; } // namespace detail } // namespace asio } // namespace sdbusplus <|endoftext|>
<commit_before> #include <qstylesheet.h> #include <klocale.h> #include <kstandarddirs.h> #include <kglobal.h> #include <kdebug.h> #include "device.h" #include "helper.h" using namespace OpieHelper; Base::Base( CategoryEdit* edit, KSync::KonnectorUIDHelper* helper, const QString &tz, bool metaSyncing, Device* dev ) { m_metaSyncing = metaSyncing; m_edit = edit; m_helper = helper; m_tz = tz; m_device = dev; } Base::~Base() { } QDateTime Base::fromUTC( time_t time ) { struct tm *lt; /* getenv can be NULL */ char* ptrTz = getenv( "TZ"); QString real_TZ = ptrTz ? QString::fromLocal8Bit( ptrTz ) : QString::null; if (!m_tz.isEmpty() ) setenv( "TZ", m_tz, true ); kdDebug(5229) << "TimeZone was " << real_TZ << " TimeZone now is " << m_tz << endl; #if defined(_OS_WIN32) || defined (Q_OS_WIN32) || defined (Q_OS_WIN64) _tzset(); #else tzset(); #endif lt = localtime( &time ); QDateTime dt; dt.setDate( QDate( lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday ) ); dt.setTime( QTime( lt->tm_hour, lt->tm_min, lt->tm_sec ) ); if (!m_tz.isEmpty() ) { unsetenv("TZ"); if (!real_TZ.isEmpty() ) setenv("TZ", real_TZ, true ); } kdDebug(5229) << "DateTime is " << dt.toString() << endl; // done return dt; } time_t Base::toUTC( const QDateTime& dt ) { time_t tmp; struct tm *lt; /* getenv can be NULL */ char* ptrTz = getenv( "TZ"); QString real_TZ = ptrTz ? QString::fromLocal8Bit( getenv("TZ") ) : QString::null; if ( !m_tz.isEmpty() ) setenv( "TZ", m_tz, true ); #if defined(_OS_WIN32) || defined (Q_OS_WIN32) || defined (Q_OS_WIN64) _tzset(); #else tzset(); #endif // get a tm structure from the system to get the correct tz_name tmp = time( 0 ); lt = localtime( &tmp ); lt->tm_sec = dt.time().second(); lt->tm_min = dt.time().minute(); lt->tm_hour = dt.time().hour(); lt->tm_mday = dt.date().day(); lt->tm_mon = dt.date().month() - 1; // 0-11 instead of 1-12 lt->tm_year = dt.date().year() - 1900; // year - 1900 //lt->tm_wday = dt.date().dayOfWeek(); ignored anyway //lt->tm_yday = dt.date().dayOfYear(); ignored anyway lt->tm_wday = -1; lt->tm_yday = -1; // tm_isdst negative -> mktime will find out about DST lt->tm_isdst = -1; // keep tm_zone and tm_gmtoff tmp = mktime( lt ); if (!m_tz.isEmpty() ) { unsetenv("TZ"); if (!real_TZ.isEmpty() ) setenv("TZ", real_TZ, true ); } return tmp; } bool Base::isMetaSyncingEnabled()const { return m_metaSyncing; } void Base::setMetaSyncingEnabled(bool meta ) { m_metaSyncing = meta; } KTempFile* Base::file() { KTempFile* fi = new KTempFile( locateLocal("tmp", "opie-konnector"), "new"); return fi; } QString Base::categoriesToNumber( const QStringList &list, const QString &app ) { kdDebug(5226) << "categoriesToNumber " << list.join(";") << endl; startover: QString dummy; QValueList<OpieCategories>::ConstIterator catIt; QValueList<OpieCategories> categories = m_edit->categories(); bool found = false; for ( QStringList::ConstIterator listIt = list.begin(); listIt != list.end(); ++listIt ) { /* skip empty category name */ if ( (*listIt).isEmpty() ) continue; found = false; for ( catIt = categories.begin(); catIt != categories.end(); ++catIt ) { if ( (*catIt).name() == (*listIt) ) { // the same name kdDebug(5226) << "Found " << (*listIt) << endl; found= true; dummy.append( (*catIt).id() + ";"); } } /* if not found and the category is not empty * * generate a new category and start over again * ugly goto to reiterate */ if ( !found && !(*listIt).isEmpty() ){ kdDebug(5226) << "Not Found category " << (*listIt) << endl; m_edit->addCategory( app, (*listIt) ); // generate a new category goto startover; } } if ( !dummy.isEmpty() ) dummy.remove(dummy.length() -1, 1 ); //remove the last ; return dummy; } QString Base::konnectorId( const QString &appName, const QString &uid ) { QString id; QString id2; // Konnector-.length() == 10 if ( uid.startsWith( "Konnector-" ) ) { // not converted id2 = uid.mid( 10 ); }else if ( m_helper) { id = m_helper->konnectorId( appName, uid ); // konnector kde if (id.isEmpty() ) { // generate new id id2 = QString::number( newId() ); id = QString::fromLatin1("Konnector-") + id2; }else if ( id.startsWith( "Konnector-" ) ) { // not converted id2 = id.mid( 10 ); } m_kde2opie.append( Kontainer( id, uid ) ); } return id2; } /* * IntelliSync(tm) is completely broken in regards to assigning UID's * it's always assigning the 0. So for us to work properly we need to rely * on uids! * We'll see if it equals '0' and then prolly assign a new uid */ QString Base::kdeId( const QString &appName, const QString &_uid ) { QString uid = _uid; if (_uid.stripWhiteSpace() == QString::fromLatin1("0") ) { kdDebug() << "broken uid found!!! reassigning" << endl; uid = QString::number( newId() ); } QString ret; if ( !m_helper ) ret = QString::fromLatin1("Konnector-") + uid; else // only if meta ret = m_helper->kdeId( appName, "Konnector-"+uid, "Konnector-"+uid); return ret; } // code copyrighted by tt FIXME // GPL from Qtopia int Base::newId() { static QMap<int, bool> ids; int id = -1 * (int) ::time(NULL ); while ( ids.contains( id ) ){ id += -1; if ( id > 0 ) id = -1; } ids.insert( id, true ); return id; } const Device* Base::device() { return m_device; } QString Base::escape( const QString& string ) { return QStyleSheet::escape( string ); } <commit_msg>We also need to escape " QStyleSheet does not escape it<commit_after> #include <qstylesheet.h> #include <klocale.h> #include <kstandarddirs.h> #include <kglobal.h> #include <kdebug.h> #include "device.h" #include "helper.h" using namespace OpieHelper; Base::Base( CategoryEdit* edit, KSync::KonnectorUIDHelper* helper, const QString &tz, bool metaSyncing, Device* dev ) { m_metaSyncing = metaSyncing; m_edit = edit; m_helper = helper; m_tz = tz; m_device = dev; } Base::~Base() { } QDateTime Base::fromUTC( time_t time ) { struct tm *lt; /* getenv can be NULL */ char* ptrTz = getenv( "TZ"); QString real_TZ = ptrTz ? QString::fromLocal8Bit( ptrTz ) : QString::null; if (!m_tz.isEmpty() ) setenv( "TZ", m_tz, true ); kdDebug(5229) << "TimeZone was " << real_TZ << " TimeZone now is " << m_tz << endl; #if defined(_OS_WIN32) || defined (Q_OS_WIN32) || defined (Q_OS_WIN64) _tzset(); #else tzset(); #endif lt = localtime( &time ); QDateTime dt; dt.setDate( QDate( lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday ) ); dt.setTime( QTime( lt->tm_hour, lt->tm_min, lt->tm_sec ) ); if (!m_tz.isEmpty() ) { unsetenv("TZ"); if (!real_TZ.isEmpty() ) setenv("TZ", real_TZ, true ); } kdDebug(5229) << "DateTime is " << dt.toString() << endl; // done return dt; } time_t Base::toUTC( const QDateTime& dt ) { time_t tmp; struct tm *lt; /* getenv can be NULL */ char* ptrTz = getenv( "TZ"); QString real_TZ = ptrTz ? QString::fromLocal8Bit( getenv("TZ") ) : QString::null; if ( !m_tz.isEmpty() ) setenv( "TZ", m_tz, true ); #if defined(_OS_WIN32) || defined (Q_OS_WIN32) || defined (Q_OS_WIN64) _tzset(); #else tzset(); #endif // get a tm structure from the system to get the correct tz_name tmp = time( 0 ); lt = localtime( &tmp ); lt->tm_sec = dt.time().second(); lt->tm_min = dt.time().minute(); lt->tm_hour = dt.time().hour(); lt->tm_mday = dt.date().day(); lt->tm_mon = dt.date().month() - 1; // 0-11 instead of 1-12 lt->tm_year = dt.date().year() - 1900; // year - 1900 //lt->tm_wday = dt.date().dayOfWeek(); ignored anyway //lt->tm_yday = dt.date().dayOfYear(); ignored anyway lt->tm_wday = -1; lt->tm_yday = -1; // tm_isdst negative -> mktime will find out about DST lt->tm_isdst = -1; // keep tm_zone and tm_gmtoff tmp = mktime( lt ); if (!m_tz.isEmpty() ) { unsetenv("TZ"); if (!real_TZ.isEmpty() ) setenv("TZ", real_TZ, true ); } return tmp; } bool Base::isMetaSyncingEnabled()const { return m_metaSyncing; } void Base::setMetaSyncingEnabled(bool meta ) { m_metaSyncing = meta; } KTempFile* Base::file() { KTempFile* fi = new KTempFile( locateLocal("tmp", "opie-konnector"), "new"); return fi; } QString Base::categoriesToNumber( const QStringList &list, const QString &app ) { kdDebug(5226) << "categoriesToNumber " << list.join(";") << endl; startover: QString dummy; QValueList<OpieCategories>::ConstIterator catIt; QValueList<OpieCategories> categories = m_edit->categories(); bool found = false; for ( QStringList::ConstIterator listIt = list.begin(); listIt != list.end(); ++listIt ) { /* skip empty category name */ if ( (*listIt).isEmpty() ) continue; found = false; for ( catIt = categories.begin(); catIt != categories.end(); ++catIt ) { if ( (*catIt).name() == (*listIt) ) { // the same name kdDebug(5226) << "Found " << (*listIt) << endl; found= true; dummy.append( (*catIt).id() + ";"); } } /* if not found and the category is not empty * * generate a new category and start over again * ugly goto to reiterate */ if ( !found && !(*listIt).isEmpty() ){ kdDebug(5226) << "Not Found category " << (*listIt) << endl; m_edit->addCategory( app, (*listIt) ); // generate a new category goto startover; } } if ( !dummy.isEmpty() ) dummy.remove(dummy.length() -1, 1 ); //remove the last ; return dummy; } QString Base::konnectorId( const QString &appName, const QString &uid ) { QString id; QString id2; // Konnector-.length() == 10 if ( uid.startsWith( "Konnector-" ) ) { // not converted id2 = uid.mid( 10 ); }else if ( m_helper) { id = m_helper->konnectorId( appName, uid ); // konnector kde if (id.isEmpty() ) { // generate new id id2 = QString::number( newId() ); id = QString::fromLatin1("Konnector-") + id2; }else if ( id.startsWith( "Konnector-" ) ) { // not converted id2 = id.mid( 10 ); } m_kde2opie.append( Kontainer( id, uid ) ); } return id2; } /* * IntelliSync(tm) is completely broken in regards to assigning UID's * it's always assigning the 0. So for us to work properly we need to rely * on uids! * We'll see if it equals '0' and then prolly assign a new uid */ QString Base::kdeId( const QString &appName, const QString &_uid ) { QString uid = _uid; if (_uid.stripWhiteSpace() == QString::fromLatin1("0") ) { kdDebug() << "broken uid found!!! reassigning" << endl; uid = QString::number( newId() ); } QString ret; if ( !m_helper ) ret = QString::fromLatin1("Konnector-") + uid; else // only if meta ret = m_helper->kdeId( appName, "Konnector-"+uid, "Konnector-"+uid); return ret; } // code copyrighted by tt FIXME // GPL from Qtopia int Base::newId() { static QMap<int, bool> ids; int id = -1 * (int) ::time(NULL ); while ( ids.contains( id ) ){ id += -1; if ( id > 0 ) id = -1; } ids.insert( id, true ); return id; } const Device* Base::device() { return m_device; } // FROM TT QStyleSheet and StringUtil it's GPLed // we also need to escape '\"' for our xml files QString Base::escape( const QString& plain ) { QString rich; for ( int i = 0; i < int(plain.length()); ++i ) { if ( plain[i] == '<' ) rich +="&lt;"; else if ( plain[i] == '>' ) rich +="&gt;"; else if ( plain[i] == '&' ) rich +="&amp;"; else if ( plain[i] == '\"' ) rich += "&quot;"; else rich += plain[i]; } return rich; } <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- decryptverifyemailcontroller.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "decryptverifyemailcontroller.h" #include <config-kleopatra.h> #include "decryptverifyemailcontroller.h" #include <crypto/gui/decryptverifyoperationwidget.h> #include <crypto/gui/decryptverifywizard.h> #include <crypto/gui/resultdisplaywidget.h> #include <crypto/decryptverifytask.h> #include <utils/classify.h> #include <utils/gnupg-helper.h> #include <utils/input.h> #include <utils/output.h> #include <utils/kleo_assert.h> #include <uiserver/assuancommand.h> #include <kleo/cryptobackendfactory.h> #include <KDebug> #include <KLocalizedString> #include <QPointer> #include <QTimer> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <memory> #include <vector> using namespace boost; using namespace GpgME; using namespace Kleo; using namespace Kleo::Crypto; using namespace Kleo::Crypto::Gui; class DecryptVerifyEMailController::Private { DecryptVerifyEMailController* const q; public: explicit Private( const shared_ptr<AssuanCommand> & cmd, DecryptVerifyEMailController* qq ); void slotWizardCanceled(); void slotTaskDone( const shared_ptr<const DecryptVerifyResult> & ); void schedule(); std::vector<shared_ptr<AbstractDecryptVerifyTask> > buildTasks(); void ensureWizardCreated(); void ensureWizardVisible(); void connectTask( const shared_ptr<AbstractDecryptVerifyTask> & task, unsigned int idx ); void reportError( int err, const QString & details ) { emit q->error( err, details ); } void addStartErrorResult( unsigned int id, const shared_ptr<DecryptVerifyResult> & res ); void cancelAllTasks(); std::vector<shared_ptr<Input> > m_inputs, m_signedDatas; std::vector<shared_ptr<Output> > m_outputs; QPointer<DecryptVerifyWizard> m_wizard; std::vector<shared_ptr<const DecryptVerifyResult> > m_results; std::vector<shared_ptr<AbstractDecryptVerifyTask> > m_runnableTasks, m_completedTasks; shared_ptr<AbstractDecryptVerifyTask> m_runningTask; weak_ptr<AssuanCommand> m_cmd; bool m_silent; DecryptVerifyOperation m_operation; Protocol m_protocol; bool m_errorDetected; VerificationMode m_verificationMode; }; DecryptVerifyEMailController::Private::Private( const shared_ptr<AssuanCommand> & cmd, DecryptVerifyEMailController* qq ) : q( qq ), m_cmd( cmd ), m_silent( false ), m_operation( DecryptVerify ), m_protocol( UnknownProtocol ), m_errorDetected( false ), m_verificationMode( Detached ) { qRegisterMetaType<VerificationResult>(); } void DecryptVerifyEMailController::Private::connectTask( const shared_ptr<AbstractDecryptVerifyTask> & t, unsigned int idx ) { connect( t.get(), SIGNAL(decryptVerifyResult(boost::shared_ptr<const Kleo::Crypto::DecryptVerifyResult>)), q, SLOT(slotTaskDone(boost::shared_ptr<const Kleo::Crypto::DecryptVerifyResult>)) ); ensureWizardCreated(); m_wizard->connectTask( t, idx ); } void DecryptVerifyEMailController::Private::slotWizardCanceled() { kDebug(); reportError( gpg_error( GPG_ERR_CANCELED ), i18n("User canceled") ); } void DecryptVerifyEMailController::Private::slotTaskDone( const shared_ptr<const DecryptVerifyResult> & result ) { assert( q->sender() ); // We could just delete the tasks here, but we can't use // Qt::QueuedConnection here (we need sender()) and other slots // might not yet have executed. Therefore, we push completed tasks // into a burial container if ( q->sender() == m_runningTask.get() ) { m_completedTasks.push_back( m_runningTask ); m_results.push_back( result ); m_runningTask.reset(); } QTimer::singleShot( 0, q, SLOT(schedule()) ); } void DecryptVerifyEMailController::Private::schedule() { if ( !m_runningTask && !m_runnableTasks.empty() ) { const shared_ptr<AbstractDecryptVerifyTask> t = m_runnableTasks.back(); m_runnableTasks.pop_back(); t->start(); m_runningTask = t; } if ( !m_runningTask ) { kleo_assert( m_runnableTasks.empty() ); #if KDAB_PENDING // remove encrypted inputs here if wanted? if ( m_wizard->removeUnencryptedFile() && m_wizard->encryptionSelected() && !errorDetected ) removeInputFiles(); #endif Q_FOREACH ( const shared_ptr<const DecryptVerifyResult> & i, m_results ) emit q->verificationResult( i->verificationResult() ); emit q->done(); } } void DecryptVerifyEMailController::Private::ensureWizardCreated() { if ( m_wizard ) return; std::auto_ptr<DecryptVerifyWizard> w( new DecryptVerifyWizard ); w->setWindowTitle( i18n( "Decrypt/Verify E-Mail" ) ); w->setAttribute( Qt::WA_DeleteOnClose ); connect( w.get(), SIGNAL(canceled()), q, SLOT(slotWizardCanceled()), Qt::QueuedConnection ); connect( q, SIGNAL( done() ), w.get(), SLOT( setOperationCompleted() ), Qt::QueuedConnection ); connect( q, SIGNAL( error( int, QString ) ), w.get(), SLOT( setOperationCompleted() ), Qt::QueuedConnection ); m_wizard = w.release(); } std::vector< shared_ptr<AbstractDecryptVerifyTask> > DecryptVerifyEMailController::Private::buildTasks() { const uint numInputs = m_inputs.size(); const uint numMessages = m_signedDatas.size(); const uint numOutputs = m_outputs.size(); // these are duplicated from DecryptVerifyCommandEMailBase::Private::checkForErrors with slightly modified error codes/messages if ( !numInputs ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), i18n("At least one input needs to be provided") ); if ( numMessages ) if ( numMessages != numInputs ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), //TODO use better error code if possible i18n("Signature/signed data count mismatch") ); else if ( m_operation != Verify || m_verificationMode != Detached ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), i18n("Signed data can only be given for detached signature verification") ); if ( numOutputs ) if ( numOutputs != numInputs ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), //TODO use better error code if possible i18n("Input/Output count mismatch") ); else if ( numMessages ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), i18n("Cannot use output and signed data simultaneously") ); kleo_assert( m_protocol != UnknownProtocol ); const CryptoBackend::Protocol * const backend = CryptoBackendFactory::instance()->protocol( m_protocol ); if ( !backend ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_UNSUPPORTED_PROTOCOL ), m_protocol == OpenPGP ? i18n("No backend support for OpenPGP") : m_protocol == CMS ? i18n("No backend support for S/MIME") : QString() ); if ( m_operation != Decrypt && !m_silent ) { ensureWizardVisible(); m_wizard->next(); } std::vector< shared_ptr<AbstractDecryptVerifyTask> > tasks; for ( unsigned int i = 0 ; i < numInputs ; ++i ) { shared_ptr<AbstractDecryptVerifyTask> task; switch ( m_operation ) { case Decrypt: { shared_ptr<DecryptTask> t( new DecryptTask ); t->setInput( m_inputs.at( i ) ); assert( numOutputs ); t->setOutput( m_outputs.at( i ) ); t->setProtocol( m_protocol ); task = t; } break; case Verify: { if ( m_verificationMode == Detached ) { shared_ptr<VerifyDetachedTask> t( new VerifyDetachedTask ); t->setInput( m_inputs.at( i ) ); t->setSignedData( m_signedDatas.at( i ) ); t->setProtocol( m_protocol ); task = t; } else { shared_ptr<VerifyOpaqueTask> t( new VerifyOpaqueTask ); t->setInput( m_inputs.at( i ) ); if ( numOutputs ) t->setOutput( m_outputs.at( i ) ); t->setProtocol( m_protocol ); task = t; } } break; case DecryptVerify: { shared_ptr<DecryptVerifyTask> t( new DecryptVerifyTask ); t->setInput( m_inputs.at( i ) ); assert( numOutputs ); t->setOutput( m_outputs.at( i ) ); t->setProtocol( m_protocol ); task = t; } } assert( task ); tasks.push_back( task ); } return tasks; } void DecryptVerifyEMailController::Private::ensureWizardVisible() { ensureWizardCreated(); q->bringToForeground( m_wizard ); } DecryptVerifyEMailController::DecryptVerifyEMailController( const shared_ptr<AssuanCommand> & cmd, QObject* parent ) : Controller( parent ), d( new Private( cmd, this ) ) { } DecryptVerifyEMailController::~DecryptVerifyEMailController() { kDebug(); } void DecryptVerifyEMailController::start() { d->m_runnableTasks = d->buildTasks(); int i = 0; Q_FOREACH( const shared_ptr<AbstractDecryptVerifyTask> task, d->m_runnableTasks ) d->connectTask( task, i++ ); d->ensureWizardVisible(); QTimer::singleShot( 0, this, SLOT(schedule()) ); } void DecryptVerifyEMailController::setInputs( const std::vector<shared_ptr<Input> > & inputs ) { d->m_inputs = inputs; } void DecryptVerifyEMailController::setSignedData( const std::vector<shared_ptr<Input> > & data ) { d->m_signedDatas = data; } void DecryptVerifyEMailController::setOutputs( const std::vector<shared_ptr<Output> > & outputs ) { d->m_outputs = outputs; } void DecryptVerifyEMailController::setWizardShown( bool shown ) { d->m_silent = !shown; if ( d->m_wizard ) d->m_wizard->setVisible( shown ); } void DecryptVerifyEMailController::setOperation( DecryptVerifyOperation operation ) { d->m_operation = operation; } void DecryptVerifyEMailController::setVerificationMode( VerificationMode vm ) { d->m_verificationMode = vm; } void DecryptVerifyEMailController::setProtocol( Protocol prot ) { d->m_protocol = prot; } void DecryptVerifyEMailController::Private::addStartErrorResult( unsigned int id, const shared_ptr<DecryptVerifyResult> & res ) { ensureWizardCreated(); m_wizard->resultWidget( id )->setResult( res ); m_results.push_back( res ); } void DecryptVerifyEMailController::cancel() { kDebug(); try { d->m_errorDetected = true; if ( d->m_wizard ) d->m_wizard->close(); d->cancelAllTasks(); } catch ( const std::exception & e ) { qDebug( "Caught exception: %s", e.what() ); } } void DecryptVerifyEMailController::Private::cancelAllTasks() { // we just kill all runnable tasks - this will not result in // signal emissions. m_runnableTasks.clear(); // a cancel() will result in a call to if ( m_runningTask ) m_runningTask->cancel(); } #include "decryptverifyemailcontroller.moc" <commit_msg>#if -> #ifdef<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- decryptverifyemailcontroller.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2008 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "decryptverifyemailcontroller.h" #include <config-kleopatra.h> #include "decryptverifyemailcontroller.h" #include <crypto/gui/decryptverifyoperationwidget.h> #include <crypto/gui/decryptverifywizard.h> #include <crypto/gui/resultdisplaywidget.h> #include <crypto/decryptverifytask.h> #include <utils/classify.h> #include <utils/gnupg-helper.h> #include <utils/input.h> #include <utils/output.h> #include <utils/kleo_assert.h> #include <uiserver/assuancommand.h> #include <kleo/cryptobackendfactory.h> #include <KDebug> #include <KLocalizedString> #include <QPointer> #include <QTimer> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <memory> #include <vector> using namespace boost; using namespace GpgME; using namespace Kleo; using namespace Kleo::Crypto; using namespace Kleo::Crypto::Gui; class DecryptVerifyEMailController::Private { DecryptVerifyEMailController* const q; public: explicit Private( const shared_ptr<AssuanCommand> & cmd, DecryptVerifyEMailController* qq ); void slotWizardCanceled(); void slotTaskDone( const shared_ptr<const DecryptVerifyResult> & ); void schedule(); std::vector<shared_ptr<AbstractDecryptVerifyTask> > buildTasks(); void ensureWizardCreated(); void ensureWizardVisible(); void connectTask( const shared_ptr<AbstractDecryptVerifyTask> & task, unsigned int idx ); void reportError( int err, const QString & details ) { emit q->error( err, details ); } void addStartErrorResult( unsigned int id, const shared_ptr<DecryptVerifyResult> & res ); void cancelAllTasks(); std::vector<shared_ptr<Input> > m_inputs, m_signedDatas; std::vector<shared_ptr<Output> > m_outputs; QPointer<DecryptVerifyWizard> m_wizard; std::vector<shared_ptr<const DecryptVerifyResult> > m_results; std::vector<shared_ptr<AbstractDecryptVerifyTask> > m_runnableTasks, m_completedTasks; shared_ptr<AbstractDecryptVerifyTask> m_runningTask; weak_ptr<AssuanCommand> m_cmd; bool m_silent; DecryptVerifyOperation m_operation; Protocol m_protocol; bool m_errorDetected; VerificationMode m_verificationMode; }; DecryptVerifyEMailController::Private::Private( const shared_ptr<AssuanCommand> & cmd, DecryptVerifyEMailController* qq ) : q( qq ), m_cmd( cmd ), m_silent( false ), m_operation( DecryptVerify ), m_protocol( UnknownProtocol ), m_errorDetected( false ), m_verificationMode( Detached ) { qRegisterMetaType<VerificationResult>(); } void DecryptVerifyEMailController::Private::connectTask( const shared_ptr<AbstractDecryptVerifyTask> & t, unsigned int idx ) { connect( t.get(), SIGNAL(decryptVerifyResult(boost::shared_ptr<const Kleo::Crypto::DecryptVerifyResult>)), q, SLOT(slotTaskDone(boost::shared_ptr<const Kleo::Crypto::DecryptVerifyResult>)) ); ensureWizardCreated(); m_wizard->connectTask( t, idx ); } void DecryptVerifyEMailController::Private::slotWizardCanceled() { kDebug(); reportError( gpg_error( GPG_ERR_CANCELED ), i18n("User canceled") ); } void DecryptVerifyEMailController::Private::slotTaskDone( const shared_ptr<const DecryptVerifyResult> & result ) { assert( q->sender() ); // We could just delete the tasks here, but we can't use // Qt::QueuedConnection here (we need sender()) and other slots // might not yet have executed. Therefore, we push completed tasks // into a burial container if ( q->sender() == m_runningTask.get() ) { m_completedTasks.push_back( m_runningTask ); m_results.push_back( result ); m_runningTask.reset(); } QTimer::singleShot( 0, q, SLOT(schedule()) ); } void DecryptVerifyEMailController::Private::schedule() { if ( !m_runningTask && !m_runnableTasks.empty() ) { const shared_ptr<AbstractDecryptVerifyTask> t = m_runnableTasks.back(); m_runnableTasks.pop_back(); t->start(); m_runningTask = t; } if ( !m_runningTask ) { kleo_assert( m_runnableTasks.empty() ); #ifdef KDAB_PENDING // remove encrypted inputs here if wanted? if ( m_wizard->removeUnencryptedFile() && m_wizard->encryptionSelected() && !errorDetected ) removeInputFiles(); #endif Q_FOREACH ( const shared_ptr<const DecryptVerifyResult> & i, m_results ) emit q->verificationResult( i->verificationResult() ); emit q->done(); } } void DecryptVerifyEMailController::Private::ensureWizardCreated() { if ( m_wizard ) return; std::auto_ptr<DecryptVerifyWizard> w( new DecryptVerifyWizard ); w->setWindowTitle( i18n( "Decrypt/Verify E-Mail" ) ); w->setAttribute( Qt::WA_DeleteOnClose ); connect( w.get(), SIGNAL(canceled()), q, SLOT(slotWizardCanceled()), Qt::QueuedConnection ); connect( q, SIGNAL( done() ), w.get(), SLOT( setOperationCompleted() ), Qt::QueuedConnection ); connect( q, SIGNAL( error( int, QString ) ), w.get(), SLOT( setOperationCompleted() ), Qt::QueuedConnection ); m_wizard = w.release(); } std::vector< shared_ptr<AbstractDecryptVerifyTask> > DecryptVerifyEMailController::Private::buildTasks() { const uint numInputs = m_inputs.size(); const uint numMessages = m_signedDatas.size(); const uint numOutputs = m_outputs.size(); // these are duplicated from DecryptVerifyCommandEMailBase::Private::checkForErrors with slightly modified error codes/messages if ( !numInputs ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), i18n("At least one input needs to be provided") ); if ( numMessages ) if ( numMessages != numInputs ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), //TODO use better error code if possible i18n("Signature/signed data count mismatch") ); else if ( m_operation != Verify || m_verificationMode != Detached ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), i18n("Signed data can only be given for detached signature verification") ); if ( numOutputs ) if ( numOutputs != numInputs ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), //TODO use better error code if possible i18n("Input/Output count mismatch") ); else if ( numMessages ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_CONFLICT ), i18n("Cannot use output and signed data simultaneously") ); kleo_assert( m_protocol != UnknownProtocol ); const CryptoBackend::Protocol * const backend = CryptoBackendFactory::instance()->protocol( m_protocol ); if ( !backend ) throw Kleo::Exception( makeGnuPGError( GPG_ERR_UNSUPPORTED_PROTOCOL ), m_protocol == OpenPGP ? i18n("No backend support for OpenPGP") : m_protocol == CMS ? i18n("No backend support for S/MIME") : QString() ); if ( m_operation != Decrypt && !m_silent ) { ensureWizardVisible(); m_wizard->next(); } std::vector< shared_ptr<AbstractDecryptVerifyTask> > tasks; for ( unsigned int i = 0 ; i < numInputs ; ++i ) { shared_ptr<AbstractDecryptVerifyTask> task; switch ( m_operation ) { case Decrypt: { shared_ptr<DecryptTask> t( new DecryptTask ); t->setInput( m_inputs.at( i ) ); assert( numOutputs ); t->setOutput( m_outputs.at( i ) ); t->setProtocol( m_protocol ); task = t; } break; case Verify: { if ( m_verificationMode == Detached ) { shared_ptr<VerifyDetachedTask> t( new VerifyDetachedTask ); t->setInput( m_inputs.at( i ) ); t->setSignedData( m_signedDatas.at( i ) ); t->setProtocol( m_protocol ); task = t; } else { shared_ptr<VerifyOpaqueTask> t( new VerifyOpaqueTask ); t->setInput( m_inputs.at( i ) ); if ( numOutputs ) t->setOutput( m_outputs.at( i ) ); t->setProtocol( m_protocol ); task = t; } } break; case DecryptVerify: { shared_ptr<DecryptVerifyTask> t( new DecryptVerifyTask ); t->setInput( m_inputs.at( i ) ); assert( numOutputs ); t->setOutput( m_outputs.at( i ) ); t->setProtocol( m_protocol ); task = t; } } assert( task ); tasks.push_back( task ); } return tasks; } void DecryptVerifyEMailController::Private::ensureWizardVisible() { ensureWizardCreated(); q->bringToForeground( m_wizard ); } DecryptVerifyEMailController::DecryptVerifyEMailController( const shared_ptr<AssuanCommand> & cmd, QObject* parent ) : Controller( parent ), d( new Private( cmd, this ) ) { } DecryptVerifyEMailController::~DecryptVerifyEMailController() { kDebug(); } void DecryptVerifyEMailController::start() { d->m_runnableTasks = d->buildTasks(); int i = 0; Q_FOREACH( const shared_ptr<AbstractDecryptVerifyTask> task, d->m_runnableTasks ) d->connectTask( task, i++ ); d->ensureWizardVisible(); QTimer::singleShot( 0, this, SLOT(schedule()) ); } void DecryptVerifyEMailController::setInputs( const std::vector<shared_ptr<Input> > & inputs ) { d->m_inputs = inputs; } void DecryptVerifyEMailController::setSignedData( const std::vector<shared_ptr<Input> > & data ) { d->m_signedDatas = data; } void DecryptVerifyEMailController::setOutputs( const std::vector<shared_ptr<Output> > & outputs ) { d->m_outputs = outputs; } void DecryptVerifyEMailController::setWizardShown( bool shown ) { d->m_silent = !shown; if ( d->m_wizard ) d->m_wizard->setVisible( shown ); } void DecryptVerifyEMailController::setOperation( DecryptVerifyOperation operation ) { d->m_operation = operation; } void DecryptVerifyEMailController::setVerificationMode( VerificationMode vm ) { d->m_verificationMode = vm; } void DecryptVerifyEMailController::setProtocol( Protocol prot ) { d->m_protocol = prot; } void DecryptVerifyEMailController::Private::addStartErrorResult( unsigned int id, const shared_ptr<DecryptVerifyResult> & res ) { ensureWizardCreated(); m_wizard->resultWidget( id )->setResult( res ); m_results.push_back( res ); } void DecryptVerifyEMailController::cancel() { kDebug(); try { d->m_errorDetected = true; if ( d->m_wizard ) d->m_wizard->close(); d->cancelAllTasks(); } catch ( const std::exception & e ) { qDebug( "Caught exception: %s", e.what() ); } } void DecryptVerifyEMailController::Private::cancelAllTasks() { // we just kill all runnable tasks - this will not result in // signal emissions. m_runnableTasks.clear(); // a cancel() will result in a call to if ( m_runningTask ) m_runningTask->cancel(); } #include "decryptverifyemailcontroller.moc" <|endoftext|>
<commit_before>#include "paletteTreeWidgets.h" #include "mainWindow/palette/paletteTree.h" #include "mainWindow/palette/draggableElement.h" using namespace qReal; using namespace gui; PaletteTreeWidgets::PaletteTreeWidgets(PaletteTree &parent, MainWindow *mainWindow , EditorManagerInterface &editorManagerProxy) : QSplitter(Qt::Vertical) , mEditorManager(&editorManagerProxy) , mParentPalette(&parent) , mMainWindow(mainWindow) , mEditorTree(new PaletteTreeWidget(parent, *mainWindow, editorManagerProxy, false)) , mUserTree(new PaletteTreeWidget(parent, *mainWindow, editorManagerProxy, true)) { initWidgets(); } PaletteTreeWidgets::PaletteTreeWidgets(PaletteTree &parent, MainWindow *mainWindow , EditorManagerInterface &editorManagerProxy , Id const &editor, Id const &diagram) : QSplitter(Qt::Vertical) , mParentPalette(&parent) , mMainWindow(mainWindow) , mEditor(editor) , mDiagram(diagram) , mEditorTree(new PaletteTreeWidget(parent, *mainWindow, editorManagerProxy, false)) , mUserTree(new PaletteTreeWidget(parent, *mainWindow, editorManagerProxy, true)) { mEditorManager = &editorManagerProxy; initWidgets(); initEditorTree(); initUserTree(); } void PaletteTreeWidgets::initWidgets() { initWidget(mEditorTree); initWidget(mUserTree); } void PaletteTreeWidgets::initWidget(PaletteTreeWidget * const tree) { tree->setHeaderHidden(true); tree->setSelectionMode(QAbstractItemView::NoSelection); addWidget(tree); } void PaletteTreeWidgets::initEditorTree() { IdList elements = mEditorManager->elements(mDiagram) + mEditorManager->groups(mDiagram); bool const sort = mEditorManager->shallPaletteBeSorted(mEditor, mDiagram); if (sort) { PaletteTreeWidget::sortByFriendlyName(elements); } if (!mEditorManager->paletteGroups(mEditor, mDiagram).empty()) { QList<QPair<QString, QList<PaletteElement>>> groups; QMap<QString, QString> descriptions; for (QString const &group : mEditorManager->paletteGroups(mEditor, mDiagram)) { QStringList const paletteGroup = mEditorManager->paletteGroupList(mEditor, mDiagram, group); QList<PaletteElement> groupElements; for (QString const &name : paletteGroup) { for (Id const &element : elements) { if (element.element() == name) { groupElements << PaletteElement(*mEditorManager, element); break; } } } groups << qMakePair(group, groupElements); descriptions[group] = mEditorManager->paletteGroupDescription(mEditor, mDiagram, group); } mEditorTree->addGroups(groups, descriptions, false, mEditorManager->friendlyName(mDiagram), sort); } else { for (Id const &element : elements) { addTopItemType(PaletteElement(*mEditorManager, element), mEditorTree); } } } void PaletteTreeWidgets::initUserTree() { refreshUserPalette(); connect(&mMainWindow->models()->exploser(), &models::Exploser::explosionsSetCouldChange , this, &PaletteTreeWidgets::refreshUserPalette); } void PaletteTreeWidgets::addTopItemType(PaletteElement const &data, QTreeWidget *tree) { QTreeWidgetItem *item = new QTreeWidgetItem; DraggableElement *element = new DraggableElement(*mMainWindow, data , mParentPalette->iconsView(), *mEditorManager); mPaletteElements.insert(data.id(), element); tree->addTopLevelItem(item); tree->setItemWidget(item, 0, element); } void PaletteTreeWidgets::resizeIcons() { if (mParentPalette->iconsView() && mParentPalette->itemsCountInARow() > 1) { const int iconSize = 48; const int widgetSize = this->size().width() - (iconSize << 1); const int itemsCount = maxItemsCountInARow(); const int newSize = (widgetSize < itemsCount * iconSize) ? (widgetSize / itemsCount) : iconSize; for (int i = 0; i < mEditorTree->topLevelItemCount(); i++) { for (int j = 0; j < mEditorTree->topLevelItem(i)->childCount(); j++) { QWidget *field = mEditorTree->itemWidget(mEditorTree->topLevelItem(i)->child(j), 0); if (!field) { break; } foreach (QObject *child, field->children()) { DraggableElement *element = dynamic_cast<DraggableElement*>(child); if (element) { element->setIconSize(newSize); } } } } } } int PaletteTreeWidgets::maxItemsCountInARow() const { int max = 0; for (int i = 0; i < mEditorTree->topLevelItemCount(); i++) { for (int j = 0; j < mEditorTree->topLevelItem(i)->childCount(); j++) { QWidget *field = mEditorTree->itemWidget(mEditorTree->topLevelItem(i)->child(j), 0); if (!field) { break; } int itemsCount = field->children().count(); if (itemsCount > max) { max = itemsCount; } } } return max; } void PaletteTreeWidgets::expand() { mEditorTree->expand(); mEditorTree->expand(); } void PaletteTreeWidgets::collapse() { mEditorTree->collapse(); mUserTree->collapse(); } void PaletteTreeWidgets::saveConfiguration(QString const &title) const { saveConfiguration(mEditorTree, title); saveConfiguration(mUserTree, title); } void PaletteTreeWidgets::saveConfiguration(PaletteTreeWidget const *tree, QString const &title) const { for (int j = 0; j < tree->topLevelItemCount(); j++) { QTreeWidgetItem const *topItem = tree->topLevelItem(j); if (topItem) { SettingsManager::setValue(title, topItem->isExpanded()); } } } void PaletteTreeWidgets::setElementVisible(Id const &metatype, bool visible) { if (mPaletteElements.contains(metatype)) { mPaletteElements[metatype]->setVisible(visible); } else { mEditorTree->setElementVisible(metatype, visible); } } void PaletteTreeWidgets::setVisibleForAllElements(bool visible) { foreach (QWidget * const element, mPaletteElements.values()) { element->setVisible(visible); } mEditorTree->setVisibleForAllElements(visible); } void PaletteTreeWidgets::setElementEnabled(Id const &metatype, bool enabled) { if (mPaletteElements.contains(metatype)) { mPaletteElements[metatype]->setEnabled(enabled); } else { mEditorTree->setElementEnabled(metatype, enabled); } } void PaletteTreeWidgets::setEnabledForAllElements(bool enabled) { foreach (QWidget * const element, mPaletteElements.values()) { element->setEnabled(enabled); } mEditorTree->setEnabledForAllElements(enabled); } void PaletteTreeWidgets::customizeExplosionTitles(QString const &userGroupTitle, QString const &userGroupDescription) { mUserGroupTitle = userGroupTitle; mUserGroupDescription = userGroupDescription; } void PaletteTreeWidgets::refreshUserPalette() { QList<QPair<QString, QList<gui::PaletteElement>>> groups; QMap<QString, QString> descriptions = { { mUserGroupTitle, mUserGroupDescription } }; QMultiMap<Id, Id> const types = mMainWindow->models()->exploser().explosions(mDiagram); for (Id const &source : types.keys()) { QList<gui::PaletteElement> groupElements; for (Id const &target : types.values(source)) { groupElements << gui::PaletteElement(source , mMainWindow->models()->logicalRepoApi().name(target) , QString(), mEditorManager->icon(source) , mEditorManager->iconSize(source) , target); } groups << qMakePair(mUserGroupTitle, groupElements); } mUserTree->addGroups(groups, descriptions, true, mEditorManager->friendlyName(mDiagram), true); } <commit_msg>Fixed user blocks palette behaviour in case of multiple subprograms<commit_after>#include "paletteTreeWidgets.h" #include "mainWindow/palette/paletteTree.h" #include "mainWindow/palette/draggableElement.h" using namespace qReal; using namespace gui; PaletteTreeWidgets::PaletteTreeWidgets(PaletteTree &parent, MainWindow *mainWindow , EditorManagerInterface &editorManagerProxy) : QSplitter(Qt::Vertical) , mEditorManager(&editorManagerProxy) , mParentPalette(&parent) , mMainWindow(mainWindow) , mEditorTree(new PaletteTreeWidget(parent, *mainWindow, editorManagerProxy, false)) , mUserTree(new PaletteTreeWidget(parent, *mainWindow, editorManagerProxy, true)) { initWidgets(); } PaletteTreeWidgets::PaletteTreeWidgets(PaletteTree &parent, MainWindow *mainWindow , EditorManagerInterface &editorManagerProxy , Id const &editor, Id const &diagram) : QSplitter(Qt::Vertical) , mParentPalette(&parent) , mMainWindow(mainWindow) , mEditor(editor) , mDiagram(diagram) , mEditorTree(new PaletteTreeWidget(parent, *mainWindow, editorManagerProxy, false)) , mUserTree(new PaletteTreeWidget(parent, *mainWindow, editorManagerProxy, true)) { mEditorManager = &editorManagerProxy; initWidgets(); initEditorTree(); initUserTree(); } void PaletteTreeWidgets::initWidgets() { initWidget(mEditorTree); initWidget(mUserTree); } void PaletteTreeWidgets::initWidget(PaletteTreeWidget * const tree) { tree->setHeaderHidden(true); tree->setSelectionMode(QAbstractItemView::NoSelection); addWidget(tree); } void PaletteTreeWidgets::initEditorTree() { IdList elements = mEditorManager->elements(mDiagram) + mEditorManager->groups(mDiagram); bool const sort = mEditorManager->shallPaletteBeSorted(mEditor, mDiagram); if (sort) { PaletteTreeWidget::sortByFriendlyName(elements); } if (!mEditorManager->paletteGroups(mEditor, mDiagram).empty()) { QList<QPair<QString, QList<PaletteElement>>> groups; QMap<QString, QString> descriptions; for (QString const &group : mEditorManager->paletteGroups(mEditor, mDiagram)) { QStringList const paletteGroup = mEditorManager->paletteGroupList(mEditor, mDiagram, group); QList<PaletteElement> groupElements; for (QString const &name : paletteGroup) { for (Id const &element : elements) { if (element.element() == name) { groupElements << PaletteElement(*mEditorManager, element); break; } } } groups << qMakePair(group, groupElements); descriptions[group] = mEditorManager->paletteGroupDescription(mEditor, mDiagram, group); } mEditorTree->addGroups(groups, descriptions, false, mEditorManager->friendlyName(mDiagram), sort); } else { for (Id const &element : elements) { addTopItemType(PaletteElement(*mEditorManager, element), mEditorTree); } } } void PaletteTreeWidgets::initUserTree() { refreshUserPalette(); connect(&mMainWindow->models()->exploser(), &models::Exploser::explosionsSetCouldChange , this, &PaletteTreeWidgets::refreshUserPalette); } void PaletteTreeWidgets::addTopItemType(PaletteElement const &data, QTreeWidget *tree) { QTreeWidgetItem *item = new QTreeWidgetItem; DraggableElement *element = new DraggableElement(*mMainWindow, data , mParentPalette->iconsView(), *mEditorManager); mPaletteElements.insert(data.id(), element); tree->addTopLevelItem(item); tree->setItemWidget(item, 0, element); } void PaletteTreeWidgets::resizeIcons() { if (mParentPalette->iconsView() && mParentPalette->itemsCountInARow() > 1) { const int iconSize = 48; const int widgetSize = this->size().width() - (iconSize << 1); const int itemsCount = maxItemsCountInARow(); const int newSize = (widgetSize < itemsCount * iconSize) ? (widgetSize / itemsCount) : iconSize; for (int i = 0; i < mEditorTree->topLevelItemCount(); i++) { for (int j = 0; j < mEditorTree->topLevelItem(i)->childCount(); j++) { QWidget *field = mEditorTree->itemWidget(mEditorTree->topLevelItem(i)->child(j), 0); if (!field) { break; } foreach (QObject *child, field->children()) { DraggableElement *element = dynamic_cast<DraggableElement*>(child); if (element) { element->setIconSize(newSize); } } } } } } int PaletteTreeWidgets::maxItemsCountInARow() const { int max = 0; for (int i = 0; i < mEditorTree->topLevelItemCount(); i++) { for (int j = 0; j < mEditorTree->topLevelItem(i)->childCount(); j++) { QWidget *field = mEditorTree->itemWidget(mEditorTree->topLevelItem(i)->child(j), 0); if (!field) { break; } int itemsCount = field->children().count(); if (itemsCount > max) { max = itemsCount; } } } return max; } void PaletteTreeWidgets::expand() { mEditorTree->expand(); mEditorTree->expand(); } void PaletteTreeWidgets::collapse() { mEditorTree->collapse(); mUserTree->collapse(); } void PaletteTreeWidgets::saveConfiguration(QString const &title) const { saveConfiguration(mEditorTree, title); saveConfiguration(mUserTree, title); } void PaletteTreeWidgets::saveConfiguration(PaletteTreeWidget const *tree, QString const &title) const { for (int j = 0; j < tree->topLevelItemCount(); j++) { QTreeWidgetItem const *topItem = tree->topLevelItem(j); if (topItem) { SettingsManager::setValue(title, topItem->isExpanded()); } } } void PaletteTreeWidgets::setElementVisible(Id const &metatype, bool visible) { if (mPaletteElements.contains(metatype)) { mPaletteElements[metatype]->setVisible(visible); } else { mEditorTree->setElementVisible(metatype, visible); } } void PaletteTreeWidgets::setVisibleForAllElements(bool visible) { foreach (QWidget * const element, mPaletteElements.values()) { element->setVisible(visible); } mEditorTree->setVisibleForAllElements(visible); } void PaletteTreeWidgets::setElementEnabled(Id const &metatype, bool enabled) { if (mPaletteElements.contains(metatype)) { mPaletteElements[metatype]->setEnabled(enabled); } else { mEditorTree->setElementEnabled(metatype, enabled); } } void PaletteTreeWidgets::setEnabledForAllElements(bool enabled) { foreach (QWidget * const element, mPaletteElements.values()) { element->setEnabled(enabled); } mEditorTree->setEnabledForAllElements(enabled); } void PaletteTreeWidgets::customizeExplosionTitles(QString const &userGroupTitle, QString const &userGroupDescription) { mUserGroupTitle = userGroupTitle; mUserGroupDescription = userGroupDescription; } void PaletteTreeWidgets::refreshUserPalette() { QList<QPair<QString, QList<gui::PaletteElement>>> groups; QMap<QString, QString> descriptions = { { mUserGroupTitle, mUserGroupDescription } }; QList<gui::PaletteElement> groupElements; QMultiMap<Id, Id> const types = mMainWindow->models()->exploser().explosions(mDiagram); for (Id const &source : types.uniqueKeys()) { for (Id const &target : types.values(source)) { groupElements << gui::PaletteElement(source , mMainWindow->models()->logicalRepoApi().name(target) , QString(), mEditorManager->icon(source) , mEditorManager->iconSize(source) , target); } } if (!groupElements.isEmpty()) { groups << qMakePair(mUserGroupTitle, groupElements); } mUserTree->addGroups(groups, descriptions, true, mEditorManager->friendlyName(mDiagram), true); } <|endoftext|>
<commit_before>/** * @defgroup pwg2_forward_scripts Scripts used in the analysis * * @ingroup pwg2_forward */ /** * @file * @ingroup pwg2_forward_scripts * */ /** * This is the macro to include the Forward multiplicity in a train. * * @ingroup pwg2_forward_scripts */ AliAnalysisTask* AddTaskFMD() { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskFMD", "No analysis manager to connect to."); return NULL; } // --- Make the task and add it to the manager --------------------- AliForwardMultiplicityTask* task = new AliForwardMultiplicityTask("FMD"); mgr->AddTask(task); // --- Set parameters on the algorithms ---------------------------- // Whether to enable low flux specific code task->SetEnableLowFlux(kFALSE); // Set the number of SPD tracklets for which we consider the event a // low flux event task->GetEventInspector().SetLowFluxCut(1000); // Set the maximum error on v_z [cm] task->GetEventInspector().SetMaxVzErr(0.2); // Set the eta axis to use - note, this overrides whatever is used // by the rest of the algorithms - but only for the energy fitter // algorithm. task->GetEnergyFitter().SetEtaAxis(200, -4, 6); // Set maximum energy loss to consider task->GetEnergyFitter().SetMaxE(10); // Set number of energy loss bins task->GetEnergyFitter().SetNEbins(300); // Set whether to use increasing bin sizes task->GetEnergyFitter().SetUseIncreasingBins(true); // Set whether to do fit the energy distributions task->GetEnergyFitter().SetDoFits(kFALSE); // Set whether to make the correction object task->GetEnergyFitter().SetDoMakeObject(kFALSE); // Set the low cut used for energy task->GetEnergyFitter().SetLowCut(0.4); // Set the number of bins to subtract from maximum of distributions // to get the lower bound of the fit range task->GetEnergyFitter().SetFitRangeBinWidth(4); // Set the maximum number of landaus to try to fit (max 5) task->GetEnergyFitter().SetNParticles(5); // Set the minimum number of entries in the distribution before // trying to fit to the data task->GetEnergyFitter().SetMinEntries(1000); // Set the low cut used for sharing - overrides settings in eloss fits // task->GetSharingFilter().SetLowCut(0.4); // Set the number of xi's (width of landau peak) to stop at task->GetSharingFilter().SetNXi(1); // Set the maximum number of particle to try to reconstruct task->GetDensityCalculator().SetMaxParticles(2); // Set the lower multiplicity cut. Overrides setting in energy loss fits. // task->GetDensityCalculator().SetMultCut(0.4); // Set the number of extra bins (beyond the secondary map border) task->GetHistCollector().SetNCutBins(1); // Set the correction cut, that is, when bins in the secondary map // is smaller than this, they are considered empty task->GetHistCollector().SetCorrectionCut(0.1); // Set the overall debug level (1: some output, 3: a lot of output) task->SetDebug(0); // Set the debug level of a single algorithm // task->GetEventInspector().SetDebug(4); // --- Set limits on fits the energy ------------------------------- // Maximum relative error on parameters AliFMDCorrELossFit::ELossFit::fgMaxRelError = .12; // Least weight to use AliFMDCorrELossFit::ELossFit::fgLeastWeight = 1e-5; // Maximum value of reduced chi^2 AliFMDCorrELossFit::ELossFit::fgMaxChi2nu = 5; // --- Set up the parameter manager --------------------------------- // AliFMDAnaParameters* pars = AliFMDAnaParameters::Instance(); AliMCEventHandler* mcHandler = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler()); Info("AddTaskFMD", "MC handler %p", mcHandler); // if(mcHandler) { // pars->SetRealData(kFALSE); // pars->SetProcessPrimary(kTRUE); // pars->SetProcessHits(kFALSE); // } // else { // pars->SetRealData(kTRUE); // pars->SetProcessPrimary(kFALSE); // pars->SetProcessHits(kFALSE); // } // pars->Init(); // --- Make the output container and connect it -------------------- TString outputfile = AliAnalysisManager::GetCommonFileName(); // outputfile += ":PWG2forwardDnDeta"; // Form(":%s",pars->GetDndetaAnalysisName()); AliAnalysisDataContainer* histOut = mgr->CreateContainer("Forward", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, histOut); return task; } <commit_msg>Allow use for MC data<commit_after>/** * @defgroup pwg2_forward_scripts Scripts used in the analysis * * @ingroup pwg2_forward */ /** * @file * @ingroup pwg2_forward_scripts * */ /** * This is the macro to include the Forward multiplicity in a train. * * @ingroup pwg2_forward_scripts */ AliAnalysisTask* AddTaskFMD(Bool_t mc) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskFMD", "No analysis manager to connect to."); return NULL; } // --- Make the task and add it to the manager --------------------- AliForwardMultiplicityBase* task = 0; if (mc) task = new AliForwardMCMultiplicityTask("FMD"); else task = new AliForwardMultiplicityTask("FMD"); mgr->AddTask(task); // Whether to enable low flux specific code task->SetEnableLowFlux(kFALSE); // Set the number of SPD tracklets for which we consider the event a // low flux event task->GetEventInspector().SetLowFluxCut(1000); // Set the maximum error on v_z [cm] task->GetEventInspector().SetMaxVzErr(0.2); // Set the eta axis to use - note, this overrides whatever is used // by the rest of the algorithms - but only for the energy fitter // algorithm. task->GetEnergyFitter().SetEtaAxis(200, -4, 6); // Set maximum energy loss to consider task->GetEnergyFitter().SetMaxE(10); // Set number of energy loss bins task->GetEnergyFitter().SetNEbins(300); // Set whether to use increasing bin sizes task->GetEnergyFitter().SetUseIncreasingBins(true); // Set whether to do fit the energy distributions task->GetEnergyFitter().SetDoFits(kFALSE); // Set whether to make the correction object task->GetEnergyFitter().SetDoMakeObject(kFALSE); // Set the low cut used for energy task->GetEnergyFitter().SetLowCut(0.4); // Set the number of bins to subtract from maximum of distributions // to get the lower bound of the fit range task->GetEnergyFitter().SetFitRangeBinWidth(4); // Set the maximum number of landaus to try to fit (max 5) task->GetEnergyFitter().SetNParticles(5); // Set the minimum number of entries in the distribution before // trying to fit to the data task->GetEnergyFitter().SetMinEntries(1000); // Set the low cut used for sharing - overrides settings in eloss fits // task->GetSharingFilter().SetLowCut(0.4); // Set the number of xi's (width of landau peak) to stop at task->GetSharingFilter().SetNXi(1); // Set the maximum number of particle to try to reconstruct task->GetDensityCalculator().SetMaxParticles(2); // Set the lower multiplicity cut. Overrides setting in energy loss fits. // task->GetDensityCalculator().SetMultCut(0.4); // Set the number of extra bins (beyond the secondary map border) task->GetHistCollector().SetNCutBins(1); // Set the correction cut, that is, when bins in the secondary map // is smaller than this, they are considered empty task->GetHistCollector().SetCorrectionCut(0.1); // Set the overall debug level (1: some output, 3: a lot of output) task->SetDebug(0); // Set the debug level of a single algorithm // task->GetEventInspector().SetDebug(4); // --- Set limits on fits the energy ------------------------------- // Maximum relative error on parameters AliFMDCorrELossFit::ELossFit::fgMaxRelError = .12; // Least weight to use AliFMDCorrELossFit::ELossFit::fgLeastWeight = 1e-5; // Maximum value of reduced chi^2 AliFMDCorrELossFit::ELossFit::fgMaxChi2nu = 5; // --- Make the output container and connect it -------------------- TString outputfile = AliAnalysisManager::GetCommonFileName(); // outputfile += ":PWG2forwardDnDeta"; // Form(":%s",pars->GetDndetaAnalysisName()); AliAnalysisDataContainer* histOut = mgr->CreateContainer("Forward", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, histOut); return task; } <|endoftext|>
<commit_before>//===- SparcDisassembler.cpp - Disassembler for Sparc -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is part of the Sparc Disassembler. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sparc-disassembler" #include "Sparc.h" #include "SparcRegisterInfo.h" #include "SparcSubtarget.h" #include "llvm/MC/MCDisassembler.h" #include "llvm/MC/MCFixedLenDisassembler.h" #include "llvm/Support/MemoryObject.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; typedef MCDisassembler::DecodeStatus DecodeStatus; namespace { /// SparcDisassembler - a disassembler class for Sparc. class SparcDisassembler : public MCDisassembler { public: /// Constructor - Initializes the disassembler. /// SparcDisassembler(const MCSubtargetInfo &STI, const MCRegisterInfo *Info) : MCDisassembler(STI), RegInfo(Info) {} virtual ~SparcDisassembler() {} const MCRegisterInfo *getRegInfo() const { return RegInfo.get(); } /// getInstruction - See MCDisassembler. virtual DecodeStatus getInstruction(MCInst &instr, uint64_t &size, const MemoryObject &region, uint64_t address, raw_ostream &vStream, raw_ostream &cStream) const; private: OwningPtr<const MCRegisterInfo> RegInfo; }; } namespace llvm { extern Target TheSparcTarget, TheSparcV9Target; } static MCDisassembler *createSparcDisassembler( const Target &T, const MCSubtargetInfo &STI) { return new SparcDisassembler(STI, T.createMCRegInfo("")); } extern "C" void LLVMInitializeSparcDisassembler() { // Register the disassembler. TargetRegistry::RegisterMCDisassembler(TheSparcTarget, createSparcDisassembler); TargetRegistry::RegisterMCDisassembler(TheSparcV9Target, createSparcDisassembler); } static const unsigned IntRegDecoderTable[] = { SP::G0, SP::G1, SP::G2, SP::G3, SP::G4, SP::G5, SP::G6, SP::G7, SP::O0, SP::O1, SP::O2, SP::O3, SP::O4, SP::O5, SP::O6, SP::O7, SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5, SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5, SP::I6, SP::I7 }; static const unsigned FPRegDecoderTable[] = { SP::F0, SP::F1, SP::F2, SP::F3, SP::F4, SP::F5, SP::F6, SP::F7, SP::F8, SP::F9, SP::F10, SP::F11, SP::F12, SP::F13, SP::F14, SP::F15, SP::F16, SP::F17, SP::F18, SP::F19, SP::F20, SP::F21, SP::F22, SP::F23, SP::F24, SP::F25, SP::F26, SP::F27, SP::F28, SP::F29, SP::F30, SP::F31 }; static const unsigned DFPRegDecoderTable[] = { SP::D0, SP::D16, SP::D1, SP::D17, SP::D2, SP::D18, SP::D3, SP::D19, SP::D4, SP::D20, SP::D5, SP::D21, SP::D6, SP::D22, SP::D7, SP::D23, SP::D8, SP::D24, SP::D9, SP::D25, SP::D10, SP::D26, SP::D11, SP::D27, SP::D12, SP::D28, SP::D13, SP::D29, SP::D14, SP::D30, SP::D15, SP::D31 }; static const unsigned QFPRegDecoderTable[] = { SP::Q0, SP::Q8, (unsigned)-1, (unsigned)-1, SP::Q1, SP::Q9, (unsigned)-1, (unsigned)-1, SP::Q2, SP::Q10, (unsigned)-1, (unsigned)-1, SP::Q3, SP::Q11, (unsigned)-1, (unsigned)-1, SP::Q4, SP::Q12, (unsigned)-1, (unsigned)-1, SP::Q5, SP::Q13, (unsigned)-1, (unsigned)-1, SP::Q6, SP::Q14, (unsigned)-1, (unsigned)-1, SP::Q7, SP::Q15, (unsigned)-1, (unsigned)-1 } ; static DecodeStatus DecodeIntRegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = IntRegDecoderTable[RegNo]; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } static DecodeStatus DecodeI64RegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = IntRegDecoderTable[RegNo]; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } static DecodeStatus DecodeFPRegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = FPRegDecoderTable[RegNo]; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } static DecodeStatus DecodeDFPRegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = DFPRegDecoderTable[RegNo]; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } static DecodeStatus DecodeQFPRegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = QFPRegDecoderTable[RegNo]; if (Reg == (unsigned)-1) return MCDisassembler::Fail; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } #include "SparcGenDisassemblerTables.inc" /// readInstruction - read four bytes from the MemoryObject /// and return 32 bit word. static DecodeStatus readInstruction32(const MemoryObject &region, uint64_t address, uint64_t &size, uint32_t &insn) { uint8_t Bytes[4]; // We want to read exactly 4 Bytes of data. if (region.readBytes(address, 4, Bytes) == -1) { size = 0; return MCDisassembler::Fail; } // Encoded as a big-endian 32-bit word in the stream. insn = (Bytes[3] << 0) | (Bytes[2] << 8) | (Bytes[1] << 16) | (Bytes[0] << 24); return MCDisassembler::Success; } DecodeStatus SparcDisassembler::getInstruction(MCInst &instr, uint64_t &Size, const MemoryObject &Region, uint64_t Address, raw_ostream &vStream, raw_ostream &cStream) const { uint32_t Insn; DecodeStatus Result = readInstruction32(Region, Address, Size, Insn); if (Result == MCDisassembler::Fail) return MCDisassembler::Fail; // Calling the auto-generated decoder function. Result = decodeInstruction(DecoderTableSparc32, instr, Insn, Address, this, STI); if (Result != MCDisassembler::Fail) { Size = 4; return Result; } return MCDisassembler::Fail; } <commit_msg>[Sparc] Replace (unsigned)-1 with ~OU as suggested by Reid Kleckner.<commit_after>//===- SparcDisassembler.cpp - Disassembler for Sparc -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is part of the Sparc Disassembler. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sparc-disassembler" #include "Sparc.h" #include "SparcRegisterInfo.h" #include "SparcSubtarget.h" #include "llvm/MC/MCDisassembler.h" #include "llvm/MC/MCFixedLenDisassembler.h" #include "llvm/Support/MemoryObject.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; typedef MCDisassembler::DecodeStatus DecodeStatus; namespace { /// SparcDisassembler - a disassembler class for Sparc. class SparcDisassembler : public MCDisassembler { public: /// Constructor - Initializes the disassembler. /// SparcDisassembler(const MCSubtargetInfo &STI, const MCRegisterInfo *Info) : MCDisassembler(STI), RegInfo(Info) {} virtual ~SparcDisassembler() {} const MCRegisterInfo *getRegInfo() const { return RegInfo.get(); } /// getInstruction - See MCDisassembler. virtual DecodeStatus getInstruction(MCInst &instr, uint64_t &size, const MemoryObject &region, uint64_t address, raw_ostream &vStream, raw_ostream &cStream) const; private: OwningPtr<const MCRegisterInfo> RegInfo; }; } namespace llvm { extern Target TheSparcTarget, TheSparcV9Target; } static MCDisassembler *createSparcDisassembler( const Target &T, const MCSubtargetInfo &STI) { return new SparcDisassembler(STI, T.createMCRegInfo("")); } extern "C" void LLVMInitializeSparcDisassembler() { // Register the disassembler. TargetRegistry::RegisterMCDisassembler(TheSparcTarget, createSparcDisassembler); TargetRegistry::RegisterMCDisassembler(TheSparcV9Target, createSparcDisassembler); } static const unsigned IntRegDecoderTable[] = { SP::G0, SP::G1, SP::G2, SP::G3, SP::G4, SP::G5, SP::G6, SP::G7, SP::O0, SP::O1, SP::O2, SP::O3, SP::O4, SP::O5, SP::O6, SP::O7, SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5, SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5, SP::I6, SP::I7 }; static const unsigned FPRegDecoderTable[] = { SP::F0, SP::F1, SP::F2, SP::F3, SP::F4, SP::F5, SP::F6, SP::F7, SP::F8, SP::F9, SP::F10, SP::F11, SP::F12, SP::F13, SP::F14, SP::F15, SP::F16, SP::F17, SP::F18, SP::F19, SP::F20, SP::F21, SP::F22, SP::F23, SP::F24, SP::F25, SP::F26, SP::F27, SP::F28, SP::F29, SP::F30, SP::F31 }; static const unsigned DFPRegDecoderTable[] = { SP::D0, SP::D16, SP::D1, SP::D17, SP::D2, SP::D18, SP::D3, SP::D19, SP::D4, SP::D20, SP::D5, SP::D21, SP::D6, SP::D22, SP::D7, SP::D23, SP::D8, SP::D24, SP::D9, SP::D25, SP::D10, SP::D26, SP::D11, SP::D27, SP::D12, SP::D28, SP::D13, SP::D29, SP::D14, SP::D30, SP::D15, SP::D31 }; static const unsigned QFPRegDecoderTable[] = { SP::Q0, SP::Q8, ~0U, ~0U, SP::Q1, SP::Q9, ~0U, ~0U, SP::Q2, SP::Q10, ~0U, ~0U, SP::Q3, SP::Q11, ~0U, ~0U, SP::Q4, SP::Q12, ~0U, ~0U, SP::Q5, SP::Q13, ~0U, ~0U, SP::Q6, SP::Q14, ~0U, ~0U, SP::Q7, SP::Q15, ~0U, ~0U } ; static DecodeStatus DecodeIntRegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = IntRegDecoderTable[RegNo]; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } static DecodeStatus DecodeI64RegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = IntRegDecoderTable[RegNo]; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } static DecodeStatus DecodeFPRegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = FPRegDecoderTable[RegNo]; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } static DecodeStatus DecodeDFPRegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = DFPRegDecoderTable[RegNo]; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } static DecodeStatus DecodeQFPRegsRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; unsigned Reg = QFPRegDecoderTable[RegNo]; if (Reg == ~0U) return MCDisassembler::Fail; Inst.addOperand(MCOperand::CreateReg(Reg)); return MCDisassembler::Success; } #include "SparcGenDisassemblerTables.inc" /// readInstruction - read four bytes from the MemoryObject /// and return 32 bit word. static DecodeStatus readInstruction32(const MemoryObject &region, uint64_t address, uint64_t &size, uint32_t &insn) { uint8_t Bytes[4]; // We want to read exactly 4 Bytes of data. if (region.readBytes(address, 4, Bytes) == -1) { size = 0; return MCDisassembler::Fail; } // Encoded as a big-endian 32-bit word in the stream. insn = (Bytes[3] << 0) | (Bytes[2] << 8) | (Bytes[1] << 16) | (Bytes[0] << 24); return MCDisassembler::Success; } DecodeStatus SparcDisassembler::getInstruction(MCInst &instr, uint64_t &Size, const MemoryObject &Region, uint64_t Address, raw_ostream &vStream, raw_ostream &cStream) const { uint32_t Insn; DecodeStatus Result = readInstruction32(Region, Address, Size, Insn); if (Result == MCDisassembler::Fail) return MCDisassembler::Fail; // Calling the auto-generated decoder function. Result = decodeInstruction(DecoderTableSparc32, instr, Insn, Address, this, STI); if (Result != MCDisassembler::Fail) { Size = 4; return Result; } return MCDisassembler::Fail; } <|endoftext|>
<commit_before>#include "aio_private.h" #define EVEN_DISTRIBUTE const int MAX_BUF_REQS = 1024 * 3; /* * each file gets the same number of outstanding requests. */ #ifdef EVEN_DISTRIBUTE #define MAX_OUTSTANDING_NREQS (AIO_DEPTH / num_open_files()) #define ALLOW_DROP #endif void aio_callback(io_context_t ctx, struct iocb* iocb, void *cb, long res, long res2) { thread_callback_s *tcb = (thread_callback_s *) cb; tcb->aio->return_cb(tcb); } async_io::async_io(const char *names[], int num, long size, int aio_depth_per_file): buffered_io(names, num, size, O_DIRECT | O_RDWR), AIO_DEPTH(aio_depth_per_file * num) { printf("aio is used\n"); buf_idx = 0; ctx = create_aio_ctx(AIO_DEPTH); for (int i = 0; i < AIO_DEPTH * 5; i++) { cbs.push_back(new thread_callback_s()); } cb = NULL; } void async_io::cleanup() { int slot = max_io_slot(ctx); while (slot < AIO_DEPTH) { io_wait(ctx, NULL); slot = max_io_slot(ctx); } buffered_io::cleanup(); } async_io::~async_io() { cleanup(); } struct iocb *async_io::construct_req(io_request &io_req, callback_t cb_func) { if (cbs.empty()) { fprintf(stderr, "no callback object left\n"); return NULL; } thread_callback_s *tcb = cbs.front(); io_callback_s *cb = (io_callback_s *) tcb; cbs.pop_front(); cb->func = cb_func; tcb->req = io_req; tcb->aio = this; assert(tcb->req.get_size() >= MIN_BLOCK_SIZE); assert(tcb->req.get_size() % MIN_BLOCK_SIZE == 0); assert(tcb->req.get_offset() % MIN_BLOCK_SIZE == 0); assert((long) tcb->req.get_buf() % MIN_BLOCK_SIZE == 0); int io_type = tcb->req.get_access_method() == READ ? A_READ : A_WRITE; if (tcb->req.get_num_bufs() == 1) return make_io_request(ctx, get_fd(tcb->req.get_offset()), tcb->req.get_size(), tcb->req.get_offset(), tcb->req.get_buf(), io_type, cb); else { int num_bufs = tcb->req.get_num_bufs(); for (int i = 0; i < num_bufs; i++) { assert((long) tcb->req.get_buf(i) % MIN_BLOCK_SIZE == 0); assert(tcb->req.get_buf_size(i) % MIN_BLOCK_SIZE == 0); } return make_io_request(ctx, get_fd(tcb->req.get_offset()), /* * iocb only contains a pointer to the io vector. * the space for the IO vector is stored * in the callback structure. */ tcb->req.get_vec(), num_bufs, tcb->req.get_offset(), io_type, cb); } } ssize_t async_io::access(io_request *requests, int num) { ssize_t ret = 0; int min = 10; /* a minimal number of IO events to wait. */ if (min > AIO_DEPTH) min = AIO_DEPTH; while (num > 0) { int slot = max_io_slot(ctx); if (slot == 0) { io_wait(ctx, NULL, min); slot = max_io_slot(ctx); } struct iocb *reqs[slot]; int min = slot > num ? num : slot; for (int i = 0; i < min; i++) { ret += requests->get_size(); reqs[i] = construct_req(*requests, aio_callback); requests++; } submit_io_request(ctx, reqs, min); num -= min; } return ret; } <commit_msg>Improve performance of AIO.<commit_after>#include "aio_private.h" #define EVEN_DISTRIBUTE const int MAX_BUF_REQS = 1024 * 3; /* * each file gets the same number of outstanding requests. */ #ifdef EVEN_DISTRIBUTE #define MAX_OUTSTANDING_NREQS (AIO_DEPTH / num_open_files()) #define ALLOW_DROP #endif void aio_callback(io_context_t ctx, struct iocb* iocb, void *cb, long res, long res2) { thread_callback_s *tcb = (thread_callback_s *) cb; tcb->aio->return_cb(tcb); } async_io::async_io(const char *names[], int num, long size, int aio_depth_per_file): buffered_io(names, num, size, O_DIRECT | O_RDWR), AIO_DEPTH(aio_depth_per_file * num) { printf("aio is used\n"); buf_idx = 0; ctx = create_aio_ctx(AIO_DEPTH); for (int i = 0; i < AIO_DEPTH * 5; i++) { cbs.push_back(new thread_callback_s()); } cb = NULL; } void async_io::cleanup() { int slot = max_io_slot(ctx); while (slot < AIO_DEPTH) { io_wait(ctx, NULL); slot = max_io_slot(ctx); } buffered_io::cleanup(); } async_io::~async_io() { cleanup(); } struct iocb *async_io::construct_req(io_request &io_req, callback_t cb_func) { if (cbs.empty()) { fprintf(stderr, "no callback object left\n"); return NULL; } thread_callback_s *tcb = cbs.front(); io_callback_s *cb = (io_callback_s *) tcb; cbs.pop_front(); cb->func = cb_func; tcb->req = io_req; tcb->aio = this; assert(tcb->req.get_size() >= MIN_BLOCK_SIZE); assert(tcb->req.get_size() % MIN_BLOCK_SIZE == 0); assert(tcb->req.get_offset() % MIN_BLOCK_SIZE == 0); assert((long) tcb->req.get_buf() % MIN_BLOCK_SIZE == 0); int io_type = tcb->req.get_access_method() == READ ? A_READ : A_WRITE; if (tcb->req.get_num_bufs() == 1) return make_io_request(ctx, get_fd(tcb->req.get_offset()), tcb->req.get_size(), tcb->req.get_offset(), tcb->req.get_buf(), io_type, cb); else { int num_bufs = tcb->req.get_num_bufs(); for (int i = 0; i < num_bufs; i++) { assert((long) tcb->req.get_buf(i) % MIN_BLOCK_SIZE == 0); assert(tcb->req.get_buf_size(i) % MIN_BLOCK_SIZE == 0); } return make_io_request(ctx, get_fd(tcb->req.get_offset()), /* * iocb only contains a pointer to the io vector. * the space for the IO vector is stored * in the callback structure. */ tcb->req.get_vec(), num_bufs, tcb->req.get_offset(), io_type, cb); } } ssize_t async_io::access(io_request *requests, int num) { ssize_t ret = 0; while (num > 0) { int slot = max_io_slot(ctx); if (slot == 0) { /* * To achieve the best performance, we need to submit requests * as long as there is a slot available. */ io_wait(ctx, NULL, 1); slot = max_io_slot(ctx); } struct iocb *reqs[slot]; int min = slot > num ? num : slot; for (int i = 0; i < min; i++) { ret += requests->get_size(); reqs[i] = construct_req(*requests, aio_callback); requests++; } submit_io_request(ctx, reqs, min); num -= min; } return ret; } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "IncrementalJIT.h" #include "IncrementalExecutor.h" #include "cling/Utils/Platform.h" #include "llvm/ExecutionEngine/Orc/LambdaResolver.h" #include "llvm/Support/DynamicLibrary.h" #ifdef __APPLE__ // Apple adds an extra '_' # define MANGLE_PREFIX "_" #else # define MANGLE_PREFIX "" #endif using namespace llvm; namespace { ///\brief Memory manager providing the lop-level link to the /// IncrementalExecutor, handles missing or special / replaced symbols. class ClingMemoryManager: public SectionMemoryManager { public: ClingMemoryManager(cling::IncrementalExecutor& Exe) {} ///\brief Simply wraps the base class's function setting AbortOnFailure /// to false and instead using the error handling mechanism to report it. void* getPointerToNamedFunction(const std::string &Name, bool /*AbortOnFailure*/ =true) override { return SectionMemoryManager::getPointerToNamedFunction(Name, false); } }; class NotifyFinalizedT { public: NotifyFinalizedT(cling::IncrementalJIT &jit) : m_JIT(jit) {} void operator()(llvm::orc::ObjectLinkingLayerBase::ObjSetHandleT H) { m_JIT.RemoveUnfinalizedSection(H); } private: cling::IncrementalJIT &m_JIT; }; } // unnamed namespace namespace cling { ///\brief Memory manager for the OrcJIT layers to resolve symbols from the /// common IncrementalJIT. I.e. the master of the Orcs. /// Each ObjectLayer instance has one Azog object. class Azog: public RTDyldMemoryManager { cling::IncrementalJIT& m_jit; struct AllocInfo { uint8_t *m_Start = nullptr; uint8_t *m_End = nullptr; uint8_t *m_Current = nullptr; void allocate(RTDyldMemoryManager *exeMM, uintptr_t Size, uint32_t Align, bool code, bool isReadOnly) { uintptr_t RequiredSize = 2*Size; // Space for internal alignment. if (code) m_Start = exeMM->allocateCodeSection(RequiredSize, Align, 0 /* SectionID */, "codeReserve"); else if (isReadOnly) m_Start = exeMM->allocateDataSection(RequiredSize, Align, 0 /* SectionID */, "rodataReserve",isReadOnly); else m_Start = exeMM->allocateDataSection(RequiredSize, Align, 0 /* SectionID */, "rwataReserve",isReadOnly); m_Current = m_Start; m_End = m_Start + RequiredSize; } uint8_t* getNextAddr(uintptr_t Size, unsigned Alignment) { if (!Alignment) Alignment = 16; assert(!(Alignment & (Alignment - 1)) && "Alignment must be a power of two."); uintptr_t RequiredSize = Alignment * ((Size + Alignment - 1)/Alignment + 1); if ( (m_Current + RequiredSize) > m_End ) { cling::errs() << "Error in block allocation by Azog. " << "Not enough memory was reserved for the current module. " << Size << " (round to " << RequiredSize << " ) was need but\n" << "We only have " << (m_End - m_Current) << ".\n"; return nullptr; } uintptr_t Addr = (uintptr_t)m_Current; // Align the address. Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1); m_Current = (uint8_t*)(Addr + Size); return (uint8_t*)Addr; } operator bool() { return m_Current != nullptr; } }; AllocInfo m_Code; AllocInfo m_ROData; AllocInfo m_RWData; public: Azog(cling::IncrementalJIT& Jit): m_jit(Jit) {} RTDyldMemoryManager* getExeMM() const { return m_jit.m_ExeMM.get(); } uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) override { uint8_t *Addr = nullptr; if (m_Code) { Addr = m_Code.getNextAddr(Size, Alignment); } if (!Addr) { Addr = getExeMM()->allocateCodeSection(Size, Alignment, SectionID, SectionName); m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr); } return Addr; } uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) override { uint8_t *Addr = nullptr; if (IsReadOnly && m_ROData) { Addr = m_ROData.getNextAddr(Size,Alignment); } else if (m_RWData) { Addr = m_RWData.getNextAddr(Size,Alignment); } if (!Addr) { Addr = getExeMM()->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly); m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr); } return Addr; } void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign, uintptr_t RODataSize, uint32_t RODataAlign, uintptr_t RWDataSize, uint32_t RWDataAlign) override { m_Code.allocate(getExeMM(),CodeSize, CodeAlign, true, false); m_ROData.allocate(getExeMM(),RODataSize, RODataAlign, false, true); m_RWData.allocate(getExeMM(),RWDataSize, RWDataAlign, false, false); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_Code.m_Start); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_ROData.m_Start); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_RWData.m_Start); } bool needsToReserveAllocationSpace() override { return true; // getExeMM()->needsToReserveAllocationSpace(); } void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { return getExeMM()->registerEHFrames(Addr, LoadAddr, Size); } void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { return getExeMM()->deregisterEHFrames(Addr, LoadAddr, Size); } uint64_t getSymbolAddress(const std::string &Name) override { return m_jit.getSymbolAddressWithoutMangling(Name, true /*also use dlsym*/) .getAddress(); } void *getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure = true) override { return getExeMM()->getPointerToNamedFunction(Name, AbortOnFailure); } using llvm::RuntimeDyld::MemoryManager::notifyObjectLoaded; void notifyObjectLoaded(ExecutionEngine *EE, const object::ObjectFile &O) override { return getExeMM()->notifyObjectLoaded(EE, O); } bool finalizeMemory(std::string *ErrMsg = nullptr) override { // Each set of objects loaded will be finalized exactly once, but since // symbol lookup during relocation may recursively trigger the // loading/relocation of other modules, and since we're forwarding all // finalizeMemory calls to a single underlying memory manager, we need to // defer forwarding the call on until all necessary objects have been // loaded. Otherwise, during the relocation of a leaf object, we will end // up finalizing memory, causing a crash further up the stack when we // attempt to apply relocations to finalized memory. // To avoid finalizing too early, look at how many objects have been // loaded but not yet finalized. This is a bit of a hack that relies on // the fact that we're lazily emitting object files: The only way you can // get more than one set of objects loaded but not yet finalized is if // they were loaded during relocation of another set. if (m_jit.m_UnfinalizedSections.size() == 1) return getExeMM()->finalizeMemory(ErrMsg); return false; }; }; // class Azog IncrementalJIT::IncrementalJIT(IncrementalExecutor& exe, std::unique_ptr<TargetMachine> TM): m_Parent(exe), m_TM(std::move(TM)), m_TMDataLayout(m_TM->createDataLayout()), m_ExeMM(llvm::make_unique<ClingMemoryManager>(m_Parent)), m_NotifyObjectLoaded(*this), m_ObjectLayer(m_SymbolMap, m_NotifyObjectLoaded, NotifyFinalizedT(*this)), m_CompileLayer(m_ObjectLayer, llvm::orc::SimpleCompiler(*m_TM)), m_LazyEmitLayer(m_CompileLayer) { // Enable JIT symbol resolution from the binary. llvm::sys::DynamicLibrary::LoadLibraryPermanently(0, 0); // Make debug symbols available. m_GDBListener = 0; // JITEventListener::createGDBRegistrationListener(); // #if MCJIT // llvm::EngineBuilder builder(std::move(m)); // std::string errMsg; // builder.setErrorStr(&errMsg); // builder.setOptLevel(llvm::CodeGenOpt::Less); // builder.setEngineKind(llvm::EngineKind::JIT); // std::unique_ptr<llvm::RTDyldMemoryManager> // MemMan(new ClingMemoryManager(*this)); // builder.setMCJITMemoryManager(std::move(MemMan)); // // EngineBuilder uses default c'ted TargetOptions, too: // llvm::TargetOptions TargetOpts; // TargetOpts.NoFramePointerElim = 1; // TargetOpts.JITEmitDebugInfo = 1; // builder.setTargetOptions(TargetOpts); // m_engine.reset(builder.create()); // assert(m_engine && "Cannot create module!"); // #endif } llvm::orc::JITSymbol IncrementalJIT::getInjectedSymbols(const std::string& Name) const { using JITSymbol = llvm::orc::JITSymbol; auto SymMapI = m_SymbolMap.find(Name); if (SymMapI != m_SymbolMap.end()) return JITSymbol(SymMapI->second, llvm::JITSymbolFlags::Exported); return JITSymbol(nullptr); } std::pair<void*, bool> IncrementalJIT::lookupSymbol(llvm::StringRef Name, void *InAddr, bool Jit) { // FIXME: See comments on DLSym below. #if !defined(LLVM_ON_WIN32) void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(Name); #else void* Addr = const_cast<void*>(platform::DLSym(Name)); #endif if (InAddr && (!Addr || Jit)) { if (Jit) { std::string Key(Name); Key.insert(0, MANGLE_PREFIX); m_SymbolMap[Key] = llvm::orc::TargetAddress(InAddr); } llvm::sys::DynamicLibrary::AddSymbol(Name, InAddr); return std::make_pair(InAddr, true); } return std::make_pair(Addr, false); } llvm::orc::JITSymbol IncrementalJIT::getSymbolAddressWithoutMangling(const std::string& Name, bool AlsoInProcess) { if (auto Sym = getInjectedSymbols(Name)) return Sym; if (AlsoInProcess) { if (RuntimeDyld::SymbolInfo SymInfo = m_ExeMM->findSymbol(Name)) return llvm::orc::JITSymbol(SymInfo.getAddress(), llvm::JITSymbolFlags::Exported); #ifdef LLVM_ON_WIN32 // FIXME: DLSym symbol lookup can overlap m_ExeMM->findSymbol wasting time // looking for a symbol in libs where it is already known not to exist. // Perhaps a better solution would be to have IncrementalJIT own the // DynamicLibraryManger instance (or at least have a reference) that will // look only through user loaded libraries. // An upside to doing it this way is RTLD_GLOBAL won't need to be used // allowing libs with competing symbols to co-exists. if (const void* Sym = platform::DLSym(Name)) return llvm::orc::JITSymbol(llvm::orc::TargetAddress(Sym), llvm::JITSymbolFlags::Exported); #endif } if (auto Sym = m_LazyEmitLayer.findSymbol(Name, false)) return Sym; return llvm::orc::JITSymbol(nullptr); } size_t IncrementalJIT::addModules(std::vector<llvm::Module*>&& modules) { // If this module doesn't have a DataLayout attached then attach the // default. for (auto&& mod: modules) { mod->setDataLayout(m_TMDataLayout); } // LLVM MERGE FIXME: update this to use new interfaces. auto Resolver = llvm::orc::createLambdaResolver( [&](const std::string &S) { if (auto Sym = getInjectedSymbols(S)) return RuntimeDyld::SymbolInfo((uint64_t)Sym.getAddress(), Sym.getFlags()); return m_ExeMM->findSymbol(S); }, [&](const std::string &Name) { if (auto Sym = getSymbolAddressWithoutMangling(Name, true) /*was: findSymbol(Name)*/) return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags()); /// This method returns the address of the specified function or variable /// that could not be resolved by getSymbolAddress() or by resolving /// possible weak symbols by the ExecutionEngine. /// It is used to resolve symbols during module linking. std::string NameNoPrefix; if (MANGLE_PREFIX[0] && !Name.compare(0, strlen(MANGLE_PREFIX), MANGLE_PREFIX)) NameNoPrefix = Name.substr(strlen(MANGLE_PREFIX), -1); else NameNoPrefix = std::move(Name); uint64_t addr = (uint64_t) getParent().NotifyLazyFunctionCreators(NameNoPrefix); return RuntimeDyld::SymbolInfo(addr, llvm::JITSymbolFlags::Weak); }); ModuleSetHandleT MSHandle = m_LazyEmitLayer.addModuleSet(std::move(modules), llvm::make_unique<Azog>(*this), std::move(Resolver)); m_UnloadPoints.push_back(MSHandle); return m_UnloadPoints.size() - 1; } // void* IncrementalJIT::finalizeMemory() { // for (auto &P : UnfinalizedSections) // if (P.second.count(LocalAddress)) // ObjectLayer.mapSectionAddress(P.first, LocalAddress, TargetAddress); // } void IncrementalJIT::removeModules(size_t handle) { if (handle == (size_t)-1) return; auto objSetHandle = m_UnloadPoints[handle]; m_LazyEmitLayer.removeModuleSet(objSetHandle); } }// end namespace cling <commit_msg>Remove unnecessary overallocation in Azog::reserveAllocationSpace<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "IncrementalJIT.h" #include "IncrementalExecutor.h" #include "cling/Utils/Platform.h" #include "llvm/ExecutionEngine/Orc/LambdaResolver.h" #include "llvm/Support/DynamicLibrary.h" #ifdef __APPLE__ // Apple adds an extra '_' # define MANGLE_PREFIX "_" #else # define MANGLE_PREFIX "" #endif using namespace llvm; namespace { ///\brief Memory manager providing the lop-level link to the /// IncrementalExecutor, handles missing or special / replaced symbols. class ClingMemoryManager: public SectionMemoryManager { public: ClingMemoryManager(cling::IncrementalExecutor& Exe) {} ///\brief Simply wraps the base class's function setting AbortOnFailure /// to false and instead using the error handling mechanism to report it. void* getPointerToNamedFunction(const std::string &Name, bool /*AbortOnFailure*/ =true) override { return SectionMemoryManager::getPointerToNamedFunction(Name, false); } }; class NotifyFinalizedT { public: NotifyFinalizedT(cling::IncrementalJIT &jit) : m_JIT(jit) {} void operator()(llvm::orc::ObjectLinkingLayerBase::ObjSetHandleT H) { m_JIT.RemoveUnfinalizedSection(H); } private: cling::IncrementalJIT &m_JIT; }; } // unnamed namespace namespace cling { ///\brief Memory manager for the OrcJIT layers to resolve symbols from the /// common IncrementalJIT. I.e. the master of the Orcs. /// Each ObjectLayer instance has one Azog object. class Azog: public RTDyldMemoryManager { cling::IncrementalJIT& m_jit; struct AllocInfo { uint8_t *m_Start = nullptr; uint8_t *m_End = nullptr; uint8_t *m_Current = nullptr; void allocate(RTDyldMemoryManager *exeMM, uintptr_t Size, uint32_t Align, bool code, bool isReadOnly) { uintptr_t RequiredSize = Size; if (code) m_Start = exeMM->allocateCodeSection(RequiredSize, Align, 0 /* SectionID */, "codeReserve"); else if (isReadOnly) m_Start = exeMM->allocateDataSection(RequiredSize, Align, 0 /* SectionID */, "rodataReserve",isReadOnly); else m_Start = exeMM->allocateDataSection(RequiredSize, Align, 0 /* SectionID */, "rwataReserve",isReadOnly); m_Current = m_Start; m_End = m_Start + RequiredSize; } uint8_t* getNextAddr(uintptr_t Size, unsigned Alignment) { if (!Alignment) Alignment = 16; assert(!(Alignment & (Alignment - 1)) && "Alignment must be a power of two."); uintptr_t RequiredSize = Alignment * ((Size + Alignment - 1)/Alignment + 1); if ( (m_Current + RequiredSize) > m_End ) { // This must be the last block. if ((m_Current + Size) <= m_End) { RequiredSize = Size; } else { cling::errs() << "Error in block allocation by Azog. " << "Not enough memory was reserved for the current module. " << Size << " (with alignment: " << RequiredSize << " ) is needed but\n" << "we only have " << (m_End - m_Current) << ".\n"; return nullptr; } } uintptr_t Addr = (uintptr_t)m_Current; // Align the address. Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1); m_Current = (uint8_t*)(Addr + Size); return (uint8_t*)Addr; } operator bool() { return m_Current != nullptr; } }; AllocInfo m_Code; AllocInfo m_ROData; AllocInfo m_RWData; public: Azog(cling::IncrementalJIT& Jit): m_jit(Jit) {} RTDyldMemoryManager* getExeMM() const { return m_jit.m_ExeMM.get(); } uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName) override { uint8_t *Addr = nullptr; if (m_Code) { Addr = m_Code.getNextAddr(Size, Alignment); } if (!Addr) { Addr = getExeMM()->allocateCodeSection(Size, Alignment, SectionID, SectionName); m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr); } return Addr; } uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly) override { uint8_t *Addr = nullptr; if (IsReadOnly && m_ROData) { Addr = m_ROData.getNextAddr(Size,Alignment); } else if (m_RWData) { Addr = m_RWData.getNextAddr(Size,Alignment); } if (!Addr) { Addr = getExeMM()->allocateDataSection(Size, Alignment, SectionID, SectionName, IsReadOnly); m_jit.m_SectionsAllocatedSinceLastLoad.insert(Addr); } return Addr; } void reserveAllocationSpace(uintptr_t CodeSize, uint32_t CodeAlign, uintptr_t RODataSize, uint32_t RODataAlign, uintptr_t RWDataSize, uint32_t RWDataAlign) override { m_Code.allocate(getExeMM(),CodeSize, CodeAlign, true, false); m_ROData.allocate(getExeMM(),RODataSize, RODataAlign, false, true); m_RWData.allocate(getExeMM(),RWDataSize, RWDataAlign, false, false); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_Code.m_Start); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_ROData.m_Start); m_jit.m_SectionsAllocatedSinceLastLoad.insert(m_RWData.m_Start); } bool needsToReserveAllocationSpace() override { return true; // getExeMM()->needsToReserveAllocationSpace(); } void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { return getExeMM()->registerEHFrames(Addr, LoadAddr, Size); } void deregisterEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override { return getExeMM()->deregisterEHFrames(Addr, LoadAddr, Size); } uint64_t getSymbolAddress(const std::string &Name) override { return m_jit.getSymbolAddressWithoutMangling(Name, true /*also use dlsym*/) .getAddress(); } void *getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure = true) override { return getExeMM()->getPointerToNamedFunction(Name, AbortOnFailure); } using llvm::RuntimeDyld::MemoryManager::notifyObjectLoaded; void notifyObjectLoaded(ExecutionEngine *EE, const object::ObjectFile &O) override { return getExeMM()->notifyObjectLoaded(EE, O); } bool finalizeMemory(std::string *ErrMsg = nullptr) override { // Each set of objects loaded will be finalized exactly once, but since // symbol lookup during relocation may recursively trigger the // loading/relocation of other modules, and since we're forwarding all // finalizeMemory calls to a single underlying memory manager, we need to // defer forwarding the call on until all necessary objects have been // loaded. Otherwise, during the relocation of a leaf object, we will end // up finalizing memory, causing a crash further up the stack when we // attempt to apply relocations to finalized memory. // To avoid finalizing too early, look at how many objects have been // loaded but not yet finalized. This is a bit of a hack that relies on // the fact that we're lazily emitting object files: The only way you can // get more than one set of objects loaded but not yet finalized is if // they were loaded during relocation of another set. if (m_jit.m_UnfinalizedSections.size() == 1) return getExeMM()->finalizeMemory(ErrMsg); return false; }; }; // class Azog IncrementalJIT::IncrementalJIT(IncrementalExecutor& exe, std::unique_ptr<TargetMachine> TM): m_Parent(exe), m_TM(std::move(TM)), m_TMDataLayout(m_TM->createDataLayout()), m_ExeMM(llvm::make_unique<ClingMemoryManager>(m_Parent)), m_NotifyObjectLoaded(*this), m_ObjectLayer(m_SymbolMap, m_NotifyObjectLoaded, NotifyFinalizedT(*this)), m_CompileLayer(m_ObjectLayer, llvm::orc::SimpleCompiler(*m_TM)), m_LazyEmitLayer(m_CompileLayer) { // Enable JIT symbol resolution from the binary. llvm::sys::DynamicLibrary::LoadLibraryPermanently(0, 0); // Make debug symbols available. m_GDBListener = 0; // JITEventListener::createGDBRegistrationListener(); // #if MCJIT // llvm::EngineBuilder builder(std::move(m)); // std::string errMsg; // builder.setErrorStr(&errMsg); // builder.setOptLevel(llvm::CodeGenOpt::Less); // builder.setEngineKind(llvm::EngineKind::JIT); // std::unique_ptr<llvm::RTDyldMemoryManager> // MemMan(new ClingMemoryManager(*this)); // builder.setMCJITMemoryManager(std::move(MemMan)); // // EngineBuilder uses default c'ted TargetOptions, too: // llvm::TargetOptions TargetOpts; // TargetOpts.NoFramePointerElim = 1; // TargetOpts.JITEmitDebugInfo = 1; // builder.setTargetOptions(TargetOpts); // m_engine.reset(builder.create()); // assert(m_engine && "Cannot create module!"); // #endif } llvm::orc::JITSymbol IncrementalJIT::getInjectedSymbols(const std::string& Name) const { using JITSymbol = llvm::orc::JITSymbol; auto SymMapI = m_SymbolMap.find(Name); if (SymMapI != m_SymbolMap.end()) return JITSymbol(SymMapI->second, llvm::JITSymbolFlags::Exported); return JITSymbol(nullptr); } std::pair<void*, bool> IncrementalJIT::lookupSymbol(llvm::StringRef Name, void *InAddr, bool Jit) { // FIXME: See comments on DLSym below. #if !defined(LLVM_ON_WIN32) void* Addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(Name); #else void* Addr = const_cast<void*>(platform::DLSym(Name)); #endif if (InAddr && (!Addr || Jit)) { if (Jit) { std::string Key(Name); Key.insert(0, MANGLE_PREFIX); m_SymbolMap[Key] = llvm::orc::TargetAddress(InAddr); } llvm::sys::DynamicLibrary::AddSymbol(Name, InAddr); return std::make_pair(InAddr, true); } return std::make_pair(Addr, false); } llvm::orc::JITSymbol IncrementalJIT::getSymbolAddressWithoutMangling(const std::string& Name, bool AlsoInProcess) { if (auto Sym = getInjectedSymbols(Name)) return Sym; if (AlsoInProcess) { if (RuntimeDyld::SymbolInfo SymInfo = m_ExeMM->findSymbol(Name)) return llvm::orc::JITSymbol(SymInfo.getAddress(), llvm::JITSymbolFlags::Exported); #ifdef LLVM_ON_WIN32 // FIXME: DLSym symbol lookup can overlap m_ExeMM->findSymbol wasting time // looking for a symbol in libs where it is already known not to exist. // Perhaps a better solution would be to have IncrementalJIT own the // DynamicLibraryManger instance (or at least have a reference) that will // look only through user loaded libraries. // An upside to doing it this way is RTLD_GLOBAL won't need to be used // allowing libs with competing symbols to co-exists. if (const void* Sym = platform::DLSym(Name)) return llvm::orc::JITSymbol(llvm::orc::TargetAddress(Sym), llvm::JITSymbolFlags::Exported); #endif } if (auto Sym = m_LazyEmitLayer.findSymbol(Name, false)) return Sym; return llvm::orc::JITSymbol(nullptr); } size_t IncrementalJIT::addModules(std::vector<llvm::Module*>&& modules) { // If this module doesn't have a DataLayout attached then attach the // default. for (auto&& mod: modules) { mod->setDataLayout(m_TMDataLayout); } // LLVM MERGE FIXME: update this to use new interfaces. auto Resolver = llvm::orc::createLambdaResolver( [&](const std::string &S) { if (auto Sym = getInjectedSymbols(S)) return RuntimeDyld::SymbolInfo((uint64_t)Sym.getAddress(), Sym.getFlags()); return m_ExeMM->findSymbol(S); }, [&](const std::string &Name) { if (auto Sym = getSymbolAddressWithoutMangling(Name, true) /*was: findSymbol(Name)*/) return RuntimeDyld::SymbolInfo(Sym.getAddress(), Sym.getFlags()); /// This method returns the address of the specified function or variable /// that could not be resolved by getSymbolAddress() or by resolving /// possible weak symbols by the ExecutionEngine. /// It is used to resolve symbols during module linking. std::string NameNoPrefix; if (MANGLE_PREFIX[0] && !Name.compare(0, strlen(MANGLE_PREFIX), MANGLE_PREFIX)) NameNoPrefix = Name.substr(strlen(MANGLE_PREFIX), -1); else NameNoPrefix = std::move(Name); uint64_t addr = (uint64_t) getParent().NotifyLazyFunctionCreators(NameNoPrefix); return RuntimeDyld::SymbolInfo(addr, llvm::JITSymbolFlags::Weak); }); ModuleSetHandleT MSHandle = m_LazyEmitLayer.addModuleSet(std::move(modules), llvm::make_unique<Azog>(*this), std::move(Resolver)); m_UnloadPoints.push_back(MSHandle); return m_UnloadPoints.size() - 1; } // void* IncrementalJIT::finalizeMemory() { // for (auto &P : UnfinalizedSections) // if (P.second.count(LocalAddress)) // ObjectLayer.mapSectionAddress(P.first, LocalAddress, TargetAddress); // } void IncrementalJIT::removeModules(size_t handle) { if (handle == (size_t)-1) return; auto objSetHandle = m_UnloadPoints[handle]; m_LazyEmitLayer.removeModuleSet(objSetHandle); } }// end namespace cling <|endoftext|>
<commit_before>#include "config.h" #include "systemintfcmds.hpp" #include "host-cmd-manager.hpp" #include "host-interface.hpp" #include <cstring> #include <ipmid-host/cmd.hpp> #include <ipmid/api.hpp> void register_netfn_app_functions() __attribute__((constructor)); using namespace sdbusplus::xyz::openbmc_project::Control::server; // For accessing Host command manager using cmdManagerPtr = std::unique_ptr<phosphor::host::command::Manager>; extern cmdManagerPtr& ipmid_get_host_cmd_manager(); //------------------------------------------------------------------- // Called by Host post response from Get_Message_Flags //------------------------------------------------------------------- ipmi_ret_t ipmi_app_read_event(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; struct oem_sel_timestamped oem_sel = {0}; *data_len = sizeof(struct oem_sel_timestamped); // either id[0] -or- id[1] can be filled in. We will use id[0] oem_sel.id[0] = SEL_OEM_ID_0; oem_sel.id[1] = SEL_OEM_ID_0; oem_sel.type = SEL_RECORD_TYPE_OEM; // Following 3 bytes are from IANA Manufactre_Id field. See below oem_sel.manuf_id[0] = 0x41; oem_sel.manuf_id[1] = 0xA7; oem_sel.manuf_id[2] = 0x00; // per IPMI spec NetFuntion for OEM oem_sel.netfun = 0x3A; // Read from the Command Manager queue. What gets returned is a // pair of <command, data> that can be directly used here auto hostCmd = ipmid_get_host_cmd_manager()->getNextCommand(); oem_sel.cmd = hostCmd.first; oem_sel.data[0] = hostCmd.second; // All '0xFF' since unused. std::memset(&oem_sel.data[1], 0xFF, 3); // Pack the actual response std::memcpy(response, &oem_sel, *data_len); return rc; } //--------------------------------------------------------------------- // Called by Host on seeing a SMS_ATN bit set. Return a hardcoded // value of 0x2 indicating we need Host read some data. //------------------------------------------------------------------- ipmi::RspType<uint8_t> ipmiAppGetMessageFlags() { // From IPMI spec V2.0 for Get Message Flags Command : // bit:[1] from LSB : 1b = Event Message Buffer Full. // Return as 0 if Event Message Buffer is not supported, // or when the Event Message buffer is disabled. // This path is used to communicate messages to the host // from within the phosphor::host::command::Manager constexpr uint8_t setEventMsgBufferFull = 0x2; return ipmi::responseSuccess(setEventMsgBufferFull); } ipmi::RspType<bool, // Receive Message Queue Interrupt Enabled bool, // Event Message Buffer Full Interrupt Enabled bool, // Event Message Buffer Enabled bool, // System Event Logging Enabled uint1_t, // Reserved bool, // OEM 0 enabled bool, // OEM 1 enabled bool // OEM 2 enabled > ipmiAppGetBMCGlobalEnable() { return ipmi::responseSuccess(true, false, false, true, 0, false, false, false); } ipmi::RspType<> ipmiAppSetBMCGlobalEnable( ipmi::Context::ptr ctx, bool receiveMessageQueueInterruptEnabled, bool eventMessageBufferFullInterruptEnabled, bool eventMessageBufferEnabled, bool systemEventLogEnable, uint1_t reserved, bool OEM0Enabled, bool OEM1Enabled, bool OEM2Enabled) { ipmi::ChannelInfo chInfo; if (ipmi::getChannelInfo(ctx->channel, chInfo) != ipmi::ccSuccess) { phosphor::logging::log<phosphor::logging::level::ERR>( "Failed to get Channel Info", phosphor::logging::entry("CHANNEL=%d", ctx->channel)); return ipmi::responseUnspecifiedError(); } if (chInfo.mediumType != static_cast<uint8_t>(ipmi::EChannelMediumType::systemInterface)) { phosphor::logging::log<phosphor::logging::level::ERR>( "Error - supported only in system interface"); return ipmi::responseCommandNotAvailable(); } // Recv Message Queue and SEL are enabled by default. // Event Message buffer are disabled by default (not supported). // Any request that try to change the mask will be rejected if (!receiveMessageQueueInterruptEnabled || !systemEventLogEnable || eventMessageBufferFullInterruptEnabled || eventMessageBufferEnabled || OEM0Enabled || OEM1Enabled || OEM2Enabled || reserved) { return ipmi::responseInvalidFieldRequest(); } return ipmi::responseSuccess(); } namespace { // Static storage to keep the object alive during process life std::unique_ptr<phosphor::host::command::Host> host __attribute__((init_priority(101))); std::unique_ptr<sdbusplus::server::manager::manager> objManager __attribute__((init_priority(101))); } // namespace void register_netfn_app_functions() { // <Read Event Message Buffer> ipmi_register_callback(NETFUN_APP, IPMI_CMD_READ_EVENT, NULL, ipmi_app_read_event, SYSTEM_INTERFACE); // <Set BMC Global Enables> ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, ipmi::app::cmdSetBmcGlobalEnables, ipmi::Privilege::Admin, ipmiAppSetBMCGlobalEnable); // <Get BMC Global Enables> ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, ipmi::app::cmdGetBmcGlobalEnables, ipmi::Privilege::User, ipmiAppGetBMCGlobalEnable); // <Get Message Flags> ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, ipmi::app::cmdGetMessageFlags, ipmi::Privilege::Admin, ipmiAppGetMessageFlags); // Create new xyz.openbmc_project.host object on the bus auto objPath = std::string{CONTROL_HOST_OBJ_MGR} + '/' + HOST_NAME + '0'; std::unique_ptr<sdbusplus::asio::connection>& sdbusp = ipmid_get_sdbus_plus_handler(); // Add sdbusplus ObjectManager. objManager = std::make_unique<sdbusplus::server::manager::manager>( *sdbusp, CONTROL_HOST_OBJ_MGR); host = std::make_unique<phosphor::host::command::Host>(*sdbusp, objPath.c_str()); sdbusp->request_name(CONTROL_HOST_BUSNAME); return; } <commit_msg>phosphor-ipmi-host: Set event msg buffer flag to hardcode to 0x0<commit_after>#include "config.h" #include "systemintfcmds.hpp" #include "host-cmd-manager.hpp" #include "host-interface.hpp" #include <cstring> #include <ipmid-host/cmd.hpp> #include <ipmid/api.hpp> void register_netfn_app_functions() __attribute__((constructor)); using namespace sdbusplus::xyz::openbmc_project::Control::server; // For accessing Host command manager using cmdManagerPtr = std::unique_ptr<phosphor::host::command::Manager>; extern cmdManagerPtr& ipmid_get_host_cmd_manager(); //------------------------------------------------------------------- // Called by Host post response from Get_Message_Flags //------------------------------------------------------------------- ipmi_ret_t ipmi_app_read_event(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; struct oem_sel_timestamped oem_sel = {0}; *data_len = sizeof(struct oem_sel_timestamped); // either id[0] -or- id[1] can be filled in. We will use id[0] oem_sel.id[0] = SEL_OEM_ID_0; oem_sel.id[1] = SEL_OEM_ID_0; oem_sel.type = SEL_RECORD_TYPE_OEM; // Following 3 bytes are from IANA Manufactre_Id field. See below oem_sel.manuf_id[0] = 0x41; oem_sel.manuf_id[1] = 0xA7; oem_sel.manuf_id[2] = 0x00; // per IPMI spec NetFuntion for OEM oem_sel.netfun = 0x3A; // Read from the Command Manager queue. What gets returned is a // pair of <command, data> that can be directly used here auto hostCmd = ipmid_get_host_cmd_manager()->getNextCommand(); oem_sel.cmd = hostCmd.first; oem_sel.data[0] = hostCmd.second; // All '0xFF' since unused. std::memset(&oem_sel.data[1], 0xFF, 3); // Pack the actual response std::memcpy(response, &oem_sel, *data_len); return rc; } //--------------------------------------------------------------------- // Called by Host on seeing a SMS_ATN bit set. Return a hardcoded // value of 0x0 to indicate Event Message Buffer is not supported //------------------------------------------------------------------- ipmi::RspType<uint8_t> ipmiAppGetMessageFlags() { // From IPMI spec V2.0 for Get Message Flags Command : // bit:[1] from LSB : 1b = Event Message Buffer Full. // Return as 0 if Event Message Buffer is not supported, // or when the Event Message buffer is disabled. // This path is used to communicate messages to the host // from within the phosphor::host::command::Manager constexpr uint8_t setEventMsgBufferNotSupported = 0x0; return ipmi::responseSuccess(setEventMsgBufferNotSupported); } ipmi::RspType<bool, // Receive Message Queue Interrupt Enabled bool, // Event Message Buffer Full Interrupt Enabled bool, // Event Message Buffer Enabled bool, // System Event Logging Enabled uint1_t, // Reserved bool, // OEM 0 enabled bool, // OEM 1 enabled bool // OEM 2 enabled > ipmiAppGetBMCGlobalEnable() { return ipmi::responseSuccess(true, false, false, true, 0, false, false, false); } ipmi::RspType<> ipmiAppSetBMCGlobalEnable( ipmi::Context::ptr ctx, bool receiveMessageQueueInterruptEnabled, bool eventMessageBufferFullInterruptEnabled, bool eventMessageBufferEnabled, bool systemEventLogEnable, uint1_t reserved, bool OEM0Enabled, bool OEM1Enabled, bool OEM2Enabled) { ipmi::ChannelInfo chInfo; if (ipmi::getChannelInfo(ctx->channel, chInfo) != ipmi::ccSuccess) { phosphor::logging::log<phosphor::logging::level::ERR>( "Failed to get Channel Info", phosphor::logging::entry("CHANNEL=%d", ctx->channel)); return ipmi::responseUnspecifiedError(); } if (chInfo.mediumType != static_cast<uint8_t>(ipmi::EChannelMediumType::systemInterface)) { phosphor::logging::log<phosphor::logging::level::ERR>( "Error - supported only in system interface"); return ipmi::responseCommandNotAvailable(); } // Recv Message Queue and SEL are enabled by default. // Event Message buffer are disabled by default (not supported). // Any request that try to change the mask will be rejected if (!receiveMessageQueueInterruptEnabled || !systemEventLogEnable || eventMessageBufferFullInterruptEnabled || eventMessageBufferEnabled || OEM0Enabled || OEM1Enabled || OEM2Enabled || reserved) { return ipmi::responseInvalidFieldRequest(); } return ipmi::responseSuccess(); } namespace { // Static storage to keep the object alive during process life std::unique_ptr<phosphor::host::command::Host> host __attribute__((init_priority(101))); std::unique_ptr<sdbusplus::server::manager::manager> objManager __attribute__((init_priority(101))); } // namespace void register_netfn_app_functions() { // <Read Event Message Buffer> ipmi_register_callback(NETFUN_APP, IPMI_CMD_READ_EVENT, NULL, ipmi_app_read_event, SYSTEM_INTERFACE); // <Set BMC Global Enables> ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, ipmi::app::cmdSetBmcGlobalEnables, ipmi::Privilege::Admin, ipmiAppSetBMCGlobalEnable); // <Get BMC Global Enables> ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, ipmi::app::cmdGetBmcGlobalEnables, ipmi::Privilege::User, ipmiAppGetBMCGlobalEnable); // <Get Message Flags> ipmi::registerHandler(ipmi::prioOpenBmcBase, ipmi::netFnApp, ipmi::app::cmdGetMessageFlags, ipmi::Privilege::Admin, ipmiAppGetMessageFlags); // Create new xyz.openbmc_project.host object on the bus auto objPath = std::string{CONTROL_HOST_OBJ_MGR} + '/' + HOST_NAME + '0'; std::unique_ptr<sdbusplus::asio::connection>& sdbusp = ipmid_get_sdbus_plus_handler(); // Add sdbusplus ObjectManager. objManager = std::make_unique<sdbusplus::server::manager::manager>( *sdbusp, CONTROL_HOST_OBJ_MGR); host = std::make_unique<phosphor::host::command::Host>(*sdbusp, objPath.c_str()); sdbusp->request_name(CONTROL_HOST_BUSNAME); return; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <functional> #include <mutex> #include <cstdlib> #ifdef WIN32 #define BIND_EVENT(IO,EV,FN) \ do{ \ client::event_listener_aux l = FN;\ IO->on(EV,l);\ } while(0) #else #define BIND_EVENT(IO,EV,FN) \ IO->on(EV,FN) #endif MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), _io(new client()), m_dialog() { ui->setupUi(this); using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; using std::placeholders::_4; socket::ptr sock = _io->socket(); BIND_EVENT(sock,"new message",std::bind(&MainWindow::OnNewMessage,this,_1,_2,_3,_4)); BIND_EVENT(sock,"user joined",std::bind(&MainWindow::OnUserJoined,this,_1,_2,_3,_4)); BIND_EVENT(sock,"user left",std::bind(&MainWindow::OnUserLeft,this,_1,_2,_3,_4)); BIND_EVENT(sock,"typing",std::bind(&MainWindow::OnTyping,this,_1,_2,_3,_4)); BIND_EVENT(sock,"stop typing",std::bind(&MainWindow::OnStopTyping,this,_1,_2,_3,_4)); BIND_EVENT(sock,"login",std::bind(&MainWindow::OnLogin,this,_1,_2,_3,_4)); _io->set_socket_open_listener(std::bind(&MainWindow::OnConnected,this,std::placeholders::_1)); _io->set_close_listener(std::bind(&MainWindow::OnClosed,this,_1)); _io->set_fail_listener(std::bind(&MainWindow::OnFailed,this)); connect(this,SIGNAL(RequestAddListItem(QListWidgetItem*)),this,SLOT(AddListItem(QListWidgetItem*))); connect(this,SIGNAL(RequestToggleInputs(bool)),this,SLOT(ToggleInputs(bool))); } MainWindow::~MainWindow() { _io->socket()->off_all(); _io->socket()->off_error(); delete ui; } void MainWindow::SendBtnClicked() { QLineEdit* messageEdit = this->findChild<QLineEdit*>("messageEdit"); QString text = messageEdit->text(); if(text.length()>0) { QByteArray bytes = text.toUtf8(); std::string msg(bytes.data(),bytes.length()); _io->socket()->emit("new message",msg); text.append(":You"); QListWidgetItem *item = new QListWidgetItem(text); item->setTextAlignment(Qt::AlignRight); Q_EMIT RequestAddListItem(item); messageEdit->clear(); } } void MainWindow::OnMessageReturn() { this->SendBtnClicked(); } void MainWindow::ShowLoginDialog() { m_dialog.reset(new NicknameDialog(this)); connect(m_dialog.get(),SIGNAL(accepted()),this,SLOT(NicknameAccept())); connect(m_dialog.get(),SIGNAL(rejected()),this,SLOT(NicknameCancelled())); m_dialog->exec(); } void MainWindow::showEvent(QShowEvent *event) { ShowLoginDialog(); } void MainWindow::TypingStop() { m_timer.reset(); _io->socket()->emit("stop typing",""); } void MainWindow::TypingChanged() { if(m_timer&&m_timer->isActive()) { m_timer->stop(); } else { _io->socket()->emit("typing",""); } m_timer.reset(new QTimer(this)); connect(m_timer.get(),SIGNAL(timeout()),this,SLOT(TypingStop())); m_timer->setSingleShot(true); m_timer->start(1000); } void MainWindow::NicknameAccept() { m_name = m_dialog->getNickname(); if(m_name.length()>0) { _io->connect("ws://localhost:3000"); } } void MainWindow::NicknameCancelled() { QApplication::exit(); } void MainWindow::AddListItem(QListWidgetItem* item) { this->findChild<QListWidget*>("listView")->addItem(item); } void MainWindow::OnNewMessage(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { if(data->get_flag() == message::flag_object) { std::string msg = data->get_map()["message"]->get_string(); std::string username = data->get_map()["username"]->get_string(); QString label = QString::fromUtf8(username.data(),username.length()); label.append(':'); label.append(QString::fromUtf8(msg.data(),msg.length())); QListWidgetItem *item= new QListWidgetItem(label); Q_EMIT RequestAddListItem(item); } } void MainWindow::OnUserJoined(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { if(data->get_flag() == message::flag_object) { std::string name = data->get_map()["username"]->get_string(); int numUser = data->get_map()["numUsers"]->get_int(); QString label = QString::fromUtf8(name.data(),name.length()); bool plural = numUser != 1; label.append(" joined\n"); label.append(plural?"there are ":"there's "); QString digits; while(numUser>=10) { digits.insert(0,QChar((numUser%10)+'0')); numUser/=10; } digits.insert(0,QChar(numUser+'0')); label.append(digits); label.append(plural?" participants":"participant"); QListWidgetItem *item= new QListWidgetItem(label); item->setTextAlignment(Qt::AlignHCenter); QFont font; font.setPointSize(9); item->setFont(font); Q_EMIT RequestAddListItem(item); } } void MainWindow::OnUserLeft(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { if(data->get_flag() == message::flag_object) { std::string name = data->get_map()["username"]->get_string(); int numUser = data->get_map()["numUsers"]->get_int(); QString label = QString::fromUtf8(name.data(),name.length()); bool plural = numUser != 1; label.append(" left\n"); label.append(plural?"there are ":"there's "); QString digits; while(numUser>=10) { digits.insert(0,QChar((numUser%10)+'0')); numUser/=10; } digits.insert(0,QChar(numUser+'0')); label.append(digits); label.append(plural?" participants":"participant"); QListWidgetItem *item= new QListWidgetItem(label); item->setTextAlignment(Qt::AlignHCenter); QFont font; font.setPointSize(9); item->setFont(font); Q_EMIT RequestAddListItem(item); } } void MainWindow::OnTyping(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { //Not implemented } void MainWindow::OnStopTyping(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { //Not implemented } void MainWindow::OnLogin(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { Q_EMIT RequestToggleInputs(true); int numUser = data->get_map()["numUsers"]->get_int(); QString digits; bool plural = numUser !=1; while(numUser>=10) { digits.insert(0,QChar((numUser%10)+'0')); numUser/=10; } digits.insert(0,QChar(numUser+'0')); digits.insert(0,plural?"there are ":"there's "); digits.append(plural? " participants":" participant"); QListWidgetItem *item = new QListWidgetItem(digits); item->setTextAlignment(Qt::AlignHCenter); QFont font; font.setPointSize(9); item->setFont(font); Q_EMIT RequestAddListItem(item); } void MainWindow::OnConnected(std::string const& nsp) { QByteArray bytes = m_name.toUtf8(); std::string nickName(bytes.data(),bytes.length()); _io->socket()->emit("add user", nickName); } void MainWindow::OnClosed(client::close_reason const& reason) { Q_EMIT RequestToggleInputs(false); } void MainWindow::OnFailed() { Q_EMIT RequestToggleInputs(false); } void MainWindow::ToggleInputs(bool loginOrNot) { if(loginOrNot)//already login { this->findChild<QWidget*>("messageEdit")->setEnabled(true); this->findChild<QWidget*>("listView")->setEnabled(true); this->findChild<QWidget*>("sendBtn")->setEnabled(true); } else { this->findChild<QWidget*>("messageEdit")->setEnabled(false); this->findChild<QWidget*>("listView")->setEnabled(false); this->findChild<QWidget*>("sendBtn")->setEnabled(false); ShowLoginDialog(); } } <commit_msg>fix messages on UI<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <functional> #include <mutex> #include <cstdlib> #ifdef WIN32 #define BIND_EVENT(IO,EV,FN) \ do{ \ client::event_listener_aux l = FN;\ IO->on(EV,l);\ } while(0) #else #define BIND_EVENT(IO,EV,FN) \ IO->on(EV,FN) #endif MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), _io(new client()), m_dialog() { ui->setupUi(this); using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; using std::placeholders::_4; socket::ptr sock = _io->socket(); BIND_EVENT(sock,"new message",std::bind(&MainWindow::OnNewMessage,this,_1,_2,_3,_4)); BIND_EVENT(sock,"user joined",std::bind(&MainWindow::OnUserJoined,this,_1,_2,_3,_4)); BIND_EVENT(sock,"user left",std::bind(&MainWindow::OnUserLeft,this,_1,_2,_3,_4)); BIND_EVENT(sock,"typing",std::bind(&MainWindow::OnTyping,this,_1,_2,_3,_4)); BIND_EVENT(sock,"stop typing",std::bind(&MainWindow::OnStopTyping,this,_1,_2,_3,_4)); BIND_EVENT(sock,"login",std::bind(&MainWindow::OnLogin,this,_1,_2,_3,_4)); _io->set_socket_open_listener(std::bind(&MainWindow::OnConnected,this,std::placeholders::_1)); _io->set_close_listener(std::bind(&MainWindow::OnClosed,this,_1)); _io->set_fail_listener(std::bind(&MainWindow::OnFailed,this)); connect(this,SIGNAL(RequestAddListItem(QListWidgetItem*)),this,SLOT(AddListItem(QListWidgetItem*))); connect(this,SIGNAL(RequestToggleInputs(bool)),this,SLOT(ToggleInputs(bool))); } MainWindow::~MainWindow() { _io->socket()->off_all(); _io->socket()->off_error(); delete ui; } void MainWindow::SendBtnClicked() { QLineEdit* messageEdit = this->findChild<QLineEdit*>("messageEdit"); QString text = messageEdit->text(); if(text.length()>0) { QByteArray bytes = text.toUtf8(); std::string msg(bytes.data(),bytes.length()); _io->socket()->emit("new message",msg); text.append(":You"); QListWidgetItem *item = new QListWidgetItem(text); item->setTextAlignment(Qt::AlignRight); Q_EMIT RequestAddListItem(item); messageEdit->clear(); } } void MainWindow::OnMessageReturn() { this->SendBtnClicked(); } void MainWindow::ShowLoginDialog() { m_dialog.reset(new NicknameDialog(this)); connect(m_dialog.get(),SIGNAL(accepted()),this,SLOT(NicknameAccept())); connect(m_dialog.get(),SIGNAL(rejected()),this,SLOT(NicknameCancelled())); m_dialog->exec(); } void MainWindow::showEvent(QShowEvent *event) { ShowLoginDialog(); } void MainWindow::TypingStop() { m_timer.reset(); _io->socket()->emit("stop typing",""); } void MainWindow::TypingChanged() { if(m_timer&&m_timer->isActive()) { m_timer->stop(); } else { _io->socket()->emit("typing",""); } m_timer.reset(new QTimer(this)); connect(m_timer.get(),SIGNAL(timeout()),this,SLOT(TypingStop())); m_timer->setSingleShot(true); m_timer->start(1000); } void MainWindow::NicknameAccept() { m_name = m_dialog->getNickname(); if(m_name.length()>0) { _io->connect("ws://localhost:3000"); } } void MainWindow::NicknameCancelled() { QApplication::exit(); } void MainWindow::AddListItem(QListWidgetItem* item) { this->findChild<QListWidget*>("listView")->addItem(item); } void MainWindow::OnNewMessage(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { if(data->get_flag() == message::flag_object) { std::string msg = data->get_map()["message"]->get_string(); std::string username = data->get_map()["username"]->get_string(); QString label = QString::fromUtf8(username.data(),username.length()); label.append(':'); label.append(QString::fromUtf8(msg.data(),msg.length())); QListWidgetItem *item= new QListWidgetItem(label); Q_EMIT RequestAddListItem(item); } } void MainWindow::OnUserJoined(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { if(data->get_flag() == message::flag_object) { std::string name = data->get_map()["username"]->get_string(); int numUser = data->get_map()["numUsers"]->get_int(); QString label = QString::fromUtf8(name.data(),name.length()); bool plural = numUser != 1; label.append(" joined\n"); label.append(plural?"there are ":"there's "); QString digits; while(numUser>=10) { digits.insert(0,QChar((numUser%10)+'0')); numUser/=10; } digits.insert(0,QChar(numUser+'0')); label.append(digits); label.append(plural?" participants":" participant"); QListWidgetItem *item= new QListWidgetItem(label); item->setTextAlignment(Qt::AlignHCenter); QFont font; font.setPointSize(9); item->setFont(font); Q_EMIT RequestAddListItem(item); } } void MainWindow::OnUserLeft(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { if(data->get_flag() == message::flag_object) { std::string name = data->get_map()["username"]->get_string(); int numUser = data->get_map()["numUsers"]->get_int(); QString label = QString::fromUtf8(name.data(),name.length()); bool plural = numUser != 1; label.append(" left\n"); label.append(plural?"there are ":"there's "); QString digits; while(numUser>=10) { digits.insert(0,QChar((numUser%10)+'0')); numUser/=10; } digits.insert(0,QChar(numUser+'0')); label.append(digits); label.append(plural?" participants":"participant"); QListWidgetItem *item= new QListWidgetItem(label); item->setTextAlignment(Qt::AlignHCenter); QFont font; font.setPointSize(9); item->setFont(font); Q_EMIT RequestAddListItem(item); } } void MainWindow::OnTyping(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { //Not implemented } void MainWindow::OnStopTyping(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { //Not implemented } void MainWindow::OnLogin(std::string const& name,message::ptr const& data,bool hasAck,message::ptr &ack_resp) { Q_EMIT RequestToggleInputs(true); int numUser = data->get_map()["numUsers"]->get_int(); QString digits; bool plural = numUser !=1; while(numUser>=10) { digits.insert(0,QChar((numUser%10)+'0')); numUser/=10; } digits.insert(0,QChar(numUser+'0')); digits.insert(0,plural?"there are ":"there's "); digits.append(plural? " participants":" participant"); QListWidgetItem *item = new QListWidgetItem(digits); item->setTextAlignment(Qt::AlignHCenter); QFont font; font.setPointSize(9); item->setFont(font); Q_EMIT RequestAddListItem(item); } void MainWindow::OnConnected(std::string const& nsp) { QByteArray bytes = m_name.toUtf8(); std::string nickName(bytes.data(),bytes.length()); _io->socket()->emit("add user", nickName); } void MainWindow::OnClosed(client::close_reason const& reason) { Q_EMIT RequestToggleInputs(false); } void MainWindow::OnFailed() { Q_EMIT RequestToggleInputs(false); } void MainWindow::ToggleInputs(bool loginOrNot) { if(loginOrNot)//already login { this->findChild<QWidget*>("messageEdit")->setEnabled(true); this->findChild<QWidget*>("listView")->setEnabled(true); this->findChild<QWidget*>("sendBtn")->setEnabled(true); } else { this->findChild<QWidget*>("messageEdit")->setEnabled(false); this->findChild<QWidget*>("listView")->setEnabled(false); this->findChild<QWidget*>("sendBtn")->setEnabled(false); ShowLoginDialog(); } } <|endoftext|>
<commit_before>#ifndef __CINT__ # include <TFile.h> # include <TString.h> # include <TGraphAsymmErrors.h> # include <TMultiGraph.h> # include <TROOT.h> # include <TError.h> # include <TSystem.h> # include <TH1F.h> # include <TStyle.h> # include <TMath.h> #else class TFile; class TGraphAsymmErrors; class TMultiGraph; class TGraph; class TH1; #endif struct RefData { //____________________________________________________________________ /** * Values used * * @ingroup pwglf_forward_otherdata */ enum { UA5, CMS, ALICE, WIP, ATLAS, PYTHIA, INEL, INELGt0, NSD }; static Bool_t Verbose(Int_t v=-1) { static Bool_t verbose = false; if (v >= 0) verbose = v; return verbose; } //____________________________________________________________________ /** * Get a pointer to our data file. @a path is the path to the file * containing the data. If it is null, then first search the * current directory, and if not found there, search in specific * AliROOT directory. If @a rw is try the file is (re-)opened in * UPDATE mode. * * @param path Path to file. * @param rw If true, open read/write. * * @return Pointer to file, or null */ static TFile* GetFile(const char* path=0, Bool_t rw=false) { TString base = ((path && path[0] != '\0') ? gSystem->BaseName(path) : "other.root"); TString realPath; if (path && path[0] != '\0') realPath = gSystem->ExpandPathName(path); if (Verbose() > 2) ::Info("GetFile", "Looking for %s (%s)", base.Data(), realPath.Data()); TObject* o = gROOT->GetListOfFiles()->FindObject(base); TFile* f = 0; if (o) { f = static_cast<TFile*>(o); if (!rw) return f; if (!f->IsWritable() && f->ReOpen("UPDATE") < 0) return 0; if (Verbose() > 2) ::Info("GetFile", "Found file %s in list of open files", base.Data()); return f; } const char* mode = (rw ? "UPDATE" : "READ"); if (!realPath.IsNull() && !gSystem->AccessPathName(realPath.Data())) { if (Verbose() > 2) ::Info("GetFile", "Trying %s", realPath.Data()); f = TFile::Open(path, mode); } if (!f && !gSystem->AccessPathName("other.root")) { if (Verbose() > 2) ::Info("GetFile", "Trying other.root"); f = TFile::Open("other.root", mode); } if (!f && gSystem->Getenv("FWD")) { TString tfwd(gSystem->Getenv("FWD")); tfwd.Append("/other.root"); if (Verbose() > 2) ::Info("GetFile", "Trying %s", tfwd.Data()); f = TFile::Open(tfwd, mode); } if (!f) { if (Verbose() > 2) ::Info("GetFile", "Trying $ALICE_PHYSICS/PWGLF/FORWARD/analysis2/other.root"); f = TFile::Open("$ALICE_PHYSICS/PWGLF/FORWARD/analysis2/other.root",mode); } if (!f) ::Error("", "Failed to open file"); else { if (Verbose() > 2) ::Info("GetFile", "Opened %s", f->GetName()); } return f; } //____________________________________________________________________ /** * Get the collision system name from the identifier (1: pp, 2: * PbPb, 3: pPb) * * @param sys Collision system identifier * * @return String or null */ static const char* SysName(UShort_t sys) { switch (sys) { case 1: return "pp"; case 2: return "PbPb"; case 3: return "pPb"; case 4: return "Pbp"; } ::Error("", "Unknown system: %d", sys); return 0; } //____________________________________________________________________ /** * Get the zero-padded collision energy name * * @param sNN Collision energy (in GeV) * * @return Zero-padded collision energy */ static const char* SNNName(UShort_t sNN) { return Form("%05d", sNN); } //____________________________________________________________________ /** * Get the centrality method prefix. @a trg is a bit mask, of which * bits 4-7 are used here. The flags are * * - 0x10 V0M * - 0x20 V0A * - 0x40 ZNA * - 0X80 ZNC * * @param trg Bits * * @return Prefix string or empty string */ static const char* CntName(UShort_t trg) { switch (trg >> 4) { case 0x01: return "V0M_"; case 0x02: return "V0A_"; case 0x04: return "ZNA_"; case 0x08: return "ZNC_"; case 0x10: return "V0C_"; case 0x20: return "CL1_"; } return ""; // V0M_"; // Default } //____________________________________________________________________ /** * Get the trigger name. If @f$ c_2 > c_1@f$ then the bits of @a * trg are ignored, save for the bits 4-7 which are interpreted * according to CntName. * * The meaning of the bits are * * - 0x001 INEL * - 0x002 INEL>0 * - 0x004 NSD * - 0x3f0 Mask for centrality estimator. * * @param trg Trigger mask. * @param c1 Least centrality @f$ c_1@f$ * @param c2 Largest centrality @f$ c_2@f$ * * @return Trigger string or null */ static const char* TrgName(UShort_t trg, UShort_t c1, UShort_t c2) { if (c2 > c1) return Form("%s%03d_%03d", CntName(trg), c1, c2); switch (trg) { case 1: return "INEL"; case 2: return "INELGT0"; case 4: return "NSD"; } ::Error("", "Unknown trigger: %d", trg); return 0; } //____________________________________________________________________ /** * Get the experiment name. * * - 0: UA5 * - 1: CMS * - 2: ALICE (published or pre-print) * - 3: ALICE Work-in-progress * - 4: ATLAS * - 5: PYTHIA (or MC) * * @param which Experiment identifier * * @return Experiment name or null */ static const char* ExpName(UShort_t which) { switch (which) { case UA5: return "UA5"; case CMS: return "CMS"; case ALICE: return "ALICE"; case WIP: return "WIP"; case ATLAS: return "ATLAS"; case PYTHIA: return "PYTHIA"; } ::Error("", "Unknown experiment: %d", which); return 0; } // _________________________________________________________________ /** * Get graphs for selected experiments under @a d. * * @param d Directory to search * @param which Which experiments to get data from * * @return Graph of data, or null */ static TMultiGraph* GetExps(TDirectory* d, UShort_t which) { TMultiGraph* ret = 0; for (UShort_t w = UA5; w <= PYTHIA; w++) { if (!(which & (1 << w))) continue; const char* expName = ExpName(w); TDirectory* expDir = 0; if (!expName || !(expDir = d->GetDirectory(expName))) { if (Verbose() >= 3) :: Warning("GetExps","Nothing for %s in %s",expName,d->GetName()); continue; } TObject* o = expDir->Get("data"); if (o) { if (!ret) ret = new TMultiGraph(); TMultiGraph* mg = static_cast<TMultiGraph*>(o); if (w == WIP) { TIter next(mg->GetListOfGraphs()); TGraph* g = 0; while ((g = static_cast<TGraph*>(next()))) if (g->GetMarkerColor() == kMagenta+3) { g->SetMarkerColor(kCyan-6); g->SetLineColor(kCyan-6); } } ret->Add(mg); } } if (!ret) { if (Verbose() >= 1) ::Error("GetExps", "Didn't get any data for exp=0x%x in dir %s", which, d->GetPath()); } return ret; } // _________________________________________________________________ /** * Get data for selected trigger and experiments under @a d. * * @param d Directory to seach * @param type Which triggers * @param which Which experiments * * @return Graph of data, or null */ static TMultiGraph* GetTrigs(TDirectory* d, UShort_t type, UShort_t which) { TMultiGraph* ret = 0; for (UShort_t t = INEL; t <= NSD; t++) { UShort_t trg = (1 << (t-INEL)); if (!(type & trg)) { if (Verbose() >= 5) ::Info("GetTrigs", "Skipping trigger 0x%x (0x%x)", trg, type); continue; } const char* trgName = TrgName(trg, 0, 0); TDirectory* trgDir = 0; if (!trgName || !(trgDir = d->GetDirectory(trgName))) { if (Verbose() >= 3) ::Warning("GetTrigs", "No directory %s for 0x%x in %s", trgName, trg, d->GetPath()); continue; } TMultiGraph* g = GetExps(trgDir, which); if (g) { if (!ret) ret = new TMultiGraph(); ret->Add(g); } } if (!ret) if (Verbose() >= 1) ::Error("GetTrigs", "Didn't get any data for trigger=0x%x and exp=0x%x in dir %s", type, which, d->GetPath()); return ret; } // _________________________________________________________________ /** * Get data for selected centrality range * * @param d Directory to search * @param experiment Which experiment * @param trigger Which centrality estimator (possibly 0) * @param centLow Least centrality * @param centHigh Largetst centrality * * @return Graph of data or null */ static TMultiGraph* GetCents(TDirectory* d, UShort_t experiment, UShort_t trigger, UShort_t centLow, UShort_t centHigh) { // We need to find the bins we can and check for the // experiments TMultiGraph* ret = 0; TIter next(d->GetListOfKeys()); TObject* obj = 0; const char* cntPre = CntName(trigger); // Info("", "trigger=0x%x pre=%s", trigger, cntPre); while ((obj = next())) { TString n(obj->GetName()); if (n.EqualTo("all")) continue; UShort_t off = 0; if (cntPre && cntPre[0] != '\0') { if (!n.BeginsWith(cntPre, TString::kIgnoreCase)) continue; off = 4; } if (n.Length() != 7+off) continue; TString l1(n(off, 3)); TString l2 = l1.Strip(TString::kLeading, '0'); TString h1(n(off+4,3)); TString h2 = h1.Strip(TString::kLeading, '0'); UShort_t c1 = l2.Atoi(); UShort_t c2 = h2.Atoi(); // Info("", "n=%s off=%d c1=%d c2=%d", n.Data(), off, c1, c2); if (c1 < centLow || c2 > centHigh) { if (Verbose() >=5) ::Info("", "Skipping %s in %s", n.Data(),d->GetPath()); continue; } TDirectory* centDir = d->GetDirectory(obj->GetName()); if (!centDir) continue; TMultiGraph* exps = GetExps(centDir, experiment); if (exps) { if (!ret) ret = new TMultiGraph(); ret->Add(exps); } } // experiment (key) if (!ret && Verbose() >= 1) ::Error("GetCents", "No graphs for centralities %d-%d%% in %s", centLow, centHigh, d->GetPath()); return ret; } //____________________________________________________________________ /** * Get a multi graph of data for a given energy and trigger type * * @param sys Collision system (1: pp, 2: PbPb, 3: pPb) * @param sNN Energy in GeV (900, 2360, 2760, 7000, 8000) * @param triggers Bit pattern of trigger type * - 0x001 INEL * - 0x002 INEL>0 * - 0x004 NSD * - 0x3F0 Mask for centrality estimator * @param centLow Low centrality cut (not pp) * @param centHigh High centrality cut (not pp) * @param experiments From which experiments * @param path Path to database * * @return A multi graph with the selected data. * * @ingroup pwglf_forward_otherdata */ static TMultiGraph* GetData(UShort_t sys, UShort_t sNN, UShort_t triggers=0x1, UShort_t centLow=0, UShort_t centHigh=0, UShort_t experiments=0x7, const char* path=0) { UShort_t trg = (triggers & 0x3F7); if (triggers & 0x2000) trg |= 0x4; TFile* f = GetFile(path,false); if (!f) return 0; TDirectory* sysDir = 0; const char* sysName = SysName(sys); if (!sysName || !(sysDir = f->GetDirectory(sysName))) { ::Error("", "Invalid system %d (%s)", sys, sysName); f->ls(); return 0; } TDirectory* sNNDir = 0; const char* sNNName = SNNName(sNN); if (!sNNName) { ::Error("", "Invalid CMS energy %d (%s)", sNN, sNNName); return 0; } if (!(sNNDir = sysDir->GetDirectory(sNNName))) { ::Warning("", "No other data for CMS energy %d (%s)", sNN, sNNName); return 0; } TMultiGraph* ret = 0; // If we have a centrality request if (centHigh > centLow) { if (centLow == 0 && centHigh >= 100) ret = GetCents(sNNDir, experiments, trg, centLow, centHigh); else { // Look for specific centrality bin TString bin(TrgName(trg,centLow,centHigh)); TDirectory* centDir=sNNDir->GetDirectory(bin); if (!centDir) { if (Verbose() >= 3) Warning("", "No directory '%s' (0x%x,%d%d)", bin.Data(), trg, centLow, centHigh); return 0; } return GetExps(centDir, experiments); } } // centHigh > centLow else ret = GetTrigs(sNNDir, trg, experiments); if (ret) { TString title; FormatTitle(title, sys, sNN, trg, centLow, centHigh); ret->SetTitle(title); } return ret; } //__________________________________________________________________ /** * Format title of a plot * * @param title On return, the title * @param sys Collision system (1: pp, 2: PbPb, 3: pPb) * @param sNN Energy in GeV (900, 2360, 2760, 7000, 8000) * @param triggers Bit pattern of trigger type * - 0x001 INEL * - 0x002 INEL>0 * - 0x004 NSD * - 0x3F0 Mask for centrality estimator * @param centLow Low centrality cut (not pp) * @param centHigh High centrality cut (not pp) * @param seenUA5 If true and sys=1, then put in p-pbar */ static void FormatTitle(TString& title, UShort_t sys, UShort_t sNN, UShort_t triggers, UShort_t centLow, UShort_t centHigh, Bool_t seenUA5=false) { TString sn(SysName(sys)); if (seenUA5) sn.Append("(p#bar{p})"); TString en(Form("#sqrt{s%s}=", (sys==1 ? "" : "_{NN}"))); if (sNN < 1000) en.Append(Form("%dGeV", sNN)); else if ((sNN % 1000) == 0) en.Append(Form("%dTeV", (sNN/1000))); else en.Append(Form("%.2fTeV", Float_t(sNN)/1000)); TString tn; if (centHigh > centLow) { TString cn(CntName(triggers)); cn.Remove(3,1); tn = Form("%d%% - %d%% central (%s)", centLow, centHigh, cn.Data()); } else { for (UShort_t t = INEL; t <= NSD; t++) { UShort_t trg = (1 << (t-INEL)); if (!(triggers & trg)) continue; if (!tn.IsNull()) tn.Append("|"); switch (t) { case INEL: tn.Append("INEL"); break; case INELGt0: tn.Append("INEL>0"); break; case NSD: tn.Append("NSD"); break; } } // for } if (!en.IsNull()) en.Prepend(", "); if (!tn.IsNull()) tn.Prepend(", "); title.Form("%s%s%s", sn.Data(), en.Data(), tn.Data()); } //=== Importing ==================================================== enum { /** Style used for UA5 data */ UA5Style = 21, /** Style used for CMS data */ CMSStyle = 29, /** Style used for ALICE published data */ ALICEStyle = 27, /** Color used for ALICE work-in-progress data */ WIPStyle = 33, /** Style used for Pythia data */ PYTHIAStyle = 28, /** Color used for UA5 data */ UA5Color = kBlue+1, /** Color used for Pytia data */ PYTHIAColor = kGray+2, /** Color used for CMS data */ CMSColor = kGreen+1, /** Color used for ALICE data */ ALICEColor = kMagenta+1, /** Color used for ALICE work-in-progress data */ WIPColor = kCyan+2 }; enum { /** Marker style INEL data */ INELStyle = 22, /** Marker style INEL>0 data */ INELGt0Style= 29, /** Marker style NSD data */ NSDStyle = 23, /** Color used for UA5 data */ INELColor = kBlue+1, /** Color used for CMS data */ INELGt0Color = kGreen+1, /** Color used for ALICE data */ NSDColor = kMagenta+1 }; enum { /** Style offset for mirror data */ MirrorOff = 4 }; //____________________________________________________________________ /** * Set graph attributes based on trigger type and experiment. * * @param g Graph * @param exp Experiment * @param mirror True if mirrored data * @param name Name of graph * @param title Title of graph * * @ingroup pwglf_forward_otherdata */ static void SetGraphAttributes(TGraph* g, Int_t /*trig*/, Int_t exp, bool mirror, const Char_t* name, const Char_t* title) { Int_t color = 0; Int_t style = 0; switch (exp) { case UA5: color = UA5Color; style = UA5Style; break; case CMS: color = CMSColor; style = CMSStyle; break; case ALICE: color = ALICEColor; style = ALICEStyle; break; case WIP: color = WIPColor; style = WIPStyle; break; case PYTHIA: color = PYTHIAColor; style = PYTHIAStyle; break; } Float_t size = g->GetMarkerSize(); switch (style) { case 21: // fall-through case 25: size *= 0.8; break; case 27: size *= 1.4; break; case 33: size *= 1.4; break; } if (mirror) style += MirrorOff; if (name) g->SetName(name); if (title) g->SetTitle(title); g->SetMarkerStyle(style); g->SetMarkerSize(size); g->SetMarkerColor(color); g->SetLineColor(color); g->SetFillColor(0); g->SetFillStyle(0); g->GetHistogram()->SetStats(kFALSE); g->GetHistogram()->SetXTitle("#eta"); g->GetHistogram()->SetYTitle("#frac{1}{N} #frac{dN_{ch}}{#eta}"); } //__________________________________________________________________ /** * Get the color for a centrality bin * * @param centLow Centrality bin * @param centHigh Centrality bin * * @return Color */ static Int_t CentralityColor(UShort_t centLow, UShort_t centHigh, UShort_t /*nBins*/=0) { #if 0 if (nBins > 0 && nBins < 6) { switch (bin) { case 1: return kRed+2; case 2: return kGreen+2; case 3: return kBlue+1; case 4: return kCyan+1; case 5: return kMagenta+1; case 6: return kYellow+2; } } #endif gStyle->SetPalette(1); Float_t fc = (centLow+double(centHigh-centLow)/2) / 100; Int_t nCol = gStyle->GetNumberOfColors(); Int_t icol = TMath::Min(nCol-1,int(fc * nCol + .5)); Int_t col = gStyle->GetColorPalette(icol); //Info("GetCentralityColor","%3d: %3d-%3d -> %3d",bin,centLow,centHigh,col); return col; } /** * Import a histogram into the data base * * @param h Histogram * @param title Title on plot * @param experiment Which experiement * @param sys Collision system * @param sNN Collision energy (in GeV) * @param trigger Trigger type * @param centLow Lease centrality * @param centHigh Largest centrality * @param path Possible path to database * * @return true on success */ static Bool_t Import(TH1* h, const char* title, UShort_t experiment, UShort_t sys, UShort_t sNN, UShort_t trigger, UShort_t centLow=0, UShort_t centHigh=0, const char* path=0) { TGraphAsymmErrors* g = new TGraphAsymmErrors(); Int_t nx = h->GetNbinsX(); Int_t j = 0; for (Int_t i = 1; i <= nx; i++) { Double_t x = h->GetXaxis()->GetBinCenter(i); Double_t ex = h->GetXaxis()->GetBinWidth(i)/2; Double_t y = h->GetBinContent(i); Double_t ey = h->GetBinError(i); if (TMath::Abs(y) < 1e-6 || ey < 1e-6) continue; g->SetPoint(j, x, y); g->SetPointError(j, ex, ex, ey, ey); j++; } if (j <= 0) return false; return Import(g, title, experiment, sys, sNN, trigger, centLow, centHigh, path); } /** * Import a graph into the data base * * @param g Graph * @param title Title on plot * @param experiment Which experiement * @param sys Collision system * @param sNN Collision energy (in GeV) * @param trigger Trigger type * @param centLow Lease centrality * @param centHigh Largest centrality * @param path Possible path to database * * @return true on success */ static Bool_t Import(TGraphAsymmErrors* g, const char* title, UShort_t experiment, UShort_t sys, UShort_t sNN, UShort_t trigger, UShort_t centLow=0, UShort_t centHigh=0, const char* path=0) { if (!g) return false; TString expName = ExpName(experiment); expName.ToLower(); const char* sNNName = SNNName(sNN); const char* sysName = SysName(sys); const char* trgName = TrgName(trigger,centLow,centHigh); TString name = Form("%s%s%s%s", expName.Data(), sysName, sNNName, trgName); SetGraphAttributes(g, trigger, experiment, false, name, title); if (centLow < centHigh) { Int_t col = CentralityColor(centLow, centHigh); g->SetMarkerColor(col); g->SetLineColor(col); g->SetFillColor(col); } TMultiGraph* mg = new TMultiGraph("data",""); mg->Add(g); return Import(mg, experiment, sys, sNN, trigger, centLow, centHigh, path); } /** * Import a graph into the data base * * @param g Graph * @param experiment Which experiement * @param sys Collision system * @param sNN Collision energy (in GeV) * @param trigger Trigger type * @param centLow Lease centrality * @param centHigh Largest centrality * @param path Possible path to database * * @return true on success */ static Bool_t Import(TMultiGraph* g, UShort_t experiment, UShort_t sys, UShort_t sNN, UShort_t trigger, UShort_t centLow=0, UShort_t centHigh=0, const char* path=0) { TFile* file = GetFile(path, true); const char* sysName = SysName(sys); const char* sNNName = SNNName(sNN); const char* trgName = TrgName(trigger, centLow, centHigh); const char* expName = ExpName(experiment); if (!sysName || !sNNName || !trgName || !expName) return false; if (Verbose() > 2) ::Info("Import", "%s @ %s for %s from %s in (%d-%d%%)", sysName, sNNName, trgName, expName, centLow, centHigh); TString dirName; dirName = Form("%s/%s/%s/%s", sysName, sNNName, trgName, expName); TDirectory* dir = file->GetDirectory(dirName); if (!dir) dir = file->mkdir(dirName); file->cd(dirName); if (Verbose() > 2) ::Info("Import", "Will write data to %s", dirName.Data()); if (dir->Get("data")) { ::Warning("", "Already have data in %s", dirName.Data()); // return false; } g->SetName("data"); g->Write(); file->cd(); file->Write(); file->Close(); return true; } }; // EOF <commit_msg>Removed obsolete DB of published other dN/deta results, and corresponding script<commit_after><|endoftext|>
<commit_before>// Undeprecate CRT functions #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 #endif #include "SenseKit.h" #include "streams/depth.h" #include "SimpleViewer.h" #include <memory.h> #ifdef _WIN32 #include <GL/glut.h> #else #include <GLUT/glut.h> #endif //from glext.h #ifndef GL_SGIS_generate_mipmap #define GL_GENERATE_MIPMAP_SGIS 0x8191 #define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192 #endif #include "utils.h" #ifdef _WIN32 //for strncpy #include <stdexcept> #endif #define GL_WIN_SIZE_X 1280 #define GL_WIN_SIZE_Y 1024 #define TEXTURE_SIZE 512 #define DEFAULT_DISPLAY_MODE DISPLAY_MODE_DEPTH #define MIN_NUM_CHUNKS(data_size, chunk_size) ((((data_size)-1) / (chunk_size) + 1)) #define MIN_CHUNKS_SIZE(data_size, chunk_size) (MIN_NUM_CHUNKS(data_size, chunk_size) * (chunk_size)) #include <algorithm> SampleViewer* SampleViewer::ms_self = NULL; void SampleViewer::glutIdle() { glutPostRedisplay(); } void SampleViewer::glutDisplay() { SampleViewer::ms_self->display(); } void SampleViewer::glutKeyboard(unsigned char key, int x, int y) { SampleViewer::ms_self->onKey(key, x, y); } SampleViewer::SampleViewer(const char* strSampleName) : m_pTexMap(NULL) { ms_self = this; strncpy(m_strSampleName, strSampleName, 255); } SampleViewer::~SampleViewer() { sensekit_depth_close(&m_depthStream); sensekit_close_streamset(&m_sensor); sensekit_terminate(); delete[] m_pTexMap; ms_self = NULL; } void SampleViewer::init(int argc, char **argv) { sensekit_initialize(); sensekit_open_streamset("1d27/0601@20/30", &m_sensor); sensekit_depth_open(m_sensor, &m_depthStream); int depthWidth = 320; int depthHeight = 240; m_width = depthWidth; m_height = depthHeight; // Texture map init m_nTexMapX = MIN_CHUNKS_SIZE(m_width, TEXTURE_SIZE); m_nTexMapY = MIN_CHUNKS_SIZE(m_height, TEXTURE_SIZE); m_pTexMap = new RGB888Pixel[m_nTexMapX * m_nTexMapY]; m_lightVector = Vector3::Normalize(Vector3(.5, -0.2, 1)); //m_lightVector = Vector3::Normalize(Vector3(0, 0, 1)); m_lightColor.r = 210; m_lightColor.g = 210; m_lightColor.b = 210; m_ambientColor.r = 30; m_ambientColor.g = 30; m_ambientColor.b = 30; return initOpenGL(argc, argv); } void SampleViewer::run() //Does not return { glutMainLoop(); } void SampleViewer::calculateNormals(sensekit_depthframe_t& frame) { int width = frame.width; int height = frame.height; int length = width * height; if (m_normalMap == nullptr || m_normalMapLen != length) { m_normalMap = new Vector3[length]; m_normalMapLen = length; } Vector3* normMap = m_normalMap; int16_t* depthData = frame.data; //top row for (int x = 0; x < m_width - 1; ++x) { *normMap = Vector3(); ++normMap; } for (int y = 1; y < height - 1; ++y) { //first pixel at start of row *normMap = Vector3(); ++normMap; for (int x = 1; x < width - 1; ++x) { int index = x + y * width; int rightIndex = index + 1; int leftIndex = index - 1; int upIndex = index - width; int downIndex = index + width; int16_t depth = *(depthData + index); int16_t depthLeft = *(depthData + leftIndex); int16_t depthRight = *(depthData + rightIndex); int16_t depthUp = *(depthData + upIndex); int16_t depthDown = *(depthData + downIndex); Vector3 normAvg; if (depth != 0 && depthRight != 0 && depthDown != 0) { float worldX1, worldY1, worldZ1; float worldX2, worldY2, worldZ2; float worldX3, worldY3, worldZ3; convert_depth_to_world(x, y, depth, &worldX1, &worldY1, &worldZ1); convert_depth_to_world(x + 1, y, depthRight, &worldX2, &worldY2, &worldZ2); convert_depth_to_world(x, y + 1, depthDown, &worldX3, &worldY3, &worldZ3); Vector3 v1 = Vector3(worldX2 - worldX1, worldY2 - worldY1, worldZ2 - worldZ1); Vector3 v2 = Vector3(worldX3 - worldX1, worldY3 - worldY1, worldZ3 - worldZ1); Vector3 norm = Vector3::CrossProduct(v2, v1); normAvg.x += norm.x; normAvg.y += norm.y; normAvg.z += norm.z; } if (depth != 0 && depthRight != 0 && depthUp != 0) { float worldX1, worldY1, worldZ1; float worldX2, worldY2, worldZ2; float worldX3, worldY3, worldZ3; convert_depth_to_world(x, y, depth, &worldX1, &worldY1, &worldZ1); convert_depth_to_world(x, y - 1, depthUp, &worldX2, &worldY2, &worldZ2); convert_depth_to_world(x + 1, y, depthRight, &worldX3, &worldY3, &worldZ3); Vector3 v1 = Vector3(worldX2 - worldX1, worldY2 - worldY1, worldZ2 - worldZ1); Vector3 v2 = Vector3(worldX3 - worldX1, worldY3 - worldY1, worldZ3 - worldZ1); Vector3 norm = Vector3::CrossProduct(v2, v1); normAvg.x += norm.x; normAvg.y += norm.y; normAvg.z += norm.z; } if (depth != 0 && depthLeft != 0 && depthUp != 0) { float worldX1, worldY1, worldZ1; float worldX2, worldY2, worldZ2; float worldX3, worldY3, worldZ3; convert_depth_to_world(x, y, depth, &worldX1, &worldY1, &worldZ1); convert_depth_to_world(x - 1, y, depthLeft, &worldX2, &worldY2, &worldZ2); convert_depth_to_world(x, y - 1, depthUp, &worldX3, &worldY3, &worldZ3); Vector3 v1 = Vector3(worldX2 - worldX1, worldY2 - worldY1, worldZ2 - worldZ1); Vector3 v2 = Vector3(worldX3 - worldX1, worldY3 - worldY1, worldZ3 - worldZ1); Vector3 norm = Vector3::CrossProduct(v2, v1); normAvg.x += norm.x; normAvg.y += norm.y; normAvg.z += norm.z; } if (depth != 0 && depthLeft != 0 && depthDown != 0) { float worldX1, worldY1, worldZ1; float worldX2, worldY2, worldZ2; float worldX3, worldY3, worldZ3; convert_depth_to_world(x, y, depth, &worldX1, &worldY1, &worldZ1); convert_depth_to_world(x, y + 1, depthDown, &worldX2, &worldY2, &worldZ2); convert_depth_to_world(x - 1, y, depthLeft, &worldX3, &worldY3, &worldZ3); Vector3 v1 = Vector3(worldX2 - worldX1, worldY2 - worldY1, worldZ2 - worldZ1); Vector3 v2 = Vector3(worldX3 - worldX1, worldY3 - worldY1, worldZ3 - worldZ1); Vector3 norm = Vector3::CrossProduct(v2, v1); normAvg.x += norm.x; normAvg.y += norm.y; normAvg.z += norm.z; } *normMap = Vector3::Normalize(normAvg); /* //reference sphere const float PI = 3.141592; float normX = 2*(x / (float)width)-1; float angleX = 0.5 * PI * normX; float normY = 2*(y / (float)height)-1; float angleY = 0.5 * PI * normY; if (sqrt(normX*normX + normY*normY) < 1) { *normMap = Vector3(sin(angleX)*cos(angleY), sin(angleY)*cos(angleX), cos(angleY)*cos(angleX)); } else { *normMap = Vector3(); } */ ++normMap; } //last pixel at end of row *normMap = Vector3(); ++normMap; } //bottom row for (int x = 0; x < m_width - 1; ++x) { *normMap = Vector3(); ++normMap; } } void SampleViewer::display() { sensekit_temp_update(); sensekit_depth_frame_open(m_depthStream, 30, &m_depthFrame); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, GL_WIN_SIZE_X, GL_WIN_SIZE_Y, 0, -1.0, 1.0); calculateHistogram(m_pDepthHist, MAX_DEPTH, *m_depthFrame); calculateNormals(*m_depthFrame); memset(m_pTexMap, 0, m_nTexMapX*m_nTexMapY*sizeof(RGB888Pixel)); short* pDepthRow = (short*)m_depthFrame->data; RGB888Pixel* pTexRow = m_pTexMap; int rowSize = m_depthFrame->width; Vector3* normMap = m_normalMap; for (int y = 0; y < m_depthFrame->height; ++y) { short* pDepth = pDepthRow; RGB888Pixel* pTex = pTexRow; for (int x = 0; x < m_depthFrame->width; ++x, ++pDepth, ++normMap, ++pTex) { if (*pDepth != 0) { /* int nHistValue = m_pDepthHist[*pDepth]; pTex->r = nHistValue; pTex->g = nHistValue; pTex->b = 0; */ } Vector3 norm = *normMap; if (!norm.isEmpty()) { /* pTex->r = (norm.x * 0.5 + 1) * 255; pTex->g = (norm.y * 0.5 + 1) * 255; pTex->b = (norm.z * 0.5 + 1) * 255; */ float diffuseFactor = Vector3::DotProduct(norm, m_lightVector); RGB888Pixel diffuseColor; if (diffuseFactor > 0) { //only add diffuse when mesh is facing the light diffuseColor.r = m_lightColor.r * diffuseFactor; diffuseColor.g = m_lightColor.g * diffuseFactor; diffuseColor.b = m_lightColor.b * diffuseFactor; } else { diffuseColor.r = 0; diffuseColor.g = 0; diffuseColor.b = 0; } pTex->r = std::max(0, std::min(255, m_ambientColor.r + diffuseColor.r)); pTex->g = std::max(0, std::min(255, m_ambientColor.g + diffuseColor.g)); pTex->b = std::max(0, std::min(255, m_ambientColor.b + diffuseColor.b)); } } pDepthRow += rowSize; pTexRow += m_nTexMapX; } sensekit_depth_frame_close(&m_depthFrame); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_nTexMapX, m_nTexMapY, 0, GL_RGB, GL_UNSIGNED_BYTE, m_pTexMap); // Display the OpenGL texture map glColor4f(1, 1, 1, 1); glBegin(GL_QUADS); int nXRes = m_width; int nYRes = m_height; // upper left glTexCoord2f(0, 0); glVertex2f(0, 0); // upper right glTexCoord2f((float)nXRes / (float)m_nTexMapX, 0); glVertex2f(GL_WIN_SIZE_X, 0); // bottom right glTexCoord2f((float)nXRes / (float)m_nTexMapX, (float)nYRes / (float)m_nTexMapY); glVertex2f(GL_WIN_SIZE_X, GL_WIN_SIZE_Y); // bottom left glTexCoord2f(0, (float)nYRes / (float)m_nTexMapY); glVertex2f(0, GL_WIN_SIZE_Y); glEnd(); // Swap the OpenGL display buffers glutSwapBuffers(); } void SampleViewer::onKey(unsigned char key, int /*x*/, int /*y*/) { switch (key) { case 27: //shutdown sensekit sensekit_terminate(); exit(1); } } void SampleViewer::initOpenGL(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(GL_WIN_SIZE_X, GL_WIN_SIZE_Y); glutCreateWindow(m_strSampleName); // glutFullScreen(); glutSetCursor(GLUT_CURSOR_NONE); initOpenGLHooks(); glDisable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); } void SampleViewer::initOpenGLHooks() { glutKeyboardFunc(glutKeyboard); glutDisplayFunc(glutDisplay); glutIdleFunc(glutIdle); } <commit_msg>Add a fade factor to depth visualization so foreground pops<commit_after>// Undeprecate CRT functions #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 #endif #include "SenseKit.h" #include "streams/depth.h" #include "SimpleViewer.h" #include <memory.h> #ifdef _WIN32 #include <GL/glut.h> #else #include <GLUT/glut.h> #endif //from glext.h #ifndef GL_SGIS_generate_mipmap #define GL_GENERATE_MIPMAP_SGIS 0x8191 #define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192 #endif #include "utils.h" #ifdef _WIN32 //for strncpy #include <stdexcept> #endif #define GL_WIN_SIZE_X 1280 #define GL_WIN_SIZE_Y 1024 #define TEXTURE_SIZE 512 #define DEFAULT_DISPLAY_MODE DISPLAY_MODE_DEPTH #define MIN_NUM_CHUNKS(data_size, chunk_size) ((((data_size)-1) / (chunk_size) + 1)) #define MIN_CHUNKS_SIZE(data_size, chunk_size) (MIN_NUM_CHUNKS(data_size, chunk_size) * (chunk_size)) #include <algorithm> SampleViewer* SampleViewer::ms_self = NULL; void SampleViewer::glutIdle() { glutPostRedisplay(); } void SampleViewer::glutDisplay() { SampleViewer::ms_self->display(); } void SampleViewer::glutKeyboard(unsigned char key, int x, int y) { SampleViewer::ms_self->onKey(key, x, y); } SampleViewer::SampleViewer(const char* strSampleName) : m_pTexMap(NULL) { ms_self = this; strncpy(m_strSampleName, strSampleName, 255); } SampleViewer::~SampleViewer() { sensekit_depth_close(&m_depthStream); sensekit_close_streamset(&m_sensor); sensekit_terminate(); delete[] m_pTexMap; ms_self = NULL; } void SampleViewer::init(int argc, char **argv) { sensekit_initialize(); sensekit_open_streamset("1d27/0601@20/30", &m_sensor); sensekit_depth_open(m_sensor, &m_depthStream); int depthWidth = 320; int depthHeight = 240; m_width = depthWidth; m_height = depthHeight; // Texture map init m_nTexMapX = MIN_CHUNKS_SIZE(m_width, TEXTURE_SIZE); m_nTexMapY = MIN_CHUNKS_SIZE(m_height, TEXTURE_SIZE); m_pTexMap = new RGB888Pixel[m_nTexMapX * m_nTexMapY]; m_lightVector = Vector3::Normalize(Vector3(.5, -0.2, 1)); //m_lightVector = Vector3::Normalize(Vector3(0, 0, 1)); m_lightColor.r = 210; m_lightColor.g = 210; m_lightColor.b = 210; m_ambientColor.r = 30; m_ambientColor.g = 30; m_ambientColor.b = 30; return initOpenGL(argc, argv); } void SampleViewer::run() //Does not return { glutMainLoop(); } void SampleViewer::calculateNormals(sensekit_depthframe_t& frame) { int width = frame.width; int height = frame.height; int length = width * height; if (m_normalMap == nullptr || m_normalMapLen != length) { m_normalMap = new Vector3[length]; m_normalMapLen = length; } Vector3* normMap = m_normalMap; int16_t* depthData = frame.data; //top row for (int x = 0; x < m_width - 1; ++x) { *normMap = Vector3(); ++normMap; } for (int y = 1; y < height - 1; ++y) { //first pixel at start of row *normMap = Vector3(); ++normMap; for (int x = 1; x < width - 1; ++x) { int index = x + y * width; int rightIndex = index + 1; int leftIndex = index - 1; int upIndex = index - width; int downIndex = index + width; int16_t depth = *(depthData + index); int16_t depthLeft = *(depthData + leftIndex); int16_t depthRight = *(depthData + rightIndex); int16_t depthUp = *(depthData + upIndex); int16_t depthDown = *(depthData + downIndex); Vector3 normAvg; if (depth != 0 && depthRight != 0 && depthDown != 0) { float worldX1, worldY1, worldZ1; float worldX2, worldY2, worldZ2; float worldX3, worldY3, worldZ3; convert_depth_to_world(x, y, depth, &worldX1, &worldY1, &worldZ1); convert_depth_to_world(x + 1, y, depthRight, &worldX2, &worldY2, &worldZ2); convert_depth_to_world(x, y + 1, depthDown, &worldX3, &worldY3, &worldZ3); Vector3 v1 = Vector3(worldX2 - worldX1, worldY2 - worldY1, worldZ2 - worldZ1); Vector3 v2 = Vector3(worldX3 - worldX1, worldY3 - worldY1, worldZ3 - worldZ1); Vector3 norm = Vector3::CrossProduct(v2, v1); normAvg.x += norm.x; normAvg.y += norm.y; normAvg.z += norm.z; } if (depth != 0 && depthRight != 0 && depthUp != 0) { float worldX1, worldY1, worldZ1; float worldX2, worldY2, worldZ2; float worldX3, worldY3, worldZ3; convert_depth_to_world(x, y, depth, &worldX1, &worldY1, &worldZ1); convert_depth_to_world(x, y - 1, depthUp, &worldX2, &worldY2, &worldZ2); convert_depth_to_world(x + 1, y, depthRight, &worldX3, &worldY3, &worldZ3); Vector3 v1 = Vector3(worldX2 - worldX1, worldY2 - worldY1, worldZ2 - worldZ1); Vector3 v2 = Vector3(worldX3 - worldX1, worldY3 - worldY1, worldZ3 - worldZ1); Vector3 norm = Vector3::CrossProduct(v2, v1); normAvg.x += norm.x; normAvg.y += norm.y; normAvg.z += norm.z; } if (depth != 0 && depthLeft != 0 && depthUp != 0) { float worldX1, worldY1, worldZ1; float worldX2, worldY2, worldZ2; float worldX3, worldY3, worldZ3; convert_depth_to_world(x, y, depth, &worldX1, &worldY1, &worldZ1); convert_depth_to_world(x - 1, y, depthLeft, &worldX2, &worldY2, &worldZ2); convert_depth_to_world(x, y - 1, depthUp, &worldX3, &worldY3, &worldZ3); Vector3 v1 = Vector3(worldX2 - worldX1, worldY2 - worldY1, worldZ2 - worldZ1); Vector3 v2 = Vector3(worldX3 - worldX1, worldY3 - worldY1, worldZ3 - worldZ1); Vector3 norm = Vector3::CrossProduct(v2, v1); normAvg.x += norm.x; normAvg.y += norm.y; normAvg.z += norm.z; } if (depth != 0 && depthLeft != 0 && depthDown != 0) { float worldX1, worldY1, worldZ1; float worldX2, worldY2, worldZ2; float worldX3, worldY3, worldZ3; convert_depth_to_world(x, y, depth, &worldX1, &worldY1, &worldZ1); convert_depth_to_world(x, y + 1, depthDown, &worldX2, &worldY2, &worldZ2); convert_depth_to_world(x - 1, y, depthLeft, &worldX3, &worldY3, &worldZ3); Vector3 v1 = Vector3(worldX2 - worldX1, worldY2 - worldY1, worldZ2 - worldZ1); Vector3 v2 = Vector3(worldX3 - worldX1, worldY3 - worldY1, worldZ3 - worldZ1); Vector3 norm = Vector3::CrossProduct(v2, v1); normAvg.x += norm.x; normAvg.y += norm.y; normAvg.z += norm.z; } *normMap = Vector3::Normalize(normAvg); /* //reference sphere const float PI = 3.141592; float normX = 2*(x / (float)width)-1; float angleX = 0.5 * PI * normX; float normY = 2*(y / (float)height)-1; float angleY = 0.5 * PI * normY; if (sqrt(normX*normX + normY*normY) < 1) { *normMap = Vector3(sin(angleX)*cos(angleY), sin(angleY)*cos(angleX), cos(angleY)*cos(angleX)); } else { *normMap = Vector3(); } */ ++normMap; } //last pixel at end of row *normMap = Vector3(); ++normMap; } //bottom row for (int x = 0; x < m_width - 1; ++x) { *normMap = Vector3(); ++normMap; } } void SampleViewer::display() { sensekit_temp_update(); sensekit_depth_frame_open(m_depthStream, 30, &m_depthFrame); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, GL_WIN_SIZE_X, GL_WIN_SIZE_Y, 0, -1.0, 1.0); calculateHistogram(m_pDepthHist, MAX_DEPTH, *m_depthFrame); calculateNormals(*m_depthFrame); memset(m_pTexMap, 0, m_nTexMapX*m_nTexMapY*sizeof(RGB888Pixel)); short* pDepthRow = (short*)m_depthFrame->data; RGB888Pixel* pTexRow = m_pTexMap; int rowSize = m_depthFrame->width; Vector3* normMap = m_normalMap; for (int y = 0; y < m_depthFrame->height; ++y) { short* pDepth = pDepthRow; RGB888Pixel* pTex = pTexRow; for (int x = 0; x < m_depthFrame->width; ++x, ++pDepth, ++normMap, ++pTex) { short depth = *pDepth; if (depth != 0) { /* int nHistValue = m_pDepthHist[*pDepth]; pTex->r = nHistValue; pTex->g = nHistValue; pTex->b = 0; */ } Vector3 norm = *normMap; if (!norm.isEmpty()) { /* pTex->r = (norm.x * 0.5 + 1) * 255; pTex->g = (norm.y * 0.5 + 1) * 255; pTex->b = (norm.z * 0.5 + 1) * 255; */ float fadeFactor = 1 - 0.6*std::max(0.0f,std::min(1.0f,((depth - 400) / 3200.0f))); float diffuseFactor = Vector3::DotProduct(norm, m_lightVector); RGB888Pixel diffuseColor; if (diffuseFactor > 0) { //only add diffuse when mesh is facing the light diffuseColor.r = m_lightColor.r * diffuseFactor; diffuseColor.g = m_lightColor.g * diffuseFactor; diffuseColor.b = m_lightColor.b * diffuseFactor; } else { diffuseColor.r = 0; diffuseColor.g = 0; diffuseColor.b = 0; } pTex->r = std::max(0, std::min(255, (int)(fadeFactor*(m_ambientColor.r + diffuseColor.r)))); pTex->g = std::max(0, std::min(255, (int)(fadeFactor*(m_ambientColor.g + diffuseColor.g)))); pTex->b = std::max(0, std::min(255, (int)(fadeFactor*(m_ambientColor.b + diffuseColor.b)))); } } pDepthRow += rowSize; pTexRow += m_nTexMapX; } sensekit_depth_frame_close(&m_depthFrame); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, m_nTexMapX, m_nTexMapY, 0, GL_RGB, GL_UNSIGNED_BYTE, m_pTexMap); // Display the OpenGL texture map glColor4f(1, 1, 1, 1); glBegin(GL_QUADS); int nXRes = m_width; int nYRes = m_height; // upper left glTexCoord2f(0, 0); glVertex2f(0, 0); // upper right glTexCoord2f((float)nXRes / (float)m_nTexMapX, 0); glVertex2f(GL_WIN_SIZE_X, 0); // bottom right glTexCoord2f((float)nXRes / (float)m_nTexMapX, (float)nYRes / (float)m_nTexMapY); glVertex2f(GL_WIN_SIZE_X, GL_WIN_SIZE_Y); // bottom left glTexCoord2f(0, (float)nYRes / (float)m_nTexMapY); glVertex2f(0, GL_WIN_SIZE_Y); glEnd(); // Swap the OpenGL display buffers glutSwapBuffers(); } void SampleViewer::onKey(unsigned char key, int /*x*/, int /*y*/) { switch (key) { case 27: //shutdown sensekit sensekit_terminate(); exit(1); } } void SampleViewer::initOpenGL(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(GL_WIN_SIZE_X, GL_WIN_SIZE_Y); glutCreateWindow(m_strSampleName); // glutFullScreen(); glutSetCursor(GLUT_CURSOR_NONE); initOpenGLHooks(); glDisable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); } void SampleViewer::initOpenGLHooks() { glutKeyboardFunc(glutKeyboard); glutDisplayFunc(glutDisplay); glutIdleFunc(glutIdle); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Holger Schletz <holger.schletz@web.de> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <QFileInfo> #include "javaruntimeenvironment7.h" #include "manualdownload.h" JavaRuntimeEnvironment7::JavaRuntimeEnvironment7() : Package("Java Runtime Environment 7", "15") { } void JavaRuntimeEnvironment7::build(NSIS *installer, Version version) { isError = false; download(version); if (!isError) { QString header; QString src; if (getConfig("Uninstall JRE6", false).toBool()) { src += loadResource(":NSIS/JavaRuntimeEnvironment7/uninstalljre6.nsh"); } src += loadResource(":NSIS/JavaRuntimeEnvironment7/main.nsh"); src.replace("${Installer}", QFileInfo(tempFiles.first()).fileName()); if (!getConfig("Use automatic update", true).toBool()) { src += loadResource(":NSIS/JavaRuntimeEnvironment7/disableautoupdate.nsh"); } if (!getConfig("Use Quickstarter", true).toBool()) { header += "!include 'WinVer.nsh'\n"; src += loadResource(":NSIS/JavaRuntimeEnvironment7/disablequickstarter.nsh"); } installer->build( objectName(), getOutputFile(), NSIS::Lzma, 120, browsers(), tempFiles, src, header ); } cleanup(); } void JavaRuntimeEnvironment7::download(Version version) { QString filename( ManualDownload::getFile( QString("jre-7u%1-windows-i586.exe").arg(version), "http://www.java.com/inc/BrowserRedirect1.jsp", "You need to download the 32 bit offline installer." ) ); if (filename.isEmpty()) { isError = true; return; } tempFiles << filename; } <commit_msg>Changed JRE7 compression method.<commit_after>/* * Copyright (c) 2012 Holger Schletz <holger.schletz@web.de> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <QFileInfo> #include "javaruntimeenvironment7.h" #include "manualdownload.h" JavaRuntimeEnvironment7::JavaRuntimeEnvironment7() : Package("Java Runtime Environment 7", "15") { } void JavaRuntimeEnvironment7::build(NSIS *installer, Version version) { isError = false; download(version); if (!isError) { QString header; QString src; if (getConfig("Uninstall JRE6", false).toBool()) { src += loadResource(":NSIS/JavaRuntimeEnvironment7/uninstalljre6.nsh"); } src += loadResource(":NSIS/JavaRuntimeEnvironment7/main.nsh"); src.replace("${Installer}", QFileInfo(tempFiles.first()).fileName()); if (!getConfig("Use automatic update", true).toBool()) { src += loadResource(":NSIS/JavaRuntimeEnvironment7/disableautoupdate.nsh"); } if (!getConfig("Use Quickstarter", true).toBool()) { header += "!include 'WinVer.nsh'\n"; src += loadResource(":NSIS/JavaRuntimeEnvironment7/disablequickstarter.nsh"); } installer->build( objectName(), getOutputFile(), NSIS::Zlib, 120, browsers(), tempFiles, src, header ); } cleanup(); } void JavaRuntimeEnvironment7::download(Version version) { QString filename( ManualDownload::getFile( QString("jre-7u%1-windows-i586.exe").arg(version), "http://www.java.com/inc/BrowserRedirect1.jsp", "You need to download the 32 bit offline installer." ) ); if (filename.isEmpty()) { isError = true; return; } tempFiles << filename; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/message_center/notification_view.h" #include "base/utf_string_conversions.h" #include "grit/ui_resources.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/text/text_elider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/size.h" #include "ui/message_center/message_center_constants.h" #include "ui/native_theme/native_theme.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/grid_layout.h" namespace { // Notification dimensions. const int kIconLeftPadding = 0; const int kIconColumnWidth = message_center::kNotificationIconWidth; const int kIconToTextPadding = 15; const int kTextToClosePadding = 10; const int kCloseColumnWidth = 8; const int kCloseRightPadding = 6; const int kIconTopPadding = 0; const int kTextTopPadding = 9; const int kCloseTopPadding = 6; const int kIconBottomPadding = 0; const int kTextBottomPadding = 12; const int kItemTitleToDetailsPadding = 3; // Notification colors. The text background colors below are used only to keep // view::Label from modifying the text color and will not actually be drawn. // See view::Label's SetEnabledColor() and SetBackgroundColor() for details. const SkColor kBackgroundColor = SkColorSetRGB(255, 255, 255); const SkColor kTitleColor = SkColorSetRGB(68, 68, 68); const SkColor kTitleBackgroundColor = SK_ColorWHITE; const SkColor kMessageColor = SkColorSetRGB(136, 136, 136); const SkColor kMessageBackgroundColor = SK_ColorBLACK; // Static function to create an empty border to be used as padding. views::Border* MakePadding(int top, int left, int bottom, int right) { return views::Border::CreateEmptyBorder(top, left, bottom, right); } // ItemViews are responsible for drawing each NotificationView item's title and // message next to each other within a single column. class ItemView : public views::View { public: ItemView(const message_center::NotificationList::NotificationItem& item); virtual ~ItemView(); private: DISALLOW_COPY_AND_ASSIGN(ItemView); }; ItemView::ItemView( const message_center::NotificationList::NotificationItem& item) { views::BoxLayout* layout = new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, kItemTitleToDetailsPadding); SetLayoutManager(layout); views::Label* title = new views::Label(item.title); title->SetHorizontalAlignment(gfx::ALIGN_LEFT); title->SetElideBehavior(views::Label::ELIDE_AT_END); title->SetEnabledColor(kTitleColor); title->SetBackgroundColor(kTitleBackgroundColor); AddChildViewAt(title, 0); views::Label* details = new views::Label(item.message); details->SetHorizontalAlignment(gfx::ALIGN_LEFT); details->SetElideBehavior(views::Label::ELIDE_AT_END); details->SetEnabledColor(kMessageColor); details->SetBackgroundColor(kMessageBackgroundColor); AddChildViewAt(details, 1); PreferredSizeChanged(); SchedulePaint(); } ItemView::~ItemView() { } } // namespace namespace message_center { NotificationView::NotificationView( NotificationList::Delegate* list_delegate, const NotificationList::Notification& notification) : MessageView(list_delegate, notification) { } NotificationView::~NotificationView() { } void NotificationView::SetUpView() { set_background(views::Background::CreateSolidBackground(kBackgroundColor)); views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); // Three columns (icon, text, close button) surrounded by padding. The icon // and close button columns and the padding have fixed widths and the text // column fills up the remaining space. To minimize the number of columns and // simplify column spanning padding is applied to each view within columns // instead of through padding columns. views::ColumnSet* columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::FIXED, kIconLeftPadding + kIconColumnWidth + kIconToTextPadding, kIconLeftPadding + kIconColumnWidth + kIconToTextPadding); // Padding + icon + padding. columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 100, views::GridLayout::USE_PREF, 0, 0); // Text + padding (kTextToClosePadding). columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::FIXED, kCloseColumnWidth + kCloseRightPadding, kCloseColumnWidth + kCloseRightPadding); // Close button + padding. // First row: Icon. This vertically spans the close button padding row, the // close button row, and all item rows. layout->StartRow(0, 0); views::ImageView* icon = new views::ImageView(); icon->SetImageSize(gfx::Size(message_center::kNotificationIconWidth, message_center::kNotificationIconWidth)); icon->SetImage(notification_.primary_icon); icon->SetHorizontalAlignment(views::ImageView::LEADING); icon->SetVerticalAlignment(views::ImageView::LEADING); icon->set_border(MakePadding(kIconTopPadding, kIconLeftPadding, kIconBottomPadding, kIconToTextPadding)); layout->AddView(icon, 1, 2 + notification_.items.size()); // First row: Title. This vertically spans the close button padding row and // the close button row. // TODO(dharcourt): Skip the title Label when there's no title text. views::Label* title = new views::Label(notification_.title); title->SetHorizontalAlignment(gfx::ALIGN_LEFT); title->SetFont(title->font().DeriveFont(4)); title->SetEnabledColor(kTitleColor); title->SetBackgroundColor(kTitleBackgroundColor); title->set_border(MakePadding(kTextTopPadding, 0, 3, kTextToClosePadding)); layout->AddView(title, 1, 2); // First row: Close button padding. views::View* padding = new views::ImageView(); padding->set_border(MakePadding(kCloseTopPadding, 1, 0, 0)); layout->AddView(padding); // Second row: Close button, which has to be on a row of its own because its // top padding can't be set using empty borders (ImageButtons don't support // borders). The resize factor of this row (100) is much higher than that of // other rows (0) to ensure the first row's height stays at kCloseTopPadding. layout->StartRow(100, 0); layout->SkipColumns(2); DCHECK(close_button_); layout->AddView(close_button_); // One row for each notification item, including appropriate padding. for (int i = 0, n = notification_.items.size(); i < n; ++i) { int bottom_padding = (i < n - 1) ? 4 : (kTextBottomPadding - 2); layout->StartRow(0, 0); layout->SkipColumns(1); ItemView* item = new ItemView(notification_.items[i]); item->set_border(MakePadding(0, 0, bottom_padding, kTextToClosePadding)); layout->AddView(item); layout->SkipColumns(1); } } } // namespace message_center <commit_msg>Added ellipses when the title of notifications is too long.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/message_center/notification_view.h" #include "base/utf_string_conversions.h" #include "grit/ui_resources.h" #include "ui/base/accessibility/accessible_view_state.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/text/text_elider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/size.h" #include "ui/message_center/message_center_constants.h" #include "ui/native_theme/native_theme.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/grid_layout.h" namespace { // Notification dimensions. const int kIconLeftPadding = 0; const int kIconColumnWidth = message_center::kNotificationIconWidth; const int kIconToTextPadding = 15; const int kTextToClosePadding = 10; const int kCloseColumnWidth = 8; const int kCloseRightPadding = 6; const int kIconTopPadding = 0; const int kTextTopPadding = 9; const int kCloseTopPadding = 6; const int kIconBottomPadding = 0; const int kTextBottomPadding = 12; const int kItemTitleToDetailsPadding = 3; // Notification colors. The text background colors below are used only to keep // view::Label from modifying the text color and will not actually be drawn. // See view::Label's SetEnabledColor() and SetBackgroundColor() for details. const SkColor kBackgroundColor = SkColorSetRGB(255, 255, 255); const SkColor kTitleColor = SkColorSetRGB(68, 68, 68); const SkColor kTitleBackgroundColor = SK_ColorWHITE; const SkColor kMessageColor = SkColorSetRGB(136, 136, 136); const SkColor kMessageBackgroundColor = SK_ColorBLACK; // Static function to create an empty border to be used as padding. views::Border* MakePadding(int top, int left, int bottom, int right) { return views::Border::CreateEmptyBorder(top, left, bottom, right); } // ItemViews are responsible for drawing each NotificationView item's title and // message next to each other within a single column. class ItemView : public views::View { public: ItemView(const message_center::NotificationList::NotificationItem& item); virtual ~ItemView(); private: DISALLOW_COPY_AND_ASSIGN(ItemView); }; ItemView::ItemView( const message_center::NotificationList::NotificationItem& item) { views::BoxLayout* layout = new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, kItemTitleToDetailsPadding); SetLayoutManager(layout); views::Label* title = new views::Label(item.title); title->SetHorizontalAlignment(gfx::ALIGN_LEFT); title->SetElideBehavior(views::Label::ELIDE_AT_END); title->SetEnabledColor(kTitleColor); title->SetBackgroundColor(kTitleBackgroundColor); AddChildViewAt(title, 0); views::Label* details = new views::Label(item.message); details->SetHorizontalAlignment(gfx::ALIGN_LEFT); details->SetElideBehavior(views::Label::ELIDE_AT_END); details->SetEnabledColor(kMessageColor); details->SetBackgroundColor(kMessageBackgroundColor); AddChildViewAt(details, 1); PreferredSizeChanged(); SchedulePaint(); } ItemView::~ItemView() { } } // namespace namespace message_center { NotificationView::NotificationView( NotificationList::Delegate* list_delegate, const NotificationList::Notification& notification) : MessageView(list_delegate, notification) { } NotificationView::~NotificationView() { } void NotificationView::SetUpView() { set_background(views::Background::CreateSolidBackground(kBackgroundColor)); views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); // Three columns (icon, text, close button) surrounded by padding. The icon // and close button columns and the padding have fixed widths and the text // column fills up the remaining space. To minimize the number of columns and // simplify column spanning padding is applied to each view within columns // instead of through padding columns. views::ColumnSet* columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::FIXED, kIconLeftPadding + kIconColumnWidth + kIconToTextPadding, kIconLeftPadding + kIconColumnWidth + kIconToTextPadding); // Padding + icon + padding. columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 100, views::GridLayout::USE_PREF, 0, 0); // Text + padding (kTextToClosePadding). columns->AddColumn(views::GridLayout::LEADING, views::GridLayout::LEADING, 0, views::GridLayout::FIXED, kCloseColumnWidth + kCloseRightPadding, kCloseColumnWidth + kCloseRightPadding); // Close button + padding. // First row: Icon. This vertically spans the close button padding row, the // close button row, and all item rows. layout->StartRow(0, 0); views::ImageView* icon = new views::ImageView(); icon->SetImageSize(gfx::Size(message_center::kNotificationIconWidth, message_center::kNotificationIconWidth)); icon->SetImage(notification_.primary_icon); icon->SetHorizontalAlignment(views::ImageView::LEADING); icon->SetVerticalAlignment(views::ImageView::LEADING); icon->set_border(MakePadding(kIconTopPadding, kIconLeftPadding, kIconBottomPadding, kIconToTextPadding)); layout->AddView(icon, 1, 2 + notification_.items.size()); // First row: Title. This vertically spans the close button padding row and // the close button row. // TODO(dharcourt): Skip the title Label when there's no title text. views::Label* title = new views::Label(notification_.title); title->SetHorizontalAlignment(gfx::ALIGN_LEFT); title->SetElideBehavior(views::Label::ELIDE_AT_END); title->SetFont(title->font().DeriveFont(4)); title->SetEnabledColor(kTitleColor); title->SetBackgroundColor(kTitleBackgroundColor); title->set_border(MakePadding(kTextTopPadding, 0, 3, kTextToClosePadding)); layout->AddView(title, 1, 2); // First row: Close button padding. views::View* padding = new views::ImageView(); padding->set_border(MakePadding(kCloseTopPadding, 1, 0, 0)); layout->AddView(padding); // Second row: Close button, which has to be on a row of its own because its // top padding can't be set using empty borders (ImageButtons don't support // borders). The resize factor of this row (100) is much higher than that of // other rows (0) to ensure the first row's height stays at kCloseTopPadding. layout->StartRow(100, 0); layout->SkipColumns(2); DCHECK(close_button_); layout->AddView(close_button_); // One row for each notification item, including appropriate padding. for (int i = 0, n = notification_.items.size(); i < n; ++i) { int bottom_padding = (i < n - 1) ? 4 : (kTextBottomPadding - 2); layout->StartRow(0, 0); layout->SkipColumns(1); ItemView* item = new ItemView(notification_.items[i]); item->set_border(MakePadding(0, 0, bottom_padding, kTextToClosePadding)); layout->AddView(item); layout->SkipColumns(1); } } } // namespace message_center <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/clipboard/clipboard.h" #include <gtk/gtk.h> #include <map> #include <set> #include <string> #include <utility> #include "base/file_path.h" #include "base/gfx/size.h" #include "base/scoped_ptr.h" #include "base/linux_util.h" #include "base/string_util.h" namespace { const char kMimeBmp[] = "image/bmp"; const char kMimeHtml[] = "text/html"; const char kMimeText[] = "text/plain"; const char kMimeURI[] = "text/uri-list"; const char kMimeWebkitSmartPaste[] = "chromium/x-webkit-paste"; std::string GdkAtomToString(const GdkAtom& atom) { gchar* name = gdk_atom_name(atom); std::string rv(name); g_free(name); return rv; } GdkAtom StringToGdkAtom(const std::string& str) { return gdk_atom_intern(str.c_str(), FALSE); } // GtkClipboardGetFunc callback. // GTK will call this when an application wants data we copied to the clipboard. void GetData(GtkClipboard* clipboard, GtkSelectionData* selection_data, guint info, gpointer user_data) { Clipboard::TargetMap* data_map = reinterpret_cast<Clipboard::TargetMap*>(user_data); std::string target_string = GdkAtomToString(selection_data->target); Clipboard::TargetMap::iterator iter = data_map->find(target_string); if (iter == data_map->end()) return; if (target_string == kMimeBmp) { gtk_selection_data_set_pixbuf(selection_data, reinterpret_cast<GdkPixbuf*>(iter->second.first)); } else if (target_string == kMimeURI) { gchar* uri_list[2]; uri_list[0] = reinterpret_cast<gchar*>(iter->second.first); uri_list[1] = NULL; gtk_selection_data_set_uris(selection_data, uri_list); } else { gtk_selection_data_set(selection_data, selection_data->target, 8, reinterpret_cast<guchar*>(iter->second.first), iter->second.second); } } // GtkClipboardClearFunc callback. // We are guaranteed this will be called exactly once for each call to // gtk_clipboard_set_with_data. void ClearData(GtkClipboard* clipboard, gpointer user_data) { Clipboard::TargetMap* map = reinterpret_cast<Clipboard::TargetMap*>(user_data); // The same data may be inserted under multiple keys, so use a set to // uniq them. std::set<char*> ptrs; for (Clipboard::TargetMap::iterator iter = map->begin(); iter != map->end(); ++iter) { if (iter->first == kMimeBmp) g_object_unref(reinterpret_cast<GdkPixbuf*>(iter->second.first)); else ptrs.insert(iter->second.first); } for (std::set<char*>::iterator iter = ptrs.begin(); iter != ptrs.end(); ++iter) { delete[] *iter; } delete map; } // Called on GdkPixbuf destruction; see WriteBitmap(). void GdkPixbufFree(guchar* pixels, gpointer data) { free(pixels); } } // namespace Clipboard::Clipboard() { clipboard_ = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); primary_selection_ = gtk_clipboard_get(GDK_SELECTION_PRIMARY); } Clipboard::~Clipboard() { // TODO(estade): do we want to save clipboard data after we exit? // gtk_clipboard_set_can_store and gtk_clipboard_store work // but have strangely awful performance. } void Clipboard::WriteObjects(const ObjectMap& objects) { clipboard_data_ = new TargetMap(); for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); ++iter) { DispatchObject(static_cast<ObjectType>(iter->first), iter->second); } SetGtkClipboard(); } // When a URL is copied from a render view context menu (via "copy link // location", for example), we additionally stick it in the X clipboard. This // matches other linux browsers. void Clipboard::DidWriteURL(const std::string& utf8_text) { gtk_clipboard_set_text(primary_selection_, utf8_text.c_str(), utf8_text.length()); } // Take ownership of the GTK clipboard and inform it of the targets we support. void Clipboard::SetGtkClipboard() { scoped_array<GtkTargetEntry> targets( new GtkTargetEntry[clipboard_data_->size()]); int i = 0; for (Clipboard::TargetMap::iterator iter = clipboard_data_->begin(); iter != clipboard_data_->end(); ++iter, ++i) { targets[i].target = const_cast<char*>(iter->first.c_str()); targets[i].flags = 0; targets[i].info = 0; } gtk_clipboard_set_with_data(clipboard_, targets.get(), clipboard_data_->size(), GetData, ClearData, clipboard_data_); // clipboard_data_ now owned by the GtkClipboard. clipboard_data_ = NULL; } void Clipboard::WriteText(const char* text_data, size_t text_len) { char* data = new char[text_len]; memcpy(data, text_data, text_len); InsertMapping(kMimeText, data, text_len); InsertMapping("TEXT", data, text_len); InsertMapping("STRING", data, text_len); InsertMapping("UTF8_STRING", data, text_len); InsertMapping("COMPOUND_TEXT", data, text_len); } void Clipboard::WriteHTML(const char* markup_data, size_t markup_len, const char* url_data, size_t url_len) { // TODO(estade): We need to expand relative links with |url_data|. static const char* html_prefix = "<meta http-equiv=\"content-type\" " "content=\"text/html; charset=utf-8\">"; int html_prefix_len = strlen(html_prefix); int total_len = html_prefix_len + markup_len; char* data = new char[total_len]; snprintf(data, total_len, "%s", html_prefix); memcpy(data + html_prefix_len, markup_data, markup_len); InsertMapping(kMimeHtml, data, total_len); } // Write an extra flavor that signifies WebKit was the last to modify the // pasteboard. This flavor has no data. void Clipboard::WriteWebSmartPaste() { InsertMapping(kMimeWebkitSmartPaste, NULL, 0); } void Clipboard::WriteBitmap(const char* pixel_data, const char* size_data) { const gfx::Size* size = reinterpret_cast<const gfx::Size*>(size_data); guchar* data = base::BGRAToRGBA(reinterpret_cast<const uint8_t*>(pixel_data), size->width(), size->height(), 0); GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB, TRUE, 8, size->width(), size->height(), size->width() * 4, GdkPixbufFree, NULL); // We store the GdkPixbuf*, and the size_t half of the pair is meaningless. // Note that this contrasts with the vast majority of entries in our target // map, which directly store the data and its length. InsertMapping(kMimeBmp, reinterpret_cast<char*>(pixbuf), 0); } void Clipboard::WriteBookmark(const char* title_data, size_t title_len, const char* url_data, size_t url_len) { // Write as a URI. char* data = new char[url_len + 1]; memcpy(data, url_data, url_len); data[url_len] = '\0'; InsertMapping(kMimeURI, data, url_len + 1); } void Clipboard::WriteData(const char* format_name, size_t format_len, const char* data_data, size_t data_len) { char* data = new char[data_len]; memcpy(data, data_data, data_len); std::string format(format_name, format_len); InsertMapping(format.c_str(), data, data_len); } // We do not use gtk_clipboard_wait_is_target_available because of // a bug with the gtk clipboard. It caches the available targets // and does not always refresh the cache when it is appropriate. bool Clipboard::IsFormatAvailable(const Clipboard::FormatType& format, Clipboard::Buffer buffer) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return false; bool format_is_plain_text = GetPlainTextFormatType() == format; if (format_is_plain_text) { // This tries a number of common text targets. if (gtk_clipboard_wait_is_text_available(clipboard)) return true; } bool retval = false; GdkAtom* targets = NULL; GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, gdk_atom_intern("TARGETS", false)); if (!data) return false; int num = 0; gtk_selection_data_get_targets(data, &targets, &num); // Some programs post data to the clipboard without any targets. If this is // the case we attempt to make sense of the contents as text. This is pretty // unfortunate since it means we have to actually copy the data to see if it // is available, but at least this path shouldn't be hit for conforming // programs. if (num <= 0) { if (format_is_plain_text) { gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text) { g_free(text); retval = true; } } } GdkAtom format_atom = StringToGdkAtom(format); for (int i = 0; i < num; i++) { if (targets[i] == format_atom) { retval = true; break; } } g_free(targets); gtk_selection_data_free(data); return retval; } bool Clipboard::IsFormatAvailableByString(const std::string& format, Clipboard::Buffer buffer) const { return IsFormatAvailable(format, buffer); } void Clipboard::ReadText(Clipboard::Buffer buffer, string16* result) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; result->clear(); gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text == NULL) return; // TODO(estade): do we want to handle the possible error here? UTF8ToUTF16(text, strlen(text), result); g_free(text); } void Clipboard::ReadAsciiText(Clipboard::Buffer buffer, std::string* result) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; result->clear(); gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text == NULL) return; result->assign(text); g_free(text); } void Clipboard::ReadFile(FilePath* file) const { *file = FilePath(); } // TODO(estade): handle different charsets. // TODO(port): set *src_url. void Clipboard::ReadHTML(Clipboard::Buffer buffer, string16* markup, std::string* src_url) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; markup->clear(); GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, StringToGdkAtom(GetHtmlFormatType())); if (!data) return; // If the data starts with 0xFEFF, i.e., Byte Order Mark, assume it is // UTF-16, otherwise assume UTF-8. if (data->length >= 2 && reinterpret_cast<uint16_t*>(data->data)[0] == 0xFEFF) { markup->assign(reinterpret_cast<uint16_t*>(data->data) + 1, (data->length / 2) - 1); } else { UTF8ToUTF16(reinterpret_cast<char*>(data->data), data->length, markup); } gtk_selection_data_free(data); } void Clipboard::ReadBookmark(string16* title, std::string* url) const { // TODO(estade): implement this. } void Clipboard::ReadData(const std::string& format, std::string* result) { GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard_, StringToGdkAtom(format)); if (!data) return; result->assign(reinterpret_cast<char*>(data->data), data->length); gtk_selection_data_free(data); } // static Clipboard::FormatType Clipboard::GetPlainTextFormatType() { return GdkAtomToString(GDK_TARGET_STRING); } // static Clipboard::FormatType Clipboard::GetPlainTextWFormatType() { return GetPlainTextFormatType(); } // static Clipboard::FormatType Clipboard::GetHtmlFormatType() { return std::string(kMimeHtml); } // static Clipboard::FormatType Clipboard::GetWebKitSmartPasteFormatType() { return std::string(kMimeWebkitSmartPaste); } void Clipboard::InsertMapping(const char* key, char* data, size_t data_len) { DCHECK(clipboard_data_->find(key) == clipboard_data_->end()); (*clipboard_data_)[key] = std::make_pair(data, data_len); } GtkClipboard* Clipboard::LookupBackingClipboard(Buffer clipboard) const { switch (clipboard) { case BUFFER_STANDARD: return clipboard_; case BUFFER_SELECTION: return primary_selection_; default: NOTREACHED(); return NULL; } } <commit_msg>Don't shoehorn a size_t into an int -- especially if the int is used in an subsequent allocation.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/clipboard/clipboard.h" #include <gtk/gtk.h> #include <map> #include <set> #include <string> #include <utility> #include "base/file_path.h" #include "base/gfx/size.h" #include "base/scoped_ptr.h" #include "base/linux_util.h" #include "base/string_util.h" namespace { const char kMimeBmp[] = "image/bmp"; const char kMimeHtml[] = "text/html"; const char kMimeText[] = "text/plain"; const char kMimeURI[] = "text/uri-list"; const char kMimeWebkitSmartPaste[] = "chromium/x-webkit-paste"; std::string GdkAtomToString(const GdkAtom& atom) { gchar* name = gdk_atom_name(atom); std::string rv(name); g_free(name); return rv; } GdkAtom StringToGdkAtom(const std::string& str) { return gdk_atom_intern(str.c_str(), FALSE); } // GtkClipboardGetFunc callback. // GTK will call this when an application wants data we copied to the clipboard. void GetData(GtkClipboard* clipboard, GtkSelectionData* selection_data, guint info, gpointer user_data) { Clipboard::TargetMap* data_map = reinterpret_cast<Clipboard::TargetMap*>(user_data); std::string target_string = GdkAtomToString(selection_data->target); Clipboard::TargetMap::iterator iter = data_map->find(target_string); if (iter == data_map->end()) return; if (target_string == kMimeBmp) { gtk_selection_data_set_pixbuf(selection_data, reinterpret_cast<GdkPixbuf*>(iter->second.first)); } else if (target_string == kMimeURI) { gchar* uri_list[2]; uri_list[0] = reinterpret_cast<gchar*>(iter->second.first); uri_list[1] = NULL; gtk_selection_data_set_uris(selection_data, uri_list); } else { gtk_selection_data_set(selection_data, selection_data->target, 8, reinterpret_cast<guchar*>(iter->second.first), iter->second.second); } } // GtkClipboardClearFunc callback. // We are guaranteed this will be called exactly once for each call to // gtk_clipboard_set_with_data. void ClearData(GtkClipboard* clipboard, gpointer user_data) { Clipboard::TargetMap* map = reinterpret_cast<Clipboard::TargetMap*>(user_data); // The same data may be inserted under multiple keys, so use a set to // uniq them. std::set<char*> ptrs; for (Clipboard::TargetMap::iterator iter = map->begin(); iter != map->end(); ++iter) { if (iter->first == kMimeBmp) g_object_unref(reinterpret_cast<GdkPixbuf*>(iter->second.first)); else ptrs.insert(iter->second.first); } for (std::set<char*>::iterator iter = ptrs.begin(); iter != ptrs.end(); ++iter) { delete[] *iter; } delete map; } // Called on GdkPixbuf destruction; see WriteBitmap(). void GdkPixbufFree(guchar* pixels, gpointer data) { free(pixels); } } // namespace Clipboard::Clipboard() { clipboard_ = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); primary_selection_ = gtk_clipboard_get(GDK_SELECTION_PRIMARY); } Clipboard::~Clipboard() { // TODO(estade): do we want to save clipboard data after we exit? // gtk_clipboard_set_can_store and gtk_clipboard_store work // but have strangely awful performance. } void Clipboard::WriteObjects(const ObjectMap& objects) { clipboard_data_ = new TargetMap(); for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); ++iter) { DispatchObject(static_cast<ObjectType>(iter->first), iter->second); } SetGtkClipboard(); } // When a URL is copied from a render view context menu (via "copy link // location", for example), we additionally stick it in the X clipboard. This // matches other linux browsers. void Clipboard::DidWriteURL(const std::string& utf8_text) { gtk_clipboard_set_text(primary_selection_, utf8_text.c_str(), utf8_text.length()); } // Take ownership of the GTK clipboard and inform it of the targets we support. void Clipboard::SetGtkClipboard() { scoped_array<GtkTargetEntry> targets( new GtkTargetEntry[clipboard_data_->size()]); int i = 0; for (Clipboard::TargetMap::iterator iter = clipboard_data_->begin(); iter != clipboard_data_->end(); ++iter, ++i) { targets[i].target = const_cast<char*>(iter->first.c_str()); targets[i].flags = 0; targets[i].info = 0; } gtk_clipboard_set_with_data(clipboard_, targets.get(), clipboard_data_->size(), GetData, ClearData, clipboard_data_); // clipboard_data_ now owned by the GtkClipboard. clipboard_data_ = NULL; } void Clipboard::WriteText(const char* text_data, size_t text_len) { char* data = new char[text_len]; memcpy(data, text_data, text_len); InsertMapping(kMimeText, data, text_len); InsertMapping("TEXT", data, text_len); InsertMapping("STRING", data, text_len); InsertMapping("UTF8_STRING", data, text_len); InsertMapping("COMPOUND_TEXT", data, text_len); } void Clipboard::WriteHTML(const char* markup_data, size_t markup_len, const char* url_data, size_t url_len) { // TODO(estade): We need to expand relative links with |url_data|. static const char* html_prefix = "<meta http-equiv=\"content-type\" " "content=\"text/html; charset=utf-8\">"; size_t html_prefix_len = strlen(html_prefix); size_t total_len = html_prefix_len + markup_len; char* data = new char[total_len]; snprintf(data, total_len, "%s", html_prefix); memcpy(data + html_prefix_len, markup_data, markup_len); InsertMapping(kMimeHtml, data, total_len); } // Write an extra flavor that signifies WebKit was the last to modify the // pasteboard. This flavor has no data. void Clipboard::WriteWebSmartPaste() { InsertMapping(kMimeWebkitSmartPaste, NULL, 0); } void Clipboard::WriteBitmap(const char* pixel_data, const char* size_data) { const gfx::Size* size = reinterpret_cast<const gfx::Size*>(size_data); guchar* data = base::BGRAToRGBA(reinterpret_cast<const uint8_t*>(pixel_data), size->width(), size->height(), 0); GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB, TRUE, 8, size->width(), size->height(), size->width() * 4, GdkPixbufFree, NULL); // We store the GdkPixbuf*, and the size_t half of the pair is meaningless. // Note that this contrasts with the vast majority of entries in our target // map, which directly store the data and its length. InsertMapping(kMimeBmp, reinterpret_cast<char*>(pixbuf), 0); } void Clipboard::WriteBookmark(const char* title_data, size_t title_len, const char* url_data, size_t url_len) { // Write as a URI. char* data = new char[url_len + 1]; memcpy(data, url_data, url_len); data[url_len] = '\0'; InsertMapping(kMimeURI, data, url_len + 1); } void Clipboard::WriteData(const char* format_name, size_t format_len, const char* data_data, size_t data_len) { char* data = new char[data_len]; memcpy(data, data_data, data_len); std::string format(format_name, format_len); InsertMapping(format.c_str(), data, data_len); } // We do not use gtk_clipboard_wait_is_target_available because of // a bug with the gtk clipboard. It caches the available targets // and does not always refresh the cache when it is appropriate. bool Clipboard::IsFormatAvailable(const Clipboard::FormatType& format, Clipboard::Buffer buffer) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return false; bool format_is_plain_text = GetPlainTextFormatType() == format; if (format_is_plain_text) { // This tries a number of common text targets. if (gtk_clipboard_wait_is_text_available(clipboard)) return true; } bool retval = false; GdkAtom* targets = NULL; GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, gdk_atom_intern("TARGETS", false)); if (!data) return false; int num = 0; gtk_selection_data_get_targets(data, &targets, &num); // Some programs post data to the clipboard without any targets. If this is // the case we attempt to make sense of the contents as text. This is pretty // unfortunate since it means we have to actually copy the data to see if it // is available, but at least this path shouldn't be hit for conforming // programs. if (num <= 0) { if (format_is_plain_text) { gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text) { g_free(text); retval = true; } } } GdkAtom format_atom = StringToGdkAtom(format); for (int i = 0; i < num; i++) { if (targets[i] == format_atom) { retval = true; break; } } g_free(targets); gtk_selection_data_free(data); return retval; } bool Clipboard::IsFormatAvailableByString(const std::string& format, Clipboard::Buffer buffer) const { return IsFormatAvailable(format, buffer); } void Clipboard::ReadText(Clipboard::Buffer buffer, string16* result) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; result->clear(); gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text == NULL) return; // TODO(estade): do we want to handle the possible error here? UTF8ToUTF16(text, strlen(text), result); g_free(text); } void Clipboard::ReadAsciiText(Clipboard::Buffer buffer, std::string* result) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; result->clear(); gchar* text = gtk_clipboard_wait_for_text(clipboard); if (text == NULL) return; result->assign(text); g_free(text); } void Clipboard::ReadFile(FilePath* file) const { *file = FilePath(); } // TODO(estade): handle different charsets. // TODO(port): set *src_url. void Clipboard::ReadHTML(Clipboard::Buffer buffer, string16* markup, std::string* src_url) const { GtkClipboard* clipboard = LookupBackingClipboard(buffer); if (clipboard == NULL) return; markup->clear(); GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, StringToGdkAtom(GetHtmlFormatType())); if (!data) return; // If the data starts with 0xFEFF, i.e., Byte Order Mark, assume it is // UTF-16, otherwise assume UTF-8. if (data->length >= 2 && reinterpret_cast<uint16_t*>(data->data)[0] == 0xFEFF) { markup->assign(reinterpret_cast<uint16_t*>(data->data) + 1, (data->length / 2) - 1); } else { UTF8ToUTF16(reinterpret_cast<char*>(data->data), data->length, markup); } gtk_selection_data_free(data); } void Clipboard::ReadBookmark(string16* title, std::string* url) const { // TODO(estade): implement this. } void Clipboard::ReadData(const std::string& format, std::string* result) { GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard_, StringToGdkAtom(format)); if (!data) return; result->assign(reinterpret_cast<char*>(data->data), data->length); gtk_selection_data_free(data); } // static Clipboard::FormatType Clipboard::GetPlainTextFormatType() { return GdkAtomToString(GDK_TARGET_STRING); } // static Clipboard::FormatType Clipboard::GetPlainTextWFormatType() { return GetPlainTextFormatType(); } // static Clipboard::FormatType Clipboard::GetHtmlFormatType() { return std::string(kMimeHtml); } // static Clipboard::FormatType Clipboard::GetWebKitSmartPasteFormatType() { return std::string(kMimeWebkitSmartPaste); } void Clipboard::InsertMapping(const char* key, char* data, size_t data_len) { DCHECK(clipboard_data_->find(key) == clipboard_data_->end()); (*clipboard_data_)[key] = std::make_pair(data, data_len); } GtkClipboard* Clipboard::LookupBackingClipboard(Buffer clipboard) const { switch (clipboard) { case BUFFER_STANDARD: return clipboard_; case BUFFER_SELECTION: return primary_selection_; default: NOTREACHED(); return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/external_tab_container.h" #include "app/win_util.h" #include "base/logging.h" #include "base/win_util.h" #include "chrome/browser/automation/automation_provider.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" #include "chrome/browser/load_notification_details.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/provisional_load_details.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/tab_contents/tab_contents_container.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/notification_service.h" #include "chrome/test/automation/automation_messages.h" static const wchar_t kWindowObjectKey[] = L"ChromeWindowObject"; // TODO(sanjeevr): The external_accel_table_ and external_accel_entry_count_ // member variables are now obsolete and we don't use them. // We need to remove them. ExternalTabContainer::ExternalTabContainer( AutomationProvider* automation) : automation_(automation), tab_contents_(NULL), external_accel_table_(NULL), external_accel_entry_count_(0), tab_contents_container_(NULL), tab_handle_(0), ignore_next_load_notification_(false) { } ExternalTabContainer::~ExternalTabContainer() { Uninitialize(GetNativeView()); } bool ExternalTabContainer::Init(Profile* profile, HWND parent, const gfx::Rect& bounds, DWORD style) { if (IsWindow()) { NOTREACHED(); return false; } set_window_style(WS_POPUP); views::WidgetWin::Init(NULL, bounds, true); if (!IsWindow()) { NOTREACHED(); return false; } // We don't ever remove the prop because the lifetime of this object // is the same as the lifetime of the window SetProp(GetNativeView(), kWindowObjectKey, this); views::FocusManager* focus_manager = views::FocusManager::GetFocusManager(GetNativeView()); focus_manager->AddKeystrokeListener(this); tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL); tab_contents_->set_delegate(this); tab_contents_->render_view_host()->AllowExternalHostBindings(); // Create a TabContentsContainer to handle focus cycling using Tab and // Shift-Tab. tab_contents_container_ = new TabContentsContainer; SetContentsView(tab_contents_container_); // Note that SetTabContents must be called after AddChildView is called tab_contents_container_->ChangeTabContents(tab_contents_); NavigationController* controller = &tab_contents_->controller(); registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, Source<NavigationController>(controller)); registrar_.Add(this, NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR, Source<NavigationController>(controller)); registrar_.Add(this, NotificationType::LOAD_STOP, Source<NavigationController>(controller)); NotificationService::current()->Notify( NotificationType::EXTERNAL_TAB_CREATED, Source<NavigationController>(controller), NotificationService::NoDetails()); // We need WS_POPUP to be on the window during initialization, but // once initialized we apply the requested style which may or may not // include the popup bit. // Note that it's important to do this before we call SetParent since // during the SetParent call we will otherwise get a WA_ACTIVATE call // that causes us to steal the current focus. SetWindowLong(GWL_STYLE, (GetWindowLong(GWL_STYLE) & ~WS_POPUP) | style); // Now apply the parenting and style if (parent) SetParent(GetNativeView(), parent); ::ShowWindow(tab_contents_->GetNativeView(), SW_SHOWNA); return true; } void ExternalTabContainer::SetAccelerators(HACCEL accel_table, int accel_table_entry_count) { external_accel_table_ = accel_table; external_accel_entry_count_ = accel_table_entry_count; } void ExternalTabContainer::ProcessUnhandledAccelerator(const MSG& msg) { // We just received an accelerator key that we had sent to external host // back. Since the external host was not interested in handling this, we // need to dispatch this message as if we had just peeked this out. (we // also need to call TranslateMessage to generate a WM_CHAR if needed). TranslateMessage(&msg); DispatchMessage(&msg); } void ExternalTabContainer::SetInitialFocus(bool reverse) { DCHECK(tab_contents_); if (tab_contents_) { static_cast<TabContents*>(tab_contents_)->Focus(); static_cast<TabContents*>(tab_contents_)->SetInitialFocus(reverse); } } // static bool ExternalTabContainer::IsExternalTabContainer(HWND window) { if (GetProp(window, kWindowObjectKey) != NULL) return true; return false; } // static ExternalTabContainer* ExternalTabContainer::GetContainerForTab( HWND tab_window) { HWND parent_window = ::GetParent(tab_window); if (!::IsWindow(parent_window)) { return NULL; } if (!IsExternalTabContainer(parent_window)) { return NULL; } ExternalTabContainer* container = reinterpret_cast<ExternalTabContainer*>( GetProp(parent_window, kWindowObjectKey)); return container; } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, TabContentsDelegate implementation: void ExternalTabContainer::OpenURLFromTab(TabContents* source, const GURL& url, const GURL& referrer, WindowOpenDisposition disposition, PageTransition::Type transition) { switch (disposition) { case CURRENT_TAB: case SINGLETON_TAB: case NEW_FOREGROUND_TAB: case NEW_BACKGROUND_TAB: case NEW_WINDOW: if (automation_) { automation_->Send(new AutomationMsg_OpenURL(0, tab_handle_, url, disposition)); } break; default: break; } } void ExternalTabContainer::NavigationStateChanged(const TabContents* source, unsigned changed_flags) { if (automation_) { automation_->Send(new AutomationMsg_NavigationStateChanged(0, tab_handle_, changed_flags)); } } void ExternalTabContainer::AddNewContents(TabContents* source, TabContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture) { if (disposition == NEW_POPUP || disposition == NEW_WINDOW) { Browser::BuildPopupWindowHelper(source, new_contents, initial_pos, Browser::TYPE_POPUP, tab_contents_->profile(), true); } else { NOTREACHED(); } } void ExternalTabContainer::ActivateContents(TabContents* contents) { } void ExternalTabContainer::LoadingStateChanged(TabContents* source) { } void ExternalTabContainer::CloseContents(TabContents* source) { } void ExternalTabContainer::MoveContents(TabContents* source, const gfx::Rect& pos) { } bool ExternalTabContainer::IsPopup(TabContents* source) { return false; } void ExternalTabContainer::URLStarredChanged(TabContents* source, bool starred) { } void ExternalTabContainer::UpdateTargetURL(TabContents* source, const GURL& url) { if (automation_) { std::wstring url_string = CA2W(url.spec().c_str()); automation_->Send( new AutomationMsg_UpdateTargetUrl(0, tab_handle_, url_string)); } } void ExternalTabContainer::ContentsZoomChange(bool zoom_in) { } void ExternalTabContainer::ToolbarSizeChanged(TabContents* source, bool finished) { } void ExternalTabContainer::ForwardMessageToExternalHost( const std::string& message, const std::string& origin, const std::string& target) { if(automation_) { automation_->Send( new AutomationMsg_ForwardMessageToExternalHost(0, tab_handle_, message, origin, target)); } } ExtensionFunctionDispatcher* ExternalTabContainer:: CreateExtensionFunctionDispatcher(RenderViewHost* render_view_host, const std::string& extension_id) { return new ExtensionFunctionDispatcher(render_view_host, NULL, extension_id); } bool ExternalTabContainer::TakeFocus(bool reverse) { if (automation_) { views::FocusManager* focus_manager = views::FocusManager::GetFocusManager(GetNativeView()); DCHECK(focus_manager); if (focus_manager) { focus_manager->ClearFocus(); automation_->Send(new AutomationMsg_TabbedOut(0, tab_handle_, win_util::IsShiftPressed())); } } return true; } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, NotificationObserver implementation: void ExternalTabContainer::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (!automation_) return; static const int kHttpClientErrorStart = 400; static const int kHttpServerErrorEnd = 510; switch (type.value) { case NotificationType::LOAD_STOP: { const LoadNotificationDetails* load = Details<LoadNotificationDetails>(details).ptr(); if (load != NULL && PageTransition::IsMainFrame(load->origin())) { automation_->Send(new AutomationMsg_TabLoaded(0, tab_handle_, load->url())); } break; } case NotificationType::NAV_ENTRY_COMMITTED: { if (ignore_next_load_notification_) { ignore_next_load_notification_ = false; return; } const NavigationController::LoadCommittedDetails* commit = Details<NavigationController::LoadCommittedDetails>(details).ptr(); if (commit->http_status_code >= kHttpClientErrorStart && commit->http_status_code <= kHttpServerErrorEnd) { automation_->Send(new AutomationMsg_NavigationFailed( 0, tab_handle_, commit->http_status_code, commit->entry->url())); ignore_next_load_notification_ = true; } else { // When the previous entry index is invalid, it will be -1, which // will still make the computation come out right (navigating to the // 0th entry will be +1). automation_->Send(new AutomationMsg_DidNavigate( 0, tab_handle_, commit->type, commit->previous_entry_index - tab_contents_->controller().last_committed_entry_index(), commit->entry->url())); } break; } case NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR: { const ProvisionalLoadDetails* load_details = Details<ProvisionalLoadDetails>(details).ptr(); automation_->Send(new AutomationMsg_NavigationFailed( 0, tab_handle_, load_details->error_code(), load_details->url())); ignore_next_load_notification_ = true; break; } default: NOTREACHED(); } } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, views::WidgetWin overrides: void ExternalTabContainer::OnDestroy() { Uninitialize(GetNativeView()); WidgetWin::OnDestroy(); } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, views::KeystrokeListener implementation: bool ExternalTabContainer::ProcessKeyStroke(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { if (!automation_) { return false; } if ((wparam == VK_TAB) && !win_util::IsCtrlPressed()) { // Tabs are handled separately (except if this is Ctrl-Tab or // Ctrl-Shift-Tab) return false; } unsigned int flags = HIWORD(lparam); bool alt = (flags & KF_ALTDOWN) != 0; if (!alt && (message == WM_SYSKEYUP || message == WM_KEYUP)) { // In case the Alt key is being released. alt = (wparam == VK_MENU); } if ((flags & KF_EXTENDED) || alt || (wparam >= VK_F1 && wparam <= VK_F24) || wparam == VK_ESCAPE || wparam == VK_RETURN || win_util::IsShiftPressed() || win_util::IsCtrlPressed()) { // If this is an extended key or if one or more of Alt, Shift and Control // are pressed, this might be an accelerator that the external host wants // to handle. If the host does not handle this accelerator, it will reflect // the accelerator back to us via the ProcessUnhandledAccelerator method. MSG msg = {0}; msg.hwnd = window; msg.message = message; msg.wParam = wparam; msg.lParam = lparam; automation_->Send(new AutomationMsg_HandleAccelerator(0, tab_handle_, msg)); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, private: void ExternalTabContainer::Uninitialize(HWND window) { if (::IsWindow(window)) { views::FocusManager* focus_manager = views::FocusManager::GetFocusManager(window); if (focus_manager) focus_manager->RemoveKeystrokeListener(this); } if (tab_contents_) { NotificationService::current()->Notify( NotificationType::EXTERNAL_TAB_CLOSED, Source<NavigationController>(&tab_contents_->controller()), Details<ExternalTabContainer>(this)); delete tab_contents_; tab_contents_ = NULL; } } <commit_msg>Re-apply 17223 (http://codereview.chromium.org/115943) to fix external tab handling of certain open dispositions.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/external_tab_container.h" #include "app/win_util.h" #include "base/logging.h" #include "base/win_util.h" #include "chrome/browser/automation/automation_provider.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extension_function_dispatcher.h" #include "chrome/browser/load_notification_details.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/provisional_load_details.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/tab_contents/tab_contents_container.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/notification_service.h" #include "chrome/test/automation/automation_messages.h" static const wchar_t kWindowObjectKey[] = L"ChromeWindowObject"; // TODO(sanjeevr): The external_accel_table_ and external_accel_entry_count_ // member variables are now obsolete and we don't use them. // We need to remove them. ExternalTabContainer::ExternalTabContainer( AutomationProvider* automation) : automation_(automation), tab_contents_(NULL), external_accel_table_(NULL), external_accel_entry_count_(0), tab_contents_container_(NULL), tab_handle_(0), ignore_next_load_notification_(false) { } ExternalTabContainer::~ExternalTabContainer() { Uninitialize(GetNativeView()); } bool ExternalTabContainer::Init(Profile* profile, HWND parent, const gfx::Rect& bounds, DWORD style) { if (IsWindow()) { NOTREACHED(); return false; } set_window_style(WS_POPUP); views::WidgetWin::Init(NULL, bounds, true); if (!IsWindow()) { NOTREACHED(); return false; } // We don't ever remove the prop because the lifetime of this object // is the same as the lifetime of the window SetProp(GetNativeView(), kWindowObjectKey, this); views::FocusManager* focus_manager = views::FocusManager::GetFocusManager(GetNativeView()); focus_manager->AddKeystrokeListener(this); tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL); tab_contents_->set_delegate(this); tab_contents_->render_view_host()->AllowExternalHostBindings(); // Create a TabContentsContainer to handle focus cycling using Tab and // Shift-Tab. tab_contents_container_ = new TabContentsContainer; SetContentsView(tab_contents_container_); // Note that SetTabContents must be called after AddChildView is called tab_contents_container_->ChangeTabContents(tab_contents_); NavigationController* controller = &tab_contents_->controller(); registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, Source<NavigationController>(controller)); registrar_.Add(this, NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR, Source<NavigationController>(controller)); registrar_.Add(this, NotificationType::LOAD_STOP, Source<NavigationController>(controller)); NotificationService::current()->Notify( NotificationType::EXTERNAL_TAB_CREATED, Source<NavigationController>(controller), NotificationService::NoDetails()); // We need WS_POPUP to be on the window during initialization, but // once initialized we apply the requested style which may or may not // include the popup bit. // Note that it's important to do this before we call SetParent since // during the SetParent call we will otherwise get a WA_ACTIVATE call // that causes us to steal the current focus. SetWindowLong(GWL_STYLE, (GetWindowLong(GWL_STYLE) & ~WS_POPUP) | style); // Now apply the parenting and style if (parent) SetParent(GetNativeView(), parent); ::ShowWindow(tab_contents_->GetNativeView(), SW_SHOWNA); return true; } void ExternalTabContainer::SetAccelerators(HACCEL accel_table, int accel_table_entry_count) { external_accel_table_ = accel_table; external_accel_entry_count_ = accel_table_entry_count; } void ExternalTabContainer::ProcessUnhandledAccelerator(const MSG& msg) { // We just received an accelerator key that we had sent to external host // back. Since the external host was not interested in handling this, we // need to dispatch this message as if we had just peeked this out. (we // also need to call TranslateMessage to generate a WM_CHAR if needed). TranslateMessage(&msg); DispatchMessage(&msg); } void ExternalTabContainer::SetInitialFocus(bool reverse) { DCHECK(tab_contents_); if (tab_contents_) { static_cast<TabContents*>(tab_contents_)->Focus(); static_cast<TabContents*>(tab_contents_)->SetInitialFocus(reverse); } } // static bool ExternalTabContainer::IsExternalTabContainer(HWND window) { if (GetProp(window, kWindowObjectKey) != NULL) return true; return false; } // static ExternalTabContainer* ExternalTabContainer::GetContainerForTab( HWND tab_window) { HWND parent_window = ::GetParent(tab_window); if (!::IsWindow(parent_window)) { return NULL; } if (!IsExternalTabContainer(parent_window)) { return NULL; } ExternalTabContainer* container = reinterpret_cast<ExternalTabContainer*>( GetProp(parent_window, kWindowObjectKey)); return container; } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, TabContentsDelegate implementation: void ExternalTabContainer::OpenURLFromTab(TabContents* source, const GURL& url, const GURL& referrer, WindowOpenDisposition disposition, PageTransition::Type transition) { switch (disposition) { case CURRENT_TAB: case SINGLETON_TAB: case NEW_FOREGROUND_TAB: case NEW_BACKGROUND_TAB: case NEW_WINDOW: if (automation_) { automation_->Send(new AutomationMsg_OpenURL(0, tab_handle_, url, disposition)); } break; default: break; } } void ExternalTabContainer::NavigationStateChanged(const TabContents* source, unsigned changed_flags) { if (automation_) { automation_->Send(new AutomationMsg_NavigationStateChanged(0, tab_handle_, changed_flags)); } } void ExternalTabContainer::AddNewContents(TabContents* source, TabContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture) { if (disposition == NEW_POPUP || disposition == NEW_WINDOW || disposition == NEW_FOREGROUND_TAB || disposition == NEW_BACKGROUND_TAB) { Browser::BuildPopupWindowHelper(source, new_contents, initial_pos, Browser::TYPE_POPUP, tab_contents_->profile(), true); } else { NOTREACHED(); } } void ExternalTabContainer::ActivateContents(TabContents* contents) { } void ExternalTabContainer::LoadingStateChanged(TabContents* source) { } void ExternalTabContainer::CloseContents(TabContents* source) { } void ExternalTabContainer::MoveContents(TabContents* source, const gfx::Rect& pos) { } bool ExternalTabContainer::IsPopup(TabContents* source) { return false; } void ExternalTabContainer::URLStarredChanged(TabContents* source, bool starred) { } void ExternalTabContainer::UpdateTargetURL(TabContents* source, const GURL& url) { if (automation_) { std::wstring url_string = CA2W(url.spec().c_str()); automation_->Send( new AutomationMsg_UpdateTargetUrl(0, tab_handle_, url_string)); } } void ExternalTabContainer::ContentsZoomChange(bool zoom_in) { } void ExternalTabContainer::ToolbarSizeChanged(TabContents* source, bool finished) { } void ExternalTabContainer::ForwardMessageToExternalHost( const std::string& message, const std::string& origin, const std::string& target) { if (automation_) { automation_->Send( new AutomationMsg_ForwardMessageToExternalHost(0, tab_handle_, message, origin, target)); } } ExtensionFunctionDispatcher* ExternalTabContainer:: CreateExtensionFunctionDispatcher(RenderViewHost* render_view_host, const std::string& extension_id) { return new ExtensionFunctionDispatcher(render_view_host, NULL, extension_id); } bool ExternalTabContainer::TakeFocus(bool reverse) { if (automation_) { views::FocusManager* focus_manager = views::FocusManager::GetFocusManager(GetNativeView()); DCHECK(focus_manager); if (focus_manager) { focus_manager->ClearFocus(); automation_->Send(new AutomationMsg_TabbedOut(0, tab_handle_, win_util::IsShiftPressed())); } } return true; } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, NotificationObserver implementation: void ExternalTabContainer::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (!automation_) return; static const int kHttpClientErrorStart = 400; static const int kHttpServerErrorEnd = 510; switch (type.value) { case NotificationType::LOAD_STOP: { const LoadNotificationDetails* load = Details<LoadNotificationDetails>(details).ptr(); if (load != NULL && PageTransition::IsMainFrame(load->origin())) { automation_->Send(new AutomationMsg_TabLoaded(0, tab_handle_, load->url())); } break; } case NotificationType::NAV_ENTRY_COMMITTED: { if (ignore_next_load_notification_) { ignore_next_load_notification_ = false; return; } const NavigationController::LoadCommittedDetails* commit = Details<NavigationController::LoadCommittedDetails>(details).ptr(); if (commit->http_status_code >= kHttpClientErrorStart && commit->http_status_code <= kHttpServerErrorEnd) { automation_->Send(new AutomationMsg_NavigationFailed( 0, tab_handle_, commit->http_status_code, commit->entry->url())); ignore_next_load_notification_ = true; } else { // When the previous entry index is invalid, it will be -1, which // will still make the computation come out right (navigating to the // 0th entry will be +1). automation_->Send(new AutomationMsg_DidNavigate( 0, tab_handle_, commit->type, commit->previous_entry_index - tab_contents_->controller().last_committed_entry_index(), commit->entry->url())); } break; } case NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR: { const ProvisionalLoadDetails* load_details = Details<ProvisionalLoadDetails>(details).ptr(); automation_->Send(new AutomationMsg_NavigationFailed( 0, tab_handle_, load_details->error_code(), load_details->url())); ignore_next_load_notification_ = true; break; } default: NOTREACHED(); } } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, views::WidgetWin overrides: void ExternalTabContainer::OnDestroy() { Uninitialize(GetNativeView()); WidgetWin::OnDestroy(); } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, views::KeystrokeListener implementation: bool ExternalTabContainer::ProcessKeyStroke(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { if (!automation_) { return false; } if ((wparam == VK_TAB) && !win_util::IsCtrlPressed()) { // Tabs are handled separately (except if this is Ctrl-Tab or // Ctrl-Shift-Tab) return false; } unsigned int flags = HIWORD(lparam); bool alt = (flags & KF_ALTDOWN) != 0; if (!alt && (message == WM_SYSKEYUP || message == WM_KEYUP)) { // In case the Alt key is being released. alt = (wparam == VK_MENU); } if ((flags & KF_EXTENDED) || alt || (wparam >= VK_F1 && wparam <= VK_F24) || wparam == VK_ESCAPE || wparam == VK_RETURN || win_util::IsShiftPressed() || win_util::IsCtrlPressed()) { // If this is an extended key or if one or more of Alt, Shift and Control // are pressed, this might be an accelerator that the external host wants // to handle. If the host does not handle this accelerator, it will reflect // the accelerator back to us via the ProcessUnhandledAccelerator method. MSG msg = {0}; msg.hwnd = window; msg.message = message; msg.wParam = wparam; msg.lParam = lparam; automation_->Send(new AutomationMsg_HandleAccelerator(0, tab_handle_, msg)); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // ExternalTabContainer, private: void ExternalTabContainer::Uninitialize(HWND window) { if (::IsWindow(window)) { views::FocusManager* focus_manager = views::FocusManager::GetFocusManager(window); if (focus_manager) focus_manager->RemoveKeystrokeListener(this); } if (tab_contents_) { NotificationService::current()->Notify( NotificationType::EXTERNAL_TAB_CLOSED, Source<NavigationController>(&tab_contents_->controller()), Details<ExternalTabContainer>(this)); delete tab_contents_; tab_contents_ = NULL; } } <|endoftext|>
<commit_before><commit_msg>An attempt to fix windows going fullscreen on startup. My best guess is that the size we're trying to restore is bigger than the current monitor causing the window to be sized to the monitor, triggering the fullscreen behavior.<commit_after><|endoftext|>
<commit_before><commit_msg>gtk: button-press events return coordinates relative to the gdk window in which the button was pressed. Convert this point to a browser window-relative coordinate when handling resizing the custom frame.<commit_after><|endoftext|>
<commit_before><commit_msg>GTK Themes: Initialize theme resources to make download shelf work.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/render_view_context_menu_win.h" #include "chrome/browser/profile.h" #include "chrome/common/l10n_util.h" #include "grit/generated_resources.h" RenderViewContextMenuWin::RenderViewContextMenuWin( WebContents* web_contents, const ContextMenuParams& params, HWND owner) : RenderViewContextMenu(web_contents, params), menu_(this, Menu::TOPLEFT, owner), sub_menu_(NULL) { InitMenu(params.node); } RenderViewContextMenuWin::~RenderViewContextMenuWin() { } void RenderViewContextMenuWin::RunMenuAt(int x, int y) { menu_.RunMenuAt(x, y); } void RenderViewContextMenuWin::AppendMenuItem(int id) { AppendItem(id, l10n_util::GetString(id), Menu::NORMAL); } void RenderViewContextMenuWin::AppendMenuItem(int id, const std::wstring& label) { AppendItem(id, label, Menu::NORMAL); } void RenderViewContextMenuWin::AppendRadioMenuItem(int id, const std::wstring& label) { AppendItem(id, label, Menu::RADIO); } void RenderViewContextMenuWin::AppendCheckboxMenuItem(int id, const std::wstring& label) { AppendItem(id, label, Menu::CHECKBOX); } void RenderViewContextMenuWin::AppendSeparator() { Menu* menu = sub_menu_ ? sub_menu_ : &menu_; menu->AppendSeparator(); } void RenderViewContextMenuWin::StartSubMenu(int id, const std::wstring& label) { if (sub_menu_) { NOTREACHED(); return; } sub_menu_ = menu_.AppendSubMenu(id, label); } void RenderViewContextMenuWin::FinishSubMenu() { DCHECK(sub_menu_); sub_menu_ = NULL; } void RenderViewContextMenuWin::AppendItem( int id, const std::wstring& label, Menu::MenuItemType type) { Menu* menu = sub_menu_ ? sub_menu_ : &menu_; menu->AppendMenuItem(id, label, type); } bool RenderViewContextMenuWin::IsCommandEnabled(int id) const { return IsItemCommandEnabled(id); } bool RenderViewContextMenuWin::IsItemChecked(int id) const { return ItemIsChecked(id); } void RenderViewContextMenuWin::ExecuteCommand(int id) { ExecuteItemCommand(id); } bool RenderViewContextMenuWin::GetAcceleratorInfo( int id, views::Accelerator* accel) { // There are no formally defined accelerators we can query so we assume // that Ctrl+C, Ctrl+V, Ctrl+X, Ctrl-A, etc do what they normally do. switch (id) { case IDS_CONTENT_CONTEXT_UNDO: *accel = views::Accelerator(L'Z', false, true, false); return true; case IDS_CONTENT_CONTEXT_REDO: *accel = views::Accelerator(L'Z', true, true, false); return true; case IDS_CONTENT_CONTEXT_CUT: *accel = views::Accelerator(L'X', false, true, false); return true; case IDS_CONTENT_CONTEXT_COPY: *accel = views::Accelerator(L'C', false, true, false); return true; case IDS_CONTENT_CONTEXT_PASTE: *accel = views::Accelerator(L'V', false, true, false); return true; case IDS_CONTENT_CONTEXT_SELECTALL: *accel = views::Accelerator(L'A', false, true, false); default: return false; } } <commit_msg>fix windows build break.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/render_view_context_menu_win.h" #include "chrome/browser/profile.h" #include "chrome/common/l10n_util.h" #include "chrome/compiler_specific.h" #include "grit/generated_resources.h" RenderViewContextMenuWin::RenderViewContextMenuWin( WebContents* web_contents, const ContextMenuParams& params, HWND owner) : RenderViewContextMenu(web_contents, params), ALLOW_THIS_IN_INITIALIZER_LIST(menu_(this, Menu::TOPLEFT, owner)), sub_menu_(NULL) { InitMenu(params.node); } RenderViewContextMenuWin::~RenderViewContextMenuWin() { } void RenderViewContextMenuWin::RunMenuAt(int x, int y) { menu_.RunMenuAt(x, y); } void RenderViewContextMenuWin::AppendMenuItem(int id) { AppendItem(id, l10n_util::GetString(id), Menu::NORMAL); } void RenderViewContextMenuWin::AppendMenuItem(int id, const std::wstring& label) { AppendItem(id, label, Menu::NORMAL); } void RenderViewContextMenuWin::AppendRadioMenuItem(int id, const std::wstring& label) { AppendItem(id, label, Menu::RADIO); } void RenderViewContextMenuWin::AppendCheckboxMenuItem(int id, const std::wstring& label) { AppendItem(id, label, Menu::CHECKBOX); } void RenderViewContextMenuWin::AppendSeparator() { Menu* menu = sub_menu_ ? sub_menu_ : &menu_; menu->AppendSeparator(); } void RenderViewContextMenuWin::StartSubMenu(int id, const std::wstring& label) { if (sub_menu_) { NOTREACHED(); return; } sub_menu_ = menu_.AppendSubMenu(id, label); } void RenderViewContextMenuWin::FinishSubMenu() { DCHECK(sub_menu_); sub_menu_ = NULL; } void RenderViewContextMenuWin::AppendItem( int id, const std::wstring& label, Menu::MenuItemType type) { Menu* menu = sub_menu_ ? sub_menu_ : &menu_; menu->AppendMenuItem(id, label, type); } bool RenderViewContextMenuWin::IsCommandEnabled(int id) const { return IsItemCommandEnabled(id); } bool RenderViewContextMenuWin::IsItemChecked(int id) const { return ItemIsChecked(id); } void RenderViewContextMenuWin::ExecuteCommand(int id) { ExecuteItemCommand(id); } bool RenderViewContextMenuWin::GetAcceleratorInfo( int id, views::Accelerator* accel) { // There are no formally defined accelerators we can query so we assume // that Ctrl+C, Ctrl+V, Ctrl+X, Ctrl-A, etc do what they normally do. switch (id) { case IDS_CONTENT_CONTEXT_UNDO: *accel = views::Accelerator(L'Z', false, true, false); return true; case IDS_CONTENT_CONTEXT_REDO: *accel = views::Accelerator(L'Z', true, true, false); return true; case IDS_CONTENT_CONTEXT_CUT: *accel = views::Accelerator(L'X', false, true, false); return true; case IDS_CONTENT_CONTEXT_COPY: *accel = views::Accelerator(L'C', false, true, false); return true; case IDS_CONTENT_CONTEXT_PASTE: *accel = views::Accelerator(L'V', false, true, false); return true; case IDS_CONTENT_CONTEXT_SELECTALL: *accel = views::Accelerator(L'A', false, true, false); default: return false; } } <|endoftext|>
<commit_before>#include <vector> #ifdef _MSC_VER #include <algorithm> #endif #include "common.h" #include "GCF.h" #include "fft_dyn_padded.h" #include "OskarBinReader.h" #include "stats_n_utils.h" #include "scatter_gridder_w_dependent_dyn_1p_halide_full.h" // Config const double wstep = 10000.0; const double t2 = 0.02/2.0; const int over = 8; const int over2 = over*over; const int pad = 2; const int gcfGrowth = 16; const int gcfMinSize = 3; const int gcfMaxSize = 128; const int src_size = over * gcfMaxSize * (over * gcfMaxSize + pad); const int gridSize = 2048; const int gridPad = 2; const int gridPitch = gridSize + gridPad; const int fullSize = gridPitch * gridSize; template <typename T> void writeImgToDisk(const char * fname, T * out){ FILE * f = fopen(fname, "wb"); if (f == NULL) { printf("Can't open %s\n", fname); return; } printf("Writing %s ...\n", fname); for (int r = 0; r < gridSize; r++, out += gridPitch) fwrite(out, sizeof(T), gridSize, f); fclose(f); } // Normalization is done inplace! inline void normalizeCPU( complexd src[] , int grid_pitch , int grid_size ) { int siz = grid_size*grid_pitch; double norm = 1.0/double(siz); #pragma omp parallel for for (int i = 0; i < siz; i++) { src[i] *= norm; } } #define __CK(a) if (res != 0) return -a int main(/* int argc, char * argv[] */) { VisData vd; int res; // res = mkFromFile(&vd, argv[1]); res = mkFromFile(&vd, "G:\\BR\\$from_cluster\\test_p00_s00_f00.vis"); __CK(1); printf("Oskar binary is inited!\n"); typedef std::vector<double> dv; typedef std::vector<Double3> d3v; typedef std::vector<Double3*> d3pv; typedef std::vector<complexd> cdv; typedef std::vector<complexd*> cdpv; typedef std::vector<int> iv; Metrix m; d3v uvwvec = d3v(vd.num_points); cdv pol0vec = cdv(vd.num_points); auto bwvec = std::vector<BlWMap>(vd.num_baselines); { // Need no mmvec and ampvec after bwvec map is created and pol0vec is filled. cdv ampvec = cdv(vd.num_points * 4); auto mmvec = std::vector<WMaxMin>(vd.num_baselines); res = readAndReshuffle(&vd, reinterpret_cast<double*>(ampvec.data()), reinterpret_cast<double*>(uvwvec.data()), &m, mmvec.data()); mkBlWpMap(mmvec.data(), vd.num_baselines, wstep, bwvec.data()); auto dst = pol0vec.begin(); auto src = ampvec.begin(); while (src != ampvec.end()) { *dst = *src; src+=4; dst++; } freeBinHandler(&vd); __CK(2); } printf("Oskar binary is read and mapped!\n"); double maxx = std::max(m.maxu, m.maxv); int maxWPlane = int(std::max(round(m.maxw / wstep), round(-m.minw / wstep))); int numOfPlanes = 2 * maxWPlane + 1; auto lsize = [maxWPlane](int i) { return std::min(gcfMaxSize, gcfMinSize + gcfGrowth * (abs(i - maxWPlane))); }; auto layerOff = [lsize](int l) { int off = 0; for (int i = 0; i < l; i++) off += lsize(i) * lsize(i); return off; }; // int layerSizesSum = 0; // for (int i = 0; i < numOfPlanes; i++) layerSizesSum += lsize(i); int layerSizesSum = layerOff(numOfPlanes); int gcfDataSize = over2 * layerSizesSum; int gcfTableSize = over2 * numOfPlanes; // double scale = double((gridSize - gcfMaxSize)/2) / maxx; double scale = double(gridSize/2 - 1) / maxx * 16.0; dv avgs = dv(numOfPlanes); { // Need no npts after finishing accums iv npts = iv(numOfPlanes); calcAccums( uvwvec.data() , avgs.data() , npts.data() , wstep , vd.num_points , numOfPlanes ); for (int n = 0; n < numOfPlanes; n++) { if (npts[n] > 0) avgs[n] /= double(npts[n]); else avgs[n] = wstep * (n - maxWPlane); // IMPORTANT! We scale w also !!! avgs[n] *= scale; } } // Oskar data are rotated already! // rotateCPU(uvwvec.data(), pol0vec.data(), vd.num_points, scale); fftw_plan plan = NULL; fftInitThreading(); cdv gcfData = cdv(gcfDataSize); cdpv gcfTable = cdpv(gcfTableSize); { // Don't need the arena after GCF calculation cdv arena = cdv(src_size); complexd * dptr = gcfData.data(); complexd ** tptr = gcfTable.data(); for (int l = 0; l < numOfPlanes; l++) { plan = mkGCFLayer( plan , dptr , tptr , arena.data() , lsize(l) , gcfMaxSize , pad , t2 , avgs[l] ); printf("W-plane %3d is created!\n", l-maxWPlane); dptr += over2 * lsize(l) * lsize(l); tptr += over2; } } fftw_destroy_plan(plan); /* auto extractLayer = [=](int l) { char name[32]; FILE * f; for (int i = 0; i < 64; i++) { sprintf(name, "o%02d%02d.dat", l, i); f = fopen(name, "wb"); fwrite(gcfTable.data()[over2 * l], sizeof(complexd), lsize(l) * lsize(l), f); fclose(f); } }; extractLayer(15); */ printf("Start gridding preps!\n"); iv blSuppvec(vd.num_baselines); int ts_ch = vd.num_times * vd.num_channels; for (int i = 0; i < vd.num_baselines; i++) { // bwvec is unsorted, thus we directly use w-plane number blSuppvec[i] = lsize(bwvec[i].wp + maxWPlane); // lsize waits maxWPlane-centered w-plane } iv gcfSuppvec(numOfPlanes); for (int i = 0; i < numOfPlanes; i++) gcfSuppvec[i] = lsize(i); cdv gridVec(fullSize); printf("Start gridding!\n"); gridKernel_scatter_halide_full( scale , wstep , vd.num_baselines , blSuppvec.data() , gridVec.data() , const_cast<const complexd *>(gcfData.data()) , const_cast<const Double3 *>(uvwvec.data()) , const_cast<const complexd *>(pol0vec.data()) , ts_ch , gridPitch , gridSize , gcfSuppvec.data() , numOfPlanes ); printf("Start normalizing!\n"); normalizeCPU( gridVec.data() , gridPitch , gridSize ); writeImgToDisk("grid.dat", gridVec.data()); return 0; } <commit_msg>Modify test program for latest Halide gridder variant (still buggy).<commit_after>#include <vector> #ifdef _MSC_VER #include <algorithm> #endif #include <ctime> #include "common.h" #include "GCF.h" #include "fft_dyn_padded.h" #include "OskarBinReader.h" #include "stats_n_utils.h" #include "scatter_gridder_w_dependent_dyn_1p_1gcf_halide.h" // Config const double wstep = 10000.0; const double t2 = 0.02/2.0; const int over = 8; const int over2 = over*over; const int pad = 2; const int gcfGrowth = 16; const int gcfMinSize = 3; const int gcfMaxSize = 128; const int src_size = over * gcfMaxSize * (over * gcfMaxSize + pad); const int gridSize = 2048; const int gridPad = 2; const int gridPitch = gridSize + gridPad; const int fullSize = gridPitch * gridSize; template <typename T> void writeImgToDisk(const char * fname, T * out){ FILE * f = fopen(fname, "wb"); if (f == NULL) { printf("Can't open %s\n", fname); return; } printf("Writing %s ...\n", fname); for (int r = 0; r < gridSize; r++, out += gridPitch) fwrite(out, sizeof(T), gridSize, f); fclose(f); } // Normalization is done inplace! inline void normalizeCPU( complexd src[] , int grid_pitch , int grid_size ) { int siz = grid_size*grid_pitch; double norm = 1.0/double(siz); #pragma omp parallel for for (int i = 0; i < siz; i++) { src[i] *= norm; } } #define __CK(a) if (res != 0) return -a int main(/* int argc, char * argv[] */) { VisData vd; int res; // res = mkFromFile(&vd, argv[1]); res = mkFromFile(&vd, "G:\\BR\\$from_cluster\\test_p00_s00_f00.vis"); __CK(1); printf("Oskar binary is inited!\n"); typedef std::vector<double> dv; typedef std::vector<Double3> d3v; typedef std::vector<Double3*> d3pv; typedef std::vector<complexd> cdv; typedef std::vector<complexd*> cdpv; typedef std::vector<int> iv; Metrix m; d3v uvwvec = d3v(vd.num_points); cdv pol0vec = cdv(vd.num_points); auto bwvec = std::vector<BlWMap>(vd.num_baselines); { // Need no mmvec and ampvec after bwvec map is created and pol0vec is filled. cdv ampvec = cdv(vd.num_points * 4); auto mmvec = std::vector<WMaxMin>(vd.num_baselines); res = readAndReshuffle(&vd, reinterpret_cast<double*>(ampvec.data()), reinterpret_cast<double*>(uvwvec.data()), &m, mmvec.data()); mkBlWpMap(mmvec.data(), vd.num_baselines, wstep, bwvec.data()); auto dst = pol0vec.begin(); auto src = ampvec.begin(); while (src != ampvec.end()) { *dst = *src; src+=4; dst++; } freeBinHandler(&vd); __CK(2); } printf("Oskar binary is read and mapped!\n"); double maxx = std::max(m.maxu, m.maxv); int maxWPlane = int(std::max(round(m.maxw / wstep), round(-m.minw / wstep))); int numOfPlanes = 2 * maxWPlane + 1; auto lsize = [maxWPlane](int i) { return std::min(gcfMaxSize, gcfMinSize + gcfGrowth * (abs(i - maxWPlane))); }; auto layerOff = [lsize](int l) { int off = 0; for (int i = 0; i < l; i++) off += lsize(i) * lsize(i); return off; }; // int layerSizesSum = 0; // for (int i = 0; i < numOfPlanes; i++) layerSizesSum += lsize(i); int layerSizesSum = layerOff(numOfPlanes); int gcfDataSize = over2 * layerSizesSum; int gcfTableSize = over2 * numOfPlanes; // double scale = double((gridSize - gcfMaxSize)/2) / maxx; double scale = double(gridSize/2 - 1) / maxx * 16.0; dv avgs = dv(numOfPlanes); { // Need no npts after finishing accums iv npts = iv(numOfPlanes); calcAccums( uvwvec.data() , avgs.data() , npts.data() , wstep , vd.num_points , numOfPlanes ); for (int n = 0; n < numOfPlanes; n++) { if (npts[n] > 0) avgs[n] /= double(npts[n]); else avgs[n] = wstep * (n - maxWPlane); // IMPORTANT! We scale w also !!! avgs[n] *= scale; } } // Oskar data are rotated already! // rotateCPU(uvwvec.data(), pol0vec.data(), vd.num_points, scale); fftw_plan plan = NULL; fftInitThreading(); cdv gcfData = cdv(gcfDataSize); cdpv gcfTable = cdpv(gcfTableSize); { // Don't need the arena after GCF calculation cdv arena = cdv(src_size); complexd * dptr = gcfData.data(); complexd ** tptr = gcfTable.data(); for (int l = 0; l < numOfPlanes; l++) { plan = mkGCFLayer( plan , dptr , tptr , arena.data() , lsize(l) , gcfMaxSize , pad , t2 , avgs[l] ); printf("W-plane %3d is created!\n", l-maxWPlane); dptr += over2 * lsize(l) * lsize(l); tptr += over2; } } fftw_destroy_plan(plan); /* auto extractLayer = [=](int l) { char name[32]; FILE * f; for (int i = 0; i < 64; i++) { sprintf(name, "o%02d%02d.dat", l, i); f = fopen(name, "wb"); fwrite(gcfTable.data()[over2 * l], sizeof(complexd), lsize(l) * lsize(l), f); fclose(f); } }; extractLayer(15); */ printf("Start gridding preps!\n"); iv blSuppvec(vd.num_baselines); d3pv uvwpvec(vd.num_baselines); Double3 * uvwp = uvwvec.data(); cdpv pol0pvec(vd.num_baselines); complexd * pol0p = pol0vec.data(); int ts_ch = vd.num_times * vd.num_channels; for (int i = 0; i < vd.num_baselines; i++) { // bwvec is unsorted, thus we directly use w-plane number blSuppvec[i] = lsize(bwvec[i].wp + maxWPlane); // lsize waits maxWPlane-centered w-plane uvwpvec[i] = uvwp; uvwp += ts_ch; pol0pvec[i] = pol0p; pol0p += ts_ch; } iv gcfSuppvec(numOfPlanes); for (int i = 0; i < numOfPlanes; i++) gcfSuppvec[i] = lsize(i); clock_t ti = clock(); cdv gridVec(fullSize); printf("Start gridding!\n"); gridKernel_scatter_halide_full( scale , wstep , 50 // vd.num_baselines , bwvec.data() , blSuppvec.data() , gridVec.data() , const_cast<const complexd **>(gcfTable.data()+maxWPlane*over2) // Center at 0 , const_cast<const Double3 **>(uvwpvec.data()) , const_cast<const complexd **>(pol0pvec.data()) , ts_ch , gridPitch , gridSize ); printf("%d\nStart normalizing!\n", clock() - ti); normalizeCPU( gridVec.data() , gridPitch , gridSize ); writeImgToDisk("grid.dat", gridVec.data()); return 0; } <|endoftext|>
<commit_before>#include "Precompiled.hpp" #include "Errors.hpp" #include "BulkMarketHistory.hpp" #include "crest/CacheOld.hpp" #include "crest/JsonHelpers.hpp" #include "crest/Urls.hpp" #include "lib/Params.hpp" #include <iostream> #include <chrono> #include <json/Reader.hpp> #include <json/Writer.hpp> #include <json/Copy.hpp> #include "model/MarketHistoryDay.hpp" std::vector<crest::CacheEntry*> get_bulk_market_history( crest::CacheOld &cache, http::Request &request, const std::vector<int> &regions, const std::vector<int> &types) { // Build requests size_t count = regions.size() * types.size(); log_info() << "GET " << request.url.path << " with " << count << " histories" << std::endl; std::vector<crest::CacheEntry*> cache_entries; cache_entries.reserve(count); for (auto i : types) { for (auto j : regions) { cache_entries.push_back(cache.get(crest::market_history_url(j, i))); } } return cache_entries; } http::Response http_get_bulk_market_history(crest::CacheOld &cache, http::Request &request) { auto start = std::chrono::high_resolution_clock::now(); std::vector<int> regions = params_regions(request); std::vector<int> types = params_inv_types(request); auto cache_entries = get_bulk_market_history(cache, request, regions, types); //Results json::Writer json_writer; json_writer.start_arr(); size_t k = 0; for (auto i : types) { for (auto j : regions) { auto &cache_entry = cache_entries[k]; std::unique_lock<std::mutex> lock(cache_entry->mutex); cache_entry->wait(lock); // Process if (cache_entry->is_data_valid()) { //JsonReader doc(cache_entry->data); //auto items = doc.as_object().get_array("items").get_native(); json_writer.start_obj(); json_writer.prop("region", j); json_writer.prop("type", i); json_writer.end_obj(); json::Parser parser( (const char*)cache_entry->data.data(), (const char*)cache_entry->data.data() + cache_entry->data.size()); crest::read_crest_items(parser, [&parser, &json_writer]() -> void { json::copy(json_writer, parser); }); } } } json_writer.end_arr(); auto end = std::chrono::high_resolution_clock::now(); log_info() << "Cache lookup took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms." << std::endl; http::Response resp; resp.status_code(http::SC_OK); resp.body = json_writer.str(); return resp; } http::Response http_get_bulk_market_history_aggregated(crest::CacheOld &cache, http::Request &request) { auto start = std::chrono::high_resolution_clock::now(); std::vector<int> regions = params_regions(request); std::vector<int> types = params_inv_types(request); auto cache_entries = get_bulk_market_history(cache, request, regions, types); //Results json::Writer json_writer; json_writer.start_obj(); size_t k = 0; for (auto i : types) { std::unordered_map<std::string, MarketHistoryDay> days; for (auto j : regions) { auto &cache_entry = cache_entries[k]; std::unique_lock<std::mutex> lock(cache_entry->mutex); cache_entry->wait(lock); // Process if (cache_entry->is_data_valid()) { auto region_days = crest::read_crest_items<std::vector<MarketHistoryDay>>(cache_entry->data); for (auto &day : region_days) { auto ret = days.emplace(day.date, day); if (!ret.second) { auto &aggregate = ret.first->second; if (day.high_price > aggregate.high_price) aggregate.high_price = day.high_price; if (day.low_price < aggregate.low_price) aggregate.low_price = day.low_price; aggregate.order_count += day.order_count; aggregate.volume += day.volume; aggregate.avg_price += day.avg_price * day.volume; } } } ++k; } if (!days.empty()) { json_writer.key(std::to_string(i)); json_writer.start_arr(); for (auto &day : days) { day.second.avg_price /= day.second.volume; //avg_price was a sum in previous loop json_writer.value(day.second); } json_writer.end_arr(); } } json_writer.end_obj(); auto end = std::chrono::high_resolution_clock::now(); log_info() << "Cache lookup took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms." << std::endl; http::Response resp; resp.status_code(http::SC_OK); resp.body = json_writer.str(); return resp; } <commit_msg>Make /bulk-market-history-aggregated ordered by date again<commit_after>#include "Precompiled.hpp" #include "Errors.hpp" #include "BulkMarketHistory.hpp" #include "crest/CacheOld.hpp" #include "crest/JsonHelpers.hpp" #include "crest/Urls.hpp" #include "lib/Params.hpp" #include <iostream> #include <chrono> #include <map> #include <json/Reader.hpp> #include <json/Writer.hpp> #include <json/Copy.hpp> #include "model/MarketHistoryDay.hpp" std::vector<crest::CacheEntry*> get_bulk_market_history( crest::CacheOld &cache, http::Request &request, const std::vector<int> &regions, const std::vector<int> &types) { // Build requests size_t count = regions.size() * types.size(); log_info() << "GET " << request.url.path << " with " << count << " histories" << std::endl; std::vector<crest::CacheEntry*> cache_entries; cache_entries.reserve(count); for (auto i : types) { for (auto j : regions) { cache_entries.push_back(cache.get(crest::market_history_url(j, i))); } } return cache_entries; } http::Response http_get_bulk_market_history(crest::CacheOld &cache, http::Request &request) { auto start = std::chrono::high_resolution_clock::now(); std::vector<int> regions = params_regions(request); std::vector<int> types = params_inv_types(request); auto cache_entries = get_bulk_market_history(cache, request, regions, types); //Results json::Writer json_writer; json_writer.start_arr(); size_t k = 0; for (auto i : types) { for (auto j : regions) { auto &cache_entry = cache_entries[k]; std::unique_lock<std::mutex> lock(cache_entry->mutex); cache_entry->wait(lock); // Process if (cache_entry->is_data_valid()) { //JsonReader doc(cache_entry->data); //auto items = doc.as_object().get_array("items").get_native(); json_writer.start_obj(); json_writer.prop("region", j); json_writer.prop("type", i); json_writer.end_obj(); json::Parser parser( (const char*)cache_entry->data.data(), (const char*)cache_entry->data.data() + cache_entry->data.size()); crest::read_crest_items(parser, [&parser, &json_writer]() -> void { json::copy(json_writer, parser); }); } } } json_writer.end_arr(); auto end = std::chrono::high_resolution_clock::now(); log_info() << "Cache lookup took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms." << std::endl; http::Response resp; resp.status_code(http::SC_OK); resp.body = json_writer.str(); return resp; } http::Response http_get_bulk_market_history_aggregated(crest::CacheOld &cache, http::Request &request) { auto start = std::chrono::high_resolution_clock::now(); std::vector<int> regions = params_regions(request); std::vector<int> types = params_inv_types(request); auto cache_entries = get_bulk_market_history(cache, request, regions, types); //Results json::Writer json_writer; json_writer.start_obj(); size_t k = 0; for (auto i : types) { std::map<std::string, MarketHistoryDay> days; for (auto j : regions) { auto &cache_entry = cache_entries[k]; std::unique_lock<std::mutex> lock(cache_entry->mutex); cache_entry->wait(lock); // Process if (cache_entry->is_data_valid()) { auto region_days = crest::read_crest_items<std::vector<MarketHistoryDay>>(cache_entry->data); for (auto &day : region_days) { auto ret = days.emplace(day.date, day); if (!ret.second) { auto &aggregate = ret.first->second; if (day.high_price > aggregate.high_price) aggregate.high_price = day.high_price; if (day.low_price < aggregate.low_price) aggregate.low_price = day.low_price; aggregate.order_count += day.order_count; aggregate.volume += day.volume; aggregate.avg_price += day.avg_price * day.volume; } } } ++k; } if (!days.empty()) { json_writer.key(std::to_string(i)); json_writer.start_arr(); for (auto &day : days) { day.second.avg_price /= day.second.volume; //avg_price was a sum in previous loop json_writer.value(day.second); } json_writer.end_arr(); } } json_writer.end_obj(); auto end = std::chrono::high_resolution_clock::now(); log_info() << "Cache lookup took " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms." << std::endl; http::Response resp; resp.status_code(http::SC_OK); resp.body = json_writer.str(); return resp; } <|endoftext|>
<commit_before>#ifndef __EXTENSION_COMPUTE_INTERESTING_RUN_OF_THE_SYSTEM_HPP #define __EXTENSION_COMPUTE_INTERESTING_RUN_OF_THE_SYSTEM_HPP #include "gr1context.hpp" /** * An extension that computes an "interesting" run of the synthesized system, i.e., a run in which * both the assumptions and the guarantees are fulfilled (forever). * * Uses the class "StructuredSlugsVariableGroup" defined in "extensionAnalyzeInitialPositions" */ template<class T> class XComputeInterestingRunOfTheSystem : public T { protected: using T::initSys; using T::safetySys; using T::safetyEnv; using T::initEnv; using T::determinize; using T::winningPositions; using T::checkRealizability; using T::preVars; using T::mgr; using T::livenessAssumptions; using T::livenessGuarantees; using T::postVars; using T::strategyDumpingData; using T::varCubePostOutput; using T::varCubePre; using T::varCubePost; using T::varCubePostInput; using T::varVectorPre; using T::varVectorPost; using T::variables; using T::variableNames; using T::doesVariableInheritType; BF currentPosition; XComputeInterestingRunOfTheSystem<T>(std::list<std::string> &filenames) : T(filenames) {} public: void computeRun() { //================================================== // First, compute a symbolic strategy for the system //================================================== // We don't want any reordering from this point onwards, as // the BDD manipulations from this point onwards are 'kind of simple'. mgr.setAutomaticOptimisation(false); // Prepare positional strategies for the individual goals std::vector<BF> positionalStrategiesForTheIndividualGoals(livenessGuarantees.size()); for (unsigned int i=0;i<livenessGuarantees.size();i++) { BF casesCovered = mgr.constantFalse(); BF strategy = mgr.constantFalse(); for (auto it = strategyDumpingData.begin();it!=strategyDumpingData.end();it++) { if (it->first == i) { BF newCases = it->second.ExistAbstract(varCubePostOutput) & !casesCovered; strategy |= newCases & it->second; casesCovered |= newCases; } } positionalStrategiesForTheIndividualGoals[i] = strategy; //BF_newDumpDot(*this,strategy,"PreInput PreOutput PostInput PostOutput","/tmp/generalStrategy.dot"); } //========================================================================================= // Then, compute a symbolic strategy for the environment to enforce its liveness objectives //========================================================================================= std::vector<BF> environmentStrategyForAchievingTheLivenessAssumptions; for (unsigned int i=0;i<livenessAssumptions.size();i++) { BF winning = mgr.constantFalse(); BF oldWinning = mgr.constantFalse(); BF moves = mgr.constantFalse(); do { oldWinning = winning; BF newMoves = ((livenessAssumptions[i] | oldWinning.SwapVariables(varVectorPre,varVectorPost)) & safetyEnv).UnivAbstract(varCubePostOutput); winning = newMoves.ExistAbstract(varCubePostInput); moves |= winning & !oldWinning & newMoves; } while (winning!=oldWinning); environmentStrategyForAchievingTheLivenessAssumptions.push_back(moves | !winning); } //==================== // Compute Runs //==================== std::vector<BF> trace; std::vector<int> systemGoals; std::vector<bool> systemGoalsSat; std::vector<int> environmentGoals; std::vector<bool> environmentGoalsSat; trace.push_back(currentPosition); systemGoals.push_back(0); environmentGoals.push_back(0); for (unsigned int i=0;(i<100) && !(trace.back().isFalse());i++) { BF currentPosition = trace.back(); BF nextPosition = currentPosition & safetyEnv & positionalStrategiesForTheIndividualGoals[systemGoals.back()] & environmentStrategyForAchievingTheLivenessAssumptions[environmentGoals.back()]; BF edge = determinize(nextPosition,postVars); std::ostringstream edgename; edgename << "/tmp/edge" << i << ".dot"; BF_newDumpDot(*this,edge,"Pre Post",edgename.str().c_str()); // Sys Liveness progress if (edge < livenessGuarantees[systemGoals.back()]) { systemGoals.push_back((systemGoals.back() + 1) % livenessGuarantees.size()); systemGoalsSat.push_back(true); } else { systemGoals.push_back(systemGoals.back()); systemGoalsSat.push_back(false); assert((edge & livenessGuarantees[systemGoals.back()]).isFalse()); } // Env Liveness progress if (edge < livenessAssumptions[environmentGoals.back()]) { environmentGoals.push_back((environmentGoals.back() + 1) % livenessAssumptions.size()); environmentGoalsSat.push_back(true); } else { environmentGoals.push_back(environmentGoals.back()); environmentGoalsSat.push_back(false); assert((edge & livenessAssumptions[environmentGoals.back()]).isFalse()); } // Compute next position assert(nextPosition < safetySys); nextPosition = nextPosition.ExistAbstract(varCubePre).SwapVariables(varVectorPre,varVectorPost); trace.push_back(nextPosition); std::ostringstream npname; npname << "/tmp/np" << i << ".dot"; BF_newDumpDot(*this,nextPosition,NULL,npname.str().c_str()); } systemGoalsSat.push_back(false); //======================== // Compute variable groups //======================== // Interpret grouped variables (the ones with an '@' in their names) // It is assumed that they have precisely the shape produced by the structured // slugs parser. This is checked, however, and an exception is thrown otherwise. std::map<std::string,StructuredSlugsVariableGroup> variableGroups; std::map<unsigned int, std::string> masterVariables; std::set<unsigned int> variablesInSomeGroup; unsigned int varPointer = 0; for (unsigned int i=0;i<variables.size();i++) { if (doesVariableInheritType(i,Pre)) { size_t firstAt = variableNames[i].find_first_of('@'); if (firstAt!=std::string::npos) { if (firstAt<variableNames[i].size()-1) { std::string prefix = variableNames[i].substr(0,firstAt); // std::cerr << variableNames[i] << std::endl; // There is a latter after the '@' // Now check if this is the master variabe if ((firstAt<variableNames[i].size()-2) && (variableNames[i][firstAt+1]=='0') && (variableNames[i][firstAt+2]=='.')) { // Master variable found. Read the information from the master variable variableGroups[prefix].setMasterVariable(varPointer); if (variableGroups[prefix].slaveVariables.size()>0) throw "Error: in the variable groups introduced by the structured slugs parser, a master variable must be listed before its slaves."; // Parse min/max information std::istringstream is(variableNames[i].substr(firstAt+3,std::string::npos)); is >> variableGroups[prefix].minValue; if (is.fail()) throw std::string("Error parsing bound-encoded variable name ")+variableNames[i]+" (reason 1)"; char sep; is >> sep; if (is.fail()) throw std::string("Error parsing bound-encoded variable name ")+variableNames[i]+" (reason 2)"; is >> variableGroups[prefix].maxValue; if (is.fail()) throw std::string("Error parsing bound-encoded variable name ")+variableNames[i]+" (reason 3)"; masterVariables[i] = prefix; } else { // Verify that slave variables are defined in the correct order variableGroups[prefix].slaveVariables.push_back(varPointer); std::istringstream is(variableNames[i].substr(firstAt+1,std::string::npos)); unsigned int number; is >> number; if (is.fail()) throw std::string("Error parsing bound-encoded variable name ")+variableNames[i]+" (reason 4)"; if (number!=variableGroups[prefix].slaveVariables.size()) throw std::string("Error: in the variable groups introduced by the structured slugs parser, the slave variables are not in the right order: ")+variableNames[i]; } } variablesInSomeGroup.insert(i); } assert(variables[i]==preVars[varPointer]); varPointer++; } } //=========================== // Compute table for the run //=========================== std::vector<std::vector<std::string> > table; int nofInputColumns = 0; for (unsigned int runPart = 0;runPart<trace.size();runPart++) { table.push_back(std::vector<std::string>()); std::vector<std::string> &thisLine = table.back(); BF thisState = trace[runPart]; // System goal number std::ostringstream systemGoalNumber; systemGoalNumber << systemGoals[runPart]; if (systemGoalsSat[runPart]) systemGoalNumber << "+"; thisLine.push_back(systemGoalNumber.str()); thisLine.push_back("|"); // Environment goal number std::ostringstream environmentGoalNumber; environmentGoalNumber << environmentGoals[runPart]; if (environmentGoalsSat[runPart]) environmentGoalNumber << "+"; thisLine.push_back(environmentGoalNumber.str()); thisLine.push_back("|"); if (!(thisState.isFalse())) { // Input ungrouped for (unsigned int i=0;i<variables.size();i++) { if (doesVariableInheritType(i,PreInput)) { if (variablesInSomeGroup.count(i)==0) { if ((thisState & variables[i]).isFalse()) { thisLine.push_back("!"+variableNames[i]); } else { thisLine.push_back(variableNames[i]); } if (runPart==0) nofInputColumns++; } } } // Input Grouped for (unsigned int i=0;i<variables.size();i++) { if (doesVariableInheritType(i,PreInput)) { if (variablesInSomeGroup.count(i)!=0) { auto it = masterVariables.find(i); if (it!=masterVariables.end()) { // This is a master variable std::ostringstream valueStream; std::string key = it->second; valueStream << key; StructuredSlugsVariableGroup &group = variableGroups[key]; unsigned int value = 0; if (!((thisState & variables[group.masterVariable]).isFalse())) value++; // Process slave variables unsigned int multiplyer=2; for (auto it = group.slaveVariables.begin();it!=group.slaveVariables.end();it++) { if (!((thisState & variables[*it]).isFalse())) value += multiplyer; multiplyer *= 2; } valueStream << "=" << (value+group.minValue); thisLine.push_back(valueStream.str()); if (runPart==0) nofInputColumns++; } } } } // Seperator thisLine.push_back("|"); // Output ungrouped for (unsigned int i=0;i<variables.size();i++) { if (doesVariableInheritType(i,PreOutput)) { if (variablesInSomeGroup.count(i)==0) { if ((thisState & variables[i]).isFalse()) { thisLine.push_back("!"+variableNames[i]); } else { thisLine.push_back(variableNames[i]); } } } } } else { thisLine.push_back("Env.Loses"); while (thisLine.size()!=table[0].size()) thisLine.push_back(""); } assert(thisLine.size()==table[0].size()); } //=========================== // Print table for the run //=========================== // Compute column lengths std::vector<unsigned int> maxLengths; maxLengths.push_back(8); maxLengths.push_back(1); maxLengths.push_back(8); maxLengths.push_back(1); for (unsigned int i=4;i<table[0].size();i++) { maxLengths.push_back(0); } for (auto it = table.begin();it!=table.end();it++) { for (unsigned int i=0;i<it->size();i++) { maxLengths[i] = std::max(maxLengths[i],(*it)[i].length()); } } // Print column headers std::cout << "Env.L.A. | Sys.L.G. | Input"; int inputColsLeft = -5; for (unsigned int i=4;i<nofInputColumns+4;i++) { inputColsLeft+=maxLengths[i]+1; } for (int i=0;i<inputColsLeft;i++) { std::cout << " "; } std::cout << "| Output"; int outputColsLeft = -7; for (unsigned int i=nofInputColumns+5;i<maxLengths.size();i++) { outputColsLeft+=maxLengths[i]+1; } for (int i=0;i<outputColsLeft;i++) { std::cout << " "; } std::cout << "\n---------+----------+-"; for (int i=0;i<inputColsLeft+5;i++) { std::cout << "-"; } std::cout << "+"; for (int i=0;i<outputColsLeft+7;i++) { std::cout << "-"; } std::cout << "\n"; // Print columns for (auto it=table.begin();it!=table.end();it++) { for (unsigned int i=0;i<maxLengths.size();i++) { for (unsigned int j=(*it)[i].length();j<maxLengths[i];j++) std::cout << " "; std::cout << (*it)[i] << " "; } std::cout << "\n"; } std::cout << "\n"; } void execute() { checkRealizability(); currentPosition = winningPositions & initEnv & initSys; if (currentPosition.isFalse()) { std::cout << "No initial position that satisfies both the initialization assumptions and the initiazation guarantees.\n"; return; } else { currentPosition = determinize(currentPosition,preVars); computeRun(); } } static GR1Context* makeInstance(std::list<std::string> &filenames) { return new XComputeInterestingRunOfTheSystem<T>(filenames); } }; #endif <commit_msg>Some bugfixes for the trace generation<commit_after>#ifndef __EXTENSION_COMPUTE_INTERESTING_RUN_OF_THE_SYSTEM_HPP #define __EXTENSION_COMPUTE_INTERESTING_RUN_OF_THE_SYSTEM_HPP #include "gr1context.hpp" /** * An extension that computes an "interesting" run of the synthesized system, i.e., a run in which * both the assumptions and the guarantees are fulfilled (forever). * * Uses the class "StructuredSlugsVariableGroup" defined in "extensionAnalyzeInitialPositions" */ template<class T> class XComputeInterestingRunOfTheSystem : public T { protected: using T::initSys; using T::safetySys; using T::safetyEnv; using T::initEnv; using T::determinize; using T::winningPositions; using T::checkRealizability; using T::preVars; using T::mgr; using T::livenessAssumptions; using T::livenessGuarantees; using T::postVars; using T::strategyDumpingData; using T::varCubePostOutput; using T::varCubePre; using T::varCubePost; using T::varCubePostInput; using T::varVectorPre; using T::varVectorPost; using T::variables; using T::variableNames; using T::doesVariableInheritType; BF currentPosition; XComputeInterestingRunOfTheSystem<T>(std::list<std::string> &filenames) : T(filenames) {} public: void computeRun() { //================================================== // First, compute a symbolic strategy for the system //================================================== // We don't want any reordering from this point onwards, as // the BDD manipulations from this point onwards are 'kind of simple'. mgr.setAutomaticOptimisation(false); // Prepare positional strategies for the individual goals std::vector<BF> positionalStrategiesForTheIndividualGoals(livenessGuarantees.size()); for (unsigned int i=0;i<livenessGuarantees.size();i++) { BF casesCovered = mgr.constantFalse(); BF strategy = mgr.constantFalse(); for (auto it = strategyDumpingData.begin();it!=strategyDumpingData.end();it++) { if (it->first == i) { BF newCases = it->second.ExistAbstract(varCubePostOutput) & !casesCovered; strategy |= newCases & it->second; casesCovered |= newCases; } } positionalStrategiesForTheIndividualGoals[i] = strategy; //BF_newDumpDot(*this,strategy,"PreInput PreOutput PostInput PostOutput","/tmp/generalStrategy.dot"); } //========================================================================================= // Then, compute a symbolic strategy for the environment to enforce its liveness objectives //========================================================================================= // 1. Step one: Compute Deadlock-avoiding strategy BF nonDeadlockingStates = mgr.constantTrue(); BF oldNonDeadlockingStates = mgr.constantFalse(); BF nonDeadlockingTransitions; while (nonDeadlockingStates!=oldNonDeadlockingStates) { oldNonDeadlockingStates = nonDeadlockingStates; nonDeadlockingTransitions = ((nonDeadlockingStates.SwapVariables(varVectorPre,varVectorPost) | !safetySys).UnivAbstract(varCubePostOutput) & safetyEnv); nonDeadlockingStates = nonDeadlockingTransitions.ExistAbstract(varCubePostInput); } BF_newDumpDot(*this,nonDeadlockingTransitions,NULL,"/tmp/ndt.dot"); BF_newDumpDot(*this,nonDeadlockingStates,NULL,"/tmp/nds.dot"); BF_newDumpDot(*this,safetyEnv,NULL,"/tmp/se.dot"); // 2. Step two: Compute strategy to work towards std::vector<BF> environmentStrategyForAchievingTheLivenessAssumptions; for (unsigned int i=0;i<livenessAssumptions.size();i++) { BF winning = mgr.constantFalse(); BF oldWinning = mgr.constantFalse(); BF moves = mgr.constantFalse(); do { oldWinning = winning; BF newMoves = ((livenessAssumptions[i] | oldWinning.SwapVariables(varVectorPre,varVectorPost)) & nonDeadlockingTransitions).UnivAbstract(varCubePostOutput); winning = newMoves.ExistAbstract(varCubePostInput); moves |= winning & !oldWinning & newMoves; } while (winning!=oldWinning); environmentStrategyForAchievingTheLivenessAssumptions.push_back(moves | !winning); } //==================== // Compute Runs //==================== std::vector<BF> trace; std::vector<int> systemGoals; std::vector<bool> systemGoalsSat; std::vector<int> environmentGoals; std::vector<bool> environmentGoalsSat; trace.push_back(currentPosition); systemGoals.push_back(0); environmentGoals.push_back(0); for (unsigned int i=0;(i<100) && !(trace.back().isFalse());i++) { BF currentPosition = trace.back(); BF nextPosition = currentPosition & safetyEnv & positionalStrategiesForTheIndividualGoals[systemGoals.back()] & environmentStrategyForAchievingTheLivenessAssumptions[environmentGoals.back()]; BF edge = determinize(nextPosition,postVars); std::ostringstream edgename; edgename << "/tmp/edge" << i << ".dot"; BF_newDumpDot(*this,edge,"Pre Post",edgename.str().c_str()); std::ostringstream flexname; flexname << "/tmp/flex" << i << ".dot"; BF_newDumpDot(*this,currentPosition,"Pre Post",flexname.str().c_str()); // Sys Liveness progress if (edge < livenessGuarantees[systemGoals.back()]) { systemGoals.push_back((systemGoals.back() + 1) % livenessGuarantees.size()); systemGoalsSat.push_back(true); } else { systemGoals.push_back(systemGoals.back()); systemGoalsSat.push_back(false); assert((edge & livenessGuarantees[systemGoals.back()]).isFalse()); } // Env Liveness progress if (edge < livenessAssumptions[environmentGoals.back()]) { environmentGoals.push_back((environmentGoals.back() + 1) % livenessAssumptions.size()); environmentGoalsSat.push_back(true); } else { environmentGoals.push_back(environmentGoals.back()); environmentGoalsSat.push_back(false); assert((edge & livenessAssumptions[environmentGoals.back()]).isFalse()); } // Compute next position assert(nextPosition < safetySys); nextPosition = determinize(nextPosition.ExistAbstract(varCubePre).SwapVariables(varVectorPre,varVectorPost),preVars); trace.push_back(nextPosition); std::ostringstream npname; npname << "/tmp/np" << i << ".dot"; BF_newDumpDot(*this,nextPosition,NULL,npname.str().c_str()); } systemGoalsSat.push_back(false); //======================== // Compute variable groups //======================== // Interpret grouped variables (the ones with an '@' in their names) // It is assumed that they have precisely the shape produced by the structured // slugs parser. This is checked, however, and an exception is thrown otherwise. std::map<std::string,StructuredSlugsVariableGroup> variableGroups; std::map<unsigned int, std::string> masterVariables; std::set<unsigned int> variablesInSomeGroup; unsigned int varPointer = 0; for (unsigned int i=0;i<variables.size();i++) { if (doesVariableInheritType(i,Pre)) { size_t firstAt = variableNames[i].find_first_of('@'); if (firstAt!=std::string::npos) { if (firstAt<variableNames[i].size()-1) { std::string prefix = variableNames[i].substr(0,firstAt); // std::cerr << variableNames[i] << std::endl; // There is a latter after the '@' // Now check if this is the master variabe if ((firstAt<variableNames[i].size()-2) && (variableNames[i][firstAt+1]=='0') && (variableNames[i][firstAt+2]=='.')) { // Master variable found. Read the information from the master variable variableGroups[prefix].setMasterVariable(varPointer); if (variableGroups[prefix].slaveVariables.size()>0) throw "Error: in the variable groups introduced by the structured slugs parser, a master variable must be listed before its slaves."; // Parse min/max information std::istringstream is(variableNames[i].substr(firstAt+3,std::string::npos)); is >> variableGroups[prefix].minValue; if (is.fail()) throw std::string("Error parsing bound-encoded variable name ")+variableNames[i]+" (reason 1)"; char sep; is >> sep; if (is.fail()) throw std::string("Error parsing bound-encoded variable name ")+variableNames[i]+" (reason 2)"; is >> variableGroups[prefix].maxValue; if (is.fail()) throw std::string("Error parsing bound-encoded variable name ")+variableNames[i]+" (reason 3)"; masterVariables[i] = prefix; } else { // Verify that slave variables are defined in the correct order variableGroups[prefix].slaveVariables.push_back(varPointer); std::istringstream is(variableNames[i].substr(firstAt+1,std::string::npos)); unsigned int number; is >> number; if (is.fail()) throw std::string("Error parsing bound-encoded variable name ")+variableNames[i]+" (reason 4)"; if (number!=variableGroups[prefix].slaveVariables.size()) throw std::string("Error: in the variable groups introduced by the structured slugs parser, the slave variables are not in the right order: ")+variableNames[i]; } } variablesInSomeGroup.insert(i); } assert(variables[i]==preVars[varPointer]); varPointer++; } } //=========================== // Compute table for the run //=========================== std::vector<std::vector<std::string> > table; int nofInputColumns = 0; for (unsigned int runPart = 0;runPart<trace.size();runPart++) { table.push_back(std::vector<std::string>()); std::vector<std::string> &thisLine = table.back(); BF thisState = trace[runPart]; // Environment goal number std::ostringstream environmentGoalNumber; environmentGoalNumber << environmentGoals[runPart]; environmentGoalNumber << ((environmentGoalsSat[runPart])?"+":" "); thisLine.push_back(environmentGoalNumber.str()); thisLine.push_back("|"); // System goal number std::ostringstream systemGoalNumber; systemGoalNumber << systemGoals[runPart]; systemGoalNumber << ((systemGoalsSat[runPart])?"+":" "); thisLine.push_back(systemGoalNumber.str()); thisLine.push_back("|"); if (!(thisState.isFalse())) { // Input ungrouped for (unsigned int i=0;i<variables.size();i++) { if (doesVariableInheritType(i,PreInput)) { if (variablesInSomeGroup.count(i)==0) { if ((thisState & variables[i]).isFalse()) { thisLine.push_back("!"+variableNames[i]); } else { thisLine.push_back(variableNames[i]); } if (runPart==0) nofInputColumns++; } } } // Input Grouped for (unsigned int i=0;i<variables.size();i++) { if (doesVariableInheritType(i,PreInput)) { if (variablesInSomeGroup.count(i)!=0) { auto it = masterVariables.find(i); if (it!=masterVariables.end()) { // This is a master variable std::ostringstream valueStream; std::string key = it->second; valueStream << key; StructuredSlugsVariableGroup &group = variableGroups[key]; unsigned int value = 0; if (!((thisState & variables[group.masterVariable]).isFalse())) value++; // Process slave variables unsigned int multiplyer=2; for (auto it = group.slaveVariables.begin();it!=group.slaveVariables.end();it++) { if (!((thisState & variables[*it]).isFalse())) value += multiplyer; multiplyer *= 2; } valueStream << "=" << (value+group.minValue); thisLine.push_back(valueStream.str()); if (runPart==0) nofInputColumns++; } } } } // Seperator thisLine.push_back("|"); // Output ungrouped for (unsigned int i=0;i<variables.size();i++) { if (doesVariableInheritType(i,PreOutput)) { if (variablesInSomeGroup.count(i)==0) { if ((thisState & variables[i]).isFalse()) { thisLine.push_back("!"+variableNames[i]); } else { thisLine.push_back(variableNames[i]); } } } } } else { thisLine.push_back("Env.Loses"); while (thisLine.size()!=table[0].size()) thisLine.push_back(""); } assert(thisLine.size()==table[0].size()); } //=========================== // Print table for the run //=========================== // Compute column lengths std::vector<unsigned int> maxLengths; maxLengths.push_back(8); maxLengths.push_back(1); maxLengths.push_back(8); maxLengths.push_back(1); for (unsigned int i=4;i<table[0].size();i++) { maxLengths.push_back(0); } for (auto it = table.begin();it!=table.end();it++) { for (unsigned int i=0;i<it->size();i++) { maxLengths[i] = std::max(maxLengths[i],(*it)[i].length()); } } // Print column headers std::cout << "Env.L.A. | Sys.L.G. | Input"; int inputColsLeft = -5; for (unsigned int i=4;i<nofInputColumns+4;i++) { inputColsLeft+=maxLengths[i]+1; } for (int i=0;i<inputColsLeft;i++) { std::cout << " "; } std::cout << "| Output"; int outputColsLeft = -7; for (unsigned int i=nofInputColumns+5;i<maxLengths.size();i++) { outputColsLeft+=maxLengths[i]+1; } for (int i=0;i<outputColsLeft;i++) { std::cout << " "; } std::cout << "\n---------+----------+-"; for (int i=0;i<inputColsLeft+5;i++) { std::cout << "-"; } std::cout << "+"; for (int i=0;i<outputColsLeft+7;i++) { std::cout << "-"; } std::cout << "\n"; // Print columns for (auto it=table.begin();it!=table.end();it++) { for (unsigned int i=0;i<maxLengths.size();i++) { for (unsigned int j=(*it)[i].length();j<maxLengths[i];j++) std::cout << " "; std::cout << (*it)[i] << " "; } std::cout << "\n"; } std::cout << "\n"; // } void execute() { checkRealizability(); currentPosition = winningPositions & initEnv & initSys; if (currentPosition.isFalse()) { std::cout << "No initial position that satisfies both the initialization assumptions and the initiazation guarantees.\n"; return; } else { currentPosition = determinize(currentPosition,preVars); computeRun(); } } static GR1Context* makeInstance(std::list<std::string> &filenames) { return new XComputeInterestingRunOfTheSystem<T>(filenames); } }; #endif <|endoftext|>