text
stringlengths
54
60.6k
<commit_before>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <NDBT.hpp> #include <NDBT_Test.hpp> #include <HugoTransactions.hpp> #include <UtilTransactions.hpp> #include <random.h> #include <getarg.h> struct Parameter { char * name; unsigned value; unsigned min; unsigned max; }; #define P_BATCH 0 #define P_PARRA 1 #define P_LOCK 2 #define P_FILT 3 #define P_BOUND 4 #define P_ACCESS 5 #define P_FETCH 6 #define P_ROWS 7 #define P_LOOPS 8 #define P_CREATE 9 #define P_LOAD 10 #define P_RESET 11 #define P_MAX 12 static Parameter g_paramters[] = { { "batch", 0, 0, 1 }, // 0, 15 { "parallelism", 0, 0, 1 }, // 0, 1 { "lock", 0, 0, 2 }, // read, exclusive, dirty { "filter", 0, 0, 3 }, // all, none, 1, 100 { "range", 0, 0, 3 }, // all, none, 1, 100 { "access", 0, 0, 2 }, // scan, idx, idx sorted { "fetch", 0, 0, 1 }, // No, yes { "size", 1000000, 1, ~0 }, { "iterations", 3, 1, ~0 }, { "create_drop", 1, 0, 1 }, { "data", 1, 0, 1 }, { "q-reset bounds", 0, 1, 0 } }; static Ndb* g_ndb = 0; static const NdbDictionary::Table * g_table; static const NdbDictionary::Index * g_index; static char g_tablename[256]; static char g_indexname[256]; int create_table(); int load_table(); int run_scan(); int clear_table(); int drop_table(); int main(int argc, const char** argv){ ndb_init(); int verbose = 1; int optind = 0; struct getargs args[1+P_MAX] = { { "verbose", 'v', arg_flag, &verbose, "Print verbose status", "verbose" } }; const int num_args = 1 + P_MAX; int i; for(i = 0; i<P_MAX; i++){ args[i+1].long_name = g_paramters[i].name; args[i+1].short_name = * g_paramters[i].name; args[i+1].type = arg_integer; args[i+1].value = &g_paramters[i].value; BaseString tmp; tmp.assfmt("min: %d max: %d", g_paramters[i].min, g_paramters[i].max); args[i+1].help = strdup(tmp.c_str()); args[i+1].arg_help = 0; } if(getarg(args, num_args, argc, argv, &optind)) { arg_printusage(args, num_args, argv[0], "tabname1 tabname2 ..."); return NDBT_WRONGARGS; } myRandom48Init(NdbTick_CurrentMillisecond()); g_ndb = new Ndb("TEST_DB"); if(g_ndb->init() != 0){ g_err << "init() failed" << endl; goto error; } if(g_ndb->waitUntilReady() != 0){ g_err << "Wait until ready failed" << endl; goto error; } for(i = optind; i<argc; i++){ const char * T = argv[i]; g_info << "Testing " << T << endl; BaseString::snprintf(g_tablename, sizeof(g_tablename), T); BaseString::snprintf(g_indexname, sizeof(g_indexname), "IDX_%s", T); if(create_table()) goto error; if(load_table()) goto error; if(run_scan()) goto error; if(clear_table()) goto error; if(drop_table()) goto error; } if(g_ndb) delete g_ndb; return NDBT_OK; error: if(g_ndb) delete g_ndb; return NDBT_FAILED; } int create_table(){ NdbDictionary::Dictionary* dict = g_ndb->getDictionary(); assert(dict); if(g_paramters[P_CREATE].value){ const NdbDictionary::Table * pTab = NDBT_Tables::getTable(g_tablename); assert(pTab); NdbDictionary::Table copy = * pTab; copy.setLogging(false); if(dict->createTable(copy) != 0){ g_err << "Failed to create table: " << g_tablename << endl; return -1; } NdbDictionary::Index x(g_indexname); x.setTable(g_tablename); x.setType(NdbDictionary::Index::OrderedIndex); x.setLogging(false); for (unsigned k = 0; k < copy.getNoOfColumns(); k++){ if(copy.getColumn(k)->getPrimaryKey()){ x.addColumnName(copy.getColumn(k)->getName()); } } if(dict->createIndex(x) != 0){ g_err << "Failed to create index: " << endl; return -1; } } g_table = dict->getTable(g_tablename); g_index = dict->getIndex(g_indexname, g_tablename); assert(g_table); assert(g_index); return 0; } int drop_table(){ if(!g_paramters[P_CREATE].value) return 0; if(g_ndb->getDictionary()->dropTable(g_table->getName()) != 0){ g_err << "Failed to drop table: " << g_table->getName() << endl; return -1; } g_table = 0; return 0; } int load_table(){ if(!g_paramters[P_LOAD].value) return 0; int rows = g_paramters[P_ROWS].value; HugoTransactions hugoTrans(* g_table); if (hugoTrans.loadTable(g_ndb, rows)){ g_err.println("Failed to load %s with %d rows", g_table->getName(), rows); return -1; } return 0; } int clear_table(){ if(!g_paramters[P_LOAD].value) return 0; int rows = g_paramters[P_ROWS].value; UtilTransactions utilTrans(* g_table); if (utilTrans.clearTable(g_ndb, rows) != 0){ g_err.println("Failed to clear table %s", g_table->getName()); return -1; } return 0; } inline void err(NdbError e){ ndbout << e << endl; } int run_scan(){ int iter = g_paramters[P_LOOPS].value; NDB_TICKS start1, stop; int sum_time= 0; int sample_rows = 0; NDB_TICKS sample_start = NdbTick_CurrentMillisecond(); Uint32 tot = g_paramters[P_ROWS].value; if(g_paramters[P_BOUND].value == 2 || g_paramters[P_FILT].value == 2) iter *= g_paramters[P_ROWS].value; NdbScanOperation * pOp = 0; NdbIndexScanOperation * pIOp = 0; NdbConnection * pTrans = 0; NdbResultSet * rs = 0; int check = 0; for(int i = 0; i<iter; i++){ start1 = NdbTick_CurrentMillisecond(); pTrans = pTrans ? pTrans : g_ndb->startTransaction(); if(!pTrans){ g_err << "Failed to start transaction" << endl; err(g_ndb->getNdbError()); return -1; } int par = g_paramters[P_PARRA].value; int bat = g_paramters[P_BATCH].value; NdbScanOperation::LockMode lm; switch(g_paramters[P_LOCK].value){ case 0: lm = NdbScanOperation::LM_CommittedRead; break; case 1: lm = NdbScanOperation::LM_Read; break; case 2: lm = NdbScanOperation::LM_Exclusive; break; default: abort(); } if(g_paramters[P_ACCESS].value == 0){ pOp = pTrans->getNdbScanOperation(g_tablename); assert(pOp); rs = pOp->readTuples(lm, bat, par); } else { if(g_paramters[P_RESET].value == 0 || pIOp == 0) { pOp= pIOp= pTrans->getNdbIndexScanOperation(g_indexname, g_tablename); bool ord = g_paramters[P_ACCESS].value == 2; rs = pIOp->readTuples(lm, bat, par, ord); } else { pIOp->reset_bounds(); } switch(g_paramters[P_BOUND].value){ case 0: // All break; case 1: // None pIOp->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, 0); break; case 2: { // 1 row default: assert(g_table->getNoOfPrimaryKeys() == 1); // only impl. so far int tot = g_paramters[P_ROWS].value; int row = rand() % tot; #if 0 fix_eq_bound(pIOp, row); #else pIOp->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, &row); #endif break; } } if(g_paramters[P_RESET].value == 1) goto execute; } assert(pOp); assert(rs); switch(g_paramters[P_FILT].value){ case 0: // All check = pOp->interpret_exit_ok(); break; case 1: // None check = pOp->interpret_exit_nok(); break; case 2: { // 1 row default: assert(g_table->getNoOfPrimaryKeys() == 1); // only impl. so far abort(); #if 0 int tot = g_paramters[P_ROWS].value; int row = rand() % tot; NdbScanFilter filter(pOp) ; filter.begin(NdbScanFilter::AND); fix_eq(filter, pOp, row); filter.end(); break; #endif } } if(check != 0){ err(pOp->getNdbError()); return -1; } assert(check == 0); for(int i = 0; i<g_table->getNoOfColumns(); i++){ pOp->getValue(i); } execute: int rows = 0; check = pTrans->execute(NoCommit); assert(check == 0); int fetch = g_paramters[P_FETCH].value; while((check = rs->nextResult(true)) == 0){ do { rows++; } while(!fetch && ((check = rs->nextResult(false)) == 0)); if(check == -1){ err(pTrans->getNdbError()); return -1; } assert(check == 2); } if(check == -1){ err(pTrans->getNdbError()); return -1; } assert(check == 1); if(g_paramters[P_RESET].value == 0) { pTrans->close(); pTrans = 0; } stop = NdbTick_CurrentMillisecond(); int time_passed= (int)(stop - start1); sample_rows += rows; sum_time+= time_passed; if(sample_rows >= tot) { int sample_time = (int)(stop - sample_start); g_info << "Found " << sample_rows << " rows" << endl; g_err.println("Time: %d ms = %u rows/sec", sample_time, (1000*sample_rows)/sample_time); sample_rows = 0; sample_start = stop; } } g_err.println("Avg time: %d ms = %u rows/sec", sum_time/iter, (1000*tot*iter)/sum_time); return 0; } <commit_msg>ndb - bugfix testScanPerf<commit_after>/* Copyright (C) 2003 MySQL AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <NDBT.hpp> #include <NDBT_Test.hpp> #include <HugoTransactions.hpp> #include <UtilTransactions.hpp> #include <random.h> #include <getarg.h> struct Parameter { char * name; unsigned value; unsigned min; unsigned max; }; #define P_BATCH 0 #define P_PARRA 1 #define P_LOCK 2 #define P_FILT 3 #define P_BOUND 4 #define P_ACCESS 5 #define P_FETCH 6 #define P_ROWS 7 #define P_LOOPS 8 #define P_CREATE 9 #define P_LOAD 10 #define P_RESET 11 #define P_MAX 12 static Parameter g_paramters[] = { { "batch", 0, 0, 1 }, // 0, 15 { "parallelism", 0, 0, 1 }, // 0, 1 { "lock", 0, 0, 2 }, // read, exclusive, dirty { "filter", 0, 0, 3 }, // all, none, 1, 100 { "range", 0, 0, 3 }, // all, none, 1, 100 { "access", 0, 0, 2 }, // scan, idx, idx sorted { "fetch", 0, 0, 1 }, // No, yes { "size", 1000000, 1, ~0 }, { "iterations", 3, 1, ~0 }, { "create_drop", 1, 0, 1 }, { "data", 1, 0, 1 }, { "q-reset bounds", 0, 1, 0 } }; static Ndb* g_ndb = 0; static const NdbDictionary::Table * g_table; static const NdbDictionary::Index * g_index; static char g_tablename[256]; static char g_indexname[256]; int create_table(); int load_table(); int run_scan(); int clear_table(); int drop_table(); int main(int argc, const char** argv){ ndb_init(); int verbose = 1; int optind = 0; struct getargs args[1+P_MAX] = { { "verbose", 'v', arg_flag, &verbose, "Print verbose status", "verbose" } }; const int num_args = 1 + P_MAX; int i; for(i = 0; i<P_MAX; i++){ args[i+1].long_name = g_paramters[i].name; args[i+1].short_name = * g_paramters[i].name; args[i+1].type = arg_integer; args[i+1].value = &g_paramters[i].value; BaseString tmp; tmp.assfmt("min: %d max: %d", g_paramters[i].min, g_paramters[i].max); args[i+1].help = strdup(tmp.c_str()); args[i+1].arg_help = 0; } if(getarg(args, num_args, argc, argv, &optind)) { arg_printusage(args, num_args, argv[0], "tabname1 tabname2 ..."); return NDBT_WRONGARGS; } myRandom48Init(NdbTick_CurrentMillisecond()); g_ndb = new Ndb("TEST_DB"); if(g_ndb->init() != 0){ g_err << "init() failed" << endl; goto error; } if(g_ndb->waitUntilReady() != 0){ g_err << "Wait until ready failed" << endl; goto error; } for(i = optind; i<argc; i++){ const char * T = argv[i]; g_info << "Testing " << T << endl; BaseString::snprintf(g_tablename, sizeof(g_tablename), T); BaseString::snprintf(g_indexname, sizeof(g_indexname), "IDX_%s", T); if(create_table()) goto error; if(load_table()) goto error; if(run_scan()) goto error; if(clear_table()) goto error; if(drop_table()) goto error; } if(g_ndb) delete g_ndb; return NDBT_OK; error: if(g_ndb) delete g_ndb; return NDBT_FAILED; } int create_table(){ NdbDictionary::Dictionary* dict = g_ndb->getDictionary(); assert(dict); if(g_paramters[P_CREATE].value){ const NdbDictionary::Table * pTab = NDBT_Tables::getTable(g_tablename); assert(pTab); NdbDictionary::Table copy = * pTab; copy.setLogging(false); if(dict->createTable(copy) != 0){ g_err << "Failed to create table: " << g_tablename << endl; return -1; } NdbDictionary::Index x(g_indexname); x.setTable(g_tablename); x.setType(NdbDictionary::Index::OrderedIndex); x.setLogging(false); for (unsigned k = 0; k < copy.getNoOfColumns(); k++){ if(copy.getColumn(k)->getPrimaryKey()){ x.addColumnName(copy.getColumn(k)->getName()); } } if(dict->createIndex(x) != 0){ g_err << "Failed to create index: " << endl; return -1; } } g_table = dict->getTable(g_tablename); g_index = dict->getIndex(g_indexname, g_tablename); assert(g_table); assert(g_index); return 0; } int drop_table(){ if(!g_paramters[P_CREATE].value) return 0; if(g_ndb->getDictionary()->dropTable(g_table->getName()) != 0){ g_err << "Failed to drop table: " << g_table->getName() << endl; return -1; } g_table = 0; return 0; } int load_table(){ if(!g_paramters[P_LOAD].value) return 0; int rows = g_paramters[P_ROWS].value; HugoTransactions hugoTrans(* g_table); if (hugoTrans.loadTable(g_ndb, rows)){ g_err.println("Failed to load %s with %d rows", g_table->getName(), rows); return -1; } return 0; } int clear_table(){ if(!g_paramters[P_LOAD].value) return 0; int rows = g_paramters[P_ROWS].value; UtilTransactions utilTrans(* g_table); if (utilTrans.clearTable(g_ndb, rows) != 0){ g_err.println("Failed to clear table %s", g_table->getName()); return -1; } return 0; } inline void err(NdbError e){ ndbout << e << endl; } int run_scan(){ int iter = g_paramters[P_LOOPS].value; NDB_TICKS start1, stop; int sum_time= 0; int sample_rows = 0; int tot_rows = 0; NDB_TICKS sample_start = NdbTick_CurrentMillisecond(); Uint32 tot = g_paramters[P_ROWS].value; if(g_paramters[P_BOUND].value == 2 || g_paramters[P_FILT].value == 2) iter *= g_paramters[P_ROWS].value; NdbScanOperation * pOp = 0; NdbIndexScanOperation * pIOp = 0; NdbConnection * pTrans = 0; NdbResultSet * rs = 0; int check = 0; for(int i = 0; i<iter; i++){ start1 = NdbTick_CurrentMillisecond(); pTrans = pTrans ? pTrans : g_ndb->startTransaction(); if(!pTrans){ g_err << "Failed to start transaction" << endl; err(g_ndb->getNdbError()); return -1; } int par = g_paramters[P_PARRA].value; int bat = g_paramters[P_BATCH].value; NdbScanOperation::LockMode lm; switch(g_paramters[P_LOCK].value){ case 0: lm = NdbScanOperation::LM_CommittedRead; break; case 1: lm = NdbScanOperation::LM_Read; break; case 2: lm = NdbScanOperation::LM_Exclusive; break; default: abort(); } if(g_paramters[P_ACCESS].value == 0){ pOp = pTrans->getNdbScanOperation(g_tablename); assert(pOp); rs = pOp->readTuples(lm, bat, par); } else { if(g_paramters[P_RESET].value == 0 || pIOp == 0) { pOp= pIOp= pTrans->getNdbIndexScanOperation(g_indexname, g_tablename); bool ord = g_paramters[P_ACCESS].value == 2; rs = pIOp->readTuples(lm, bat, par, ord); } else { pIOp->reset_bounds(); } switch(g_paramters[P_BOUND].value){ case 0: // All break; case 1: // None pIOp->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, 0); break; case 2: { // 1 row default: assert(g_table->getNoOfPrimaryKeys() == 1); // only impl. so far int tot = g_paramters[P_ROWS].value; int row = rand() % tot; #if 0 fix_eq_bound(pIOp, row); #else pIOp->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, &row); #endif break; } } if(g_paramters[P_RESET].value == 2) goto execute; } assert(pOp); assert(rs); switch(g_paramters[P_FILT].value){ case 0: // All check = pOp->interpret_exit_ok(); break; case 1: // None check = pOp->interpret_exit_nok(); break; case 2: { // 1 row default: assert(g_table->getNoOfPrimaryKeys() == 1); // only impl. so far abort(); #if 0 int tot = g_paramters[P_ROWS].value; int row = rand() % tot; NdbScanFilter filter(pOp) ; filter.begin(NdbScanFilter::AND); fix_eq(filter, pOp, row); filter.end(); break; #endif } } if(check != 0){ err(pOp->getNdbError()); return -1; } assert(check == 0); if(g_paramters[P_RESET].value == 1) g_paramters[P_RESET].value = 2; for(int i = 0; i<g_table->getNoOfColumns(); i++){ pOp->getValue(i); } execute: int rows = 0; check = pTrans->execute(NoCommit); assert(check == 0); int fetch = g_paramters[P_FETCH].value; while((check = rs->nextResult(true)) == 0){ do { rows++; } while(!fetch && ((check = rs->nextResult(false)) == 0)); if(check == -1){ err(pTrans->getNdbError()); return -1; } assert(check == 2); } if(check == -1){ err(pTrans->getNdbError()); return -1; } assert(check == 1); if(g_paramters[P_RESET].value == 0) { pTrans->close(); pTrans = 0; } stop = NdbTick_CurrentMillisecond(); int time_passed= (int)(stop - start1); sample_rows += rows; sum_time+= time_passed; tot_rows+= rows; if(sample_rows >= tot) { int sample_time = (int)(stop - sample_start); g_info << "Found " << sample_rows << " rows" << endl; g_err.println("Time: %d ms = %u rows/sec", sample_time, (1000*sample_rows)/sample_time); sample_rows = 0; sample_start = stop; } } g_err.println("Avg time: %d ms = %u rows/sec", sum_time/tot_rows, (1000*tot_rows)/sum_time); return 0; } <|endoftext|>
<commit_before>// File: GameDQNBridge.cpp // Description: Implement the bridge class between game and DQN // Date: 2015-07-04 // License: Apache // Feel free to contact me if there's any questions // #include "GameDQNBridge.h" #include "defaults.h" #include <string> #include <qlearning/dqn.h> #include <qlearning/ale.h> #include <ale_interface.hpp> GameDQNBridge::GameDQNBridge(ALEInterface& ale, qlearning::DQN& dqn, const bool update) : ale_(ale), dqn_(dqn), update_(update) {} double GameDQNBridge::play(double epsilon) { qlearning::ALE ale; std::deque<qlearning::FDataP> past; double total = 0.0; for (int frame = 0; !ale_.game_over(); frame++) { const auto current = ale.PreprocessScreen(ale_.getScreen()); past.push_back(current); if (past.size() < qlearning::ICount) { for (int i = 0; i < skip_frame + 1 && !ale_.game_over(); i++) { total += ale_.act(PLAYER_A_NOOP); } } else { if (past.size() > qlearning::ICount) { past.pop_front(); } qlearning::IFrames input; std::copy(past.begin(), past.end(), input.begin()); const Action action = dqn_.SelectAction(input, epsilon); double recent = 0.0; for (int i = 0; i < skip_frame + 1 && !ale_.game_over(); i++) { recent += ale_.act(action); } total += recent; const double reward = (recent == 0 ? 0 : recent /= std::abs(recent)); if (update_) { const auto trans = ale_.game_over() ? qlearning::Trans(input, action, reward, boost::none) : qlearning::Trans(input, action, reward, ale.PreprocessScreen(ale_.getScreen())); dqn_.AddTrans(trans); if (dqn_.get_size() > memory_threshold) { dqn_.Update(); } } } } ale_.reset_game(); return total; } <commit_msg>Add comments<commit_after>// File: GameDQNBridge.cpp // Description: Implement the bridge class between game and DQN // Date: 2015-07-04 // License: Apache // Feel free to contact me if there's any questions // #include "GameDQNBridge.h" #include "defaults.h" #include <string> #include <qlearning/dqn.h> #include <qlearning/ale.h> #include <ale_interface.hpp> GameDQNBridge::GameDQNBridge(ALEInterface& ale, qlearning::DQN& dqn, const bool update) : ale_(ale), dqn_(dqn), update_(update) {} double GameDQNBridge::play(double epsilon) { qlearning::ALE ale; std::deque<qlearning::FDataP> past; //frame sequence double total = 0.0; for (int frame = 0; !ale_.game_over(); frame++) { const auto current = ale.PreprocessScreen(ale_.getScreen()); past.push_back(current); //fill frame sequence if (past.size() < qlearning::ICount) { for (int i = 0; i < skip_frame + 1 && !ale_.game_over(); i++) { total += ale_.act(PLAYER_A_NOOP); } } else { //pop history frame if (past.size() > qlearning::ICount) { past.pop_front(); } qlearning::IFrames input; std::copy(past.begin(), past.end(), input.begin()); //get action const Action action = dqn_.SelectAction(input, epsilon); //get recent score double recent = 0.0; for (int i = 0; i < skip_frame + 1 && !ale_.game_over(); i++) { recent += ale_.act(action); } total += recent; const double reward = (recent == 0 ? 0 : recent /= std::abs(recent)); //update solver if (update_) { const auto trans = ale_.game_over() ? qlearning::Trans(input, action, reward, boost::none) : qlearning::Trans(input, action, reward, ale.PreprocessScreen(ale_.getScreen())); dqn_.AddTrans(trans); if (dqn_.get_size() > memory_threshold) { dqn_.Update(); } } } } ale_.reset_game(); return total; } <|endoftext|>
<commit_before>#include "engine/fs/file_system.h" #include "engine/fs/memory_file_device.h" #include "engine/iallocator.h" #include "engine/math_utils.h" #include "engine/string.h" namespace Lumix { namespace FS { class LUMIX_ENGINE_API MemoryFile final : public IFile { public: MemoryFile(IFile* file, MemoryFileDevice& device, IAllocator& allocator) : m_device(device) , m_buffer(nullptr) , m_size(0) , m_capacity(0) , m_pos(0) , m_file(file) , m_write(false) , m_allocator(allocator) { } ~MemoryFile() { if (m_file) { m_file->release(); } m_allocator.deallocate(m_buffer); } IFileDevice& getDevice() override { return m_device; } bool open(const Path& path, Mode mode) override { ASSERT(!m_buffer); // reopen is not supported currently m_write = !!(mode & Mode::WRITE); if(m_file) { if(m_file->open(path, mode)) { if(mode & Mode::READ) { m_capacity = m_size = m_file->size(); m_buffer = (u8*)m_allocator.allocate(sizeof(u8) * m_size); m_file->read(m_buffer, m_size); m_pos = 0; } return true; } } else { if(mode & Mode::WRITE) { return true; } } return false; } void close() override { if(m_file) { if(m_write) { m_file->seek(SeekMode::BEGIN, 0); m_file->write(m_buffer, m_size); } m_file->close(); } m_allocator.deallocate(m_buffer); m_buffer = nullptr; } bool read(void* buffer, size_t size) override { size_t amount = m_pos + size < m_size ? size : m_size - m_pos; copyMemory(buffer, m_buffer + m_pos, (int)amount); m_pos += amount; return amount == size; } bool write(const void* buffer, size_t size) override { size_t pos = m_pos; size_t cap = m_capacity; size_t sz = m_size; if(pos + size > cap) { size_t new_cap = Math::maximum(cap * 2, pos + size); u8* new_data = (u8*)m_allocator.allocate(sizeof(u8) * new_cap); copyMemory(new_data, m_buffer, (int)sz); m_allocator.deallocate(m_buffer); m_buffer = new_data; m_capacity = new_cap; } copyMemory(m_buffer + pos, buffer, (int)size); m_pos += size; m_size = pos + size > sz ? pos + size : sz; return true; } const void* getBuffer() const override { return m_buffer; } size_t size() override { return m_size; } bool seek(SeekMode base, size_t pos) override { switch(base) { case SeekMode::BEGIN: ASSERT(pos <= (i32)m_size); m_pos = pos; break; case SeekMode::CURRENT: ASSERT(0 <= i32(m_pos + pos) && i32(m_pos + pos) <= i32(m_size)); m_pos += pos; break; case SeekMode::END: ASSERT(pos <= (i32)m_size); m_pos = m_size - pos; break; default: ASSERT(0); break; } bool ret = m_pos <= m_size; m_pos = Math::minimum(m_pos, m_size); return ret; } size_t pos() override { return m_pos; } private: IAllocator& m_allocator; MemoryFileDevice& m_device; u8* m_buffer; size_t m_size; size_t m_capacity; size_t m_pos; IFile* m_file; bool m_write; }; void MemoryFileDevice::destroyFile(IFile* file) { LUMIX_DELETE(m_allocator, file); } IFile* MemoryFileDevice::createFile(IFile* child) { return LUMIX_NEW(m_allocator, MemoryFile)(child, *this, m_allocator); } } // namespace FS } // namespace Lumix <commit_msg>fixed - terrain material fails to load<commit_after>#include "engine/fs/file_system.h" #include "engine/fs/memory_file_device.h" #include "engine/iallocator.h" #include "engine/math_utils.h" #include "engine/string.h" namespace Lumix { namespace FS { class LUMIX_ENGINE_API MemoryFile final : public IFile { public: MemoryFile(IFile* file, MemoryFileDevice& device, IAllocator& allocator) : m_device(device) , m_buffer(nullptr) , m_size(0) , m_capacity(0) , m_pos(0) , m_file(file) , m_write(false) , m_allocator(allocator) { } ~MemoryFile() { if (m_file) { m_file->release(); } m_allocator.deallocate(m_buffer); } IFileDevice& getDevice() override { return m_device; } bool open(const Path& path, Mode mode) override { ASSERT(!m_buffer); // reopen is not supported currently m_write = !!(mode & Mode::WRITE); if(m_file) { if(m_file->open(path, mode)) { if(mode & Mode::READ) { m_capacity = m_size = m_file->size(); m_buffer = (u8*)m_allocator.allocate(sizeof(u8) * m_size); m_file->read(m_buffer, m_size); m_file->close(); m_pos = 0; } return true; } } else { if(mode & Mode::WRITE) { return true; } } return false; } void close() override { if(m_file) { if(m_write) { m_file->seek(SeekMode::BEGIN, 0); m_file->write(m_buffer, m_size); m_file->close(); } } m_allocator.deallocate(m_buffer); m_buffer = nullptr; } bool read(void* buffer, size_t size) override { size_t amount = m_pos + size < m_size ? size : m_size - m_pos; copyMemory(buffer, m_buffer + m_pos, (int)amount); m_pos += amount; return amount == size; } bool write(const void* buffer, size_t size) override { size_t pos = m_pos; size_t cap = m_capacity; size_t sz = m_size; if(pos + size > cap) { size_t new_cap = Math::maximum(cap * 2, pos + size); u8* new_data = (u8*)m_allocator.allocate(sizeof(u8) * new_cap); copyMemory(new_data, m_buffer, (int)sz); m_allocator.deallocate(m_buffer); m_buffer = new_data; m_capacity = new_cap; } copyMemory(m_buffer + pos, buffer, (int)size); m_pos += size; m_size = pos + size > sz ? pos + size : sz; return true; } const void* getBuffer() const override { return m_buffer; } size_t size() override { return m_size; } bool seek(SeekMode base, size_t pos) override { switch(base) { case SeekMode::BEGIN: ASSERT(pos <= (i32)m_size); m_pos = pos; break; case SeekMode::CURRENT: ASSERT(0 <= i32(m_pos + pos) && i32(m_pos + pos) <= i32(m_size)); m_pos += pos; break; case SeekMode::END: ASSERT(pos <= (i32)m_size); m_pos = m_size - pos; break; default: ASSERT(0); break; } bool ret = m_pos <= m_size; m_pos = Math::minimum(m_pos, m_size); return ret; } size_t pos() override { return m_pos; } private: IAllocator& m_allocator; MemoryFileDevice& m_device; u8* m_buffer; size_t m_size; size_t m_capacity; size_t m_pos; IFile* m_file; bool m_write; }; void MemoryFileDevice::destroyFile(IFile* file) { LUMIX_DELETE(m_allocator, file); } IFile* MemoryFileDevice::createFile(IFile* child) { return LUMIX_NEW(m_allocator, MemoryFile)(child, *this, m_allocator); } } // namespace FS } // namespace Lumix <|endoftext|>
<commit_before>#include "engine/config/precompiled.h" #if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS) #include "engine/system/system.h" #include <Windows.h> DEA_START() struct window_platform { HWND hwnd; LPCWSTR name; }; /* Translation unit locals */ namespace { void close_windows(pod_vector<window> &windows, pod_vector<HWND> &windows_to_close) { for (auto window_to_close = windows_to_close.get_begin(); window_to_close != windows_to_close.get_end(); ++window_to_close) { for (auto window = windows.get_begin(); window != windows.get_end(); ++window) { if (*window_to_close == window->wnd->hwnd) { destroy_window(*window, false); windows.remove_it(window); break; } } } windows_to_close.clear(); } } pod_vector<HWND> *windows_to_close = NULL; void init_system_data() { /* TODO: Memory manager */ windows_to_close = new pod_vector<HWND>(1); } void destroy_system_data() { /* TODO: Memory manager */ if (windows_to_close) delete windows_to_close; } void error_popup(const char *msg, const bool kill_program) { dea_assert(msg && "error_popup: msg is NULL"); MessageBoxA(NULL, msg, kill_program ? "Fatal Error" : "Error", MB_OK | MB_ICONERROR); if (kill_program) ExitProcess(~(UINT)0); } LRESULT CALLBACK wnd_proc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam) { /* Unused parametres, can't get rid of these */ (void *)hwnd; (void *)wparam; (void *)lparam; switch (umessage) { case WM_DESTROY: { /* We don't want to do anything as we manually destroy windows */ return 0; } case WM_CLOSE: { if (windows_to_close) { windows_to_close->push_back(hwnd); } else { /* TODO: Localization/Error number */ error_popup("Error closing a window", false); } return 0; } default: { return DefWindowProc(hwnd, umessage, wparam, lparam); } } } void create_window(const uint width, const uint height, const float pos_x, const float pos_y, const wchar_t *name, const bool fullscreen, window &out_wnd) { int position_x = 0; int position_y = 0; HINSTANCE hinstance = GetModuleHandle(NULL); /* TODO: Memory manager */ out_wnd.wnd = new window_platform; out_wnd.wnd->hwnd = NULL; out_wnd.wnd->name = name; out_wnd.width = width; out_wnd.height = height; /* Setup the windows class with default settings */ WNDCLASSEX wc; memset(&wc, 0, sizeof(wc)); wc.cbSize = sizeof(wc); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = wnd_proc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hinstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hIconSm = wc.hIcon; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = name; // Register the window class. if (RegisterClassEx(&wc) == 0) { /* TODO: Localization/Error number */ error_popup("Failed to register window class", true); } if (!fullscreen) { position_x = (int)((GetSystemMetrics(SM_CXSCREEN) - width) * pos_x); position_y = (int)((GetSystemMetrics(SM_CYSCREEN) - height) * pos_y); } else { DEVMODE screen_settings; memset(&screen_settings, 0, sizeof(screen_settings)); screen_settings.dmSize = sizeof(screen_settings); screen_settings.dmPelsHeight = (unsigned long)height; screen_settings.dmPelsWidth = (unsigned long)width; screen_settings.dmBitsPerPel = 32; screen_settings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; ChangeDisplaySettings(&screen_settings, CDS_FULLSCREEN); } DWORD style = WS_OVERLAPPEDWINDOW | WS_VISIBLE; DWORD exStyle = 0; // Create the window with the screen settings and get the handle to it. out_wnd.wnd->hwnd = CreateWindowEx(exStyle, name, name, style, position_x, position_y, (int)width, (int)height, NULL, NULL, hinstance, NULL); if (out_wnd.wnd->hwnd == NULL) { /* TODO: Localization/Error number */ error_popup("Failed to create a window", true); } ShowWindow(out_wnd.wnd->hwnd, SW_SHOW); } void destroy_window(window &wnd, const bool fullscreen) { dea_assert(wnd.wnd && "destroy_window: Platform specific window pointer is NULL"); if (fullscreen) { ChangeDisplaySettings(NULL, 0); } DestroyWindow(wnd.wnd->hwnd); wnd.wnd->hwnd = NULL; HINSTANCE hinstance = GetModuleHandle(NULL); UnregisterClass(wnd.wnd->name, hinstance); hinstance = NULL; /* TODO: Memory manager */ delete wnd.wnd; } void focus_window(window &wnd) { dea_assert(wnd.wnd && wnd.wnd->hwnd); SetForegroundWindow(wnd.wnd->hwnd); SetFocus(wnd.wnd->hwnd); } void run(pod_vector<window> &windows) { MSG msg; ZeroMemory(&msg, sizeof(MSG)); bool running = true; while (running) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } if (msg.message == WM_QUIT) { running = false; } else { if (windows_to_close && !windows_to_close->empty()) { close_windows(windows, *windows_to_close); if (windows.empty()) running = false; } /* Run frame */ } } } DEA_END() #endif // DEA_PLATFORM == DEA_PLATFORM_WINDOWS<commit_msg>System: Just a bit of re-organizing.<commit_after>#include "engine/config/precompiled.h" #if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS) #include "engine/system/system.h" #include <Windows.h> DEA_START() struct window_platform { HWND hwnd; LPCWSTR name; }; /* Translation unit locals */ namespace { void close_windows(pod_vector<window> &windows, pod_vector<HWND> &windows_to_close) { for (auto window_to_close = windows_to_close.get_begin(); window_to_close != windows_to_close.get_end(); ++window_to_close) { for (auto window = windows.get_begin(); window != windows.get_end(); ++window) { if (*window_to_close == window->wnd->hwnd) { destroy_window(*window, false); windows.remove_it(window); break; } } } windows_to_close.clear(); } /* Could use a better implementation */ pod_vector<HWND> *windows_to_close = NULL; LRESULT CALLBACK wnd_proc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam) { /* Unused parametres, can't get rid of these */ (void *)hwnd; (void *)wparam; (void *)lparam; switch (umessage) { case WM_DESTROY: { /* We don't want to do anything as we manually destroy windows */ return 0; } case WM_CLOSE: { if (windows_to_close) { windows_to_close->push_back(hwnd); } else { /* TODO: Localization/Error number */ error_popup("Error closing a window", false); } return 0; } default: { return DefWindowProc(hwnd, umessage, wparam, lparam); } } } } void init_system_data() { /* TODO: Memory manager */ windows_to_close = new pod_vector<HWND>(1); } void destroy_system_data() { /* TODO: Memory manager */ if (windows_to_close) delete windows_to_close; } void error_popup(const char *msg, const bool kill_program) { dea_assert(msg && "error_popup: msg is NULL"); MessageBoxA(NULL, msg, kill_program ? "Fatal Error" : "Error", MB_OK | MB_ICONERROR); if (kill_program) ExitProcess(~(UINT)0); } /* TODO: Create a string class for the name */ void create_window(const uint width, const uint height, const float pos_x, const float pos_y, const wchar_t *name, const bool fullscreen, window &out_wnd) { int position_x = 0; int position_y = 0; HINSTANCE hinstance = GetModuleHandle(NULL); /* TODO: Memory manager */ out_wnd.wnd = new window_platform; out_wnd.wnd->hwnd = NULL; out_wnd.wnd->name = name; out_wnd.width = width; out_wnd.height = height; /* Setup the windows class with default settings */ WNDCLASSEX wc; memset(&wc, 0, sizeof(wc)); wc.cbSize = sizeof(wc); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = wnd_proc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hinstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hIconSm = wc.hIcon; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = name; // Register the window class. if (RegisterClassEx(&wc) == 0) { /* TODO: Localization/Error number */ error_popup("Failed to register window class", true); } if (!fullscreen) { position_x = (int)((GetSystemMetrics(SM_CXSCREEN) - width) * pos_x); position_y = (int)((GetSystemMetrics(SM_CYSCREEN) - height) * pos_y); } else { DEVMODE screen_settings; memset(&screen_settings, 0, sizeof(screen_settings)); screen_settings.dmSize = sizeof(screen_settings); screen_settings.dmPelsHeight = (unsigned long)height; screen_settings.dmPelsWidth = (unsigned long)width; screen_settings.dmBitsPerPel = 32; screen_settings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; ChangeDisplaySettings(&screen_settings, CDS_FULLSCREEN); } DWORD style = WS_OVERLAPPEDWINDOW | WS_VISIBLE; DWORD exStyle = 0; // Create the window with the screen settings and get the handle to it. out_wnd.wnd->hwnd = CreateWindowEx(exStyle, name, name, style, position_x, position_y, (int)width, (int)height, NULL, NULL, hinstance, NULL); if (out_wnd.wnd->hwnd == NULL) { /* TODO: Localization/Error number */ error_popup("Failed to create a window", true); } ShowWindow(out_wnd.wnd->hwnd, SW_SHOW); } void destroy_window(window &wnd, const bool fullscreen) { dea_assert(wnd.wnd && "destroy_window: Platform specific window pointer is NULL"); if (fullscreen) { ChangeDisplaySettings(NULL, 0); } DestroyWindow(wnd.wnd->hwnd); wnd.wnd->hwnd = NULL; HINSTANCE hinstance = GetModuleHandle(NULL); UnregisterClass(wnd.wnd->name, hinstance); hinstance = NULL; /* TODO: Memory manager */ delete wnd.wnd; } void focus_window(window &wnd) { dea_assert(wnd.wnd && wnd.wnd->hwnd); SetForegroundWindow(wnd.wnd->hwnd); SetFocus(wnd.wnd->hwnd); } void run(pod_vector<window> &windows) { MSG msg; ZeroMemory(&msg, sizeof(MSG)); bool running = true; while (running) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } if (msg.message == WM_QUIT) { running = false; } else { if (windows_to_close && !windows_to_close->empty()) { close_windows(windows, *windows_to_close); if (windows.empty()) running = false; } /* Run frame */ } } } DEA_END() #endif // DEA_PLATFORM == DEA_PLATFORM_WINDOWS<|endoftext|>
<commit_before>#include "util/funcs.h" #include "util/bitmap.h" #include "night_atmosphere.h" #include "util/file-system.h" #include "util/token.h" #include "resource.h" #include "util/sound.h" #include "globals.h" #include <vector> using namespace std; /* static int screenX(){ return 320; } static int screenY(){ return 240; } */ NightAtmosphere::NightAtmosphere(): Atmosphere(), darkness(128), lightning(false){ lamp = new Bitmap(Filesystem::find(Filesystem::RelativePath("sprites/lamp.png")).path()); thunder = Resource::getSound("sounds/thunder.wav"); /* addLight(500, 30, 50, 30, Bitmap::makeColor(32,32,0), 0); addLight(300, 30, 70, 30, Bitmap::makeColor(0,32,192), 128); */ } NightAtmosphere::~NightAtmosphere(){ for (vector<Light*>::iterator it = lights.begin(); it != lights.end(); it++){ delete (*it); } delete lamp; } /* lights should not overlap! the effect completely messes up if they do */ void NightAtmosphere::drawLight(Bitmap * original, Bitmap * work, const int x, const int y, const int lower_width, const int upper_width, const int black, const int dark_alpha, const int light, const int light_alpha, bool draw_light){ int center_x = x; // int center_x = screenX(); /* const int black = Bitmap::makeColor(0,0,0); const int light = Bitmap::makeColor(32,32,0); const int light_alpha = 0; const int dark_alpha = 128; */ int where_x = center_x - lower_width; int total = lower_width * 2; if (where_x < 0){ total += where_x; where_x = 0; } if (total <= 0){ return; } int left = total - lower_width * 2; int middle = total - lower_width; int right = total; if (center_x - lower_width > 0){ left = 0; middle = lower_width; right = lower_width * 2; } Bitmap save(*original, where_x, 0, total, work->getWidth()); int top = y; if (draw_light){ Bitmap::transBlender(0, 0, 0, dark_alpha); Bitmap::drawingMode(Bitmap::MODE_TRANS); /* int top = -save.getHeight() / 3; top = 30; */ int lamp_height = save.getHeight() - top; /* y = tan(theta) * x */ int lamp_top = (int)(((double)lower_width * 2.0 / (double)lamp_height) * (double)upper_width); // int top = 0; save.triangle(left, top, middle, top, left, save.getHeight(), black); save.triangle(right, top, middle, top, right, save.getHeight(), black); int nwidth = (int)((double) lamp_top / ((double) lamp_height / (double) lower_width)); save.triangle(middle, top, middle - nwidth, top + lamp_top, middle + nwidth, top + lamp_top, black); save.rectangleFill(0, 0, right, top, black); Bitmap::drawingMode(Bitmap::MODE_SOLID); int xwidth = (int)((double) lamp_height / ((double)(save.getHeight() - top) / (double) lower_width)); save.light(middle, top, xwidth, lamp_height, lamp_top, light_alpha, dark_alpha, light, black); lamp->draw(middle - 8, top, save); } else { lamp->draw(middle - 8, top, save); } save.draw(where_x, 0, *work); } int NightAtmosphere::getSkyColor() const { if (lightning){ return Bitmap::makeColor(255, 255, 255); } else { return Bitmap::makeColor(0, 0, 0); } } int NightAtmosphere::getSkyDarkness() const { if (lightning){ return lightningFade; } else { return 255 - darkness; } } void NightAtmosphere::drawFront(Bitmap * work, int x){ Bitmap::transBlender(0, 0, 0, getSkyDarkness()); work->applyTrans(getSkyColor()); } void NightAtmosphere::drawBackground(Bitmap * work, int x){ } void NightAtmosphere::drawScreen(Bitmap * work, int x){ } void NightAtmosphere::addLight(const int x, const int y, const int lower_width, const int upper_width, const int color, const int alpha){ lights.push_back(new Light(x, y, lower_width, upper_width, color, alpha)); } void NightAtmosphere::drawForeground(Bitmap * work, int x){ const int sky = getSkyColor(); Bitmap save = Bitmap::temporaryBitmap(work->getWidth(), work->getHeight()); work->Blit(save); Bitmap::transBlender(0, 0, 0, getSkyDarkness()); work->applyTrans(sky); for (vector<Light*>::iterator it = lights.begin(); it != lights.end(); it++){ Light * light = *it; int my_x = light->x - x; int my_y = light->y; drawLight(&save, work, my_x, my_y, light->lower_width, light->upper_width, sky, darkness, light->color, light->alpha, ! lightning); } } void NightAtmosphere::act(const Scene & level){ if (lightning){ if (lightningFade > 0){ lightningFade *= 0.7; } else { lightning = false; } if (thunderPause == 0){ thunder->play(); thunderPause -= 1; } else if (thunderPause > 0){ thunderPause -= 1; } } else if (Util::rnd(300) == 0){ lightning = true; lightningFade = 255; thunderPause = 2 + Util::rnd(6); // thunder->play(); } } void NightAtmosphere::processLight(Token * token){ int x; *token >> x; addLight(x, 30, 50, 30, Bitmap::makeColor(32,32,0), 0); } void NightAtmosphere::interpret(Token * message){ Token * night = message->findToken("message/night"); if (night != NULL){ vector<Token*> lights = night->findTokens("night/lamp"); for (vector<Token*>::iterator it = lights.begin(); it != lights.end(); it++){ Token * token = *it; try{ processLight(token); } catch (const TokenException & e){ Global::debug(0) << "Could not add light to night atmosphere: " << e.getReason() << endl; } } } } <commit_msg>delay thunder more<commit_after>#include "util/funcs.h" #include "util/bitmap.h" #include "night_atmosphere.h" #include "util/file-system.h" #include "util/token.h" #include "resource.h" #include "util/sound.h" #include "globals.h" #include <vector> using namespace std; /* static int screenX(){ return 320; } static int screenY(){ return 240; } */ NightAtmosphere::NightAtmosphere(): Atmosphere(), darkness(128), lightning(false), thunder(NULL), thunderPause(-1){ lamp = new Bitmap(Filesystem::find(Filesystem::RelativePath("sprites/lamp.png")).path()); thunder = Resource::getSound("sounds/thunder.wav"); /* addLight(500, 30, 50, 30, Bitmap::makeColor(32,32,0), 0); addLight(300, 30, 70, 30, Bitmap::makeColor(0,32,192), 128); */ } NightAtmosphere::~NightAtmosphere(){ for (vector<Light*>::iterator it = lights.begin(); it != lights.end(); it++){ delete (*it); } delete lamp; } /* lights should not overlap! the effect completely messes up if they do */ void NightAtmosphere::drawLight(Bitmap * original, Bitmap * work, const int x, const int y, const int lower_width, const int upper_width, const int black, const int dark_alpha, const int light, const int light_alpha, bool draw_light){ int center_x = x; // int center_x = screenX(); /* const int black = Bitmap::makeColor(0,0,0); const int light = Bitmap::makeColor(32,32,0); const int light_alpha = 0; const int dark_alpha = 128; */ int where_x = center_x - lower_width; int total = lower_width * 2; if (where_x < 0){ total += where_x; where_x = 0; } if (total <= 0){ return; } int left = total - lower_width * 2; int middle = total - lower_width; int right = total; if (center_x - lower_width > 0){ left = 0; middle = lower_width; right = lower_width * 2; } Bitmap save(*original, where_x, 0, total, work->getWidth()); int top = y; if (draw_light){ Bitmap::transBlender(0, 0, 0, dark_alpha); Bitmap::drawingMode(Bitmap::MODE_TRANS); /* int top = -save.getHeight() / 3; top = 30; */ int lamp_height = save.getHeight() - top; /* y = tan(theta) * x */ int lamp_top = (int)(((double)lower_width * 2.0 / (double)lamp_height) * (double)upper_width); // int top = 0; save.triangle(left, top, middle, top, left, save.getHeight(), black); save.triangle(right, top, middle, top, right, save.getHeight(), black); int nwidth = (int)((double) lamp_top / ((double) lamp_height / (double) lower_width)); save.triangle(middle, top, middle - nwidth, top + lamp_top, middle + nwidth, top + lamp_top, black); save.rectangleFill(0, 0, right, top, black); Bitmap::drawingMode(Bitmap::MODE_SOLID); int xwidth = (int)((double) lamp_height / ((double)(save.getHeight() - top) / (double) lower_width)); save.light(middle, top, xwidth, lamp_height, lamp_top, light_alpha, dark_alpha, light, black); lamp->draw(middle - 8, top, save); } else { lamp->draw(middle - 8, top, save); } save.draw(where_x, 0, *work); } int NightAtmosphere::getSkyColor() const { if (lightning){ return Bitmap::makeColor(255, 255, 255); } else { return Bitmap::makeColor(0, 0, 0); } } int NightAtmosphere::getSkyDarkness() const { if (lightning){ return lightningFade; } else { return 255 - darkness; } } void NightAtmosphere::drawFront(Bitmap * work, int x){ Bitmap::transBlender(0, 0, 0, getSkyDarkness()); work->applyTrans(getSkyColor()); } void NightAtmosphere::drawBackground(Bitmap * work, int x){ } void NightAtmosphere::drawScreen(Bitmap * work, int x){ } void NightAtmosphere::addLight(const int x, const int y, const int lower_width, const int upper_width, const int color, const int alpha){ lights.push_back(new Light(x, y, lower_width, upper_width, color, alpha)); } void NightAtmosphere::drawForeground(Bitmap * work, int x){ const int sky = getSkyColor(); Bitmap save = Bitmap::temporaryBitmap(work->getWidth(), work->getHeight()); work->Blit(save); Bitmap::transBlender(0, 0, 0, getSkyDarkness()); work->applyTrans(sky); for (vector<Light*>::iterator it = lights.begin(); it != lights.end(); it++){ Light * light = *it; int my_x = light->x - x; int my_y = light->y; drawLight(&save, work, my_x, my_y, light->lower_width, light->upper_width, sky, darkness, light->color, light->alpha, ! lightning); } } void NightAtmosphere::act(const Scene & level){ if (lightning){ if (lightningFade > 0){ lightningFade *= 0.7; } else { lightning = false; } } else if (Util::rnd(300) == 0){ lightning = true; lightningFade = 255; thunderPause = 20 + Util::rnd(4); // thunder->play(); } if (thunderPause == 0){ thunder->play(); thunderPause -= 1; } else if (thunderPause > 0){ thunderPause -= 1; } } void NightAtmosphere::processLight(Token * token){ int x; *token >> x; addLight(x, 30, 50, 30, Bitmap::makeColor(32,32,0), 0); } void NightAtmosphere::interpret(Token * message){ Token * night = message->findToken("message/night"); if (night != NULL){ vector<Token*> lights = night->findTokens("night/lamp"); for (vector<Token*>::iterator it = lights.begin(); it != lights.end(); it++){ Token * token = *it; try{ processLight(token); } catch (const TokenException & e){ Global::debug(0) << "Could not add light to night atmosphere: " << e.getReason() << endl; } } } } <|endoftext|>
<commit_before>/* * This file is part of `et engine` * Copyright 2009-2015 by Sergey Reznik * Please, modify content only if you know what are you doing. * */ #include <et/core/tools.h> #if (ET_PLATFORM_WIN) #include <et/platform/platformtools.h> #include <et/core/filesystem.h> #include <et/core/containers.h> #include <Shlobj.h> #include <ShellAPI.h> #include <CommDlg.h> static bool shouldInitializeTime = true; static uint64_t performanceFrequency = 0; static uint64_t initialCounter = 0; static const ET_STRING_TYPE currentFolder = ET_STRING_FROM_CONST_CHAR("."); static const ET_STRING_TYPE previousFolder = ET_STRING_FROM_CONST_CHAR(".."); static const ET_STRING_TYPE allFilesMask = ET_STRING_FROM_CONST_CHAR("*.*"); void initTime() { LARGE_INTEGER c = { }; LARGE_INTEGER f = { }; shouldInitializeTime = false; QueryPerformanceCounter(&c); QueryPerformanceFrequency(&f); initialCounter = c.QuadPart; performanceFrequency = f.QuadPart; } uint64_t et::queryContiniousTimeInMilliSeconds() { if (shouldInitializeTime) initTime(); LARGE_INTEGER c = { }; QueryPerformanceCounter(&c); return 1000 * (c.QuadPart - initialCounter) / performanceFrequency; } float et::queryContiniousTimeInSeconds() { return static_cast<float>(queryContiniousTimeInMilliSeconds()) / 1000.0f; } uint64_t et::queryCurrentTimeInMicroSeconds() { LARGE_INTEGER c = { }; QueryPerformanceCounter(&c); return 1000000 * c.QuadPart / performanceFrequency; } const char et::pathDelimiter = '\\'; const char et::invalidPathDelimiter = '/'; std::string et::applicationPath() { char ExePath[MAX_PATH] = { }; GetModuleFileNameA(nullptr, ExePath, MAX_PATH); return getFilePath(normalizeFilePath(ExePath)); } bool et::fileExists(const std::string& name) { auto attr = GetFileAttributes(ET_STRING_TO_PARAM_TYPE(name).c_str()); return (attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY); } bool et::folderExists(const std::string& folder) { auto attr = GetFileAttributes(ET_STRING_TO_PARAM_TYPE(folder).c_str()); return (attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY); } void et::findFiles(const std::string& folder, const std::string& mask, bool recursive, StringList& list) { ET_STRING_TYPE normalizedFolder = ET_STRING_TO_PARAM_TYPE(addTrailingSlash(folder)); ET_STRING_TYPE searchPath = normalizedFolder + ET_STRING_TO_PARAM_TYPE(mask); StringList folderList; if (recursive) { ET_STRING_TYPE foldersSearchPath = normalizedFolder + allFilesMask; WIN32_FIND_DATA folders = { }; HANDLE folderSearch = FindFirstFile(foldersSearchPath.c_str(), &folders); if (folderSearch != INVALID_HANDLE_VALUE) { do { bool isFolder = (folders.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; ET_STRING_TYPE name(folders.cFileName); if (isFolder && (name != currentFolder) && (name != previousFolder)) folderList.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name)); } while (FindNextFile(folderSearch, &folders)); FindClose(folderSearch); } } WIN32_FIND_DATA data = { }; HANDLE search = FindFirstFile(searchPath.c_str(), &data); if (search != INVALID_HANDLE_VALUE) { do { bool isAcceptable = ((data.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) == FILE_ATTRIBUTE_NORMAL) || ((data.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) == FILE_ATTRIBUTE_ARCHIVE) || ((data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY); ET_STRING_TYPE name(data.cFileName); if (isAcceptable && (name != currentFolder) && (name != previousFolder)) list.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name)); } while (FindNextFile(search, &data)); FindClose(search); } if (recursive) { for (const std::string& i : folderList) findFiles(i, mask, recursive, list); } } std::string et::applicationPackagePath() { ET_CHAR_TYPE buffer[MAX_PATH] = { }; GetCurrentDirectory(MAX_PATH, buffer); return addTrailingSlash(ET_STRING_TO_OUTPUT_TYPE(buffer)); } std::string et::applicationDataFolder() { ET_CHAR_TYPE buffer[MAX_PATH] = { }; GetCurrentDirectory(MAX_PATH, buffer); return addTrailingSlash(ET_STRING_TO_OUTPUT_TYPE(buffer)); } std::string et::documentsBaseFolder() { wchar_t* path = nullptr; SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &path); if (path == nullptr) return emptyString; std::string result = addTrailingSlash(unicodeToUtf8(path)); CoTaskMemFree(path); return result; } std::string et::libraryBaseFolder() { wchar_t* path = nullptr; SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &path); if (path == nullptr) return emptyString; std::string result = addTrailingSlash(unicodeToUtf8(path)); CoTaskMemFree(path); return result; } bool et::createDirectory(const std::string& name, bool recursive) { if (recursive) { char delim[] = {pathDelimiter, 0}; bool gotError = false; StringList components = split(name, std::string(delim)); std::string path; for (auto& dir : components) { path += dir + "\\"; if (!folderExists(path)) gotError |= ::CreateDirectory(ET_STRING_TO_PARAM_TYPE(path).c_str(), nullptr) == 0; } return !gotError; } return ::CreateDirectory(ET_STRING_TO_PARAM_TYPE(name).c_str(), nullptr) == 0; } bool et::removeFile(const std::string& name) { ET_STRING_TYPE aName = ET_STRING_TO_PARAM_TYPE(name); aName.resize(aName.size() + 1); aName.back() = 0; SHFILEOPSTRUCT fop = { }; fop.wFunc = FO_DELETE; fop.pFrom = aName.c_str(); fop.fFlags = FOF_NO_UI; return SHFileOperation(&fop) == 0; } bool et::copyFile(const std::string& from, const std::string& to) { ET_STRING_TYPE aFrom= ET_STRING_TO_PARAM_TYPE(from); ET_STRING_TYPE aTo = ET_STRING_TO_PARAM_TYPE(to); aFrom.resize(aFrom.size() + 1); aTo.resize(aTo.size() + 1); aFrom.back() = 0; aTo.back() = 0; SHFILEOPSTRUCT fop = { }; fop.wFunc = FO_COPY; fop.pFrom = aFrom.c_str(); fop.pTo = aTo.c_str(); fop.fFlags = FOF_NO_UI; return SHFileOperation(&fop) == 0; } bool et::removeDirectory(const std::string& name) { ET_STRING_TYPE aName = ET_STRING_TO_PARAM_TYPE(name); aName.resize(aName.size() + 1); aName.back() = 0; SHFILEOPSTRUCT fop = { }; fop.wFunc = FO_DELETE; fop.pFrom = aName.c_str(); fop.fFlags = FOF_NO_UI; return SHFileOperation(&fop) == 0; } void et::findSubfolders(const std::string& folder, bool recursive, StringList& list) { StringList folderList; ET_STRING_TYPE normalizedFolder = ET_STRING_TO_PARAM_TYPE(addTrailingSlash(folder)); ET_STRING_TYPE foldersSearchPath = normalizedFolder + allFilesMask; WIN32_FIND_DATA folders = { }; HANDLE folderSearch = FindFirstFile(foldersSearchPath.c_str(), &folders); if (folderSearch != INVALID_HANDLE_VALUE) { do { ET_STRING_TYPE name(folders.cFileName); bool isFolder = (folders.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; if (isFolder && (name != currentFolder) && (name != previousFolder)) { folderList.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name + ET_STRING_FROM_CONST_CHAR("\\"))); } } while (FindNextFile(folderSearch, &folders)); FindClose(folderSearch); } if (recursive) { for (const std::string& i : folderList) findSubfolders(i, true, list); } list.insert(list.end(), folderList.begin(), folderList.end()); } void et::openUrl(const std::string& url) { ShellExecute(nullptr, ET_STRING_FROM_CONST_CHAR("open"), ET_STRING_TO_PARAM_TYPE(url).c_str(), 0, 0, SW_SHOWNORMAL); } std::string et::unicodeToUtf8(const std::wstring& w) { int mbcWidth = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, 0, 0, 0, 0); if (mbcWidth == 0) return emptyString; DataStorage<char> result(mbcWidth + 1, 0); WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, result.data(), static_cast<int>(result.size()), 0, 0); return std::string(result.data()); } std::wstring et::utf8ToUnicode(const std::string& mbcs) { int uWidth = MultiByteToWideChar(CP_UTF8, 0, mbcs.c_str(), -1, 0, 0); if (uWidth == 0) { switch (GetLastError()) { case ERROR_INSUFFICIENT_BUFFER: std::cout << "A supplied buffer size was not large enough, " "or it was incorrectly set to NULL." << std::endl; break; case ERROR_INVALID_FLAGS: std::cout << "The values supplied for flags were not valid." << std::endl; break; case ERROR_INVALID_PARAMETER: std::cout << "Any of the parameter values was invalid." << std::endl; break; case ERROR_NO_UNICODE_TRANSLATION: std::cout << "Invalid Unicode was found in a string" << std::endl; break; default: std::cout << "Failed to convert utf-8 to wchar_t" << std::endl; } return std::wstring(); } DataStorage<wchar_t> result(uWidth + 1, 0); MultiByteToWideChar(CP_UTF8, 0, mbcs.c_str(), -1, result.data(), static_cast<int>(result.size())); return std::wstring(result.data()); } std::string et::applicationIdentifierForCurrentProject() { return "com.et.app"; } uint64_t et::getFileDate(const std::string& path) { WIN32_FIND_DATA findData = { }; HANDLE search = FindFirstFile(ET_STRING_TO_PARAM_TYPE(path).c_str(), &findData); FindClose(search); return findData.ftLastWriteTime.dwLowDateTime | (static_cast<uint64_t>(findData.ftLastWriteTime.dwHighDateTime) << 32); } std::vector<et::Screen> et::availableScreens() { std::vector<et::Screen> result; EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hMonitor, HDC, LPRECT, LPARAM dwData) -> BOOL { MONITORINFO info = { sizeof(MONITORINFO) }; GetMonitorInfo(hMonitor, &info); recti screenRect(info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right - info.rcMonitor.left, info.rcMonitor.bottom - info.rcMonitor.top); recti workarea(info.rcWork.left, info.rcWork.top, info.rcWork.right - info.rcWork.left, info.rcWork.bottom - info.rcWork.top); std::vector<et::Screen>* r = reinterpret_cast<std::vector<et::Screen>*>(dwData); r->emplace_back(screenRect, workarea, 1); return 1; }, reinterpret_cast<LPARAM>(&result)); return result; } std::string et::selectFile(const StringList&, SelectFileMode mode, const std::string& defaultName) { ET_STRING_TYPE defaultFileName = ET_STRING_TO_PARAM_TYPE(defaultName); DataStorage<ET_CHAR_TYPE> defaultFileNameData(etMax(size_t(MAX_PATH), defaultFileName.size()) + 1, 0); etCopyMemory(defaultFileNameData.data(), defaultFileName.data(), defaultFileName.size()); OPENFILENAME of = { }; of.lStructSize = sizeof(of); of.hInstance = GetModuleHandle(nullptr); of.Flags = OFN_DONTADDTORECENT | OFN_ENABLESIZING | OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST; of.lpstrFile = defaultFileNameData.data(); of.nMaxFile = MAX_PATH; #if (_UNICODE) of.lpstrFilter = L"All Files\0*.*\0\0"; #else of.lpstrFilter = "All Files\0*.*\0\0"; #endif auto func = (mode == SelectFileMode::Save) ? GetSaveFileName : GetOpenFileName; return func(&of) ? ET_STRING_TO_OUTPUT_TYPE(of.lpstrFile) : emptyString; } void et::alert(const std::string& title, const std::string& message, const std::string&, AlertType type) { UINT alType = MB_ICONINFORMATION; switch (type) { case AlertType::Warning: { alType = MB_ICONWARNING; break; } case AlertType::Error: { alType = MB_ICONERROR; break; } default: break; } MessageBoxA(nullptr, message.c_str(), title.c_str(), alType); } #endif // ET_PLATFORM_WIN <commit_msg>currentScreen function added to windows<commit_after>/* * This file is part of `et engine` * Copyright 2009-2015 by Sergey Reznik * Please, modify content only if you know what are you doing. * */ #include <et/core/tools.h> #if (ET_PLATFORM_WIN) #include <et/platform/platformtools.h> #include <et/core/filesystem.h> #include <et/core/containers.h> #include <Shlobj.h> #include <ShellAPI.h> #include <CommDlg.h> static bool shouldInitializeTime = true; static uint64_t performanceFrequency = 0; static uint64_t initialCounter = 0; static const ET_STRING_TYPE currentFolder = ET_STRING_FROM_CONST_CHAR("."); static const ET_STRING_TYPE previousFolder = ET_STRING_FROM_CONST_CHAR(".."); static const ET_STRING_TYPE allFilesMask = ET_STRING_FROM_CONST_CHAR("*.*"); void initTime() { LARGE_INTEGER c = { }; LARGE_INTEGER f = { }; shouldInitializeTime = false; QueryPerformanceCounter(&c); QueryPerformanceFrequency(&f); initialCounter = c.QuadPart; performanceFrequency = f.QuadPart; } uint64_t et::queryContiniousTimeInMilliSeconds() { if (shouldInitializeTime) initTime(); LARGE_INTEGER c = { }; QueryPerformanceCounter(&c); return 1000 * (c.QuadPart - initialCounter) / performanceFrequency; } float et::queryContiniousTimeInSeconds() { return static_cast<float>(queryContiniousTimeInMilliSeconds()) / 1000.0f; } uint64_t et::queryCurrentTimeInMicroSeconds() { LARGE_INTEGER c = { }; QueryPerformanceCounter(&c); return 1000000 * c.QuadPart / performanceFrequency; } const char et::pathDelimiter = '\\'; const char et::invalidPathDelimiter = '/'; std::string et::applicationPath() { char ExePath[MAX_PATH] = { }; GetModuleFileNameA(nullptr, ExePath, MAX_PATH); return getFilePath(normalizeFilePath(ExePath)); } bool et::fileExists(const std::string& name) { auto attr = GetFileAttributes(ET_STRING_TO_PARAM_TYPE(name).c_str()); return (attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY); } bool et::folderExists(const std::string& folder) { auto attr = GetFileAttributes(ET_STRING_TO_PARAM_TYPE(folder).c_str()); return (attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY); } void et::findFiles(const std::string& folder, const std::string& mask, bool recursive, StringList& list) { ET_STRING_TYPE normalizedFolder = ET_STRING_TO_PARAM_TYPE(addTrailingSlash(folder)); ET_STRING_TYPE searchPath = normalizedFolder + ET_STRING_TO_PARAM_TYPE(mask); StringList folderList; if (recursive) { ET_STRING_TYPE foldersSearchPath = normalizedFolder + allFilesMask; WIN32_FIND_DATA folders = { }; HANDLE folderSearch = FindFirstFile(foldersSearchPath.c_str(), &folders); if (folderSearch != INVALID_HANDLE_VALUE) { do { bool isFolder = (folders.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; ET_STRING_TYPE name(folders.cFileName); if (isFolder && (name != currentFolder) && (name != previousFolder)) folderList.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name)); } while (FindNextFile(folderSearch, &folders)); FindClose(folderSearch); } } WIN32_FIND_DATA data = { }; HANDLE search = FindFirstFile(searchPath.c_str(), &data); if (search != INVALID_HANDLE_VALUE) { do { bool isAcceptable = ((data.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) == FILE_ATTRIBUTE_NORMAL) || ((data.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) == FILE_ATTRIBUTE_ARCHIVE) || ((data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY); ET_STRING_TYPE name(data.cFileName); if (isAcceptable && (name != currentFolder) && (name != previousFolder)) list.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name)); } while (FindNextFile(search, &data)); FindClose(search); } if (recursive) { for (const std::string& i : folderList) findFiles(i, mask, recursive, list); } } std::string et::applicationPackagePath() { ET_CHAR_TYPE buffer[MAX_PATH] = { }; GetCurrentDirectory(MAX_PATH, buffer); return addTrailingSlash(ET_STRING_TO_OUTPUT_TYPE(buffer)); } std::string et::applicationDataFolder() { ET_CHAR_TYPE buffer[MAX_PATH] = { }; GetCurrentDirectory(MAX_PATH, buffer); return addTrailingSlash(ET_STRING_TO_OUTPUT_TYPE(buffer)); } std::string et::documentsBaseFolder() { wchar_t* path = nullptr; SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &path); if (path == nullptr) return emptyString; std::string result = addTrailingSlash(unicodeToUtf8(path)); CoTaskMemFree(path); return result; } std::string et::libraryBaseFolder() { wchar_t* path = nullptr; SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &path); if (path == nullptr) return emptyString; std::string result = addTrailingSlash(unicodeToUtf8(path)); CoTaskMemFree(path); return result; } bool et::createDirectory(const std::string& name, bool recursive) { if (recursive) { char delim[] = {pathDelimiter, 0}; bool gotError = false; StringList components = split(name, std::string(delim)); std::string path; for (auto& dir : components) { path += dir + "\\"; if (!folderExists(path)) gotError |= ::CreateDirectory(ET_STRING_TO_PARAM_TYPE(path).c_str(), nullptr) == 0; } return !gotError; } return ::CreateDirectory(ET_STRING_TO_PARAM_TYPE(name).c_str(), nullptr) == 0; } bool et::removeFile(const std::string& name) { ET_STRING_TYPE aName = ET_STRING_TO_PARAM_TYPE(name); aName.resize(aName.size() + 1); aName.back() = 0; SHFILEOPSTRUCT fop = { }; fop.wFunc = FO_DELETE; fop.pFrom = aName.c_str(); fop.fFlags = FOF_NO_UI; return SHFileOperation(&fop) == 0; } bool et::copyFile(const std::string& from, const std::string& to) { ET_STRING_TYPE aFrom= ET_STRING_TO_PARAM_TYPE(from); ET_STRING_TYPE aTo = ET_STRING_TO_PARAM_TYPE(to); aFrom.resize(aFrom.size() + 1); aTo.resize(aTo.size() + 1); aFrom.back() = 0; aTo.back() = 0; SHFILEOPSTRUCT fop = { }; fop.wFunc = FO_COPY; fop.pFrom = aFrom.c_str(); fop.pTo = aTo.c_str(); fop.fFlags = FOF_NO_UI; return SHFileOperation(&fop) == 0; } bool et::removeDirectory(const std::string& name) { ET_STRING_TYPE aName = ET_STRING_TO_PARAM_TYPE(name); aName.resize(aName.size() + 1); aName.back() = 0; SHFILEOPSTRUCT fop = { }; fop.wFunc = FO_DELETE; fop.pFrom = aName.c_str(); fop.fFlags = FOF_NO_UI; return SHFileOperation(&fop) == 0; } void et::findSubfolders(const std::string& folder, bool recursive, StringList& list) { StringList folderList; ET_STRING_TYPE normalizedFolder = ET_STRING_TO_PARAM_TYPE(addTrailingSlash(folder)); ET_STRING_TYPE foldersSearchPath = normalizedFolder + allFilesMask; WIN32_FIND_DATA folders = { }; HANDLE folderSearch = FindFirstFile(foldersSearchPath.c_str(), &folders); if (folderSearch != INVALID_HANDLE_VALUE) { do { ET_STRING_TYPE name(folders.cFileName); bool isFolder = (folders.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY; if (isFolder && (name != currentFolder) && (name != previousFolder)) { folderList.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name + ET_STRING_FROM_CONST_CHAR("\\"))); } } while (FindNextFile(folderSearch, &folders)); FindClose(folderSearch); } if (recursive) { for (const std::string& i : folderList) findSubfolders(i, true, list); } list.insert(list.end(), folderList.begin(), folderList.end()); } void et::openUrl(const std::string& url) { ShellExecute(nullptr, ET_STRING_FROM_CONST_CHAR("open"), ET_STRING_TO_PARAM_TYPE(url).c_str(), 0, 0, SW_SHOWNORMAL); } std::string et::unicodeToUtf8(const std::wstring& w) { int mbcWidth = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, 0, 0, 0, 0); if (mbcWidth == 0) return emptyString; DataStorage<char> result(mbcWidth + 1, 0); WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, result.data(), static_cast<int>(result.size()), 0, 0); return std::string(result.data()); } std::wstring et::utf8ToUnicode(const std::string& mbcs) { int uWidth = MultiByteToWideChar(CP_UTF8, 0, mbcs.c_str(), -1, 0, 0); if (uWidth == 0) { switch (GetLastError()) { case ERROR_INSUFFICIENT_BUFFER: std::cout << "A supplied buffer size was not large enough, " "or it was incorrectly set to NULL." << std::endl; break; case ERROR_INVALID_FLAGS: std::cout << "The values supplied for flags were not valid." << std::endl; break; case ERROR_INVALID_PARAMETER: std::cout << "Any of the parameter values was invalid." << std::endl; break; case ERROR_NO_UNICODE_TRANSLATION: std::cout << "Invalid Unicode was found in a string" << std::endl; break; default: std::cout << "Failed to convert utf-8 to wchar_t" << std::endl; } return std::wstring(); } DataStorage<wchar_t> result(uWidth + 1, 0); MultiByteToWideChar(CP_UTF8, 0, mbcs.c_str(), -1, result.data(), static_cast<int>(result.size())); return std::wstring(result.data()); } std::string et::applicationIdentifierForCurrentProject() { return "com.et.app"; } uint64_t et::getFileDate(const std::string& path) { WIN32_FIND_DATA findData = { }; HANDLE search = FindFirstFile(ET_STRING_TO_PARAM_TYPE(path).c_str(), &findData); FindClose(search); return findData.ftLastWriteTime.dwLowDateTime | (static_cast<uint64_t>(findData.ftLastWriteTime.dwHighDateTime) << 32); } std::vector<et::Screen> et::availableScreens() { std::vector<et::Screen> result; EnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hMonitor, HDC, LPRECT, LPARAM dwData) -> BOOL { MONITORINFO info = { sizeof(MONITORINFO) }; GetMonitorInfo(hMonitor, &info); recti screenRect(info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right - info.rcMonitor.left, info.rcMonitor.bottom - info.rcMonitor.top); recti workarea(info.rcWork.left, info.rcWork.top, info.rcWork.right - info.rcWork.left, info.rcWork.bottom - info.rcWork.top); std::vector<et::Screen>* r = reinterpret_cast<std::vector<et::Screen>*>(dwData); r->emplace_back(screenRect, workarea, 1); return 1; }, reinterpret_cast<LPARAM>(&result)); return result; } et::Screen et::currentScreen() { return availableScreens().front(); } std::string et::selectFile(const StringList&, SelectFileMode mode, const std::string& defaultName) { ET_STRING_TYPE defaultFileName = ET_STRING_TO_PARAM_TYPE(defaultName); DataStorage<ET_CHAR_TYPE> defaultFileNameData(etMax(size_t(MAX_PATH), defaultFileName.size()) + 1, 0); etCopyMemory(defaultFileNameData.data(), defaultFileName.data(), defaultFileName.size()); OPENFILENAME of = { }; of.lStructSize = sizeof(of); of.hInstance = GetModuleHandle(nullptr); of.Flags = OFN_DONTADDTORECENT | OFN_ENABLESIZING | OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST; of.lpstrFile = defaultFileNameData.data(); of.nMaxFile = MAX_PATH; #if (_UNICODE) of.lpstrFilter = L"All Files\0*.*\0\0"; #else of.lpstrFilter = "All Files\0*.*\0\0"; #endif auto func = (mode == SelectFileMode::Save) ? GetSaveFileName : GetOpenFileName; return func(&of) ? ET_STRING_TO_OUTPUT_TYPE(of.lpstrFile) : emptyString; } void et::alert(const std::string& title, const std::string& message, const std::string&, AlertType type) { UINT alType = MB_ICONINFORMATION; switch (type) { case AlertType::Warning: { alType = MB_ICONWARNING; break; } case AlertType::Error: { alType = MB_ICONERROR; break; } default: break; } MessageBoxA(nullptr, message.c_str(), title.c_str(), alType); } #endif // ET_PLATFORM_WIN <|endoftext|>
<commit_before>#include "Buttongrid.h" Buttongrid::Buttongrid(){ if(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); //Had to add one more, to avoid some bug } Buttongrid::Buttongrid(unsigned char size){ if(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); //Had to add one more, to avoid some bug columns = size; rows = size; gridSize = size; //Allocate memory for labels if(gridSize!=NULL){ if(labels = (unsigned char**)malloc(gridSize * sizeof(unsigned char*))){ for(int i=0; i<gridSize; i++) { if(labels[i] = (unsigned char*)malloc(gridSize)){ memset(labels[i],0,gridSize); } } } } this->init(); } Buttongrid::Buttongrid(unsigned char r, unsigned char c){ if(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); //Had to add one more, to avoid some bug columns = c; rows = r; //gridSize = size; //Allocate memory for labels if(rows!=NULL){ if(labels = (unsigned char**)malloc(rows * sizeof(unsigned char*))){ for(int i=0; i<rows; i++) { if(labels[i] = (unsigned char*)malloc(columns)){ memset(labels[i],0,columns); } } } } //Allocate memory for names if(rows >= 0 && columns >= 0){ char qty = rows * columns; if(names = (const char**) malloc(qty * 8 * sizeof(char))){ memset(names,0,qty*8*sizeof(char)); } } //this->init(); } Buttongrid::Buttongrid(unsigned int width, unsigned int height, int backgroundColor, int textColor, int borderColor){ if(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); //Had to add one more, to avoid some bug x = 0; y = 0; this->setSize(width,height); this->setColors(backgroundColor,textColor,borderColor); this->init(); } Buttongrid::~Buttongrid(){ if(text) free(text); } void Buttongrid::init(){ Button::init(); type = 0x31; borderWidth = 2; charPos = 0; // Initialize labels with position ID for(byte r=1; r<=rows; r++) { for(byte c=1; c<=columns; c++) { labels[r-1][c-1] = c+columns*(r-1); //Serial.print("Row "); //Serial.print(r); //Serial.print(" Col "); //Serial.print(c); //Serial.print(" Num "); //Serial.println(c+columns*(r-1)); } } } void Buttongrid::drawGrid(){ int xPos,yPos,width,height; int btnWidth,btnHeight; xPos = x; yPos = y; width = w; height = h; btnWidth = w / columns; btnHeight = h / rows; //--nums background rectangle Tft.fillRectangle(xPos,yPos,width,height,bgColor); //-- outer border for(byte i=borderWidth; i!=0;i--){ Tft.drawRectangle(xPos++,yPos++,width--,height--,borderColor); width--; height--; } //-- horizontal lines for(byte j=1;j<rows;j++) { // draw # horizontal lines depending on borderWidth for(byte i=0; i<borderWidth;i++){ Tft.drawHorizontalLine(x,y+btnHeight*j+i-vGap,width+borderWidth,borderColor); } //Only draw gaps in between edges if(vGap>0){ //Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK); for(byte i=0; i<borderWidth;i++){ Tft.drawHorizontalLine(x,y+btnHeight*j+i+borderWidth+vGap,width+borderWidth,borderColor); } } } //-- vertical lines for(byte j=1;j<columns;j++) { // draw # of vertical lines depending on borderWidth for(byte i=0; i<borderWidth;i++){ Tft.drawVerticalLine(x+btnWidth*j+i-hGap,y+borderWidth,height+borderWidth,borderColor); } //Only draw gaps in between edges if(hGap>0){ //Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK); for(byte i=0; i<borderWidth;i++){ Tft.drawVerticalLine(x+btnWidth*j+i+borderWidth+hGap,y+borderWidth,height+borderWidth,borderColor); } } } //-- Gaps fill if(hGap > 0){ for(byte j=1;j<columns;j++){ Tft.fillRectangle(x+j*btnWidth+borderWidth-hGap,y,hGap*2,h,myCanvas->bgColor); } } if(vGap > 0){ for(byte j=1;j<rows;j++){ Tft.fillRectangle(x,y+j*btnHeight+borderWidth-vGap,w,vGap*2,myCanvas->bgColor); } } //-- draw contents byte colIndex=0; byte rowIndex=0; for(byte r=1; r<=rows; r++) { for(byte c=1; c<=columns; c++) { printName(getNumber(r,c)); } } } void Buttongrid::setEventHandler(void (*functionPointer)(Buttongrid *, unsigned char)){ eventHandler = functionPointer; } void Buttongrid::configure(byte size, byte f){ columns = size; rows = size; gridSize = size; font_size = f; show(); } unsigned char Buttongrid::getColumn(unsigned char num){ unsigned char val = num%columns; return val==0 ? columns : val; } unsigned char Buttongrid::getRow(unsigned char num){ num -= 1; unsigned char mod = num%columns; return num/columns + 1; } unsigned char Buttongrid::getNumber(unsigned char row, unsigned char column){ unsigned char val = column + (row - 1) * columns; return val; } void Buttongrid::setNum(unsigned char id){ int boundX1, boundX2, boundY1, boundY2; int btnWidth = w/columns; int btnHeight = h/rows; unsigned char colIndex = getColumn(id)-1; unsigned char rowIndex = getRow(id)-1; unsigned char digits = Tft.Get_Digits(id); //Calculates initial position of text inside the btnWidth //considering the number's width and font size. int xPos = btnWidth/2 - (digits*FONT_X*font_size)/2;//btnWidth/(2) - 6*digits -2; int yPos = btnHeight/(2) - 8; //Calculates position of the text considering //its column or row and the btnWidth. xPos = x+(colIndex*btnWidth)+xPos+borderWidth; yPos = y+yPos+(rowIndex*btnHeight); //Draw contents function Tft.drawNumber(id,xPos,yPos,font_size,BLACK); } void Buttongrid::setLabel(unsigned char id, unsigned char label){ int boundX1, boundX2, boundY1, boundY2; int btnWidth = w/columns; int btnHeight = h/rows; unsigned char colIndex = getColumn(id)-1; unsigned char rowIndex = getRow(id)-1; unsigned char digits = Tft.Get_Digits(label); //labels[rowIndex][colIndex] = label; <---- No, can't do this! No enough memory to hold strings for each button //Calculates initial position of text inside the btnWidth //considering the number's width and font size. int xPos = (btnWidth - digits*6*font_size)/2;//btnWidth/(2) - 6*digits -2; int yPos = (btnHeight-FONT_Y*fontSize)/2;//btnHeight/(2) - 8; //Calculates position of the text considering //its column or row and the btnWidth. xPos = x+(colIndex*btnWidth)+xPos+borderWidth+hGap;//+(2*borderWidth);//+borderWidth; yPos = y+(rowIndex*btnHeight)+yPos+borderWidth+vGap;//+(2*borderWidth); //Draw contents function Tft.drawNumber(label,xPos,yPos,font_size,BLACK); } void Buttongrid::setName(unsigned char id, const char name[8]){ names[id] = name; return; } void Buttongrid::setName(unsigned char id, char number){ //names[id] = ; return; } void Buttongrid::printName(unsigned char id){ const char* name = names[id]; // Calculate characters in name int n; for(n=0;n<8;n++){ if(name[n] == 0) break; } Serial.print(n); Serial.print(" characters for id: "); Serial.print(id); Serial.print(" "); Serial.println(names[id]); //setNum(id); setLabel(id,labels[getRow(id)-1][getColumn(id)-1]); return; // If name is empty draw the id, else draw the name if(n==0){ setNum(id); }else{ //i++; int boundX1, boundX2, boundY1, boundY2; int btnWidth = w/columns; int btnHeight = h/rows; unsigned char colIndex = getColumn(id)-1; unsigned char rowIndex = getRow(id)-1; int xPos = btnWidth/2 - (n*FONT_X*font_size)/2; int yPos = btnHeight/(2) - 8; xPos = x+(colIndex*btnWidth)+xPos+3*borderWidth; yPos = y+yPos+(rowIndex*btnHeight); Tft.drawString((char*)names[id],xPos, yPos, font_size, fgColor); } return; } void Buttongrid::clear(){ drawGrid(); lastPressed = 0; } //Overriden virtual methods bool Buttongrid::checkTouch(Point* p){ int boundX1, boundX2, boundY1, boundY2; int btnWidth = w/columns; int btnHeight = h/rows; bool pressed = false; if(lastMillis + debounceTime < millis()){ if((p->x > x+borderWidth) && (p->x < x+w-borderWidth) && (p->y > y+borderWidth) && (p->y < y+h-borderWidth)){ //num coordinates for(int r = 1;(r <= rows)&&(!pressed); r++) { // Determine the bounding y's for this row boundY1 = y+(btnHeight)*(r-1)+borderWidth; boundY2 = y+(btnHeight)*r-borderWidth; for(int c = 1;(c <= columns)&&(!pressed);c++) { // Determine the bounding x's for this column boundX1 = x + (btnWidth)*(c-1) + borderWidth; boundX2 = x + (btnWidth)*c - borderWidth; int num = columns*(r - 1) + c; if((p->x > boundX1) && (p->x < boundX2) && (p->y > boundY1) && (p->y < boundY2)){ // Restore last button pressed appearance if(clearLastPressed && lastPressed != 0){ int lastX = x + (btnWidth)*(getColumn(lastPressed)-1) + borderWidth; int lastY = y+(btnHeight)*(getRow(lastPressed)-1)+borderWidth; if(HIGHLIGHT == 1){ Tft.fillRectangle(lastX,lastY,btnWidth-borderWidth-1,btnHeight-borderWidth-1,bgColor); } //setLabel(lastPressed,labels[getRow(lastPressed)-1][getColumn(lastPressed)-1]); printName(lastPressed); } // Highlight currently pressed button if(HIGHLIGHT == 1){ Tft.fillRectangle(boundX1,boundY1,btnWidth-borderWidth-1,btnHeight-borderWidth-1,highlightColor); } //setNum(num); //setLabel(num,labels[r-1][c-1]); printName(num); // Call event handler with pressed button id eventHandler(this,num); pressed = true; lastPressed = num; } }// -- columns for loop }// --rows for loop }// -- if touch within widget area touched = !touched; lastMillis = millis(); }// -- debounce return true; // <--- False means block further event checking. } void Buttongrid::show(){ drawGrid(); update(); } void Buttongrid::update(){ return; } <commit_msg>Removed Serial prints from printName in ButtonGrid<commit_after>#include "Buttongrid.h" Buttongrid::Buttongrid(){ if(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); //Had to add one more, to avoid some bug } Buttongrid::Buttongrid(unsigned char size){ if(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); //Had to add one more, to avoid some bug columns = size; rows = size; gridSize = size; //Allocate memory for labels if(gridSize!=NULL){ if(labels = (unsigned char**)malloc(gridSize * sizeof(unsigned char*))){ for(int i=0; i<gridSize; i++) { if(labels[i] = (unsigned char*)malloc(gridSize)){ memset(labels[i],0,gridSize); } } } } this->init(); } Buttongrid::Buttongrid(unsigned char r, unsigned char c){ if(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); //Had to add one more, to avoid some bug columns = c; rows = r; //gridSize = size; //Allocate memory for labels if(rows!=NULL){ if(labels = (unsigned char**)malloc(rows * sizeof(unsigned char*))){ for(int i=0; i<rows; i++) { if(labels[i] = (unsigned char*)malloc(columns)){ memset(labels[i],0,columns); } } } } //Allocate memory for names if(rows >= 0 && columns >= 0){ char qty = rows * columns; if(names = (const char**) malloc(qty * 8 * sizeof(char))){ memset(names,0,qty*8*sizeof(char)); } } //this->init(); } Buttongrid::Buttongrid(unsigned int width, unsigned int height, int backgroundColor, int textColor, int borderColor){ if(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); //Had to add one more, to avoid some bug x = 0; y = 0; this->setSize(width,height); this->setColors(backgroundColor,textColor,borderColor); this->init(); } Buttongrid::~Buttongrid(){ if(text) free(text); } void Buttongrid::init(){ Button::init(); type = 0x31; borderWidth = 2; charPos = 0; // Initialize labels with position ID for(byte r=1; r<=rows; r++) { for(byte c=1; c<=columns; c++) { labels[r-1][c-1] = c+columns*(r-1); //Serial.print("Row "); //Serial.print(r); //Serial.print(" Col "); //Serial.print(c); //Serial.print(" Num "); //Serial.println(c+columns*(r-1)); } } } void Buttongrid::drawGrid(){ int xPos,yPos,width,height; int btnWidth,btnHeight; xPos = x; yPos = y; width = w; height = h; btnWidth = w / columns; btnHeight = h / rows; //--nums background rectangle Tft.fillRectangle(xPos,yPos,width,height,bgColor); //-- outer border for(byte i=borderWidth; i!=0;i--){ Tft.drawRectangle(xPos++,yPos++,width--,height--,borderColor); width--; height--; } //-- horizontal lines for(byte j=1;j<rows;j++) { // draw # horizontal lines depending on borderWidth for(byte i=0; i<borderWidth;i++){ Tft.drawHorizontalLine(x,y+btnHeight*j+i-vGap,width+borderWidth,borderColor); } //Only draw gaps in between edges if(vGap>0){ //Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK); for(byte i=0; i<borderWidth;i++){ Tft.drawHorizontalLine(x,y+btnHeight*j+i+borderWidth+vGap,width+borderWidth,borderColor); } } } //-- vertical lines for(byte j=1;j<columns;j++) { // draw # of vertical lines depending on borderWidth for(byte i=0; i<borderWidth;i++){ Tft.drawVerticalLine(x+btnWidth*j+i-hGap,y+borderWidth,height+borderWidth,borderColor); } //Only draw gaps in between edges if(hGap>0){ //Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK); for(byte i=0; i<borderWidth;i++){ Tft.drawVerticalLine(x+btnWidth*j+i+borderWidth+hGap,y+borderWidth,height+borderWidth,borderColor); } } } //-- Gaps fill if(hGap > 0){ for(byte j=1;j<columns;j++){ Tft.fillRectangle(x+j*btnWidth+borderWidth-hGap,y,hGap*2,h,myCanvas->bgColor); } } if(vGap > 0){ for(byte j=1;j<rows;j++){ Tft.fillRectangle(x,y+j*btnHeight+borderWidth-vGap,w,vGap*2,myCanvas->bgColor); } } //-- draw contents byte colIndex=0; byte rowIndex=0; for(byte r=1; r<=rows; r++) { for(byte c=1; c<=columns; c++) { printName(getNumber(r,c)); } } } void Buttongrid::setEventHandler(void (*functionPointer)(Buttongrid *, unsigned char)){ eventHandler = functionPointer; } void Buttongrid::configure(byte size, byte f){ columns = size; rows = size; gridSize = size; font_size = f; show(); } unsigned char Buttongrid::getColumn(unsigned char num){ unsigned char val = num%columns; return val==0 ? columns : val; } unsigned char Buttongrid::getRow(unsigned char num){ num -= 1; unsigned char mod = num%columns; return num/columns + 1; } unsigned char Buttongrid::getNumber(unsigned char row, unsigned char column){ unsigned char val = column + (row - 1) * columns; return val; } void Buttongrid::setNum(unsigned char id){ int boundX1, boundX2, boundY1, boundY2; int btnWidth = w/columns; int btnHeight = h/rows; unsigned char colIndex = getColumn(id)-1; unsigned char rowIndex = getRow(id)-1; unsigned char digits = Tft.Get_Digits(id); //Calculates initial position of text inside the btnWidth //considering the number's width and font size. int xPos = btnWidth/2 - (digits*FONT_X*font_size)/2;//btnWidth/(2) - 6*digits -2; int yPos = btnHeight/(2) - 8; //Calculates position of the text considering //its column or row and the btnWidth. xPos = x+(colIndex*btnWidth)+xPos+borderWidth; yPos = y+yPos+(rowIndex*btnHeight); //Draw contents function Tft.drawNumber(id,xPos,yPos,font_size,BLACK); } void Buttongrid::setLabel(unsigned char id, unsigned char label){ int boundX1, boundX2, boundY1, boundY2; int btnWidth = w/columns; int btnHeight = h/rows; unsigned char colIndex = getColumn(id)-1; unsigned char rowIndex = getRow(id)-1; unsigned char digits = Tft.Get_Digits(label); //labels[rowIndex][colIndex] = label; <---- No, can't do this! No enough memory to hold strings for each button //Calculates initial position of text inside the btnWidth //considering the number's width and font size. int xPos = (btnWidth - digits*6*font_size)/2;//btnWidth/(2) - 6*digits -2; int yPos = (btnHeight-FONT_Y*fontSize)/2;//btnHeight/(2) - 8; //Calculates position of the text considering //its column or row and the btnWidth. xPos = x+(colIndex*btnWidth)+xPos+borderWidth+hGap;//+(2*borderWidth);//+borderWidth; yPos = y+(rowIndex*btnHeight)+yPos+borderWidth+vGap;//+(2*borderWidth); //Draw contents function Tft.drawNumber(label,xPos,yPos,font_size,BLACK); } void Buttongrid::setName(unsigned char id, const char name[8]){ names[id] = name; return; } void Buttongrid::setName(unsigned char id, char number){ //names[id] = ; return; } void Buttongrid::printName(unsigned char id){ const char* name = names[id]; // Calculate characters in name int n; for(n=0;n<8;n++){ if(name[n] == 0) break; } //Serial.print(n); //Serial.print(" characters for id: "); //Serial.print(id); //Serial.print(" "); //Serial.println(names[id]); //setNum(id); setLabel(id,labels[getRow(id)-1][getColumn(id)-1]); return; // If name is empty draw the id, else draw the name if(n==0){ setNum(id); }else{ //i++; int boundX1, boundX2, boundY1, boundY2; int btnWidth = w/columns; int btnHeight = h/rows; unsigned char colIndex = getColumn(id)-1; unsigned char rowIndex = getRow(id)-1; int xPos = btnWidth/2 - (n*FONT_X*font_size)/2; int yPos = btnHeight/(2) - 8; xPos = x+(colIndex*btnWidth)+xPos+3*borderWidth; yPos = y+yPos+(rowIndex*btnHeight); Tft.drawString((char*)names[id],xPos, yPos, font_size, fgColor); } return; } void Buttongrid::clear(){ drawGrid(); lastPressed = 0; } //Overriden virtual methods bool Buttongrid::checkTouch(Point* p){ int boundX1, boundX2, boundY1, boundY2; int btnWidth = w/columns; int btnHeight = h/rows; bool pressed = false; if(lastMillis + debounceTime < millis()){ if((p->x > x+borderWidth) && (p->x < x+w-borderWidth) && (p->y > y+borderWidth) && (p->y < y+h-borderWidth)){ //num coordinates for(int r = 1;(r <= rows)&&(!pressed); r++) { // Determine the bounding y's for this row boundY1 = y+(btnHeight)*(r-1)+borderWidth; boundY2 = y+(btnHeight)*r-borderWidth; for(int c = 1;(c <= columns)&&(!pressed);c++) { // Determine the bounding x's for this column boundX1 = x + (btnWidth)*(c-1) + borderWidth; boundX2 = x + (btnWidth)*c - borderWidth; int num = columns*(r - 1) + c; if((p->x > boundX1) && (p->x < boundX2) && (p->y > boundY1) && (p->y < boundY2)){ // Restore last button pressed appearance if(clearLastPressed && lastPressed != 0){ int lastX = x + (btnWidth)*(getColumn(lastPressed)-1) + borderWidth; int lastY = y+(btnHeight)*(getRow(lastPressed)-1)+borderWidth; if(HIGHLIGHT == 1){ Tft.fillRectangle(lastX,lastY,btnWidth-borderWidth-1,btnHeight-borderWidth-1,bgColor); } //setLabel(lastPressed,labels[getRow(lastPressed)-1][getColumn(lastPressed)-1]); printName(lastPressed); } // Highlight currently pressed button if(HIGHLIGHT == 1){ Tft.fillRectangle(boundX1,boundY1,btnWidth-borderWidth-1,btnHeight-borderWidth-1,highlightColor); } //setNum(num); //setLabel(num,labels[r-1][c-1]); printName(num); // Call event handler with pressed button id eventHandler(this,num); pressed = true; lastPressed = num; } }// -- columns for loop }// --rows for loop }// -- if touch within widget area touched = !touched; lastMillis = millis(); }// -- debounce return true; // <--- False means block further event checking. } void Buttongrid::show(){ drawGrid(); update(); } void Buttongrid::update(){ return; } <|endoftext|>
<commit_before>#include "chimera/render/BSPTree.hpp" #include <SDL2/SDL.h> template <class T> void swapFace(T& a, T& b) { T c = b; b = a; a = c; } glm::vec3 aprox(const glm::vec3& dado) { return glm::vec3((fabs(dado.x) < EPSILON) ? 0.0f : dado.x, (fabs(dado.y) < EPSILON) ? 0.0f : dado.y, (fabs(dado.z) < EPSILON) ? 0.0f : dado.z); } glm::vec3 intersect(const glm::vec3& linestart, const glm::vec3& lineend, const glm::vec3& vertex, const glm::vec3& normal, float& percentage) { float num = glm::dot(normal, linestart); glm::vec3 direction = lineend - linestart; float linelength = glm::dot(normal, direction); float D = -glm::dot(normal, vertex); // direção inversa percentage = -(num + D) / linelength; glm::vec3 intersection = linestart + percentage * direction; return aprox(intersection); } void splitTriangle(const glm::vec3& fx, Chimera::Triangle* _pTriangle, Chimera::Triangle* _partition, std::vector<Chimera::Triangle>* _pListPolygon) { glm::vec3& a = _pTriangle->vertex[0].position; glm::vec3& b = _pTriangle->vertex[1].position; glm::vec3& c = _pTriangle->vertex[2].position; // acerto para vertex do tex final igualar a rotacao do triangulo Chimera::VertexData* pVertex_a = nullptr; Chimera::VertexData* pVertex_b = nullptr; Chimera::VertexData* pVertex_c = nullptr; // Normaliza Triangulo para que o corte do hiper-plano esteja nos segmentos de reta CA e CB (corte em a e b) if (fx.x * fx.z >= 0) { // corte em a e c swapFace(b, c); swapFace(a, b); pVertex_a = &_pTriangle->vertex[2]; // old c pVertex_b = &_pTriangle->vertex[0]; // old a pVertex_c = &_pTriangle->vertex[1]; // old b } else if (fx.y * fx.z >= 0) { // corte em b e c swapFace(a, c); swapFace(a, b); //-- pVertex_a = &_pTriangle->vertex[1]; // old b pVertex_b = &_pTriangle->vertex[2]; // old c pVertex_c = &_pTriangle->vertex[0]; // old a } else { // Cortre em a e b pVertex_a = &_pTriangle->vertex[0]; // old a pVertex_b = &_pTriangle->vertex[1]; // old b pVertex_c = &_pTriangle->vertex[2]; // old c } float propAC = 0.0; float propBC = 0.0; glm::vec3 A = intersect(a, c, _partition->vertex[0].position, _partition->normal(), propAC); glm::vec3 B = intersect(b, c, _partition->vertex[0].position, _partition->normal(), propBC); // PA texture coord glm::vec2 deltaA = (pVertex_c->texture - pVertex_a->texture) * propAC; glm::vec2 texA = pVertex_a->texture + deltaA; // PB texture coord glm::vec2 deltaB = (pVertex_c->texture - pVertex_b->texture) * propBC; glm::vec2 texB = pVertex_b->texture + deltaB; //-- T1 Chimera::Triangle T1(a, b, A); T1.vertex[0].texture = pVertex_a->texture; // a old b T1.vertex[1].texture = pVertex_b->texture; // b old c T1.vertex[2].texture = texA; // A //-- T2 Chimera::Triangle T2(b, B, A); T2.vertex[0].texture = pVertex_b->texture; // b old c T2.vertex[1].texture = texB; // B T2.vertex[2].texture = texA; // A // -- T3 Chimera::Triangle T3(A, B, c); T3.vertex[0].texture = texA; // A T3.vertex[1].texture = texB; // B T3.vertex[2].texture = pVertex_c->texture; // c old a for (int i = 0; i < 3; i++) { T1.vertex[i].normal = _pTriangle->vertex[i].normal; T2.vertex[i].normal = _pTriangle->vertex[i].normal; T3.vertex[i].normal = _pTriangle->vertex[i].normal; } _pListPolygon->push_back(T1); _pListPolygon->push_back(T2); _pListPolygon->push_back(T3); } SIDE classifyPoly(Chimera::Triangle* plane, Chimera::Triangle* poly, glm::vec3& _resultTest) { // ref: http://www.cs.utah.edu/~jsnider/SeniorProj/BSP/default.htm unsigned short infront = 0; unsigned short behind = 0; unsigned short onPlane = 0; float result[3]; for (unsigned short a = 0; a < 3; a++) { glm::vec3 direction = plane->vertex[0].position - poly->vertex[a].position; result[a] = glm::dot(direction, plane->normal()); if (result[a] > EPSILON) { behind++; } else if (result[a] < -EPSILON) { infront++; } else { onPlane++; infront++; behind++; } } _resultTest.x = result[0]; _resultTest.y = result[1]; _resultTest.z = result[2]; if (onPlane == 3) return SIDE::CP_ONPLANE; if (behind == 3) return SIDE::CP_BACK; if (infront == 3) return SIDE::CP_FRONT; return SIDE::CP_SPANNING; } BSPTreeNode* bsptreeBuild(std::vector<Chimera::Triangle>* _pListPolygon) { if (_pListPolygon->empty() == true) return nullptr; // tree->partition BSPTreeNode* tree = new BSPTreeNode(_pListPolygon->back()); _pListPolygon->pop_back(); tree->polygons.push_back(tree->partition); std::vector<Chimera::Triangle> front_list; std::vector<Chimera::Triangle> back_list; while (_pListPolygon->empty() == false) { Chimera::Triangle poly = _pListPolygon->back(); _pListPolygon->pop_back(); glm::vec3 result; SIDE teste = classifyPoly(&tree->partition, &poly, result); if (teste == SIDE::CP_BACK) back_list.push_back(poly); else if (teste == SIDE::CP_FRONT) front_list.push_back(poly); else if (teste == SIDE::CP_ONPLANE) tree->polygons.push_back(poly); else // CP_SPANNING splitTriangle(result, &poly, &tree->partition, _pListPolygon); } tree->front = bsptreeBuild(&front_list); tree->back = bsptreeBuild(&back_list); return tree; } //------PARSER METODOS------ SIDE classifyPoint(Chimera::Triangle* plane, glm::vec3* eye) { // ref: http://www.cs.utah.edu/~jsnider/SeniorProj/BSP/default.htm float result; glm::vec3* vec1 = (glm::vec3*)&plane->vertex[0]; glm::vec3 dir = (*vec1) - (*eye); result = glm::dot(dir, plane->normal()); if (result < -EPSILON) return SIDE::CP_FRONT; if (result > EPSILON) return SIDE::CP_BACK; return SIDE::CP_ONPLANE; } void drawPolygon(BSPTreeNode* tree, std::vector<Chimera::VertexData>* _pOutVertex, bool logdata, bool frontSide) { // tree->arrayTriangle.DrawPolygons(); // Abaixo equivale a esta linha for (auto it = tree->polygons.begin(); it != tree->polygons.end(); it++) { Chimera::Triangle t = (*it); // if (t.getSerial() == 10) // 8, 9, 10 // continue; _pOutVertex->push_back(t.vertex[0]); _pOutVertex->push_back(t.vertex[1]); _pOutVertex->push_back(t.vertex[2]); // FIXME: remover depois de concluir o algoritmo if (logdata == true) { if (frontSide == true) SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Face F: %d", t.getSerial()); else SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Face B: %d", t.getSerial()); } } } void traverseTree(BSPTreeNode* tree, glm::vec3* eye, std::vector<Chimera::VertexData>* _pOutVertex, bool logdata) { // ref: https://web.cs.wpi.edu/~matt/courses/cs563/talks/bsp/document.html if (tree == nullptr) return; SIDE result = classifyPoint(&tree->partition, eye); if (result == SIDE::CP_FRONT) { traverseTree(tree->back, eye, _pOutVertex, logdata); drawPolygon(tree, _pOutVertex, logdata, true); traverseTree(tree->front, eye, _pOutVertex, logdata); } else if (result == SIDE::CP_BACK) { traverseTree(tree->front, eye, _pOutVertex, logdata); drawPolygon(tree, _pOutVertex, logdata, false); traverseTree(tree->back, eye, _pOutVertex, logdata); } else { // result == SIDE::CP_ONPLANE // the eye point is on the partition plane... traverseTree(tree->front, eye, _pOutVertex, logdata); traverseTree(tree->back, eye, _pOutVertex, logdata); } } void bsptreeDraw(BSPTreeNode* _pRoot, glm::vec3* eye, std::vector<Chimera::VertexData>* _pOutVertex, bool logdata) { traverseTree(_pRoot, eye, _pOutVertex, logdata); } bool getIntersect(glm::vec3* linestart, glm::vec3* lineend, glm::vec3* vertex, glm::vec3* normal, glm::vec3* intersection, float* percentage) { glm::vec3 direction, L1; float linelength, dist_from_plane; direction.x = lineend->x - linestart->x; direction.y = lineend->y - linestart->y; direction.z = lineend->z - linestart->z; linelength = glm::dot(direction, *normal); if (fabsf(linelength) < 0.0001) { return false; } L1.x = vertex->x - linestart->x; L1.y = vertex->y - linestart->y; L1.z = vertex->z - linestart->z; dist_from_plane = glm::dot(L1, *normal); *percentage = dist_from_plane / linelength; if (*percentage < 0.0f) { return false; } else if (*percentage > 1.0f) { return false; } intersection->x = linestart->x + direction.x * (*percentage); intersection->y = linestart->y + direction.y * (*percentage); intersection->z = linestart->z + direction.z * (*percentage); return true; }<commit_msg>melhoria<commit_after>#include "chimera/render/BSPTree.hpp" #include <SDL2/SDL.h> template <class T> void swapFace(T& a, T& b) { T c = b; b = a; a = c; } glm::vec3 aprox(const glm::vec3& dado) { return glm::vec3((fabs(dado.x) < EPSILON) ? 0.0f : dado.x, (fabs(dado.y) < EPSILON) ? 0.0f : dado.y, (fabs(dado.z) < EPSILON) ? 0.0f : dado.z); } bool intersect(const glm::vec3& linestart, const glm::vec3& lineend, const glm::vec3& vertex, const glm::vec3& normal, glm::vec3& intersection, float& percentage) { glm::vec3 direction = lineend - linestart; float linelength = glm::dot(direction, normal); if (fabsf(linelength) < 0.0001) return false; glm::vec3 L1 = vertex - linestart; float dist_from_plane = glm::dot(L1, normal); percentage = dist_from_plane / linelength; if (percentage < 0.0f) return false; else if (percentage > 1.0f) return false; intersection = linestart + (direction * percentage); return true; } void splitTriangle(const glm::vec3& fx, Chimera::Triangle* _pTriangle, Chimera::Triangle* _partition, std::vector<Chimera::Triangle>* _pListPolygon) { glm::vec3& a = _pTriangle->vertex[0].position; glm::vec3& b = _pTriangle->vertex[1].position; glm::vec3& c = _pTriangle->vertex[2].position; // acerto para vertex do tex final igualar a rotacao do triangulo Chimera::VertexData* pVertex_a = nullptr; Chimera::VertexData* pVertex_b = nullptr; Chimera::VertexData* pVertex_c = nullptr; // Normaliza Triangulo para que o corte do hiper-plano esteja nos segmentos de reta CA e CB (corte em a e b) if (fx.x * fx.z >= 0) { // corte em a e c swapFace(b, c); swapFace(a, b); pVertex_a = &_pTriangle->vertex[2]; // old c pVertex_b = &_pTriangle->vertex[0]; // old a pVertex_c = &_pTriangle->vertex[1]; // old b } else if (fx.y * fx.z >= 0) { // corte em b e c swapFace(a, c); swapFace(a, b); //-- pVertex_a = &_pTriangle->vertex[1]; // old b pVertex_b = &_pTriangle->vertex[2]; // old c pVertex_c = &_pTriangle->vertex[0]; // old a } else { // Cortre em a e b pVertex_a = &_pTriangle->vertex[0]; // old a pVertex_b = &_pTriangle->vertex[1]; // old b pVertex_c = &_pTriangle->vertex[2]; // old c } float propAC = 0.0; float propBC = 0.0; glm::vec3 A, B; intersect(a, c, _partition->vertex[0].position, _partition->normal(), A, propAC); intersect(b, c, _partition->vertex[0].position, _partition->normal(), B, propBC); // PA texture coord glm::vec2 deltaA = (pVertex_c->texture - pVertex_a->texture) * propAC; glm::vec2 texA = pVertex_a->texture + deltaA; // PB texture coord glm::vec2 deltaB = (pVertex_c->texture - pVertex_b->texture) * propBC; glm::vec2 texB = pVertex_b->texture + deltaB; //-- T1 Chimera::Triangle T1(a, b, A); T1.vertex[0].texture = pVertex_a->texture; // a old b T1.vertex[1].texture = pVertex_b->texture; // b old c T1.vertex[2].texture = texA; // A //-- T2 Chimera::Triangle T2(b, B, A); T2.vertex[0].texture = pVertex_b->texture; // b old c T2.vertex[1].texture = texB; // B T2.vertex[2].texture = texA; // A // -- T3 Chimera::Triangle T3(A, B, c); T3.vertex[0].texture = texA; // A T3.vertex[1].texture = texB; // B T3.vertex[2].texture = pVertex_c->texture; // c old a for (int i = 0; i < 3; i++) { T1.vertex[i].normal = _pTriangle->vertex[i].normal; T2.vertex[i].normal = _pTriangle->vertex[i].normal; T3.vertex[i].normal = _pTriangle->vertex[i].normal; } _pListPolygon->push_back(T1); _pListPolygon->push_back(T2); _pListPolygon->push_back(T3); } SIDE classifyPoly(Chimera::Triangle* plane, Chimera::Triangle* poly, glm::vec3& _resultTest) { // ref: http://www.cs.utah.edu/~jsnider/SeniorProj/BSP/default.htm unsigned short infront = 0; unsigned short behind = 0; unsigned short onPlane = 0; float result[3]; for (unsigned short a = 0; a < 3; a++) { glm::vec3 direction = plane->vertex[0].position - poly->vertex[a].position; result[a] = glm::dot(direction, plane->normal()); if (result[a] > EPSILON) { behind++; } else if (result[a] < -EPSILON) { infront++; } else { onPlane++; infront++; behind++; } } _resultTest.x = result[0]; _resultTest.y = result[1]; _resultTest.z = result[2]; if (onPlane == 3) return SIDE::CP_ONPLANE; if (behind == 3) return SIDE::CP_BACK; if (infront == 3) return SIDE::CP_FRONT; return SIDE::CP_SPANNING; } BSPTreeNode* bsptreeBuild(std::vector<Chimera::Triangle>* _pListPolygon) { if (_pListPolygon->empty() == true) return nullptr; // tree->partition BSPTreeNode* tree = new BSPTreeNode(_pListPolygon->back()); _pListPolygon->pop_back(); tree->polygons.push_back(tree->partition); std::vector<Chimera::Triangle> front_list; std::vector<Chimera::Triangle> back_list; while (_pListPolygon->empty() == false) { Chimera::Triangle poly = _pListPolygon->back(); _pListPolygon->pop_back(); glm::vec3 result; SIDE teste = classifyPoly(&tree->partition, &poly, result); if (teste == SIDE::CP_BACK) back_list.push_back(poly); else if (teste == SIDE::CP_FRONT) front_list.push_back(poly); else if (teste == SIDE::CP_ONPLANE) tree->polygons.push_back(poly); else // CP_SPANNING splitTriangle(result, &poly, &tree->partition, _pListPolygon); } tree->front = bsptreeBuild(&front_list); tree->back = bsptreeBuild(&back_list); return tree; } //------PARSER METODOS------ SIDE classifyPoint(Chimera::Triangle* plane, glm::vec3* eye) { // ref: http://www.cs.utah.edu/~jsnider/SeniorProj/BSP/default.htm float result; glm::vec3* vec1 = (glm::vec3*)&plane->vertex[0]; glm::vec3 dir = (*vec1) - (*eye); result = glm::dot(dir, plane->normal()); if (result < -EPSILON) return SIDE::CP_FRONT; if (result > EPSILON) return SIDE::CP_BACK; return SIDE::CP_ONPLANE; } void drawPolygon(BSPTreeNode* tree, std::vector<Chimera::VertexData>* _pOutVertex, bool logdata, bool frontSide) { // tree->arrayTriangle.DrawPolygons(); // Abaixo equivale a esta linha for (auto it = tree->polygons.begin(); it != tree->polygons.end(); it++) { Chimera::Triangle t = (*it); // if (t.getSerial() == 10) // 8, 9, 10 // continue; _pOutVertex->push_back(t.vertex[0]); _pOutVertex->push_back(t.vertex[1]); _pOutVertex->push_back(t.vertex[2]); // FIXME: remover depois de concluir o algoritmo if (logdata == true) { if (frontSide == true) SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Face F: %d", t.getSerial()); else SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Face B: %d", t.getSerial()); } } } void traverseTree(BSPTreeNode* tree, glm::vec3* eye, std::vector<Chimera::VertexData>* _pOutVertex, bool logdata) { // ref: https://web.cs.wpi.edu/~matt/courses/cs563/talks/bsp/document.html if (tree == nullptr) return; SIDE result = classifyPoint(&tree->partition, eye); if (result == SIDE::CP_FRONT) { traverseTree(tree->back, eye, _pOutVertex, logdata); drawPolygon(tree, _pOutVertex, logdata, true); traverseTree(tree->front, eye, _pOutVertex, logdata); } else if (result == SIDE::CP_BACK) { traverseTree(tree->front, eye, _pOutVertex, logdata); drawPolygon(tree, _pOutVertex, logdata, false); traverseTree(tree->back, eye, _pOutVertex, logdata); } else { // result == SIDE::CP_ONPLANE // the eye point is on the partition plane... traverseTree(tree->front, eye, _pOutVertex, logdata); traverseTree(tree->back, eye, _pOutVertex, logdata); } } void bsptreeDraw(BSPTreeNode* _pRoot, glm::vec3* eye, std::vector<Chimera::VertexData>* _pOutVertex, bool logdata) { traverseTree(_pRoot, eye, _pOutVertex, logdata); } <|endoftext|>
<commit_before><commit_msg>Reverse prefetch field trial defaults<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/gtk/menu_gtk.h" #include "app/gfx/gtk_util.h" #include "app/l10n_util.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/stl_util-inl.h" #include "base/string_util.h" #include "chrome/browser/gtk/standard_menus.h" #include "chrome/common/gtk_util.h" #include "third_party/skia/include/core/SkBitmap.h" using gtk_util::ConvertAcceleratorsFromWindowsStyle; bool MenuGtk::block_activation_ = false; MenuGtk::MenuGtk(MenuGtk::Delegate* delegate, const MenuCreateMaterial* menu_data, GtkAccelGroup* accel_group) : delegate_(delegate), dummy_accel_group_(gtk_accel_group_new()), menu_(gtk_menu_new()), factory_(this) { ConnectSignalHandlers(); BuildMenuIn(menu_.get(), menu_data, accel_group); } MenuGtk::MenuGtk(MenuGtk::Delegate* delegate, bool load) : delegate_(delegate), dummy_accel_group_(NULL), menu_(gtk_menu_new()), factory_(this) { ConnectSignalHandlers(); if (load) BuildMenuFromDelegate(); } MenuGtk::~MenuGtk() { menu_.Destroy(); STLDeleteContainerPointers(submenus_we_own_.begin(), submenus_we_own_.end()); if (dummy_accel_group_) g_object_unref(dummy_accel_group_); } void MenuGtk::ConnectSignalHandlers() { // We connect afterwards because OnMenuShow calls SetMenuItemInfo, which may // take a long time or even start a nested message loop. g_signal_connect(menu_.get(), "show", G_CALLBACK(OnMenuShow), this); g_signal_connect(menu_.get(), "hide", G_CALLBACK(OnMenuHidden), this); } void MenuGtk::AppendMenuItemWithLabel(int command_id, const std::string& label) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_menu_item_new_with_mnemonic(converted_label.c_str()); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendMenuItemWithIcon(int command_id, const std::string& label, const SkBitmap& icon) { GtkWidget* menu_item = BuildMenuItemWithImage(label, icon); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendCheckMenuItemWithLabel(int command_id, const std::string& label) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_check_menu_item_new_with_mnemonic(converted_label.c_str()); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendSeparator() { GtkWidget* menu_item = gtk_separator_menu_item_new(); gtk_widget_show(menu_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item); } void MenuGtk::AppendMenuItem(int command_id, GtkWidget* menu_item) { g_object_set_data(G_OBJECT(menu_item), "menu-id", reinterpret_cast<void*>(command_id)); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); gtk_widget_show(menu_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item); } void MenuGtk::Popup(GtkWidget* widget, GdkEvent* event) { DCHECK(event->type == GDK_BUTTON_PRESS) << "Non-button press event sent to RunMenuAt"; GdkEventButton* event_button = reinterpret_cast<GdkEventButton*>(event); Popup(widget, event_button->button, event_button->time); } void MenuGtk::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) { gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, WidgetMenuPositionFunc, widget, button_type, timestamp); } void MenuGtk::PopupAsContext(guint32 event_time) { // TODO(estade): |button| value of 3 (6th argument) is not strictly true, // but does it matter? gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, NULL, NULL, 3, event_time); } void MenuGtk::PopupAsContextAt(guint32 event_time, gfx::Point point) { gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, PointMenuPositionFunc, &point, 3, event_time); } void MenuGtk::PopupAsFromKeyEvent(GtkWidget* widget) { Popup(widget, 0, gtk_get_current_event_time()); gtk_menu_shell_select_first(GTK_MENU_SHELL(menu_.get()), FALSE); } void MenuGtk::Cancel() { gtk_menu_popdown(GTK_MENU(menu_.get())); } void MenuGtk::BuildMenuIn(GtkWidget* menu, const MenuCreateMaterial* menu_data, GtkAccelGroup* accel_group) { // We keep track of the last menu item in order to group radio items. GtkWidget* last_menu_item = NULL; for (; menu_data->type != MENU_END; ++menu_data) { GtkWidget* menu_item = NULL; std::string label; if (menu_data->label_argument) { label = l10n_util::GetStringFUTF8( menu_data->label_id, l10n_util::GetStringUTF16(menu_data->label_argument)); } else if (menu_data->label_id) { label = l10n_util::GetStringUTF8(menu_data->label_id); } else if (menu_data->type != MENU_SEPARATOR) { label = delegate_->GetLabel(menu_data->id); DCHECK(!label.empty()); } label = ConvertAcceleratorsFromWindowsStyle(label); switch (menu_data->type) { case MENU_RADIO: if (GTK_IS_RADIO_MENU_ITEM(last_menu_item)) { menu_item = gtk_radio_menu_item_new_with_mnemonic_from_widget( GTK_RADIO_MENU_ITEM(last_menu_item), label.c_str()); } else { menu_item = gtk_radio_menu_item_new_with_mnemonic( NULL, label.c_str()); } break; case MENU_CHECKBOX: menu_item = gtk_check_menu_item_new_with_mnemonic(label.c_str()); break; case MENU_SEPARATOR: menu_item = gtk_separator_menu_item_new(); break; case MENU_NORMAL: default: menu_item = gtk_menu_item_new_with_mnemonic(label.c_str()); break; } if (menu_data->submenu) { GtkWidget* submenu = gtk_menu_new(); BuildMenuIn(submenu, menu_data->submenu, accel_group); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu); } else if (menu_data->custom_submenu) { gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), menu_data->custom_submenu->menu_.get()); submenus_we_own_.push_back(menu_data->custom_submenu); } if (menu_data->accel_key) { // If we ever want to let the user do any key remaping, we'll need to // change the following so we make a gtk_accel_map which keeps the actual // keys. gtk_widget_add_accelerator(menu_item, "activate", menu_data->only_show || !accel_group ? dummy_accel_group_ : accel_group, menu_data->accel_key, GdkModifierType(menu_data->accel_modifiers), GTK_ACCEL_VISIBLE); } g_object_set_data(G_OBJECT(menu_item), "menu-data", const_cast<MenuCreateMaterial*>(menu_data)); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); gtk_widget_show(menu_item); gtk_menu_append(menu, menu_item); last_menu_item = menu_item; } } GtkWidget* MenuGtk::BuildMenuItemWithImage(const std::string& label, const SkBitmap& icon) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_image_menu_item_new_with_mnemonic(converted_label.c_str()); GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&icon); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item), gtk_image_new_from_pixbuf(pixbuf)); g_object_unref(pixbuf); if (delegate_->AlwaysShowImages()) gtk_util::SetAlwaysShowImage(menu_item); return menu_item; } void MenuGtk::BuildMenuFromDelegate() { // Note that the menu IDs start at 1, not 0. for (int i = 1; i <= delegate_->GetItemCount(); ++i) { GtkWidget* menu_item = NULL; if (delegate_->IsItemSeparator(i)) { menu_item = gtk_separator_menu_item_new(); } else if (delegate_->HasIcon(i)) { const SkBitmap* icon = delegate_->GetIcon(i); menu_item = BuildMenuItemWithImage(delegate_->GetLabel(i), *icon); } else { menu_item = gtk_menu_item_new_with_label(delegate_->GetLabel(i).c_str()); } AppendMenuItem(i, menu_item); } } // static void MenuGtk::OnMenuItemActivated(GtkMenuItem* menuitem, MenuGtk* menu) { if (block_activation_) return; // We receive activation messages when highlighting a menu that has a // submenu. Ignore them. if (gtk_menu_item_get_submenu(menuitem)) return; const MenuCreateMaterial* data = reinterpret_cast<const MenuCreateMaterial*>( g_object_get_data(G_OBJECT(menuitem), "menu-data")); int id; if (data) { id = data->id; } else { id = reinterpret_cast<intptr_t>(g_object_get_data(G_OBJECT(menuitem), "menu-id")); } // The menu item can still be activated by hotkeys even if it is disabled. if (menu->delegate_->IsCommandEnabled(id)) menu->delegate_->ExecuteCommand(id); } // static void MenuGtk::WidgetMenuPositionFunc(GtkMenu* menu, int* x, int* y, gboolean* push_in, void* void_widget) { GtkWidget* widget = GTK_WIDGET(void_widget); GtkRequisition menu_req; gtk_widget_size_request(GTK_WIDGET(menu), &menu_req); gdk_window_get_origin(widget->window, x, y); GdkScreen *screen = gtk_widget_get_screen(widget); gint monitor = gdk_screen_get_monitor_at_point(screen, *x, *y); GdkRectangle screen_rect; gdk_screen_get_monitor_geometry(screen, monitor, &screen_rect); if (GTK_WIDGET_NO_WINDOW(widget)) { *x += widget->allocation.x; *y += widget->allocation.y; } *y += widget->allocation.height; bool start_align = !!g_object_get_data(G_OBJECT(widget), "left-align-popup"); if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) start_align = !start_align; if (!start_align) *x += widget->allocation.width - menu_req.width; // If the menu would run off the bottom of the screen, and there is more // screen space up than down, then pop upwards. if (*y + menu_req.height >= screen_rect.height && *y > screen_rect.height / 2) { *y -= menu_req.height; } *push_in = FALSE; } // static void MenuGtk::PointMenuPositionFunc(GtkMenu* menu, int* x, int* y, gboolean* push_in, gpointer userdata) { *push_in = TRUE; gfx::Point* point = reinterpret_cast<gfx::Point*>(userdata); *x = point->x(); *y = point->y(); } void MenuGtk::UpdateMenu() { gtk_container_foreach(GTK_CONTAINER(menu_.get()), SetMenuItemInfo, this); } // static void MenuGtk::OnMenuShow(GtkWidget* widget, MenuGtk* menu) { MessageLoop::current()->PostTask(FROM_HERE, menu->factory_.NewRunnableMethod(&MenuGtk::UpdateMenu)); } // static void MenuGtk::OnMenuHidden(GtkWidget* widget, MenuGtk* menu) { menu->delegate_->StoppedShowing(); } // static void MenuGtk::SetMenuItemInfo(GtkWidget* widget, gpointer userdata) { if (GTK_IS_SEPARATOR_MENU_ITEM(widget)) { // We need to explicitly handle this case because otherwise we'll ask the // menu delegate about something with an invalid id. return; } MenuGtk* menu = reinterpret_cast<MenuGtk*>(userdata); int id; const MenuCreateMaterial* data = reinterpret_cast<const MenuCreateMaterial*>( g_object_get_data(G_OBJECT(widget), "menu-data")); if (data) { id = data->id; } else { id = reinterpret_cast<intptr_t>(g_object_get_data(G_OBJECT(widget), "menu-id")); } if (GTK_IS_CHECK_MENU_ITEM(widget)) { GtkCheckMenuItem* item = GTK_CHECK_MENU_ITEM(widget); // gtk_check_menu_item_set_active() will send the activate signal. Touching // the underlying "active" property will also call the "activate" handler // for this menu item. So we prevent the "activate" handler from // being called while we set the checkbox. // Why not use one of the glib signal-blocking functions? Because when we // toggle a radio button, it will deactivate one of the other radio buttons, // which we don't have a pointer to. // Wny not make this a member variable? Because "menu" is a pointer to the // root of the MenuGtk and we want to disable *all* MenuGtks, including // submenus. block_activation_ = true; gtk_check_menu_item_set_active(item, menu->delegate_->IsItemChecked(id)); block_activation_ = false; } if (GTK_IS_MENU_ITEM(widget)) { gtk_widget_set_sensitive( widget, menu->delegate_->IsCommandEnabled(id)); GtkWidget* submenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(widget)); if (submenu) { gtk_container_foreach(GTK_CONTAINER(submenu), &SetMenuItemInfo, userdata); } } } <commit_msg>GTK: Fix popup menu positioning.<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/gtk/menu_gtk.h" #include "app/gfx/gtk_util.h" #include "app/l10n_util.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/stl_util-inl.h" #include "base/string_util.h" #include "chrome/browser/gtk/standard_menus.h" #include "chrome/common/gtk_util.h" #include "third_party/skia/include/core/SkBitmap.h" using gtk_util::ConvertAcceleratorsFromWindowsStyle; bool MenuGtk::block_activation_ = false; MenuGtk::MenuGtk(MenuGtk::Delegate* delegate, const MenuCreateMaterial* menu_data, GtkAccelGroup* accel_group) : delegate_(delegate), dummy_accel_group_(gtk_accel_group_new()), menu_(gtk_menu_new()), factory_(this) { ConnectSignalHandlers(); BuildMenuIn(menu_.get(), menu_data, accel_group); } MenuGtk::MenuGtk(MenuGtk::Delegate* delegate, bool load) : delegate_(delegate), dummy_accel_group_(NULL), menu_(gtk_menu_new()), factory_(this) { ConnectSignalHandlers(); if (load) BuildMenuFromDelegate(); } MenuGtk::~MenuGtk() { menu_.Destroy(); STLDeleteContainerPointers(submenus_we_own_.begin(), submenus_we_own_.end()); if (dummy_accel_group_) g_object_unref(dummy_accel_group_); } void MenuGtk::ConnectSignalHandlers() { // We connect afterwards because OnMenuShow calls SetMenuItemInfo, which may // take a long time or even start a nested message loop. g_signal_connect(menu_.get(), "show", G_CALLBACK(OnMenuShow), this); g_signal_connect(menu_.get(), "hide", G_CALLBACK(OnMenuHidden), this); } void MenuGtk::AppendMenuItemWithLabel(int command_id, const std::string& label) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_menu_item_new_with_mnemonic(converted_label.c_str()); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendMenuItemWithIcon(int command_id, const std::string& label, const SkBitmap& icon) { GtkWidget* menu_item = BuildMenuItemWithImage(label, icon); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendCheckMenuItemWithLabel(int command_id, const std::string& label) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_check_menu_item_new_with_mnemonic(converted_label.c_str()); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendSeparator() { GtkWidget* menu_item = gtk_separator_menu_item_new(); gtk_widget_show(menu_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item); } void MenuGtk::AppendMenuItem(int command_id, GtkWidget* menu_item) { g_object_set_data(G_OBJECT(menu_item), "menu-id", reinterpret_cast<void*>(command_id)); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); gtk_widget_show(menu_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item); } void MenuGtk::Popup(GtkWidget* widget, GdkEvent* event) { DCHECK(event->type == GDK_BUTTON_PRESS) << "Non-button press event sent to RunMenuAt"; GdkEventButton* event_button = reinterpret_cast<GdkEventButton*>(event); Popup(widget, event_button->button, event_button->time); } void MenuGtk::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) { gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, WidgetMenuPositionFunc, widget, button_type, timestamp); } void MenuGtk::PopupAsContext(guint32 event_time) { // TODO(estade): |button| value of 3 (6th argument) is not strictly true, // but does it matter? gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, NULL, NULL, 3, event_time); } void MenuGtk::PopupAsContextAt(guint32 event_time, gfx::Point point) { gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, PointMenuPositionFunc, &point, 3, event_time); } void MenuGtk::PopupAsFromKeyEvent(GtkWidget* widget) { Popup(widget, 0, gtk_get_current_event_time()); gtk_menu_shell_select_first(GTK_MENU_SHELL(menu_.get()), FALSE); } void MenuGtk::Cancel() { gtk_menu_popdown(GTK_MENU(menu_.get())); } void MenuGtk::BuildMenuIn(GtkWidget* menu, const MenuCreateMaterial* menu_data, GtkAccelGroup* accel_group) { // We keep track of the last menu item in order to group radio items. GtkWidget* last_menu_item = NULL; for (; menu_data->type != MENU_END; ++menu_data) { GtkWidget* menu_item = NULL; std::string label; if (menu_data->label_argument) { label = l10n_util::GetStringFUTF8( menu_data->label_id, l10n_util::GetStringUTF16(menu_data->label_argument)); } else if (menu_data->label_id) { label = l10n_util::GetStringUTF8(menu_data->label_id); } else if (menu_data->type != MENU_SEPARATOR) { label = delegate_->GetLabel(menu_data->id); DCHECK(!label.empty()); } label = ConvertAcceleratorsFromWindowsStyle(label); switch (menu_data->type) { case MENU_RADIO: if (GTK_IS_RADIO_MENU_ITEM(last_menu_item)) { menu_item = gtk_radio_menu_item_new_with_mnemonic_from_widget( GTK_RADIO_MENU_ITEM(last_menu_item), label.c_str()); } else { menu_item = gtk_radio_menu_item_new_with_mnemonic( NULL, label.c_str()); } break; case MENU_CHECKBOX: menu_item = gtk_check_menu_item_new_with_mnemonic(label.c_str()); break; case MENU_SEPARATOR: menu_item = gtk_separator_menu_item_new(); break; case MENU_NORMAL: default: menu_item = gtk_menu_item_new_with_mnemonic(label.c_str()); break; } if (menu_data->submenu) { GtkWidget* submenu = gtk_menu_new(); BuildMenuIn(submenu, menu_data->submenu, accel_group); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu); } else if (menu_data->custom_submenu) { gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), menu_data->custom_submenu->menu_.get()); submenus_we_own_.push_back(menu_data->custom_submenu); } if (menu_data->accel_key) { // If we ever want to let the user do any key remaping, we'll need to // change the following so we make a gtk_accel_map which keeps the actual // keys. gtk_widget_add_accelerator(menu_item, "activate", menu_data->only_show || !accel_group ? dummy_accel_group_ : accel_group, menu_data->accel_key, GdkModifierType(menu_data->accel_modifiers), GTK_ACCEL_VISIBLE); } g_object_set_data(G_OBJECT(menu_item), "menu-data", const_cast<MenuCreateMaterial*>(menu_data)); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); gtk_widget_show(menu_item); gtk_menu_append(menu, menu_item); last_menu_item = menu_item; } } GtkWidget* MenuGtk::BuildMenuItemWithImage(const std::string& label, const SkBitmap& icon) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_image_menu_item_new_with_mnemonic(converted_label.c_str()); GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&icon); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item), gtk_image_new_from_pixbuf(pixbuf)); g_object_unref(pixbuf); if (delegate_->AlwaysShowImages()) gtk_util::SetAlwaysShowImage(menu_item); return menu_item; } void MenuGtk::BuildMenuFromDelegate() { // Note that the menu IDs start at 1, not 0. for (int i = 1; i <= delegate_->GetItemCount(); ++i) { GtkWidget* menu_item = NULL; if (delegate_->IsItemSeparator(i)) { menu_item = gtk_separator_menu_item_new(); } else if (delegate_->HasIcon(i)) { const SkBitmap* icon = delegate_->GetIcon(i); menu_item = BuildMenuItemWithImage(delegate_->GetLabel(i), *icon); } else { menu_item = gtk_menu_item_new_with_label(delegate_->GetLabel(i).c_str()); } AppendMenuItem(i, menu_item); } } // static void MenuGtk::OnMenuItemActivated(GtkMenuItem* menuitem, MenuGtk* menu) { if (block_activation_) return; // We receive activation messages when highlighting a menu that has a // submenu. Ignore them. if (gtk_menu_item_get_submenu(menuitem)) return; const MenuCreateMaterial* data = reinterpret_cast<const MenuCreateMaterial*>( g_object_get_data(G_OBJECT(menuitem), "menu-data")); int id; if (data) { id = data->id; } else { id = reinterpret_cast<intptr_t>(g_object_get_data(G_OBJECT(menuitem), "menu-id")); } // The menu item can still be activated by hotkeys even if it is disabled. if (menu->delegate_->IsCommandEnabled(id)) menu->delegate_->ExecuteCommand(id); } // static void MenuGtk::WidgetMenuPositionFunc(GtkMenu* menu, int* x, int* y, gboolean* push_in, void* void_widget) { GtkWidget* widget = GTK_WIDGET(void_widget); GtkRequisition menu_req; gtk_widget_size_request(GTK_WIDGET(menu), &menu_req); gdk_window_get_origin(widget->window, x, y); GdkScreen *screen = gtk_widget_get_screen(widget); gint monitor = gdk_screen_get_monitor_at_point(screen, *x, *y); GdkRectangle screen_rect; gdk_screen_get_monitor_geometry(screen, monitor, &screen_rect); if (GTK_WIDGET_NO_WINDOW(widget)) { *x += widget->allocation.x; *y += widget->allocation.y; } *y += widget->allocation.height; bool start_align = !!g_object_get_data(G_OBJECT(widget), "left-align-popup"); if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) start_align = !start_align; if (!start_align) *x += widget->allocation.width - menu_req.width; // If the menu would run off the bottom of the screen, and there is more // screen space up than down, then pop upwards. if (*y + menu_req.height >= screen_rect.height && *y > screen_rect.height / 2) { *y -= menu_req.height; } *push_in = FALSE; } // static void MenuGtk::PointMenuPositionFunc(GtkMenu* menu, int* x, int* y, gboolean* push_in, gpointer userdata) { *push_in = TRUE; gfx::Point* point = reinterpret_cast<gfx::Point*>(userdata); *x = point->x(); *y = point->y(); GtkRequisition menu_req; gtk_widget_size_request(GTK_WIDGET(menu), &menu_req); GdkScreen* screen = gdk_screen_get_default(); gint screen_height = gdk_screen_get_height(screen); if (*y + menu_req.height >= screen_height) *y -= menu_req.height; } void MenuGtk::UpdateMenu() { gtk_container_foreach(GTK_CONTAINER(menu_.get()), SetMenuItemInfo, this); } // static void MenuGtk::OnMenuShow(GtkWidget* widget, MenuGtk* menu) { MessageLoop::current()->PostTask(FROM_HERE, menu->factory_.NewRunnableMethod(&MenuGtk::UpdateMenu)); } // static void MenuGtk::OnMenuHidden(GtkWidget* widget, MenuGtk* menu) { menu->delegate_->StoppedShowing(); } // static void MenuGtk::SetMenuItemInfo(GtkWidget* widget, gpointer userdata) { if (GTK_IS_SEPARATOR_MENU_ITEM(widget)) { // We need to explicitly handle this case because otherwise we'll ask the // menu delegate about something with an invalid id. return; } MenuGtk* menu = reinterpret_cast<MenuGtk*>(userdata); int id; const MenuCreateMaterial* data = reinterpret_cast<const MenuCreateMaterial*>( g_object_get_data(G_OBJECT(widget), "menu-data")); if (data) { id = data->id; } else { id = reinterpret_cast<intptr_t>(g_object_get_data(G_OBJECT(widget), "menu-id")); } if (GTK_IS_CHECK_MENU_ITEM(widget)) { GtkCheckMenuItem* item = GTK_CHECK_MENU_ITEM(widget); // gtk_check_menu_item_set_active() will send the activate signal. Touching // the underlying "active" property will also call the "activate" handler // for this menu item. So we prevent the "activate" handler from // being called while we set the checkbox. // Why not use one of the glib signal-blocking functions? Because when we // toggle a radio button, it will deactivate one of the other radio buttons, // which we don't have a pointer to. // Wny not make this a member variable? Because "menu" is a pointer to the // root of the MenuGtk and we want to disable *all* MenuGtks, including // submenus. block_activation_ = true; gtk_check_menu_item_set_active(item, menu->delegate_->IsItemChecked(id)); block_activation_ = false; } if (GTK_IS_MENU_ITEM(widget)) { gtk_widget_set_sensitive( widget, menu->delegate_->IsCommandEnabled(id)); GtkWidget* submenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(widget)); if (submenu) { gtk_container_foreach(GTK_CONTAINER(submenu), &SetMenuItemInfo, userdata); } } } <|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/net/referrer.h" #include "base/logging.h" namespace chrome_browser_net { void Referrer::SuggestHost(const std::string& host) { // Limit how large our list can get, in case we start make mistakes about // what hostnames are in sub-resources (example: Some advertisments have // a link to the ad agency, and then provide a "surprising" redirect to // the advertised entity, which appears to be a subresource on the page // hosting the ad). static const size_t kMaxSuggestions = 8; if (host.empty()) return; if (kMaxSuggestions <= size()) { DeleteLeastUseful(); DCHECK(kMaxSuggestions > size()); } // Add in the new suggestion. (*this)[host]; } void Referrer::DeleteLeastUseful() { std::string least_useful_name; // We use longs for durations because we will use multiplication on them. int64 least_useful_latency; // Duration in milliseconds. int64 least_useful_lifetime; // Duration in milliseconds. const base::Time kNow(base::Time::Now()); // Avoid multiple calls. for (HostNameMap::iterator it = this->begin(); it != this->end(); ++it) { int64 lifetime = (kNow - it->second.birth_time()).InMilliseconds(); int64 latency = it->second.latency().InMilliseconds(); if (!least_useful_name.empty()) { if (!latency && !least_useful_latency) { // Older name is less useful. if (lifetime <= least_useful_lifetime) continue; } else { // Compare the ratios latency/lifetime vs. // least_useful_latency/least_useful_lifetime by cross multiplying (to // avoid integer division hassles). Overflow's won't happen until // both latency and lifetime pass about 49 days. if (latency * least_useful_lifetime >= least_useful_latency * lifetime) { continue; } } } least_useful_name = it->first; least_useful_latency = latency; least_useful_lifetime = lifetime; } erase(least_useful_name); } void Referrer::AccrueValue(const base::TimeDelta& delta, const std::string host) { DCHECK(this->find(host) != this->end()); (*this)[host].AccrueValue(delta); } } // namespace chrome_browser_net <commit_msg>fix linux opt build Set initial values to 0.<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/net/referrer.h" #include "base/logging.h" namespace chrome_browser_net { void Referrer::SuggestHost(const std::string& host) { // Limit how large our list can get, in case we start make mistakes about // what hostnames are in sub-resources (example: Some advertisments have // a link to the ad agency, and then provide a "surprising" redirect to // the advertised entity, which appears to be a subresource on the page // hosting the ad). static const size_t kMaxSuggestions = 8; if (host.empty()) return; if (kMaxSuggestions <= size()) { DeleteLeastUseful(); DCHECK(kMaxSuggestions > size()); } // Add in the new suggestion. (*this)[host]; } void Referrer::DeleteLeastUseful() { std::string least_useful_name; // We use longs for durations because we will use multiplication on them. int64 least_useful_latency = 0; // Duration in milliseconds. int64 least_useful_lifetime = 0; // Duration in milliseconds. const base::Time kNow(base::Time::Now()); // Avoid multiple calls. for (HostNameMap::iterator it = this->begin(); it != this->end(); ++it) { int64 lifetime = (kNow - it->second.birth_time()).InMilliseconds(); int64 latency = it->second.latency().InMilliseconds(); if (!least_useful_name.empty()) { if (!latency && !least_useful_latency) { // Older name is less useful. if (lifetime <= least_useful_lifetime) continue; } else { // Compare the ratios latency/lifetime vs. // least_useful_latency/least_useful_lifetime by cross multiplying (to // avoid integer division hassles). Overflow's won't happen until // both latency and lifetime pass about 49 days. if (latency * least_useful_lifetime >= least_useful_latency * lifetime) { continue; } } } least_useful_name = it->first; least_useful_latency = latency; least_useful_lifetime = lifetime; } erase(least_useful_name); } void Referrer::AccrueValue(const base::TimeDelta& delta, const std::string host) { DCHECK(this->find(host) != this->end()); (*this)[host].AccrueValue(delta); } } // namespace chrome_browser_net <|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/options_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/host_content_settings_map.h" #include "chrome/browser/host_zoom_map.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/pref_service.h" #include "chrome/common/pref_names.h" #include "chrome/installer/util/google_update_settings.h" // static void OptionsUtil::ResetToDefaults(Profile* profile) { // TODO(tc): It would be nice if we could generate this list automatically so // changes to any of the options pages doesn't require updating this list // manually. PrefService* prefs = profile->GetPrefs(); const wchar_t* kUserPrefs[] = { prefs::kAcceptLanguages, prefs::kAlternateErrorPagesEnabled, prefs::kClearSiteDataOnExit, prefs::kCookieBehavior, prefs::kDefaultCharset, prefs::kDnsPrefetchingEnabled, #if defined(OS_LINUX) || defined(OS_FREEBSD) || defined(OS_OPENBSD) prefs::kCertRevocationCheckingEnabled, prefs::kSSL2Enabled, prefs::kSSL3Enabled, prefs::kTLS1Enabled, #endif #if defined(OS_CHROMEOS) prefs::kTimeZone, prefs::kTapToClickEnabled, prefs::kVertEdgeScrollEnabled, prefs::kTouchpadSpeedFactor, prefs::kTouchpadSensitivity, #endif prefs::kDownloadDefaultDirectory, prefs::kDownloadExtensionsToOpen, prefs::kEnableSpellCheck, prefs::kAutoFillEnabled, prefs::kHomePage, prefs::kHomePageIsNewTabPage, prefs::kMixedContentFiltering, prefs::kPrivacyFilterRules, prefs::kPromptForDownload, prefs::kPasswordManagerEnabled, prefs::kRestoreOnStartup, prefs::kSafeBrowsingEnabled, prefs::kSearchSuggestEnabled, prefs::kShowHomeButton, prefs::kSpellCheckDictionary, prefs::kURLsToRestoreOnStartup, prefs::kWebKitDefaultFixedFontSize, prefs::kWebKitDefaultFontSize, prefs::kWebKitFixedFontFamily, prefs::kWebKitJavaEnabled, prefs::kWebKitJavascriptEnabled, prefs::kWebKitLoadsImagesAutomatically, prefs::kWebKitPluginsEnabled, prefs::kWebKitSansSerifFontFamily, prefs::kWebKitSerifFontFamily, }; profile->GetDownloadManager()->ResetAutoOpenFiles(); profile->GetHostContentSettingsMap()->ResetToDefaults(); profile->GetHostZoomMap()->ResetToDefaults(); for (size_t i = 0; i < arraysize(kUserPrefs); ++i) prefs->ClearPref(kUserPrefs[i]); PrefService* local_state = g_browser_process->local_state(); // Note that we don't reset the kMetricsReportingEnabled preference here // because the reset will reset it to the default setting specified in Chrome // source, not the default setting selected by the user on the web page where // they downloaded Chrome. This means that if the user ever resets their // settings they'll either inadvertedly enable this logging or disable it. // One is undesirable for them, one is undesirable for us. For now, we just // don't reset it. const wchar_t* kLocalStatePrefs[] = { prefs::kApplicationLocale, }; for (size_t i = 0; i < arraysize(kLocalStatePrefs); ++i) local_state->ClearPref(kLocalStatePrefs[i]); } // static bool OptionsUtil::ResolveMetricsReportingEnabled(bool enabled) { GoogleUpdateSettings::SetCollectStatsConsent(enabled); bool update_pref = GoogleUpdateSettings::GetCollectStatsConsent(); if (enabled != update_pref) { DLOG(INFO) << "OptionsUtil: Unable to set crash report status to " << enabled; } // Only change the pref if GoogleUpdateSettings::GetCollectStatsConsent // succeeds. enabled = update_pref; MetricsService* metrics = g_browser_process->metrics_service(); DCHECK(metrics); if (metrics) { metrics->SetUserPermitsUpload(enabled); if (enabled) metrics->Start(); else metrics->Stop(); } return enabled; } <commit_msg>Make "Reset to Defaults" reset geolocation permissions too<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/options_util.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/download/download_manager.h" #include "chrome/browser/geolocation/geolocation_content_settings_map.h" #include "chrome/browser/host_content_settings_map.h" #include "chrome/browser/host_zoom_map.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/pref_service.h" #include "chrome/common/pref_names.h" #include "chrome/installer/util/google_update_settings.h" // static void OptionsUtil::ResetToDefaults(Profile* profile) { // TODO(tc): It would be nice if we could generate this list automatically so // changes to any of the options pages doesn't require updating this list // manually. PrefService* prefs = profile->GetPrefs(); const wchar_t* kUserPrefs[] = { prefs::kAcceptLanguages, prefs::kAlternateErrorPagesEnabled, prefs::kClearSiteDataOnExit, prefs::kCookieBehavior, prefs::kDefaultCharset, prefs::kDnsPrefetchingEnabled, #if defined(OS_LINUX) || defined(OS_FREEBSD) || defined(OS_OPENBSD) prefs::kCertRevocationCheckingEnabled, prefs::kSSL2Enabled, prefs::kSSL3Enabled, prefs::kTLS1Enabled, #endif #if defined(OS_CHROMEOS) prefs::kTimeZone, prefs::kTapToClickEnabled, prefs::kVertEdgeScrollEnabled, prefs::kTouchpadSpeedFactor, prefs::kTouchpadSensitivity, #endif prefs::kDownloadDefaultDirectory, prefs::kDownloadExtensionsToOpen, prefs::kEnableSpellCheck, prefs::kAutoFillEnabled, prefs::kHomePage, prefs::kHomePageIsNewTabPage, prefs::kMixedContentFiltering, prefs::kPrivacyFilterRules, prefs::kPromptForDownload, prefs::kPasswordManagerEnabled, prefs::kRestoreOnStartup, prefs::kSafeBrowsingEnabled, prefs::kSearchSuggestEnabled, prefs::kShowHomeButton, prefs::kSpellCheckDictionary, prefs::kURLsToRestoreOnStartup, prefs::kWebKitDefaultFixedFontSize, prefs::kWebKitDefaultFontSize, prefs::kWebKitFixedFontFamily, prefs::kWebKitJavaEnabled, prefs::kWebKitJavascriptEnabled, prefs::kWebKitLoadsImagesAutomatically, prefs::kWebKitPluginsEnabled, prefs::kWebKitSansSerifFontFamily, prefs::kWebKitSerifFontFamily, }; profile->GetDownloadManager()->ResetAutoOpenFiles(); profile->GetHostContentSettingsMap()->ResetToDefaults(); profile->GetGeolocationContentSettingsMap()->ResetToDefault(); profile->GetHostZoomMap()->ResetToDefaults(); for (size_t i = 0; i < arraysize(kUserPrefs); ++i) prefs->ClearPref(kUserPrefs[i]); PrefService* local_state = g_browser_process->local_state(); // Note that we don't reset the kMetricsReportingEnabled preference here // because the reset will reset it to the default setting specified in Chrome // source, not the default setting selected by the user on the web page where // they downloaded Chrome. This means that if the user ever resets their // settings they'll either inadvertedly enable this logging or disable it. // One is undesirable for them, one is undesirable for us. For now, we just // don't reset it. const wchar_t* kLocalStatePrefs[] = { prefs::kApplicationLocale, }; for (size_t i = 0; i < arraysize(kLocalStatePrefs); ++i) local_state->ClearPref(kLocalStatePrefs[i]); } // static bool OptionsUtil::ResolveMetricsReportingEnabled(bool enabled) { GoogleUpdateSettings::SetCollectStatsConsent(enabled); bool update_pref = GoogleUpdateSettings::GetCollectStatsConsent(); if (enabled != update_pref) { DLOG(INFO) << "OptionsUtil: Unable to set crash report status to " << enabled; } // Only change the pref if GoogleUpdateSettings::GetCollectStatsConsent // succeeds. enabled = update_pref; MetricsService* metrics = g_browser_process->metrics_service(); DCHECK(metrics); if (metrics) { metrics->SetUserPermitsUpload(enabled); if (enabled) metrics->Start(); else metrics->Stop(); } return enabled; } <|endoftext|>
<commit_before>// // Copyright (C) 2005-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <stdlib.h> // APPLICATION INCLUDES #include <os/OsConfigDb.h> #include "sipXmediaFactoryImpl.h" #include "CpPhoneMediaInterface.h" #include <sdp/SdpCodec.h> #include <mp/MpMediaTask.h> #include <mp/MpMisc.h> #include <mp/MpCodec.h> #include <mp/MpCallFlowGraph.h> #include <mp/dmaTask.h> #include <mp/MpCodecFactory.h> #include <sdp/SdpCodecList.h> #include "mi/CpMediaInterfaceFactoryFactory.h" #ifdef INCLUDE_RTCP /* [ */ #include <rtcp/RTCManager.h> #endif /* INCLUDE_RTCP ] */ #ifdef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY #include <mp/NetInTask.h> #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // GLOBAL FUNCTION #define MAX_MANAGED_FLOW_GRAPHS 16 // STATIC VARIABLE INITIALIZATIONS int sipXmediaFactoryImpl::miInstanceCount=0; CpMediaInterfaceFactory* spFactory = NULL; int siInstanceCount=0; #ifndef DISABLE_DEFAULT_PHONE_MEDIA_INTERFACE_FACTORY extern "C" CpMediaInterfaceFactory* cpDefaultMediaFactoryFactory(OsConfigDb* pConfigDb) { // TODO: Add locking if (spFactory == NULL) { spFactory = new CpMediaInterfaceFactory(); spFactory->setFactoryImplementation(new sipXmediaFactoryImpl(pConfigDb)); } siInstanceCount++ ; // Assert some sane value assert(siInstanceCount < 11) ; return spFactory; } extern "C" CpMediaInterfaceFactory* sipXmediaFactoryFactory(OsConfigDb* pConfigDb) { return(cpDefaultMediaFactoryFactory(pConfigDb)); } #endif extern "C" void sipxDestroyMediaFactoryFactory() { // TODO: Add locking if (siInstanceCount > 0) { siInstanceCount-- ; if (siInstanceCount == 0) { if (spFactory) { delete spFactory ; spFactory = NULL ; } } } } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor sipXmediaFactoryImpl::sipXmediaFactoryImpl(OsConfigDb* pConfigDb) { int maxFlowGraph = -1 ; UtlString strInBandDTMF ; if (pConfigDb) { pConfigDb->get("PHONESET_MAX_ACTIVE_CALLS_ALLOWED", maxFlowGraph) ; pConfigDb->get("PHONESET_SEND_INBAND_DTMF", strInBandDTMF) ; strInBandDTMF.toUpper() ; OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::sipXmediaFactoryImpl maxFlowGraph = %d", maxFlowGraph); } // Max Flow graphs if (maxFlowGraph <=0 ) { maxFlowGraph = MAX_MANAGED_FLOW_GRAPHS; } // Start audio subsystem if still not started. if (miInstanceCount == 0) { mpStartUp(8000, 80, 16*maxFlowGraph, pConfigDb, mnCodecPaths, mpCodecPaths); } // Should we send inband DTMF by default? if (strInBandDTMF.compareTo("DISABLE") == 0) { MpCallFlowGraph::setInbandDTMF(false) ; } else { MpCallFlowGraph::setInbandDTMF(true) ; } // init the media processing task mpMediaTask = MpMediaTask::getMediaTask(maxFlowGraph); #ifdef INCLUDE_RTCP /* [ */ mpiRTCPControl = CRTCManager::getRTCPControl(); #endif /* INCLUDE_RTCP ] */ if (miInstanceCount == 0) { #ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY mpStartTasks(); #else if (OS_SUCCESS != startNetInTask()) { OsSysLog::add(FAC_MP, PRI_ERR, "Could not start NetInTask!!"); } #endif } miGain = 7 ; ++miInstanceCount; // We are missing synchronization -- give the tasks time to start OsTask::delay(100) ; } // Destructor sipXmediaFactoryImpl::~sipXmediaFactoryImpl() { // TODO: Shutdown --miInstanceCount; if (miInstanceCount == 0) { #ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY mpStopTasks(); #else shutdownNetInTask(); #endif mpShutdown(); } } /* ============================ MANIPULATORS ============================== */ CpMediaInterface* sipXmediaFactoryImpl::createMediaInterface( const char* publicAddress, const char* localAddress, int numCodecs, SdpCodec* sdpCodecArray[], const char* locale, int expeditedIpTos, const char* szStunServer, int iStunPort, int iStunKeepAliveSecs, const char* szTurnServer, int iTurnPort, const char* szTurnUsername, const char* szTurnPassword, int iTurnKeepAlivePeriodSecs, UtlBoolean bEnableICE) { return new CpPhoneMediaInterface(this, publicAddress, localAddress, numCodecs, sdpCodecArray, locale, expeditedIpTos, szStunServer, iStunPort, iStunKeepAliveSecs, szTurnServer, iTurnPort, szTurnUsername, szTurnPassword, iTurnKeepAlivePeriodSecs, bEnableICE) ; } OsStatus sipXmediaFactoryImpl::setSpeakerVolume(int iVolume) { OsStatus rc = OS_SUCCESS ; MpCodec_setVolume(iVolume) ; return rc ; } OsStatus sipXmediaFactoryImpl::setSpeakerDevice(const UtlString& device) { OsStatus rc = OS_SUCCESS ; DmaTask::setCallDevice(device.data()) ; return rc ; } OsStatus sipXmediaFactoryImpl::setMicrophoneGain(int iGain) { OsStatus rc ; miGain = iGain ; rc = MpCodec_setGain(miGain) ; return rc ; } OsStatus sipXmediaFactoryImpl::setMicrophoneDevice(const UtlString& device) { OsStatus rc = OS_SUCCESS ; DmaTask::setInputDevice(device.data()) ; #ifdef WIN32 dmaSignalMicDeviceChange(); #endif return rc ; } OsStatus sipXmediaFactoryImpl::muteMicrophone(UtlBoolean bMute) { if (bMute) { MpCodec_setGain(0) ; } else { MpCodec_setGain(miGain) ; } return OS_SUCCESS ; } OsStatus sipXmediaFactoryImpl::setAudioAECMode(const MEDIA_AEC_MODE mode) { if (MpCallFlowGraph::setAECMode((FLOWGRAPH_AEC_MODE)mode)) { return OS_SUCCESS; }else { return OS_NOT_SUPPORTED; } } OsStatus sipXmediaFactoryImpl::enableAGC(UtlBoolean bEnable) { if (MpCallFlowGraph::setAGC(bEnable)) { return OS_SUCCESS; }else { return OS_NOT_SUPPORTED; } } OsStatus sipXmediaFactoryImpl::setAudioNoiseReductionMode(const MEDIA_NOISE_REDUCTION_MODE mode) { if (mode == MEDIA_NOISE_REDUCTION_DISABLED) { if (MpCallFlowGraph::setAudioNoiseReduction(FALSE)) { return OS_SUCCESS; } } else { if (MpCallFlowGraph::setAudioNoiseReduction(TRUE)) { return OS_SUCCESS; } } return OS_NOT_SUPPORTED; } OsStatus sipXmediaFactoryImpl::buildCodecFactory(SdpCodecList* pFactory, const UtlString& sAudioPreferences, const UtlString& sVideoPreferences, int videoFormat, int* iRejected) { OsStatus rc = OS_FAILED; *iRejected = 0; if (pFactory) { pFactory->clearCodecs(); // If preferred codecs supplied - add them, else add all supported // codecs. if (sAudioPreferences.length() > 0) { *iRejected = pFactory->addCodecs(sAudioPreferences); OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::buildCodecFactory: supported codecs = %s with NumReject %d", sAudioPreferences.data(), *iRejected); rc = OS_SUCCESS; } else { // Build up the supported codecs MpCodecFactory *pCodecFactory = MpCodecFactory::getMpCodecFactory(); pCodecFactory->addCodecsToList(*pFactory); *iRejected = 0; rc = OS_SUCCESS; } #ifdef VIDEO // [ // If preferred codecs supplied - add them, else add all supported // codecs. if (sVideoPreferences.length() > 0) { *iRejected = pFactory->addCodecs(sVideoPreferences); OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::buildCodecFactory: supported codecs = %s with NumReject %d", sVideoPreferences.data(), *iRejected); rc = OS_SUCCESS; } else { // Build up the supported codecs SdpCodec::SdpCodecTypes videoCodecs[] = {}; const int numVideoCodecs = sizeof(videoCodecs)/sizeof(SdpCodec::SdpCodecTypes); *iRejected = pFactory->addCodecs(numVideoCodecs, videoCodecs); rc = OS_SUCCESS; } #endif // VIDEO ] } return rc; } OsStatus sipXmediaFactoryImpl::updateVideoPreviewWindow(void* displayContext) { return OS_NOT_SUPPORTED ; } /* ============================ ACCESSORS ================================= */ OsStatus sipXmediaFactoryImpl::getSpeakerVolume(int& iVolume) const { OsStatus rc = OS_SUCCESS ; iVolume = MpCodec_getVolume() ; if (iVolume==-1) { rc = OS_FAILED; iVolume = 0; } return rc ; } OsStatus sipXmediaFactoryImpl::getSpeakerDevice(UtlString& device) const { OsStatus rc = OS_SUCCESS ; device = DmaTask::getCallDevice() ; return rc ; } OsStatus sipXmediaFactoryImpl::getMicrophoneGain(int& iGain) const { OsStatus rc = OS_SUCCESS ; iGain = MpCodec_getGain() ; return rc ; } OsStatus sipXmediaFactoryImpl::getMicrophoneDevice(UtlString& device) const { OsStatus rc = OS_SUCCESS ; device = DmaTask::getMicDevice() ; return rc ; } OsStatus sipXmediaFactoryImpl::setVideoPreviewDisplay(void* pDisplay) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::setVideoQuality(int quality) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::setVideoParameters(int bitRate, int frameRate) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoQuality(int& quality) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoBitRate(int& bitRate) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoFrameRate(int& frameRate) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getLocalAudioConnectionId(int& connectionId) const { connectionId = -1 ; return OS_NOT_SUPPORTED ; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <commit_msg>Reformat sipXmediaFactoryImpl code. Logic itself is unchanged.<commit_after>// // Copyright (C) 2005-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <stdlib.h> // APPLICATION INCLUDES #include <os/OsConfigDb.h> #include "sipXmediaFactoryImpl.h" #include "CpPhoneMediaInterface.h" #include <sdp/SdpCodec.h> #include <mp/MpMediaTask.h> #include <mp/MpMisc.h> #include <mp/MpCodec.h> #include <mp/MpCallFlowGraph.h> #include <mp/dmaTask.h> #include <mp/MpCodecFactory.h> #include <sdp/SdpCodecList.h> #include "mi/CpMediaInterfaceFactoryFactory.h" #ifdef INCLUDE_RTCP /* [ */ #include <rtcp/RTCManager.h> #endif /* INCLUDE_RTCP ] */ #ifdef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY #include <mp/NetInTask.h> #endif // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // GLOBAL FUNCTION #define MAX_MANAGED_FLOW_GRAPHS 16 // STATIC VARIABLE INITIALIZATIONS int sipXmediaFactoryImpl::miInstanceCount=0; CpMediaInterfaceFactory* spFactory = NULL; int siInstanceCount=0; #ifndef DISABLE_DEFAULT_PHONE_MEDIA_INTERFACE_FACTORY extern "C" CpMediaInterfaceFactory* cpDefaultMediaFactoryFactory(OsConfigDb* pConfigDb) { // TODO: Add locking if (spFactory == NULL) { spFactory = new CpMediaInterfaceFactory(); spFactory->setFactoryImplementation(new sipXmediaFactoryImpl(pConfigDb)); } siInstanceCount++; // Assert some sane value assert(siInstanceCount < 11); return spFactory; } extern "C" CpMediaInterfaceFactory* sipXmediaFactoryFactory(OsConfigDb* pConfigDb) { return(cpDefaultMediaFactoryFactory(pConfigDb)); } #endif extern "C" void sipxDestroyMediaFactoryFactory() { // TODO: Add locking if (siInstanceCount > 0) { siInstanceCount--; if (siInstanceCount == 0) { if (spFactory) { delete spFactory; spFactory = NULL; } } } } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor sipXmediaFactoryImpl::sipXmediaFactoryImpl(OsConfigDb* pConfigDb) { int maxFlowGraph = -1; UtlString strInBandDTMF; if (pConfigDb) { pConfigDb->get("PHONESET_MAX_ACTIVE_CALLS_ALLOWED", maxFlowGraph); pConfigDb->get("PHONESET_SEND_INBAND_DTMF", strInBandDTMF); strInBandDTMF.toUpper(); OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::sipXmediaFactoryImpl" " maxFlowGraph = %d", maxFlowGraph); } // Max Flow graphs if (maxFlowGraph <=0 ) { maxFlowGraph = MAX_MANAGED_FLOW_GRAPHS; } // Start audio subsystem if still not started. if (miInstanceCount == 0) { mpStartUp(8000, 80, 16*maxFlowGraph, pConfigDb, mnCodecPaths, mpCodecPaths); } // Should we send inband DTMF by default? if (strInBandDTMF.compareTo("DISABLE") == 0) { MpCallFlowGraph::setInbandDTMF(false); } else { MpCallFlowGraph::setInbandDTMF(true); } // init the media processing task mpMediaTask = MpMediaTask::getMediaTask(maxFlowGraph); #ifdef INCLUDE_RTCP /* [ */ mpiRTCPControl = CRTCManager::getRTCPControl(); #endif /* INCLUDE_RTCP ] */ if (miInstanceCount == 0) { #ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY mpStartTasks(); #else if (OS_SUCCESS != startNetInTask()) { OsSysLog::add(FAC_MP, PRI_ERR, "Could not start NetInTask!!"); } #endif } miGain = 7; ++miInstanceCount; // We are missing synchronization -- give the tasks time to start OsTask::delay(100); } // Destructor sipXmediaFactoryImpl::~sipXmediaFactoryImpl() { // TODO: Shutdown --miInstanceCount; if (miInstanceCount == 0) { #ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY mpStopTasks(); #else shutdownNetInTask(); #endif mpShutdown(); } } /* ============================ MANIPULATORS ============================== */ CpMediaInterface* sipXmediaFactoryImpl::createMediaInterface(const char* publicAddress, const char* localAddress, int numCodecs, SdpCodec* sdpCodecArray[], const char* locale, int expeditedIpTos, const char* szStunServer, int iStunPort, int iStunKeepAliveSecs, const char* szTurnServer, int iTurnPort, const char* szTurnUsername, const char* szTurnPassword, int iTurnKeepAlivePeriodSecs, UtlBoolean bEnableICE) { return new CpPhoneMediaInterface(this, publicAddress, localAddress, numCodecs, sdpCodecArray, locale, expeditedIpTos, szStunServer, iStunPort, iStunKeepAliveSecs, szTurnServer, iTurnPort, szTurnUsername, szTurnPassword, iTurnKeepAlivePeriodSecs, bEnableICE); } OsStatus sipXmediaFactoryImpl::setSpeakerVolume(int iVolume) { OsStatus rc = OS_SUCCESS; MpCodec_setVolume(iVolume); return rc; } OsStatus sipXmediaFactoryImpl::setSpeakerDevice(const UtlString& device) { OsStatus rc = OS_SUCCESS; DmaTask::setCallDevice(device.data()); return rc; } OsStatus sipXmediaFactoryImpl::setMicrophoneGain(int iGain) { OsStatus rc; miGain = iGain; rc = MpCodec_setGain(miGain); return rc; } OsStatus sipXmediaFactoryImpl::setMicrophoneDevice(const UtlString& device) { OsStatus rc = OS_SUCCESS; DmaTask::setInputDevice(device.data()); #ifdef WIN32 dmaSignalMicDeviceChange(); #endif return rc; } OsStatus sipXmediaFactoryImpl::muteMicrophone(UtlBoolean bMute) { if (bMute) { MpCodec_setGain(0); } else { MpCodec_setGain(miGain); } return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::setAudioAECMode(const MEDIA_AEC_MODE mode) { if (MpCallFlowGraph::setAECMode((FLOWGRAPH_AEC_MODE)mode)) { return OS_SUCCESS; } else { return OS_NOT_SUPPORTED; } } OsStatus sipXmediaFactoryImpl::enableAGC(UtlBoolean bEnable) { if (MpCallFlowGraph::setAGC(bEnable)) { return OS_SUCCESS; } else { return OS_NOT_SUPPORTED; } } OsStatus sipXmediaFactoryImpl::setAudioNoiseReductionMode(const MEDIA_NOISE_REDUCTION_MODE mode) { if (mode == MEDIA_NOISE_REDUCTION_DISABLED) { if (MpCallFlowGraph::setAudioNoiseReduction(FALSE)) { return OS_SUCCESS; } } else { if (MpCallFlowGraph::setAudioNoiseReduction(TRUE)) { return OS_SUCCESS; } } return OS_NOT_SUPPORTED; } OsStatus sipXmediaFactoryImpl::buildCodecFactory(SdpCodecList* pFactory, const UtlString& sAudioPreferences, const UtlString& sVideoPreferences, int videoFormat, int* iRejected) { OsStatus rc = OS_FAILED; *iRejected = 0; if (pFactory) { pFactory->clearCodecs(); // If preferred codecs supplied - add them, else add all supported // codecs. if (sAudioPreferences.length() > 0) { *iRejected = pFactory->addCodecs(sAudioPreferences); OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::buildCodecFactory: " "supported codecs = %s with NumReject %d", sAudioPreferences.data(), *iRejected); rc = OS_SUCCESS; } else { // Build up the supported codecs MpCodecFactory *pCodecFactory = MpCodecFactory::getMpCodecFactory(); pCodecFactory->addCodecsToList(*pFactory); *iRejected = 0; rc = OS_SUCCESS; } #ifdef VIDEO // [ // If preferred codecs supplied - add them, else add all supported // codecs. if (sVideoPreferences.length() > 0) { *iRejected = pFactory->addCodecs(sVideoPreferences); OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::buildCodecFactory: " "supported codecs = %s with NumReject %d", sVideoPreferences.data(), *iRejected); rc = OS_SUCCESS; } else { // Build up the supported codecs SdpCodec::SdpCodecTypes videoCodecs[] = {}; const int numVideoCodecs = sizeof(videoCodecs)/sizeof(SdpCodec::SdpCodecTypes); *iRejected = pFactory->addCodecs(numVideoCodecs, videoCodecs); rc = OS_SUCCESS; } #endif // VIDEO ] } return rc; } OsStatus sipXmediaFactoryImpl::updateVideoPreviewWindow(void* displayContext) { return OS_NOT_SUPPORTED; } /* ============================ ACCESSORS ================================= */ OsStatus sipXmediaFactoryImpl::getSpeakerVolume(int& iVolume) const { OsStatus rc = OS_SUCCESS; iVolume = MpCodec_getVolume(); if (iVolume==-1) { rc = OS_FAILED; iVolume = 0; } return rc; } OsStatus sipXmediaFactoryImpl::getSpeakerDevice(UtlString& device) const { OsStatus rc = OS_SUCCESS; device = DmaTask::getCallDevice(); return rc; } OsStatus sipXmediaFactoryImpl::getMicrophoneGain(int& iGain) const { OsStatus rc = OS_SUCCESS; iGain = MpCodec_getGain(); return rc; } OsStatus sipXmediaFactoryImpl::getMicrophoneDevice(UtlString& device) const { OsStatus rc = OS_SUCCESS; device = DmaTask::getMicDevice(); return rc; } OsStatus sipXmediaFactoryImpl::setVideoPreviewDisplay(void* pDisplay) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::setVideoQuality(int quality) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::setVideoParameters(int bitRate, int frameRate) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoQuality(int& quality) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoBitRate(int& bitRate) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoFrameRate(int& frameRate) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getLocalAudioConnectionId(int& connectionId) const { connectionId = -1; return OS_NOT_SUPPORTED; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>// // Created by malachi on 12/27/17. // #include <catch.hpp> #include "../coap-dispatcher.h" #include "../coap-uripath-dispatcher.h" #include "test-data.h" #include "test-observer.h" using namespace moducom::coap; using namespace moducom::coap::experimental; using namespace moducom::pipeline; extern dispatcher_handler_factory_fn test_sub_factories[]; IDispatcherHandler* context_handler_factory(FactoryDispatcherHandlerContext& ctx) { IncomingContext& context = ctx.incoming_context; #ifdef FEATURE_MCCOAP_INLINE_TOKEN return new (ctx.handler_memory.data()) ContextDispatcherHandler(context); #else static moducom::dynamic::PoolBase<moducom::coap::layer2::Token, 8> token_pool; return new (ctx.handler_memory.data()) ContextDispatcherHandler(context, token_pool); #endif } IDispatcherHandler* test_factory1(FactoryDispatcherHandlerContext& ctx) { return new (ctx.handler_memory.data()) Buffer16BitDeltaObserver(IsInterestedBase::Never); } /* // Does not work because compiler struggles to cast back down to IMessageObserver // for some reason template <const char* uri_path, IMessageObserver* observer> IDispatcherHandler* uri_helper3(MemoryChunk chunk) { return new (chunk.data()) UriPathDispatcherHandler(uri_path, *observer); } */ template <typename T> struct array_helper { static CONSTEXPR int count() { return 0; } }; template <typename T, ptrdiff_t N> struct array_helper<T[N]> { typedef T element_t; static CONSTEXPR ptrdiff_t count() { return N; } }; /* template <class TArray> int _array_helper_count(TArray array) { array_helper<TArray, > array_descriptor; return array_helper<TArray>::count(); } */ template <typename T, int size> CONSTEXPR int _array_helper_count(T (&) [size]) { return size; } template <typename T, int size> CONSTEXPR T* _array_helper_contents(T (&t) [size]) { return t; } /* template <dispatcher_handler_factory_fn factories[N], int N> IDispatcherHandler* uri_plus_factory_dispatcher(MemoryChunk chunk) { } */ IDispatcherHandler* test_factory2(FactoryDispatcherHandlerContext& ctx) { MemoryChunk& uri_handler_chunk = ctx.handler_memory; MemoryChunk v1_handler_chunk = ctx.handler_memory.remainder(sizeof(SingleUriPathObserver)); MemoryChunk v1_handler_inner_chunk = v1_handler_chunk.remainder(sizeof(FactoryDispatcherHandler)); FactoryDispatcherHandler* fdh = new (v1_handler_chunk.data()) FactoryDispatcherHandler( v1_handler_inner_chunk, ctx.incoming_context, test_sub_factories, 1); // TODO: will need some way to invoke fdh destructor return new (uri_handler_chunk.data()) SingleUriPathObserver("v1", *fdh); } extern CONSTEXPR char STR_TEST[] = "TEST"; /* template <typename T, int size> CONSTEXPR dispatcher_handler_factory_fn uri_helper_helper(T a [size], const char* name) { return &uri_plus_factory_dispatcher<TEST_FACTORY4_NAME, a, size>; }; */ template <class TArray> dispatcher_handler_factory_fn uri_helper2(const TArray& array) { typedef array_helper<TArray> array_helper_t; int count = _array_helper_count(array); const void* contents = _array_helper_contents(array); // really needs real constexpr from C++11 to work //return &uri_plus_factory_dispatcher<array, count, name>; /* MemoryChunk& uri_handler_chunk = chunk; MemoryChunk sub_handler_chunk = chunk.remainder(sizeof(UriPathDispatcherHandler)); MemoryChunk sub_handler_inner_chunk = sub_handler_chunk.remainder(sizeof(FactoryDispatcherHandler)); FactoryDispatcherHandler* fdh = new (sub_handler_chunk.data()) FactoryDispatcherHandler( sub_handler_inner_chunk, array, count); return new (uri_handler_chunk.data()) UriPathDispatcherHandler(uri_path, *fdh); */ }; dispatcher_handler_factory_fn test_factories[] = { context_handler_factory, test_factory1, test_factory2, uri_plus_factory_dispatcher<STR_TEST, test_sub_factories, 1> }; class TestDispatcherHandler2 : public DispatcherHandlerBase { public: void on_payload(const MemoryChunk::readonly_t& payload_part, bool last_chunk) OVERRIDE { REQUIRE(payload_part[0] == 0x10); REQUIRE(payload_part[1] == 0x11); REQUIRE(payload_part[2] == 0x12); REQUIRE(payload_part.length() == 7); } }; extern CONSTEXPR char POS_HANDLER_URI[] = "POS"; extern TestDispatcherHandler2 pos_handler; TestDispatcherHandler2 pos_handler; dispatcher_handler_factory_fn test_sub_factories[] = { uri_plus_observer_dispatcher<POS_HANDLER_URI, TestDispatcherHandler2> }; TEST_CASE("CoAP dispatcher tests", "[coap-dispatcher]") { SECTION("Test 1") { MemoryChunk chunk(buffer_16bit_delta, sizeof(buffer_16bit_delta)); Buffer16BitDeltaObserver dispatcherHandler; Dispatcher dispatcher; //layer3::MemoryChunk<128> chunk; dispatcher.head(&dispatcherHandler); dispatcher.dispatch(chunk); // Dummy test just so we can set a breakpoint here REQUIRE(chunk.length() == sizeof(buffer_16bit_delta)); } SECTION("Factory") { MemoryChunk chunk(buffer_plausible, sizeof(buffer_plausible)); // in-place new holder // FIX: OK all those virtual function tables seem to be bloating // our handlers way, way up... layer3::MemoryChunk<512> dispatcherBuffer; IncomingContext context; FactoryDispatcherHandler fdh(dispatcherBuffer, context, test_factories); Dispatcher dispatcher; // doesn't fully test new UriPath handler because Buffer16BitDeltaObserver // is not stateless (and shouldn't be expected to be) but because of that // setting it to "Currently" makes it unable to test its own options properly dispatcher.head(&fdh); dispatcher.dispatch(chunk); } SECTION("Array experimentation") { int array[] = { 1, 2, 3 }; int count = _array_helper_count(array); REQUIRE(count == 3); } SECTION("Size ofs") { int size1 = sizeof(IMessageObserver); #ifdef FEATURE_DISCRETE_OBSERVERS int size2 = sizeof(IOptionAndPayloadObserver); int size3 = sizeof(IOptionObserver); #endif int size4 = sizeof(IDispatcherHandler); int size5 = sizeof(IIsInterested); int size6 = sizeof(DispatcherHandlerBase); int size7 = sizeof(SingleUriPathObserver); int size8 = sizeof(FactoryDispatcherHandler); } } <commit_msg>Begin phasing out old Dispatcher in favor of DecoderSubject<commit_after>// // Created by malachi on 12/27/17. // #include <catch.hpp> #include "../coap-dispatcher.h" #include "../coap-uripath-dispatcher.h" #include "test-data.h" #include "test-observer.h" using namespace moducom::coap; using namespace moducom::coap::experimental; using namespace moducom::pipeline; extern dispatcher_handler_factory_fn test_sub_factories[]; IDispatcherHandler* context_handler_factory(FactoryDispatcherHandlerContext& ctx) { IncomingContext& context = ctx.incoming_context; #ifdef FEATURE_MCCOAP_INLINE_TOKEN return new (ctx.handler_memory.data()) ContextDispatcherHandler(context); #else static moducom::dynamic::PoolBase<moducom::coap::layer2::Token, 8> token_pool; return new (ctx.handler_memory.data()) ContextDispatcherHandler(context, token_pool); #endif } IDispatcherHandler* test_factory1(FactoryDispatcherHandlerContext& ctx) { return new (ctx.handler_memory.data()) Buffer16BitDeltaObserver(IsInterestedBase::Never); } /* // Does not work because compiler struggles to cast back down to IMessageObserver // for some reason template <const char* uri_path, IMessageObserver* observer> IDispatcherHandler* uri_helper3(MemoryChunk chunk) { return new (chunk.data()) UriPathDispatcherHandler(uri_path, *observer); } */ template <typename T> struct array_helper { static CONSTEXPR int count() { return 0; } }; template <typename T, ptrdiff_t N> struct array_helper<T[N]> { typedef T element_t; static CONSTEXPR ptrdiff_t count() { return N; } }; /* template <class TArray> int _array_helper_count(TArray array) { array_helper<TArray, > array_descriptor; return array_helper<TArray>::count(); } */ template <typename T, int size> CONSTEXPR int _array_helper_count(T (&) [size]) { return size; } template <typename T, int size> CONSTEXPR T* _array_helper_contents(T (&t) [size]) { return t; } /* template <dispatcher_handler_factory_fn factories[N], int N> IDispatcherHandler* uri_plus_factory_dispatcher(MemoryChunk chunk) { } */ IDispatcherHandler* test_factory2(FactoryDispatcherHandlerContext& ctx) { MemoryChunk& uri_handler_chunk = ctx.handler_memory; MemoryChunk v1_handler_chunk = ctx.handler_memory.remainder(sizeof(SingleUriPathObserver)); MemoryChunk v1_handler_inner_chunk = v1_handler_chunk.remainder(sizeof(FactoryDispatcherHandler)); FactoryDispatcherHandler* fdh = new (v1_handler_chunk.data()) FactoryDispatcherHandler( v1_handler_inner_chunk, ctx.incoming_context, test_sub_factories, 1); // TODO: will need some way to invoke fdh destructor return new (uri_handler_chunk.data()) SingleUriPathObserver("v1", *fdh); } extern CONSTEXPR char STR_TEST[] = "TEST"; /* template <typename T, int size> CONSTEXPR dispatcher_handler_factory_fn uri_helper_helper(T a [size], const char* name) { return &uri_plus_factory_dispatcher<TEST_FACTORY4_NAME, a, size>; }; */ template <class TArray> dispatcher_handler_factory_fn uri_helper2(const TArray& array) { typedef array_helper<TArray> array_helper_t; int count = _array_helper_count(array); const void* contents = _array_helper_contents(array); // really needs real constexpr from C++11 to work //return &uri_plus_factory_dispatcher<array, count, name>; /* MemoryChunk& uri_handler_chunk = chunk; MemoryChunk sub_handler_chunk = chunk.remainder(sizeof(UriPathDispatcherHandler)); MemoryChunk sub_handler_inner_chunk = sub_handler_chunk.remainder(sizeof(FactoryDispatcherHandler)); FactoryDispatcherHandler* fdh = new (sub_handler_chunk.data()) FactoryDispatcherHandler( sub_handler_inner_chunk, array, count); return new (uri_handler_chunk.data()) UriPathDispatcherHandler(uri_path, *fdh); */ }; dispatcher_handler_factory_fn test_factories[] = { context_handler_factory, test_factory1, test_factory2, uri_plus_factory_dispatcher<STR_TEST, test_sub_factories, 1> }; class TestDispatcherHandler2 : public DispatcherHandlerBase { public: void on_payload(const MemoryChunk::readonly_t& payload_part, bool last_chunk) OVERRIDE { REQUIRE(payload_part[0] == 0x10); REQUIRE(payload_part[1] == 0x11); REQUIRE(payload_part[2] == 0x12); REQUIRE(payload_part.length() == 7); } }; extern CONSTEXPR char POS_HANDLER_URI[] = "POS"; extern TestDispatcherHandler2 pos_handler; TestDispatcherHandler2 pos_handler; dispatcher_handler_factory_fn test_sub_factories[] = { uri_plus_observer_dispatcher<POS_HANDLER_URI, TestDispatcherHandler2> }; TEST_CASE("CoAP dispatcher tests", "[coap-dispatcher]") { SECTION("Factory") { MemoryChunk chunk(buffer_plausible, sizeof(buffer_plausible)); // in-place new holder // FIX: OK all those virtual function tables seem to be bloating // our handlers way, way up... layer3::MemoryChunk<512> dispatcherBuffer; IncomingContext context; FactoryDispatcherHandler fdh(dispatcherBuffer, context, test_factories); Dispatcher dispatcher; // doesn't fully test new UriPath handler because Buffer16BitDeltaObserver // is not stateless (and shouldn't be expected to be) but because of that // setting it to "Currently" makes it unable to test its own options properly dispatcher.head(&fdh); dispatcher.dispatch(chunk); } SECTION("Array experimentation") { int array[] = { 1, 2, 3 }; int count = _array_helper_count(array); REQUIRE(count == 3); } SECTION("Size ofs") { int size1 = sizeof(IMessageObserver); #ifdef FEATURE_DISCRETE_OBSERVERS int size2 = sizeof(IOptionAndPayloadObserver); int size3 = sizeof(IOptionObserver); #endif int size4 = sizeof(IDispatcherHandler); int size5 = sizeof(IIsInterested); int size6 = sizeof(DispatcherHandlerBase); int size7 = sizeof(SingleUriPathObserver); int size8 = sizeof(FactoryDispatcherHandler); } } <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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. The full license is available in the file LICENSE. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ #ifndef FMIWRAPPER_HPP #define FMIWRAPPER_HPP #include "ComponentEssentials.h" #include "ComponentUtilities.h" #include "FMI/fmi_import_context.h" #include <FMI1/fmi1_import.h> #include <FMI2/fmi2_import.h> #include <JM/jm_portability.h> //! //! @file FMIWrapper.hpp //! @author Robert Braun <robert.braun@liu.se> //! @date 2021-01-27 //! @brief Wrapper component for functional mockup units (.fmu) //! using namespace hopsan; void jmLogger(jm_callbacks *c, jm_string module, jm_log_level_enu_t log_level, jm_string message) { (void)module; hopsan::Component* pComponent = (hopsan::Component*)(c->context); if (pComponent) { switch (log_level) { case jm_log_level_fatal: pComponent->addFatalMessage(message); break; case jm_log_level_error: pComponent->addErrorMessage(message); break; case jm_log_level_warning: pComponent->addWarningMessage(message); break; // Typically the jm logger info messages are not something we want to see in Hopsan, so show them as debug type case jm_log_level_verbose: case jm_log_level_info: case jm_log_level_debug: pComponent->addDebugMessage(message); break; default: break; } } } void fmiLogger(fmi2ComponentEnvironment pComponentEnvironment, fmi2_string_t instanceName, fmi2_status_t status, fmi2_string_t category, fmi2_string_t message, ...) { hopsan::Component* pComponent = (hopsan::Component*)pComponentEnvironment; if (pComponent == NULL) { return; } char buffer[512]; va_list args; va_start(args, message); vsnprintf(buffer, 512, message, args); va_end(args); switch (status) { // Typically info messages are not something we want to see in Hopsan, so show them as debug type case fmi2_status_ok: pComponent->addDebugMessage(buffer); break; case fmi2_status_warning: pComponent->addWarningMessage(buffer); break; case fmi2_status_error: pComponent->addErrorMessage(buffer); break; case fmi2_status_fatal: pComponent->addFatalMessage(buffer); break; default: // Discard break; } } class FMIWrapper : public ComponentSignal { private: TempDirectoryHandle *mpTempDir; HString mFmuPath, mLastFmuPath; std::map<fmi2_value_reference_t,double*> mOutputs; std::map<fmi2_value_reference_t,double*> mInputs; std::map<fmi2_value_reference_t,double> mRealParameters; std::map<fmi2_value_reference_t,bool> mBoolParameters; std::map<fmi2_value_reference_t,int> mIntParameters; std::map<fmi2_value_reference_t,HString> mStringParameters; std::vector<Port*> mPorts; jm_callbacks callbacks; jm_status_enu_t status; fmi_import_context_t* context; fmi_version_enu_t version; fmi2_callback_functions_t fmiCallbackFunctions; fmi2_status_t fmistatus; fmi2_import_t* fmu; public: static Component *Creator() { return new FMIWrapper(); } void configure() { addConstant("path", "Path to functional mockup unit (FMU)", "", mFmuPath); setReconfigurationParameter("path"); } void reconfigure() { if(mFmuPath == mLastFmuPath) { return; //Path did not change, do nothing } mLastFmuPath = mFmuPath; deconfigure(); //Make sure to unload FMU and free memory before loading a new one for(int i=0; i<mPorts.size(); ++i) { removePort(mPorts[i]->getName()); } std::vector<HString> parameters; this->getParameterNames(parameters); for(int i=0; i<parameters.size(); ++i) { if(parameters[i] != "path") { this->unRegisterParameter(parameters[i]); } } mPorts.clear(); mOutputs.clear(); mInputs.clear(); mRealParameters.clear(); mStringParameters.clear(); mBoolParameters.clear(); mIntParameters.clear(); callbacks.malloc = malloc; callbacks.calloc = calloc; callbacks.realloc = realloc; callbacks.free = free; callbacks.logger = jmLogger; callbacks.log_level = jm_log_level_debug; callbacks.context = static_cast<jm_voidp>(this); context = fmi_import_allocate_context(&callbacks); addInfoMessage("Loading FMU from "+mFmuPath+"..."); mpTempDir = new TempDirectoryHandle("fmu"); if(!mpTempDir->isValid()) { addErrorMessage("Unable to create temp directory: "+mpTempDir->path()); return; } addDebugMessage("Using temporary directory: "+mpTempDir->path()); version = fmi_import_get_fmi_version(context, mFmuPath.c_str(), mpTempDir->path().c_str()); if(version != fmi_version_2_0_enu) { //! @todo Implement FMI 1.0 support addErrorMessage("The code only supports version 2.0"); return; } addDebugMessage("FMU version: 2.0"); fmu = fmi2_import_parse_xml(context, mpTempDir->path().c_str(), NULL); if(!fmu) { addErrorMessage("Parsing model description failed"); return; } addDebugMessage("Successfully parsed model description"); if(fmi2_import_get_fmu_kind(fmu) == fmi2_fmu_kind_me) { addErrorMessage("Only FMI for co-simulation is supported"); return; } addDebugMessage("FMU supports FMI for co-simulation"); fmi2_fmu_kind_enu_t fmuKind = fmi2_import_get_fmu_kind(fmu); if (fmuKind == fmi2_fmu_kind_me_and_cs) { fmuKind = fmi2_fmu_kind_cs; } //Loop through variables in FMU and generate the lists fmi2_import_variable_list_t *pVarList = fmi2_import_get_variable_list(fmu,0); for(size_t i=0; i<fmi2_import_get_variable_list_size(pVarList); ++i) { fmi2_import_variable_t *pVar = fmi2_import_get_variable(pVarList, i); const char* name = fmi2_import_get_variable_name(pVar); const char* description = fmi2_import_get_variable_description(pVar); if(description == NULL) { description = ""; } fmi2_base_type_enu_t type = fmi2_import_get_variable_base_type(pVar); fmi2_causality_enu_t causality = fmi2_import_get_causality(pVar); fmi2_value_reference_t vr = fmi2_import_get_variable_vr(pVar); if(causality == fmi2_causality_enu_parameter && type == fmi2_base_type_str) { addDebugMessage("String parameter: "+HString(name)); addConstant(name, description, "", mStringParameters[vr]); } else if(causality == fmi2_causality_enu_parameter && type == fmi2_base_type_bool) { addDebugMessage("Boolean parameter: "+HString(name)); addConstant(name, description, "", mBoolParameters[vr]); } else if(causality == fmi2_causality_enu_parameter && type == fmi2_base_type_int) { addDebugMessage("Integer parameter: "+HString(name)); addConstant(name, description, "", mIntParameters[vr]); } else if(causality == fmi2_causality_enu_parameter) { addDebugMessage("Real parameter: "+HString(name)); addConstant(name, description, "", mRealParameters[vr]); } else if(causality == fmi2_causality_enu_input && type == fmi2_base_type_real) { addDebugMessage("Input: "+HString(name)); mPorts.push_back(addInputVariable(name, description, "", 0, &mInputs[vr])); } else if(causality == fmi2_causality_enu_output && type == fmi2_base_type_real) { addDebugMessage("Output: "+HString(name)); mPorts.push_back(addOutputVariable(name, description, "", &mOutputs[vr])); } } fmiCallbackFunctions.logger = fmiLogger; fmiCallbackFunctions.allocateMemory = calloc; fmiCallbackFunctions.freeMemory = free; fmiCallbackFunctions.componentEnvironment = (fmi2ComponentEnvironment*)this; //Load FMU binary status = fmi2_import_create_dllfmu(fmu, fmi2_fmu_kind_cs, &fmiCallbackFunctions); if (status == jm_status_error) { addErrorMessage("Failed to load .dll/.so file (error: "+HString(fmi2_import_get_last_error(fmu))+")"); return; } addDebugMessage("Successfully loaded .dll/.so file"); //Instantiate FMU HString instanceName = getName(); HString resourceDir = "file://"+mpTempDir->path()+"/resources"; fmi2_boolean_t visible = fmi2_false; jm_status_enu_t jmstatus = fmi2_import_instantiate(fmu, instanceName.c_str(), fmi2_cosimulation, resourceDir.c_str(), visible); if (jmstatus == jm_status_error) { stopSimulation("Failed to instantiate FMU"); return; } addInfoMessage("Successfully instantiated FMU"); } void initialize() { addInfoMessage("Initializing FMU 2.0 import"); std::map<fmi2_value_reference_t,double>::iterator itr; for(itr = mRealParameters.begin(); itr != mRealParameters.end(); itr++) { fmistatus = fmi2_import_set_real(fmu, &itr->first, 1, &itr->second); } std::map<fmi2_value_reference_t,HString>::iterator its; for(its = mStringParameters.begin(); its != mStringParameters.end(); ++its) { const char* value = its->second.c_str(); fmistatus = fmi2_import_set_string(fmu, &its->first, 1, &value); } std::map<fmi2_value_reference_t,bool>::iterator itb; for(itb = mBoolParameters.begin(); itb != mBoolParameters.end(); ++itb) { int value = int(itb->second); fmistatus = fmi2_import_set_boolean(fmu, &its->first, 1, &value); } std::map<fmi2_value_reference_t,int>::iterator iti; for(iti = mIntParameters.begin(); iti != mIntParameters.end(); ++iti) { fmistatus = fmi2_import_set_integer(fmu, &its->first, 1, &iti->second); } //Setup experiment fmistatus = fmi2_import_setup_experiment(fmu, fmi2_false, 0, mTime, fmi2_false, 10); if(fmistatus != fmi2_status_ok) { stopSimulation("fmi2_import_setup_experiment() failed"); return; } //Enter initialization mode fmistatus = fmi2_import_enter_initialization_mode(fmu); if(fmistatus != fmi2_status_ok) { stopSimulation("fmi2_import_enter_initialization_mode() failed"); return; } //Exit initialization mode fmistatus = fmi2_import_exit_initialization_mode(fmu); if(fmistatus != fmi2_status_ok) { stopSimulation("fmi2_import_exit_initialization_mode() failed"); return; } } void simulateOneTimestep() { //Read inputs std::map<fmi2_value_reference_t,double*>::iterator it; for(it = mInputs.begin(); it != mInputs.end(); it++) { fmistatus = fmi2_import_set_real(fmu, &it->first, 1, it->second); } //Take step fmistatus = fmi2_import_do_step(fmu, mTime, mTimestep, true); if (fmistatus != fmi2_status_ok) { stopSimulation("fmi2_import_do_step failed"); return; } //Write outputs for(it = mOutputs.begin(); it != mOutputs.end(); it++) { fmistatus = fmi2_import_get_real(fmu, &it->first, 1, it->second); } } void finalize() { if(fmu) { fmistatus = fmi2_import_terminate(fmu); } } void deconfigure() { if(fmu) { fmi2_import_free_instance(fmu); fmi2_import_destroy_dllfmu(fmu); fmi2_import_free(fmu); fmu = NULL; } if(context) { fmi_import_free_context(context); context = NULL; } delete mpTempDir; } }; #endif // FMIWRAPPER_HPP <commit_msg>Correct calling sequence for finalize in FMIWrapper<commit_after>/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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. The full license is available in the file LICENSE. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ #ifndef FMIWRAPPER_HPP #define FMIWRAPPER_HPP #include "ComponentEssentials.h" #include "ComponentUtilities.h" #include "FMI/fmi_import_context.h" #include <FMI1/fmi1_import.h> #include <FMI2/fmi2_import.h> #include <JM/jm_portability.h> //! //! @file FMIWrapper.hpp //! @author Robert Braun <robert.braun@liu.se> //! @date 2021-01-27 //! @brief Wrapper component for functional mockup units (.fmu) //! using namespace hopsan; void jmLogger(jm_callbacks *c, jm_string module, jm_log_level_enu_t log_level, jm_string message) { (void)module; hopsan::Component* pComponent = (hopsan::Component*)(c->context); if (pComponent) { switch (log_level) { case jm_log_level_fatal: pComponent->addFatalMessage(message); break; case jm_log_level_error: pComponent->addErrorMessage(message); break; case jm_log_level_warning: pComponent->addWarningMessage(message); break; // Typically the jm logger info messages are not something we want to see in Hopsan, so show them as debug type case jm_log_level_verbose: case jm_log_level_info: case jm_log_level_debug: pComponent->addDebugMessage(message); break; default: break; } } } void fmiLogger(fmi2ComponentEnvironment pComponentEnvironment, fmi2_string_t instanceName, fmi2_status_t status, fmi2_string_t category, fmi2_string_t message, ...) { hopsan::Component* pComponent = (hopsan::Component*)pComponentEnvironment; if (pComponent == NULL) { return; } char buffer[512]; va_list args; va_start(args, message); vsnprintf(buffer, 512, message, args); va_end(args); switch (status) { // Typically info messages are not something we want to see in Hopsan, so show them as debug type case fmi2_status_ok: pComponent->addDebugMessage(buffer); break; case fmi2_status_warning: pComponent->addWarningMessage(buffer); break; case fmi2_status_error: pComponent->addErrorMessage(buffer); break; case fmi2_status_fatal: pComponent->addFatalMessage(buffer); break; default: // Discard break; } } class FMIWrapper : public ComponentSignal { private: TempDirectoryHandle *mpTempDir; HString mFmuPath, mLastFmuPath; std::map<fmi2_value_reference_t,double*> mOutputs; std::map<fmi2_value_reference_t,double*> mInputs; std::map<fmi2_value_reference_t,double> mRealParameters; std::map<fmi2_value_reference_t,bool> mBoolParameters; std::map<fmi2_value_reference_t,int> mIntParameters; std::map<fmi2_value_reference_t,HString> mStringParameters; std::vector<Port*> mPorts; jm_callbacks callbacks; jm_status_enu_t status; fmi_import_context_t* context; fmi_version_enu_t version; fmi2_callback_functions_t fmiCallbackFunctions; fmi2_status_t fmistatus; fmi2_import_t* fmu; public: static Component *Creator() { return new FMIWrapper(); } void configure() { addConstant("path", "Path to functional mockup unit (FMU)", "", mFmuPath); setReconfigurationParameter("path"); } void reconfigure() { if(mFmuPath == mLastFmuPath) { return; //Path did not change, do nothing } mLastFmuPath = mFmuPath; deconfigure(); //Make sure to unload FMU and free memory before loading a new one for(int i=0; i<mPorts.size(); ++i) { removePort(mPorts[i]->getName()); } std::vector<HString> parameters; this->getParameterNames(parameters); for(int i=0; i<parameters.size(); ++i) { if(parameters[i] != "path") { this->unRegisterParameter(parameters[i]); } } mPorts.clear(); mOutputs.clear(); mInputs.clear(); mRealParameters.clear(); mStringParameters.clear(); mBoolParameters.clear(); mIntParameters.clear(); callbacks.malloc = malloc; callbacks.calloc = calloc; callbacks.realloc = realloc; callbacks.free = free; callbacks.logger = jmLogger; callbacks.log_level = jm_log_level_debug; callbacks.context = static_cast<jm_voidp>(this); context = fmi_import_allocate_context(&callbacks); addInfoMessage("Loading FMU from "+mFmuPath+"..."); mpTempDir = new TempDirectoryHandle("fmu"); if(!mpTempDir->isValid()) { addErrorMessage("Unable to create temp directory: "+mpTempDir->path()); return; } addDebugMessage("Using temporary directory: "+mpTempDir->path()); version = fmi_import_get_fmi_version(context, mFmuPath.c_str(), mpTempDir->path().c_str()); if(version != fmi_version_2_0_enu) { //! @todo Implement FMI 1.0 support addErrorMessage("The code only supports version 2.0"); return; } addDebugMessage("FMU version: 2.0"); fmu = fmi2_import_parse_xml(context, mpTempDir->path().c_str(), NULL); if(!fmu) { addErrorMessage("Parsing model description failed"); return; } addDebugMessage("Successfully parsed model description"); if(fmi2_import_get_fmu_kind(fmu) == fmi2_fmu_kind_me) { addErrorMessage("Only FMI for co-simulation is supported"); return; } addDebugMessage("FMU supports FMI for co-simulation"); fmi2_fmu_kind_enu_t fmuKind = fmi2_import_get_fmu_kind(fmu); if (fmuKind == fmi2_fmu_kind_me_and_cs) { fmuKind = fmi2_fmu_kind_cs; } //Loop through variables in FMU and generate the lists fmi2_import_variable_list_t *pVarList = fmi2_import_get_variable_list(fmu,0); for(size_t i=0; i<fmi2_import_get_variable_list_size(pVarList); ++i) { fmi2_import_variable_t *pVar = fmi2_import_get_variable(pVarList, i); const char* name = fmi2_import_get_variable_name(pVar); const char* description = fmi2_import_get_variable_description(pVar); if(description == NULL) { description = ""; } fmi2_base_type_enu_t type = fmi2_import_get_variable_base_type(pVar); fmi2_causality_enu_t causality = fmi2_import_get_causality(pVar); fmi2_value_reference_t vr = fmi2_import_get_variable_vr(pVar); if(causality == fmi2_causality_enu_parameter && type == fmi2_base_type_str) { addDebugMessage("String parameter: "+HString(name)); addConstant(name, description, "", mStringParameters[vr]); } else if(causality == fmi2_causality_enu_parameter && type == fmi2_base_type_bool) { addDebugMessage("Boolean parameter: "+HString(name)); addConstant(name, description, "", mBoolParameters[vr]); } else if(causality == fmi2_causality_enu_parameter && type == fmi2_base_type_int) { addDebugMessage("Integer parameter: "+HString(name)); addConstant(name, description, "", mIntParameters[vr]); } else if(causality == fmi2_causality_enu_parameter) { addDebugMessage("Real parameter: "+HString(name)); addConstant(name, description, "", mRealParameters[vr]); } else if(causality == fmi2_causality_enu_input && type == fmi2_base_type_real) { addDebugMessage("Input: "+HString(name)); mPorts.push_back(addInputVariable(name, description, "", 0, &mInputs[vr])); } else if(causality == fmi2_causality_enu_output && type == fmi2_base_type_real) { addDebugMessage("Output: "+HString(name)); mPorts.push_back(addOutputVariable(name, description, "", &mOutputs[vr])); } } fmiCallbackFunctions.logger = fmiLogger; fmiCallbackFunctions.allocateMemory = calloc; fmiCallbackFunctions.freeMemory = free; fmiCallbackFunctions.componentEnvironment = (fmi2ComponentEnvironment*)this; //Load FMU binary status = fmi2_import_create_dllfmu(fmu, fmi2_fmu_kind_cs, &fmiCallbackFunctions); if (status == jm_status_error) { addErrorMessage("Failed to load .dll/.so file (error: "+HString(fmi2_import_get_last_error(fmu))+")"); return; } addDebugMessage("Successfully loaded .dll/.so file"); //Instantiate FMU HString instanceName = getName(); HString resourceDir = "file://"+mpTempDir->path()+"/resources"; fmi2_boolean_t visible = fmi2_false; jm_status_enu_t jmstatus = fmi2_import_instantiate(fmu, instanceName.c_str(), fmi2_cosimulation, resourceDir.c_str(), visible); if (jmstatus == jm_status_error) { stopSimulation("Failed to instantiate FMU"); return; } addInfoMessage("Successfully instantiated FMU"); } void initialize() { addInfoMessage("Initializing FMU 2.0 import"); std::map<fmi2_value_reference_t,double>::iterator itr; for(itr = mRealParameters.begin(); itr != mRealParameters.end(); itr++) { fmistatus = fmi2_import_set_real(fmu, &itr->first, 1, &itr->second); } std::map<fmi2_value_reference_t,HString>::iterator its; for(its = mStringParameters.begin(); its != mStringParameters.end(); ++its) { const char* value = its->second.c_str(); fmistatus = fmi2_import_set_string(fmu, &its->first, 1, &value); } std::map<fmi2_value_reference_t,bool>::iterator itb; for(itb = mBoolParameters.begin(); itb != mBoolParameters.end(); ++itb) { int value = int(itb->second); fmistatus = fmi2_import_set_boolean(fmu, &its->first, 1, &value); } std::map<fmi2_value_reference_t,int>::iterator iti; for(iti = mIntParameters.begin(); iti != mIntParameters.end(); ++iti) { fmistatus = fmi2_import_set_integer(fmu, &its->first, 1, &iti->second); } //Setup experiment fmistatus = fmi2_import_setup_experiment(fmu, fmi2_false, 0, mTime, fmi2_false, 10); if(fmistatus != fmi2_status_ok) { stopSimulation("fmi2_import_setup_experiment() failed"); return; } //Enter initialization mode fmistatus = fmi2_import_enter_initialization_mode(fmu); if(fmistatus != fmi2_status_ok) { stopSimulation("fmi2_import_enter_initialization_mode() failed"); return; } //Exit initialization mode fmistatus = fmi2_import_exit_initialization_mode(fmu); if(fmistatus != fmi2_status_ok) { stopSimulation("fmi2_import_exit_initialization_mode() failed"); return; } } void simulateOneTimestep() { //Read inputs std::map<fmi2_value_reference_t,double*>::iterator it; for(it = mInputs.begin(); it != mInputs.end(); it++) { fmistatus = fmi2_import_set_real(fmu, &it->first, 1, it->second); } //Take step fmistatus = fmi2_import_do_step(fmu, mTime, mTimestep, true); if (fmistatus != fmi2_status_ok) { stopSimulation("fmi2_import_do_step failed"); return; } //Write outputs for(it = mOutputs.begin(); it != mOutputs.end(); it++) { fmistatus = fmi2_import_get_real(fmu, &it->first, 1, it->second); } } void finalize() { if(fmu) { fmistatus = fmi2_import_reset(fmu); } } void deconfigure() { if(fmu) { fmistatus = fmi2_import_terminate(fmu); fmi2_import_free_instance(fmu); fmi2_import_destroy_dllfmu(fmu); fmi2_import_free(fmu); fmu = NULL; } if(context) { fmi_import_free_context(context); context = NULL; } delete mpTempDir; } }; #endif // FMIWRAPPER_HPP <|endoftext|>
<commit_before>#include <string> #include <sstream> #include <iostream> #include <fstream> #include <iomanip> #include <map> #include <list> using namespace std; // this function takes a line that may contain a name and/or email address, // and returns just the name, while fixing the "bad cases". std::string contributor_name(const std::string& line) { string result; size_t position_of_email_address = line.find_first_of('<'); if(position_of_email_address != string::npos) { // there is an e-mail address. // Hauke once committed as "John Smith", fix that. if(line.find("hauke.heibel") != string::npos) result = "Hauke Heibel"; else { // just remove the e-mail address result = line.substr(0, position_of_email_address); } } else { // there is no e-mail address. if(line.find("convert-repo") != string::npos) result = ""; else result = line; } // remove trailing spaces size_t length = result.length(); while(length >= 1 && result[length-1] == ' ') result.erase(--length); return result; } // parses hg churn output to generate a contributors map. map<string,int> contributors_map_from_churn_output(const char *filename) { map<string,int> contributors_map; string line; ifstream churn_out; churn_out.open(filename, ios::in); while(!getline(churn_out,line).eof()) { // remove the histograms "******" that hg churn may draw at the end of some lines size_t first_star = line.find_first_of('*'); if(first_star != string::npos) line.erase(first_star); // remove trailing spaces size_t length = line.length(); while(length >= 1 && line[length-1] == ' ') line.erase(--length); // now the last space indicates where the number starts size_t last_space = line.find_last_of(' '); // get the number (of changesets or of modified lines for each contributor) int number; istringstream(line.substr(last_space+1)) >> number; // get the name of the contributor line.erase(last_space); string name = contributor_name(line); map<string,int>::iterator it = contributors_map.find(name); // if new contributor, insert if(it == contributors_map.end()) contributors_map.insert(pair<string,int>(name, number)); // if duplicate, just add the number else it->second += number; } churn_out.close(); return contributors_map; } struct contributor { string name; int changedlines; int changesets; string url; string misc; contributor() : changedlines(0), changesets(0) {} bool operator < (const contributor& other) { return changedlines > other.changedlines; } }; void add_online_info_into_contributors_list(list<contributor>& contributors_list, const char *filename) { string line; ifstream online_info; online_info.open(filename, ios::in); while(!getline(online_info,line).eof()) { string hgname, realname, url, misc; size_t last_bar = line.find_last_of('|'); if(last_bar == string::npos) continue; if(last_bar < line.length()) misc = line.substr(last_bar+1); line.erase(last_bar); last_bar = line.find_last_of('|'); if(last_bar == string::npos) continue; if(last_bar < line.length()) url = line.substr(last_bar+1); line.erase(last_bar); last_bar = line.find_last_of('|'); if(last_bar == string::npos) continue; if(last_bar < line.length()) realname = line.substr(last_bar+1); line.erase(last_bar); hgname = line; // remove the example line if(hgname.find("MercurialName") != string::npos) continue; list<contributor>::iterator it; for(it=contributors_list.begin(); it != contributors_list.end() && it->name != hgname; ++it) {} if(it == contributors_list.end()) { contributor c; c.name = realname; c.url = url; c.misc = misc; contributors_list.push_back(c); } else { it->name = realname; it->url = url; it->misc = misc; } } } ostream& operator<<(ostream& stream, const contributor& c) { stream << c.name << "|" << c.changedlines << "|" << c.changesets << "|" << c.url << "|" << c.misc; } int main() { // parse the hg churn output files map<string,int> contributors_map_for_changedlines = contributors_map_from_churn_output("churn-changedlines.out"); map<string,int> contributors_map_for_changesets = contributors_map_from_churn_output("churn-changesets.out"); // merge into the contributors list list<contributor> contributors_list; map<string,int>::iterator it; for(it=contributors_map_for_changedlines.begin(); it != contributors_map_for_changedlines.end(); ++it) { contributor c; c.name = it->first; c.changedlines = it->second; c.changesets = contributors_map_for_changesets.find(it->first)->second; contributors_list.push_back(c); } add_online_info_into_contributors_list(contributors_list, "online-info.out"); contributors_list.sort(); cout << "{| cellpadding=\"5\"\n"; cout << "!\n"; cout << "! Lines changed\n(changesets)\n"; cout << "! Misc\n"; list<contributor>::iterator itc; int i = 0; for(itc=contributors_list.begin(); itc != contributors_list.end(); ++itc) { if(itc->name.length() == 0) continue; if(i%2) cout << "|-\n"; else cout << "|- style=\"background:#FFFFD0\"\n"; if(itc->url.length()) cout << "| [" << itc->url << " " << itc->name << "]\n"; else cout << "| " << itc->name << "\n"; if(itc->changedlines) cout << "| " << itc->changedlines << " (" << itc->changesets << ")\n"; else cout << "| (no own changesets) \n"; cout << "| " << itc->misc << "\n"; i++; } cout << "|}" << endl; } <commit_msg>* sort by last name alphabetically * replace (no own changesets) by (no information)<commit_after>#include <string> #include <sstream> #include <iostream> #include <fstream> #include <iomanip> #include <map> #include <list> using namespace std; // this function takes a line that may contain a name and/or email address, // and returns just the name, while fixing the "bad cases". std::string contributor_name(const std::string& line) { string result; size_t position_of_email_address = line.find_first_of('<'); if(position_of_email_address != string::npos) { // there is an e-mail address. // Hauke once committed as "John Smith", fix that. if(line.find("hauke.heibel") != string::npos) result = "Hauke Heibel"; else { // just remove the e-mail address result = line.substr(0, position_of_email_address); } } else { // there is no e-mail address. if(line.find("convert-repo") != string::npos) result = ""; else result = line; } // remove trailing spaces size_t length = result.length(); while(length >= 1 && result[length-1] == ' ') result.erase(--length); return result; } // parses hg churn output to generate a contributors map. map<string,int> contributors_map_from_churn_output(const char *filename) { map<string,int> contributors_map; string line; ifstream churn_out; churn_out.open(filename, ios::in); while(!getline(churn_out,line).eof()) { // remove the histograms "******" that hg churn may draw at the end of some lines size_t first_star = line.find_first_of('*'); if(first_star != string::npos) line.erase(first_star); // remove trailing spaces size_t length = line.length(); while(length >= 1 && line[length-1] == ' ') line.erase(--length); // now the last space indicates where the number starts size_t last_space = line.find_last_of(' '); // get the number (of changesets or of modified lines for each contributor) int number; istringstream(line.substr(last_space+1)) >> number; // get the name of the contributor line.erase(last_space); string name = contributor_name(line); map<string,int>::iterator it = contributors_map.find(name); // if new contributor, insert if(it == contributors_map.end()) contributors_map.insert(pair<string,int>(name, number)); // if duplicate, just add the number else it->second += number; } churn_out.close(); return contributors_map; } // find the last name, i.e. the last word. // for "van den Schbling" types of last names, that's not a problem, that's actually what we want. string lastname(const string& name) { size_t last_space = name.find_last_of(' '); if(last_space >= name.length()-1) return name; else return name.substr(last_space+1); } struct contributor { string name; int changedlines; int changesets; string url; string misc; contributor() : changedlines(0), changesets(0) {} bool operator < (const contributor& other) { return lastname(name).compare(lastname(other.name)) < 0; } }; void add_online_info_into_contributors_list(list<contributor>& contributors_list, const char *filename) { string line; ifstream online_info; online_info.open(filename, ios::in); while(!getline(online_info,line).eof()) { string hgname, realname, url, misc; size_t last_bar = line.find_last_of('|'); if(last_bar == string::npos) continue; if(last_bar < line.length()) misc = line.substr(last_bar+1); line.erase(last_bar); last_bar = line.find_last_of('|'); if(last_bar == string::npos) continue; if(last_bar < line.length()) url = line.substr(last_bar+1); line.erase(last_bar); last_bar = line.find_last_of('|'); if(last_bar == string::npos) continue; if(last_bar < line.length()) realname = line.substr(last_bar+1); line.erase(last_bar); hgname = line; // remove the example line if(hgname.find("MercurialName") != string::npos) continue; list<contributor>::iterator it; for(it=contributors_list.begin(); it != contributors_list.end() && it->name != hgname; ++it) {} if(it == contributors_list.end()) { contributor c; c.name = realname; c.url = url; c.misc = misc; contributors_list.push_back(c); } else { it->name = realname; it->url = url; it->misc = misc; } } } int main() { // parse the hg churn output files map<string,int> contributors_map_for_changedlines = contributors_map_from_churn_output("churn-changedlines.out"); map<string,int> contributors_map_for_changesets = contributors_map_from_churn_output("churn-changesets.out"); // merge into the contributors list list<contributor> contributors_list; map<string,int>::iterator it; for(it=contributors_map_for_changedlines.begin(); it != contributors_map_for_changedlines.end(); ++it) { contributor c; c.name = it->first; c.changedlines = it->second; c.changesets = contributors_map_for_changesets.find(it->first)->second; contributors_list.push_back(c); } add_online_info_into_contributors_list(contributors_list, "online-info.out"); contributors_list.sort(); cout << "{| cellpadding=\"5\"\n"; cout << "!\n"; cout << "! Lines changed\n(changesets)\n"; cout << "!\n"; list<contributor>::iterator itc; int i = 0; for(itc=contributors_list.begin(); itc != contributors_list.end(); ++itc) { if(itc->name.length() == 0) continue; if(i%2) cout << "|-\n"; else cout << "|- style=\"background:#FFFFD0\"\n"; if(itc->url.length()) cout << "| [" << itc->url << " " << itc->name << "]\n"; else cout << "| " << itc->name << "\n"; if(itc->changedlines) cout << "| " << itc->changedlines << " (" << itc->changesets << ")\n"; else cout << "| (no information)\n"; cout << "| " << itc->misc << "\n"; i++; } cout << "|}" << endl; } <|endoftext|>
<commit_before><commit_msg>Removed empty file<commit_after><|endoftext|>
<commit_before>/* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/GrGpuResourcePriv.h" #include "src/gpu/d3d/GrD3DGpu.h" #include "src/gpu/d3d/GrD3DTextureResource.h" void GrD3DTextureResource::setResourceState(const GrD3DGpu* gpu, D3D12_RESOURCE_STATES newResourceState) { D3D12_RESOURCE_STATES currentResourceState = this->currentState(); if (newResourceState == currentResourceState) { return; } D3D12_RESOURCE_TRANSITION_BARRIER barrier; barrier.pResource = this->d3dResource(); barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.StateBefore = currentResourceState; barrier.StateAfter = newResourceState; gpu->addResourceBarriers(this->resource(), 1, &barrier); this->updateResourceState(newResourceState); } bool GrD3DTextureResource::InitTextureResourceInfo(GrD3DGpu* gpu, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES initialState, GrProtected isProtected, D3D12_CLEAR_VALUE* clearValue, GrD3DTextureResourceInfo* info) { if (0 == desc.Width || 0 == desc.Height) { return false; } // TODO: We don't support protected memory at the moment if (isProtected == GrProtected::kYes) { return false; } // If MipLevels is 0, for some formats the API will automatically calculate the maximum // number of levels supported and use that -- we don't support that. SkASSERT(desc.MipLevels > 0); ID3D12Resource* resource = nullptr; D3D12_HEAP_PROPERTIES heapProperties = {}; heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT; heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProperties.CreationNodeMask = 1; heapProperties.VisibleNodeMask = 1; HRESULT hr = gpu->device()->CreateCommittedResource( &heapProperties, D3D12_HEAP_FLAG_NONE, &desc, initialState, clearValue, IID_PPV_ARGS(&resource)); if (!SUCCEEDED(hr)) { return false; } info->fResource.reset(resource); info->fResourceState = initialState; info->fFormat = desc.Format; info->fLevelCount = desc.MipLevels; info->fSampleQualityPattern = desc.SampleDesc.Quality; info->fProtected = isProtected; return true; } std::pair<GrD3DTextureResourceInfo, sk_sp<GrD3DResourceState>> GrD3DTextureResource::CreateMSAA( GrD3DGpu* gpu, SkISize dimensions, int sampleCnt, const GrD3DTextureResourceInfo& info, SkColor4f clearColor) { GrD3DTextureResourceInfo msInfo; sk_sp<GrD3DResourceState> msState; // create msaa surface D3D12_RESOURCE_DESC msTextureDesc = {}; msTextureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; msTextureDesc.Alignment = 0; // Default alignment (64KB) msTextureDesc.Width = dimensions.fWidth; msTextureDesc.Height = dimensions.fHeight; msTextureDesc.DepthOrArraySize = 1; msTextureDesc.MipLevels = 1; msTextureDesc.Format = info.fFormat; msTextureDesc.SampleDesc.Count = sampleCnt; msTextureDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN; msTextureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // Use default for dxgi format msTextureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; D3D12_CLEAR_VALUE clearValue = {}; clearValue.Format = info.fFormat; clearValue.Color[0] = clearColor.fR; clearValue.Color[1] = clearColor.fG; clearValue.Color[2] = clearColor.fB; clearValue.Color[3] = clearColor.fA; if (!InitTextureResourceInfo(gpu, msTextureDesc, D3D12_RESOURCE_STATE_RENDER_TARGET, info.fProtected, &clearValue, &msInfo)) { return {}; } msState.reset(new GrD3DResourceState( static_cast<D3D12_RESOURCE_STATES>(msInfo.fResourceState))); return std::make_pair(msInfo, msState); } GrD3DTextureResource::~GrD3DTextureResource() { // Should have been reset() before SkASSERT(!fResource); } void GrD3DTextureResource::prepareForPresent(GrD3DGpu* gpu) { this->setResourceState(gpu, D3D12_RESOURCE_STATE_PRESENT); } void GrD3DTextureResource::releaseResource(GrD3DGpu* gpu) { // TODO: do we need to migrate resource state if we change queues? if (fResource) { fResource->removeOwningTexture(); fResource.reset(nullptr); } } void GrD3DTextureResource::setResourceRelease(sk_sp<GrRefCntedCallback> releaseHelper) { SkASSERT(fResource); // Forward the release proc on to GrD3DTextureResource::Resource fResource->setRelease(std::move(releaseHelper)); } void GrD3DTextureResource::Resource::freeGPUData() const { this->invokeReleaseProc(); fResource.reset(); // Release our ref to the resource } <commit_msg>Make sure we release all refs in GrD3DTextureResource::releaseResource.<commit_after>/* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/GrGpuResourcePriv.h" #include "src/gpu/d3d/GrD3DGpu.h" #include "src/gpu/d3d/GrD3DTextureResource.h" void GrD3DTextureResource::setResourceState(const GrD3DGpu* gpu, D3D12_RESOURCE_STATES newResourceState) { D3D12_RESOURCE_STATES currentResourceState = this->currentState(); if (newResourceState == currentResourceState) { return; } D3D12_RESOURCE_TRANSITION_BARRIER barrier; barrier.pResource = this->d3dResource(); barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; barrier.StateBefore = currentResourceState; barrier.StateAfter = newResourceState; gpu->addResourceBarriers(this->resource(), 1, &barrier); this->updateResourceState(newResourceState); } bool GrD3DTextureResource::InitTextureResourceInfo(GrD3DGpu* gpu, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES initialState, GrProtected isProtected, D3D12_CLEAR_VALUE* clearValue, GrD3DTextureResourceInfo* info) { if (0 == desc.Width || 0 == desc.Height) { return false; } // TODO: We don't support protected memory at the moment if (isProtected == GrProtected::kYes) { return false; } // If MipLevels is 0, for some formats the API will automatically calculate the maximum // number of levels supported and use that -- we don't support that. SkASSERT(desc.MipLevels > 0); ID3D12Resource* resource = nullptr; D3D12_HEAP_PROPERTIES heapProperties = {}; heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT; heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; heapProperties.CreationNodeMask = 1; heapProperties.VisibleNodeMask = 1; HRESULT hr = gpu->device()->CreateCommittedResource( &heapProperties, D3D12_HEAP_FLAG_NONE, &desc, initialState, clearValue, IID_PPV_ARGS(&resource)); if (!SUCCEEDED(hr)) { return false; } info->fResource.reset(resource); info->fResourceState = initialState; info->fFormat = desc.Format; info->fLevelCount = desc.MipLevels; info->fSampleQualityPattern = desc.SampleDesc.Quality; info->fProtected = isProtected; return true; } std::pair<GrD3DTextureResourceInfo, sk_sp<GrD3DResourceState>> GrD3DTextureResource::CreateMSAA( GrD3DGpu* gpu, SkISize dimensions, int sampleCnt, const GrD3DTextureResourceInfo& info, SkColor4f clearColor) { GrD3DTextureResourceInfo msInfo; sk_sp<GrD3DResourceState> msState; // create msaa surface D3D12_RESOURCE_DESC msTextureDesc = {}; msTextureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; msTextureDesc.Alignment = 0; // Default alignment (64KB) msTextureDesc.Width = dimensions.fWidth; msTextureDesc.Height = dimensions.fHeight; msTextureDesc.DepthOrArraySize = 1; msTextureDesc.MipLevels = 1; msTextureDesc.Format = info.fFormat; msTextureDesc.SampleDesc.Count = sampleCnt; msTextureDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN; msTextureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // Use default for dxgi format msTextureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; D3D12_CLEAR_VALUE clearValue = {}; clearValue.Format = info.fFormat; clearValue.Color[0] = clearColor.fR; clearValue.Color[1] = clearColor.fG; clearValue.Color[2] = clearColor.fB; clearValue.Color[3] = clearColor.fA; if (!InitTextureResourceInfo(gpu, msTextureDesc, D3D12_RESOURCE_STATE_RENDER_TARGET, info.fProtected, &clearValue, &msInfo)) { return {}; } msState.reset(new GrD3DResourceState( static_cast<D3D12_RESOURCE_STATES>(msInfo.fResourceState))); return std::make_pair(msInfo, msState); } GrD3DTextureResource::~GrD3DTextureResource() { // Should have been reset() before SkASSERT(!fResource); SkASSERT(!fInfo.fResource); } void GrD3DTextureResource::prepareForPresent(GrD3DGpu* gpu) { this->setResourceState(gpu, D3D12_RESOURCE_STATE_PRESENT); } void GrD3DTextureResource::releaseResource(GrD3DGpu* gpu) { // TODO: do we need to migrate resource state if we change queues? if (fResource) { fResource->removeOwningTexture(); fResource.reset(); } fInfo.fResource.reset(); } void GrD3DTextureResource::setResourceRelease(sk_sp<GrRefCntedCallback> releaseHelper) { SkASSERT(fResource); // Forward the release proc on to GrD3DTextureResource::Resource fResource->setRelease(std::move(releaseHelper)); } void GrD3DTextureResource::Resource::freeGPUData() const { this->invokeReleaseProc(); fResource.reset(); // Release our ref to the resource } <|endoftext|>
<commit_before>/*- * Copyright (c) 2012 Michael Marner <michael@20papercups.net> * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 "MatrixSwitch.h" namespace wcl { MatrixSwitch::MatrixSwitch(const std::string& ipAddress, unsigned int switchID) : mIP(ipAddress), mSwitchID(switchID) { // nothing to do here... } MatrixSwitch::~MatrixSwitch() { // nothing to do here either... } bool MatrixSwitch::route(unsigned int inputID, unsigned int outputID) { // note: I don't know how many simultaneous connections // the matrix switch supports. So, rather than connect // on creation and disconnect on destruction, we'll just // create a socket each method call. if (inputID < 1 && inputID >36 && outputID < 1 && outputID > 36) return false; // connects on port 23 always wcl::TCPSocket s(mIP, 23); char message[14]; message[13] = 0; sprintf(message, "*%3d0004%2d%2d!", mSwitchID, outputID, inputID); s.writeUntil(message, 13); s.close(); return true; } bool MatrixSwitch::disconnect(unsigned int outputID) { if (outputID < 1 && outputID > 36) return false; // connects on port 23 always wcl::TCPSocket s(mIP, 23); char message[14]; message[13] = 0; sprintf(message, "*%3d0004%2d%2d!", mSwitchID, outputID, 0); s.writeUntil(message, 13); s.close(); return true; } }; <commit_msg>Fix return value when routing.<commit_after>/*- * Copyright (c) 2012 Michael Marner <michael@20papercups.net> * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 "MatrixSwitch.h" namespace wcl { MatrixSwitch::MatrixSwitch(const std::string& ipAddress, unsigned int switchID) : mIP(ipAddress), mSwitchID(switchID) { // nothing to do here... } MatrixSwitch::~MatrixSwitch() { // nothing to do here either... } bool MatrixSwitch::route(unsigned int inputID, unsigned int outputID) { // note: I don't know how many simultaneous connections // the matrix switch supports. So, rather than connect // on creation and disconnect on destruction, we'll just // create a socket each method call. if (inputID < 1 && inputID >36 && outputID < 1 && outputID > 36) return false; // connects on port 23 always wcl::TCPSocket s(mIP, 23); char message[14]; message[13] = 0; sprintf(message, "*%3d0004%2d%2d!", mSwitchID, outputID, inputID); s.writeUntil(message, 13); s.close(); return true; } bool MatrixSwitch::disconnect(unsigned int outputID) { if (outputID < 1 && outputID > 36) return false; // connects on port 23 always wcl::TCPSocket s(mIP, 23); char message[14]; message[13] = 0; sprintf(message, "*%3d0004%2d%2d!", mSwitchID, outputID, 0); s.writeUntil(message, 13); s.close(); return true; } }; <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_LOG_MIX_HPP #define STAN_MATH_PRIM_MAT_FUN_LOG_MIX_HPP #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/err/check_bounded.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/mat/meta/is_constant_struct.hpp> #include <stan/math/prim/mat/fun/log_sum_exp.hpp> #include <stan/math/prim/mat/fun/log.hpp> #include <stan/math/prim/mat/fun/exp.hpp> #include <stan/math/prim/mat/fun/max.hpp> #include <stan/math/prim/mat/fun/dot_product.hpp> #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <string> namespace stan { namespace math { /** * Return the log mixture density with specified mixing proportion * and log densities. * * * @param theta vector of mixing proportions in [0, 1]. * @param lambda vector of log densities. * @return log mixture of densities in specified proportion */ template <typename T_theta, typename T_lam> typename return_type<T_theta, T_lam>::type log_mix(const T_theta& theta, const T_lam& lambda) { static const std::string function = "log_mix"; typedef typename stan::partials_return_type<T_theta, T_lam>::type T_partials_return; const size_t N = theta.size(); for (size_t n = 0; n < N; ++n) { check_not_nan(function, "lambda", lambda[n]); check_not_nan(function, "theta", theta[n]); check_finite(function, "lambda", lambda[n]); check_finite(function, "theta", theta[n]); check_bounded(function, "theta", theta[n], 0, 1); } check_consistent_sizes(function, "theta", theta, "lambda", lambda); Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> theta_dbl(N, 1); scalar_seq_view<T_theta> theta_vec(theta); for (size_t n = 0; n < N; ++n) theta_dbl[n] = value_of(theta_vec[n]); Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> lambda_dbl(N, 1); scalar_seq_view<T_lam> lam_vec(lambda); for (size_t n = 0; n < N; ++n) lambda_dbl[n] = value_of(lam_vec[n]); /** * Vector containing log-prob of each density, log_sum_exp applied as * part of return call. */ Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> logp_tmp(N, 1); logp_tmp = log(theta_dbl) + lambda_dbl; /** * Calculate derivatives */ Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> exp_lambda_dbl(N, 1); /** * Exp-normalise to prevent overflow, as: * (exp(x-a) * exp(a)) / (exp(y-a) * exp(a)) = exp(x-a) / exp(y-a) */ double max_val = max(lambda_dbl); for (size_t n = 0; n < N; ++n) exp_lambda_dbl[n] = exp((lambda_dbl[n] - max_val)); T_partials_return dot_exp_lam_theta = dot_product(exp_lambda_dbl, theta_dbl); Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> theta_deriv(N, 1); theta_deriv = exp_lambda_dbl / dot_exp_lam_theta; Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> lam_deriv(N, 1); for (size_t n = 0; n < N; ++n) lam_deriv[n] = (exp_lambda_dbl[n] * theta_dbl[n]) / dot_exp_lam_theta; operands_and_partials<T_theta, T_lam> ops_partials(theta, lambda); if (!(is_constant_struct<T_theta>::value && is_constant_struct<T_lam>::value)) { if (!is_constant_struct<T_theta>::value) ops_partials.edge1_.partials_ = theta_deriv; if (!is_constant_struct<T_lam>::value) ops_partials.edge2_.partials_ = lam_deriv; } return ops_partials.build(log_sum_exp(logp_tmp)); } } } #endif <commit_msg>Final tidying<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_LOG_MIX_HPP #define STAN_MATH_PRIM_MAT_FUN_LOG_MIX_HPP #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/err/check_bounded.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_consistent_sizes.hpp> #include <stan/math/prim/scal/err/check_finite.hpp> #include <stan/math/prim/scal/fun/value_of.hpp> #include <stan/math/prim/mat/meta/is_constant_struct.hpp> #include <stan/math/prim/mat/fun/log_sum_exp.hpp> #include <stan/math/prim/mat/fun/log.hpp> #include <stan/math/prim/mat/fun/exp.hpp> #include <stan/math/prim/mat/fun/max.hpp> #include <stan/math/prim/mat/fun/dot_product.hpp> #include <stan/math/prim/mat/fun/value_of.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <string> #include <algorithm> namespace stan { namespace math { /** * Return the log mixture density with specified mixing proportion * and log densities. * * * @param theta vector of mixing proportions in [0, 1]. * @param lambda vector of log densities. * @return log mixture of densities in specified proportion */ template <typename T_theta, typename T_lam> typename return_type<T_theta, T_lam>::type log_mix(const T_theta& theta, const T_lam& lambda) { static const std::string function = "log_mix"; typedef typename stan::partials_return_type<T_theta, T_lam>::type T_partials_return; const size_t N = theta.size(); for (size_t n = 0; n < N; ++n) { check_not_nan(function, "lambda", lambda[n]); check_not_nan(function, "theta", theta[n]); check_finite(function, "lambda", lambda[n]); check_finite(function, "theta", theta[n]); check_bounded(function, "theta", theta[n], 0, 1); } check_consistent_sizes(function, "theta", theta, "lambda", lambda); Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> theta_dbl(N, 1); scalar_seq_view<T_theta> theta_vec(theta); for (size_t n = 0; n < N; ++n) theta_dbl[n] = value_of(theta_vec[n]); Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> lambda_dbl(N, 1); scalar_seq_view<T_lam> lam_vec(lambda); for (size_t n = 0; n < N; ++n) lambda_dbl[n] = value_of(lam_vec[n]); /** * Vector containing log-prob of each density, log_sum_exp applied as * part of return call. */ Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> logp_tmp(N, 1); logp_tmp = log(theta_dbl) + lambda_dbl; /** * Calculate derivatives * * Exp-normalise to prevent overflow, as: * (exp(x-a) * exp(a)) / (exp(y-a) * exp(a)) = exp(x-a) / exp(y-a) */ Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> exp_lambda_dbl(N, 1); double max_val = max(lambda_dbl); for (size_t n = 0; n < N; ++n) exp_lambda_dbl[n] = exp((lambda_dbl[n] - max_val)); T_partials_return dot_exp_lam_theta = dot_product(exp_lambda_dbl, theta_dbl); Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> theta_deriv(N, 1); theta_deriv = exp_lambda_dbl / dot_exp_lam_theta; Eigen::Matrix<T_partials_return, Eigen::Dynamic, 1> lam_deriv(N, 1); for (size_t n = 0; n < N; ++n) lam_deriv[n] = (exp_lambda_dbl[n] * theta_dbl[n]) / dot_exp_lam_theta; operands_and_partials<T_theta, T_lam> ops_partials(theta, lambda); if (!(is_constant_struct<T_theta>::value && is_constant_struct<T_lam>::value)) { if (!is_constant_struct<T_theta>::value) ops_partials.edge1_.partials_ = theta_deriv; if (!is_constant_struct<T_lam>::value) ops_partials.edge2_.partials_ = lam_deriv; } return ops_partials.build(log_sum_exp(logp_tmp)); } } } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: StorageNativeInputStream.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2005-03-23 09:41:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Ocke Janssen * * ************************************************************************/ #if HAVE_CONFIG_H #include <config.h> #endif #ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_ #include <com/sun/star/io/XStream.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_ #include <com/sun/star/document/XDocumentSubStorageSupplier.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_ #include <com/sun/star/embed/ElementModes.hpp> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #include "hsqldb/HStorageAccess.h" #include "hsqldb/HStorageMap.hxx" #include "hsqldb/StorageNativeInputStream.h" #include "jvmaccess/virtualmachine.hxx" #include "com/sun/star/lang/XSingleComponentFactory.hpp" #include <rtl/logfile.hxx> #include <limits> using namespace ::com::sun::star::container; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::document; using namespace ::com::sun::star::embed; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::connectivity::hsqldb; #define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) ) /*****************************************************************************/ /* exception macros */ #define ThrowException(env, type, msg) { \ env->ThrowNew(env->FindClass(type), msg); } /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: openStream * Signature: (Ljava/lang/String;Ljava/lang/String;I)V */ JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_openStream (JNIEnv * env, jobject obj_this,jstring key, jstring name, jint mode) { #if OSL_DEBUG_LEVEL > 1 { ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name); sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".input")); ::rtl::OString sName = ::rtl::OUStringToOString(sOrgName,RTL_TEXTENCODING_ASCII_US); getStreams()[sOrgName] = fopen( sName.getStr(), "a+" ); } #endif StorageContainer::registerStream(env,name,key,mode); } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: read * Signature: (Ljava/lang/String;Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2 (JNIEnv * env, jobject obj_this,jstring key, jstring name) { return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2(env,obj_this,name,key); } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: read * Signature: (Ljava/lang/String;Ljava/lang/String;[BII)I */ JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3BII (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer, jint off, jint len) { return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2_3BII(env,obj_this,name,key,buffer,off,len); } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: close * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_close (JNIEnv * env, jobject obj_this,jstring key, jstring name) { #if OSL_DEBUG_LEVEL > 1 { ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name); sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".input")); fclose( getStreams()[sOrgName] ); getStreams().erase(sOrgName); } #endif StorageContainer::revokeStream(env,name,key); } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: skip * Signature: (Ljava/lang/String;Ljava/lang/String;J)J */ JNIEXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_skip (JNIEnv * env, jobject obj_this,jstring key, jstring name, jlong n) { if ( n < 0 ) ThrowException( env, "java/io/IOException", "n < 0"); ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key); OSL_ENSURE(pHelper.get(),"No stream helper!"); if ( pHelper.get() ) { Reference<XInputStream> xIn = pHelper->getInputStream(); if ( xIn.is() ) { try { sal_Int64 nBytesSkipped = 0; sal_Int64 tmpLongVal = n; sal_Int32 tmpIntVal; try { do { if (tmpLongVal >= ::std::numeric_limits<sal_Int64>::max() ) tmpIntVal = ::std::numeric_limits<sal_Int32>::max(); else // Casting is safe here. tmpIntVal = static_cast<sal_Int32>(tmpLongVal); tmpLongVal -= tmpIntVal; xIn->skipBytes(tmpIntVal); } while (tmpLongVal > 0); } catch(Exception& e ) { } return n - tmpLongVal; } catch(Exception& e) { OSL_ENSURE(0,"Exception catched! : skip();"); StorageContainer::throwJavaException(e,env); } } } else { ThrowException( env, "java/io/IOException", "Stream is not valid"); } return 0; } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: available * Signature: (Ljava/lang/String;Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_available (JNIEnv * env, jobject obj_this,jstring key, jstring name) { ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key); OSL_ENSURE(pHelper.get(),"No stream helper!"); Reference<XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference<XInputStream>(); if ( xIn.is() ) { try { return xIn->available(); } catch(Exception& e) { OSL_ENSURE(0,"Exception catched! : available();"); StorageContainer::throwJavaException(e,env); } } else { ThrowException( env, "java/io/IOException", "Stream is not valid"); } return 0; } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: read * Signature: (Ljava/lang/String;Ljava/lang/String;[B)I */ JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3B (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer) { ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key); Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>(); OSL_ENSURE(xIn.is(),"Input stream is NULL!"); sal_Int32 nBytesRead = 0; if ( xIn.is() ) { jsize nLen = env->GetArrayLength(buffer); Sequence< ::sal_Int8 > aData(nLen); try { nBytesRead = xIn->readBytes(aData,nLen); } catch(Exception& e) { OSL_ENSURE(0,"Exception catched! : skip();"); StorageContainer::throwJavaException(e,env); } // Casting bytesRead to an int is okay, since the user can // only pass in an integer length to read, so the bytesRead // must <= len. // if (nBytesRead <= 0) { return -1; } OSL_ENSURE(nLen >= nBytesRead,"Buffer is too small!"); OSL_ENSURE(aData.getLength() >= nBytesRead,"Buffer is too small!"); env->SetByteArrayRegion(buffer,0,nBytesRead,&aData[0]); #if OSL_DEBUG_LEVEL > 1 ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name); sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".input")); fwrite(&aData[0],sizeof(sal_Int8),nBytesRead,getStreams()[sOrgName]); #endif } return nBytesRead; } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS dba28 (1.3.22); FILE MERGED 2005/03/30 11:27:29 fs 1.3.22.3: RESYNC: (1.3-1.4); FILE MERGED 2005/03/23 14:58:31 fs 1.3.22.2: #i45314# logging facilities 2005/03/21 12:53:33 fs 1.3.22.1: copying the changes from CWS dba26 herein, since they're needed to fix i45314<commit_after>/************************************************************************* * * $RCSfile: StorageNativeInputStream.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-03-30 11:52:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER 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): Ocke Janssen * * ************************************************************************/ #if HAVE_CONFIG_H #include <config.h> #endif #ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_ #include <com/sun/star/io/XStream.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_ #include <com/sun/star/document/XDocumentSubStorageSupplier.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_ #include <com/sun/star/embed/ElementModes.hpp> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef CONNECTIVITY_HSQLDB_STORAGEACCESS_HXX #include "hsqldb/HStorageAccess.hxx" #endif #include "hsqldb/HStorageMap.hxx" #include "hsqldb/StorageNativeInputStream.h" #include "jvmaccess/virtualmachine.hxx" #ifndef _COM_SUN_STAR_LANG_XSINGLECOMPONENTFACTORY_HPP_ #include <com/sun/star/lang/XSingleComponentFactory.hpp> #endif #ifndef CONNECTIVITY_HSQLDB_ACCESSLOG_HXX #include "accesslog.hxx" #endif #include <limits> using namespace ::com::sun::star::container; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::document; using namespace ::com::sun::star::embed; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; using namespace ::connectivity::hsqldb; #define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) ) /*****************************************************************************/ /* exception macros */ #define ThrowException(env, type, msg) { \ env->ThrowNew(env->FindClass(type), msg); } /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: openStream * Signature: (Ljava/lang/String;Ljava/lang/String;I)V */ JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_openStream (JNIEnv * env, jobject obj_this,jstring key, jstring name, jint mode) { #if OSL_DEBUG_LEVEL > 1 { OperationLogFile( env, name, "input" ).logOperation( "openStream" ); LogFile( env, name, "input" ).create(); } #endif StorageContainer::registerStream(env,name,key,mode); } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: read * Signature: (Ljava/lang/String;Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2 (JNIEnv * env, jobject obj_this,jstring key, jstring name) { #if OSL_DEBUG_LEVEL > 1 OperationLogFile( env, name, "input" ).logOperation( "read()" ); DataLogFile aDataLog( env, name, "input" ); return read_from_storage_stream( env, obj_this, name, key, &aDataLog ); #else return read_from_storage_stream( env, obj_this, name, key ); #endif } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: read * Signature: (Ljava/lang/String;Ljava/lang/String;[BII)I */ JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3BII (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer, jint off, jint len) { #if OSL_DEBUG_LEVEL > 1 OperationLogFile( env, name, "input" ).logOperation( "read( byte[], int, int )" ); DataLogFile aDataLog( env, name, "input" ); return read_from_storage_stream_into_buffer( env, obj_this, name, key, buffer, off, len, &aDataLog ); #else return read_from_storage_stream_into_buffer(env,obj_this,name,key,buffer,off,len); #endif } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: close * Signature: (Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_close (JNIEnv * env, jobject obj_this,jstring key, jstring name) { #if OSL_DEBUG_LEVEL > 1 OperationLogFile aOpLog( env, name, "input" ); aOpLog.logOperation( "close" ); aOpLog.close(); LogFile aDataLog( env, name, "input" ); aDataLog.close(); #endif StorageContainer::revokeStream(env,name,key); } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: skip * Signature: (Ljava/lang/String;Ljava/lang/String;J)J */ JNIEXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_skip (JNIEnv * env, jobject obj_this,jstring key, jstring name, jlong n) { #if OSL_DEBUG_LEVEL > 1 OperationLogFile( env, name, "input" ).logOperation( "skip()" ); #endif if ( n < 0 ) ThrowException( env, "java/io/IOException", "n < 0"); ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key); OSL_ENSURE(pHelper.get(),"No stream helper!"); if ( pHelper.get() ) { Reference<XInputStream> xIn = pHelper->getInputStream(); if ( xIn.is() ) { try { sal_Int64 nBytesSkipped = 0; sal_Int64 tmpLongVal = n; sal_Int32 tmpIntVal; try { do { if (tmpLongVal >= ::std::numeric_limits<sal_Int64>::max() ) tmpIntVal = ::std::numeric_limits<sal_Int32>::max(); else // Casting is safe here. tmpIntVal = static_cast<sal_Int32>(tmpLongVal); tmpLongVal -= tmpIntVal; xIn->skipBytes(tmpIntVal); } while (tmpLongVal > 0); } catch(Exception& e ) { } return n - tmpLongVal; } catch(Exception& e) { OSL_ENSURE(0,"Exception catched! : skip();"); StorageContainer::throwJavaException(e,env); } } } else { ThrowException( env, "java/io/IOException", "Stream is not valid"); } return 0; } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: available * Signature: (Ljava/lang/String;Ljava/lang/String;)I */ JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_available (JNIEnv * env, jobject obj_this,jstring key, jstring name) { #if OSL_DEBUG_LEVEL > 1 OperationLogFile aOpLog( env, name, "input" ); aOpLog.logOperation( "available" ); #endif ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key); OSL_ENSURE(pHelper.get(),"No stream helper!"); Reference<XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference<XInputStream>(); if ( xIn.is() ) { try { jint nAvailable = xIn->available(); #if OSL_DEBUG_LEVEL > 1 aOpLog.logReturn( nAvailable ); #endif return nAvailable; } catch(Exception& e) { OSL_ENSURE(0,"Exception catched! : available();"); StorageContainer::throwJavaException(e,env); } } else { ThrowException( env, "java/io/IOException", "Stream is not valid"); } return 0; } // ----------------------------------------------------------------------------- /* * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream * Method: read * Signature: (Ljava/lang/String;Ljava/lang/String;[B)I */ JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3B (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer) { #if OSL_DEBUG_LEVEL > 1 OperationLogFile aOpLog( env, name, "input" ); aOpLog.logOperation( "read( byte[] )" ); DataLogFile aDataLog( env, name, "input" ); #endif ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key); Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>(); OSL_ENSURE(xIn.is(),"Input stream is NULL!"); jint nBytesRead = 0; if ( xIn.is() ) { jsize nLen = env->GetArrayLength(buffer); Sequence< ::sal_Int8 > aData(nLen); try { nBytesRead = xIn->readBytes(aData,nLen); } catch(Exception& e) { OSL_ENSURE(0,"Exception catched! : skip();"); StorageContainer::throwJavaException(e,env); } // Casting bytesRead to an int is okay, since the user can // only pass in an integer length to read, so the bytesRead // must <= len. // if (nBytesRead <= 0) { #if OSL_DEBUG_LEVEL > 1 aOpLog.logReturn( (jint)-1 ); #endif return -1; } OSL_ENSURE(nLen >= nBytesRead,"Buffer is too small!"); OSL_ENSURE(aData.getLength() >= nBytesRead,"Buffer is too small!"); env->SetByteArrayRegion(buffer,0,nBytesRead,&aData[0]); #if OSL_DEBUG_LEVEL > 1 aDataLog.write( &aData[0], nBytesRead ); #endif } #if OSL_DEBUG_LEVEL > 1 aOpLog.logReturn( nBytesRead ); #endif return nBytesRead; } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before><commit_msg>fix tree by commenting out histograms<commit_after><|endoftext|>
<commit_before> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include "Grappa.hpp" #include "CompletionEvent.hpp" #include "ParallelLoop.hpp" #include "Collective.hpp" #include "Statistics.hpp" #include <string> DECLARE_uint64( num_starting_workers ); DEFINE_uint64( num_test_workers, 4, "Number of workers for the tests"); DEFINE_uint64( iters_per_task, 10000, "Iterations per task" ); DEFINE_string( test_type, "yields", "options: {yields,sequential_updates, sequential_updates16" ); DEFINE_uint64( private_array_size, 1, "Size of private array of 8-bytes for each task" ); using namespace Grappa; CompletionEvent * final; CompletionEvent * task_barrier; struct SixteenBytes { uint64_t val1; uint64_t val2; }; struct Cacheline { uint64_t val; char padding[56]; }; uint64_t * values8; SixteenBytes * values16; // Performance output of the test, not used as cumulative statistics // Initial value 0 should make merge just use Core 0's GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_avg, 0 ); GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_max, 0 ); GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_min, 0 ); // core-shared counter for counting progress uint64_t numst; uint64_t waitCount; // TODO: for traces, change to SimpleStatistic bool running; void user_main( void * args ) { srand((unsigned int)Grappa_walltime()); // must have enough threads because they all join a barrier CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers ); if (FLAGS_test_type.compare("yields")==0) { LOG(INFO) << ( "Test yields" ); { struct runtimes_t { double runtime_avg, runtime_min, runtime_max; }; runtimes_t r; on_all_cores( [&r] { // per core timing double start, end; running = false; final = new CompletionEvent(FLAGS_num_test_workers); task_barrier = new CompletionEvent(FLAGS_num_test_workers); for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) { privateTask( [&start] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // first task to exit the local barrier will start the timer if ( !running ) { Grappa::Statistics::reset(); start = Grappa_walltime(); running = true; } // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { Grappa_yield(); } final->complete(); }); } LOG(INFO) << ( "waiting" ); final->wait(); end = Grappa_walltime(); double runtime = end-start; LOG(INFO) << "took time " << runtime; Grappa::barrier(); LOG(INFO) << ( "all done" ); // sort out timing double r_sum = Grappa::allreduce<double, collective_add>( runtime ); double r_min = Grappa::allreduce<double, collective_min>( runtime ); double r_max = Grappa::allreduce<double, collective_max>( runtime ); if ( Grappa::mycore()==0 ) { r.runtime_avg = r_sum / Grappa::cores(); r.runtime_min = r_min; r.runtime_max = r_max; } }); context_switch_test_runtime_avg = r.runtime_avg; context_switch_test_runtime_max = r.runtime_max; context_switch_test_runtime_min = r.runtime_min; Grappa::Statistics::merge_and_print(); // Streams overlap // BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg // << ", cores_time_max = " << r.runtime_max // << ", cores_time_min = " << r.runtime_min); } } else if (FLAGS_test_type.compare("cvwakes")==0) { LOG(INFO) << ( "Test cv wakes" ); { struct runtimes_t { double runtime_avg, runtime_min, runtime_max; }; runtimes_t r; on_all_cores( [&r] { // per core timing double start, end; ConditionVariable * cvs = new ConditionVariable[FLAGS_num_test_workers]; bool * asleep = new bool[FLAGS_num_test_workers]; for( int i=0; i<FLAGS_num_test_workers; i++) { asleep[i] = false; } final = new CompletionEvent(1); task_barrier = new CompletionEvent(FLAGS_num_test_workers); running = false; waitCount = 0; numst = 0; for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) { privateTask( [asleep,&start,cvs] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // first task to exit the local barrier will start the timer if ( !running ) { // can safely reset statistics here because // no messages are sent between cores in the // timed portion Grappa::Statistics::reset(); start = Grappa_walltime(); running = true; } uint64_t tid = numst++; uint64_t partner = (tid + FLAGS_num_test_workers/2)%FLAGS_num_test_workers; uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers; // do the work while( waitCount++ < total_iters ) { if ( asleep[partner] ) { // TODO also test just wake up case Grappa::signal( &cvs[partner] ); } asleep[tid] = true; Grappa::wait( &cvs[tid] ); asleep[tid] = false; } // only first if ( running ) { final->complete(); // signal to finish as soon as the parent task gets scheduled running = false; } }); } LOG(INFO) << ( "waiting" ); final->wait(); end = Grappa_walltime(); double runtime = end-start; LOG(INFO) << "took time " << runtime; // wake all for (int i=0; i<FLAGS_num_test_workers; i++) { Grappa::signal(&cvs[i]); } LOG(INFO) << ( "woke all" ); Grappa::barrier(); LOG(INFO) << ( "all done" ); // sort out timing double r_sum = Grappa::allreduce<double, collective_add>( runtime ); double r_min = Grappa::allreduce<double, collective_min>( runtime ); double r_max = Grappa::allreduce<double, collective_max>( runtime ); if ( Grappa::mycore()==0 ) { r.runtime_avg = r_sum / Grappa::cores(); r.runtime_min = r_min; r.runtime_max = r_max; } }); context_switch_test_runtime_avg = r.runtime_avg; context_switch_test_runtime_max = r.runtime_max; context_switch_test_runtime_min = r.runtime_min; Grappa::Statistics::merge_and_print(); // Streams overlap // BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg // << ", cores_time_max = " << r.runtime_max // << ", cores_time_min = " << r.runtime_min); } } else if (FLAGS_test_type.compare("sequential_updates")==0) { LOG(INFO) << ( "Test sequential_updates" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { values8[t] += 1; Grappa_yield(); } final->complete(); }); } final->wait(); double end = Grappa_walltime(); double runtime = end-start; LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task); } } else if (FLAGS_test_type.compare("sequential_updates16")==0) { LOG(INFO) << ( "Test sequential_updates16" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values16 = new SixteenBytes[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { values16[t].val1 += 1; values16[t].val2 += 1; Grappa_yield(); } final->complete(); }); } final->wait(); double end = Grappa_walltime(); double runtime = end-start; LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task); } } else if (FLAGS_test_type.compare("private_array")==0) { LOG(INFO) << ( "Test private_array" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { uint64_t myarray[FLAGS_private_array_size]; // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { for (uint64_t j=0; j<FLAGS_private_array_size; j++) { myarray[j] += 1; } Grappa_yield(); } values8[t] = myarray[rand()%FLAGS_private_array_size]; final->complete(); }); } final->wait(); double end = Grappa_walltime(); LOG(INFO) << "result = " << values8[rand()%FLAGS_num_starting_workers]; double runtime = end-start; LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task); } } else if (FLAGS_test_type.compare("private_array_bycache")==0) { LOG(INFO) << ( "Test private_array_bycache" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { Cacheline myarray[FLAGS_private_array_size]; // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { for (uint64_t j=0; j<FLAGS_private_array_size; j++) { myarray[j].val += 1; } Grappa_yield(); } values8[t] = myarray[rand()%FLAGS_private_array_size].val; final->complete(); }); } final->wait(); double end = Grappa_walltime(); LOG(INFO) << "result = " << values8[rand()%FLAGS_num_starting_workers]; double runtime = end-start; LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task); } } else { CHECK( false ); // Unrecognized test_type } DVLOG(5) << ( "user main is exiting" ); } int main (int argc, char** argv) { Grappa_init( &argc, &argv ); Grappa_activate(); DVLOG(1) << "Spawning user main Thread...."; Grappa_run_user_main( &user_main, (void*)NULL ); VLOG(5) << "run_user_main returned"; CHECK( Grappa_done() ); Grappa_finish( 0 ); } <commit_msg>remove private barrier from switch test since scheduler already won't run the threads until parent suspends<commit_after> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #include "Grappa.hpp" #include "CompletionEvent.hpp" #include "ParallelLoop.hpp" #include "Collective.hpp" #include "Statistics.hpp" #include <string> DECLARE_uint64( num_starting_workers ); DEFINE_uint64( num_test_workers, 4, "Number of workers for the tests"); DEFINE_uint64( iters_per_task, 10000, "Iterations per task" ); DEFINE_string( test_type, "yields", "options: {yields,sequential_updates, sequential_updates16" ); DEFINE_uint64( private_array_size, 1, "Size of private array of 8-bytes for each task" ); using namespace Grappa; CompletionEvent * final; CompletionEvent * task_barrier; struct SixteenBytes { uint64_t val1; uint64_t val2; }; struct Cacheline { uint64_t val; char padding[56]; }; uint64_t * values8; SixteenBytes * values16; // Performance output of the test, not used as cumulative statistics // Initial value 0 should make merge just use Core 0's GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_avg, 0 ); GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_max, 0 ); GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_min, 0 ); // core-shared counter for counting progress uint64_t numst; uint64_t waitCount; // TODO: for traces, change to SimpleStatistic bool running; void user_main( void * args ) { srand((unsigned int)Grappa_walltime()); // must have enough threads because they all join a barrier CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers ); if (FLAGS_test_type.compare("yields")==0) { LOG(INFO) << ( "Test yields" ); { struct runtimes_t { double runtime_avg, runtime_min, runtime_max; }; runtimes_t r; on_all_cores( [&r] { // per core timing double start, end; running = false; final = new CompletionEvent(FLAGS_num_test_workers); task_barrier = new CompletionEvent(FLAGS_num_test_workers); for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) { privateTask( [&start] { // wait for all to start (to hack scheduler yield) // task_barrier->complete(); // task_barrier->wait(); // first task to exit the local barrier will start the timer if ( !running ) { Grappa::Statistics::reset(); start = Grappa_walltime(); running = true; } // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { Grappa_yield(); } final->complete(); }); } LOG(INFO) << ( "waiting" ); final->wait(); end = Grappa_walltime(); double runtime = end-start; LOG(INFO) << "took time " << runtime; Grappa::barrier(); LOG(INFO) << ( "all done" ); // sort out timing double r_sum = Grappa::allreduce<double, collective_add>( runtime ); double r_min = Grappa::allreduce<double, collective_min>( runtime ); double r_max = Grappa::allreduce<double, collective_max>( runtime ); if ( Grappa::mycore()==0 ) { r.runtime_avg = r_sum / Grappa::cores(); r.runtime_min = r_min; r.runtime_max = r_max; } }); context_switch_test_runtime_avg = r.runtime_avg; context_switch_test_runtime_max = r.runtime_max; context_switch_test_runtime_min = r.runtime_min; Grappa::Statistics::merge_and_print(); // Streams overlap // BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg // << ", cores_time_max = " << r.runtime_max // << ", cores_time_min = " << r.runtime_min); } } else if (FLAGS_test_type.compare("cvwakes")==0) { LOG(INFO) << ( "Test cv wakes" ); { struct runtimes_t { double runtime_avg, runtime_min, runtime_max; }; runtimes_t r; on_all_cores( [&r] { // per core timing double start, end; ConditionVariable * cvs = new ConditionVariable[FLAGS_num_test_workers]; bool * asleep = new bool[FLAGS_num_test_workers]; for( int i=0; i<FLAGS_num_test_workers; i++) { asleep[i] = false; } final = new CompletionEvent(1); task_barrier = new CompletionEvent(FLAGS_num_test_workers); running = false; waitCount = 0; numst = 0; for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) { privateTask( [asleep,&start,cvs] { // wait for all to start (to hack scheduler yield) //task_barrier->complete(); //task_barrier->wait(); // first task to exit the local barrier will start the timer if ( !running ) { // can safely reset statistics here because // no messages are sent between cores in the // timed portion Grappa::Statistics::reset(); start = Grappa_walltime(); running = true; } uint64_t tid = numst++; uint64_t partner = (tid + FLAGS_num_test_workers/2)%FLAGS_num_test_workers; uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers; // do the work while( waitCount++ < total_iters ) { if ( asleep[partner] ) { // TODO also test just wake up case Grappa::signal( &cvs[partner] ); } asleep[tid] = true; Grappa::wait( &cvs[tid] ); asleep[tid] = false; } // only first if ( running ) { final->complete(); // signal to finish as soon as the parent task gets scheduled running = false; } }); } LOG(INFO) << ( "waiting" ); final->wait(); end = Grappa_walltime(); double runtime = end-start; LOG(INFO) << "took time " << runtime; // wake all for (int i=0; i<FLAGS_num_test_workers; i++) { Grappa::signal(&cvs[i]); } LOG(INFO) << ( "woke all" ); Grappa::barrier(); LOG(INFO) << ( "all done" ); // sort out timing double r_sum = Grappa::allreduce<double, collective_add>( runtime ); double r_min = Grappa::allreduce<double, collective_min>( runtime ); double r_max = Grappa::allreduce<double, collective_max>( runtime ); if ( Grappa::mycore()==0 ) { r.runtime_avg = r_sum / Grappa::cores(); r.runtime_min = r_min; r.runtime_max = r_max; } }); context_switch_test_runtime_avg = r.runtime_avg; context_switch_test_runtime_max = r.runtime_max; context_switch_test_runtime_min = r.runtime_min; Grappa::Statistics::merge_and_print(); // Streams overlap // BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg // << ", cores_time_max = " << r.runtime_max // << ", cores_time_min = " << r.runtime_min); } } else if (FLAGS_test_type.compare("sequential_updates")==0) { LOG(INFO) << ( "Test sequential_updates" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { values8[t] += 1; Grappa_yield(); } final->complete(); }); } final->wait(); double end = Grappa_walltime(); double runtime = end-start; LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task); } } else if (FLAGS_test_type.compare("sequential_updates16")==0) { LOG(INFO) << ( "Test sequential_updates16" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values16 = new SixteenBytes[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { values16[t].val1 += 1; values16[t].val2 += 1; Grappa_yield(); } final->complete(); }); } final->wait(); double end = Grappa_walltime(); double runtime = end-start; LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task); } } else if (FLAGS_test_type.compare("private_array")==0) { LOG(INFO) << ( "Test private_array" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { uint64_t myarray[FLAGS_private_array_size]; // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { for (uint64_t j=0; j<FLAGS_private_array_size; j++) { myarray[j] += 1; } Grappa_yield(); } values8[t] = myarray[rand()%FLAGS_private_array_size]; final->complete(); }); } final->wait(); double end = Grappa_walltime(); LOG(INFO) << "result = " << values8[rand()%FLAGS_num_starting_workers]; double runtime = end-start; LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task); } } else if (FLAGS_test_type.compare("private_array_bycache")==0) { LOG(INFO) << ( "Test private_array_bycache" ); { final = new CompletionEvent(FLAGS_num_starting_workers); task_barrier = new CompletionEvent(FLAGS_num_starting_workers); values8 = new uint64_t[FLAGS_num_starting_workers]; double start = Grappa_walltime(); for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) { privateTask( [t] { Cacheline myarray[FLAGS_private_array_size]; // wait for all to start (to hack scheduler yield) task_barrier->complete(); task_barrier->wait(); // do the work for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { for (uint64_t j=0; j<FLAGS_private_array_size; j++) { myarray[j].val += 1; } Grappa_yield(); } values8[t] = myarray[rand()%FLAGS_private_array_size].val; final->complete(); }); } final->wait(); double end = Grappa_walltime(); LOG(INFO) << "result = " << values8[rand()%FLAGS_num_starting_workers]; double runtime = end-start; LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task); } } else { CHECK( false ); // Unrecognized test_type } DVLOG(5) << ( "user main is exiting" ); } int main (int argc, char** argv) { Grappa_init( &argc, &argv ); Grappa_activate(); DVLOG(1) << "Spawning user main Thread...."; Grappa_run_user_main( &user_main, (void*)NULL ); VLOG(5) << "run_user_main returned"; CHECK( Grappa_done() ); Grappa_finish( 0 ); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "content/public/common/content_switches.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Smooth scrolling confuses the scrollbar test. launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // See comment above TestingInstance in ppapi/test/testing_instance.h. // Basically it sets a series of numbered cookies. The value of "..." means // it's still working and we should continue to wait, any other value // indicates completion (in this case it will start with "PASS" or "FAIL"). // This keeps us from timing out on cookie waits for long tests. int progress_number = 0; std::string progress; while (true) { std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d", progress_number); progress = WaitUntilCookieNonEmpty(tab.get(), test_url, cookie_name.c_str(), TestTimeouts::large_test_timeout_ms()); if (progress != "...") break; progress_number++; } if (progress_number == 0) { // Failing the first time probably means the plugin wasn't loaded. ASSERT_FALSE(progress.empty()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; } else { ASSERT_FALSE(progress.empty()) << "Test timed out."; } EXPECT_STREQ("PASS", progress.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) // http://crbug.com/91729 TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 #if defined(OS_WIN) // It often takes too long time (and fails otherwise) on Windows. #define MAYBE_URLLoader DISABLED_URLLoader #else #define MAYBE_URLLoader FAILS_URLLoader #endif TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Crypto) TEST_PPAPI_OUT_OF_PROCESS(Crypto) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) #if !defined(OS_WIN) // Times out on Windows XP: http://crbug.com/95557 TEST_PPAPI_OUT_OF_PROCESS(PostMessage) #endif TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(VideoDecoder) TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } // http://crbug.com/101154 TEST_F(OutOfProcessPPAPITest, DISABLED_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/96767 #if !defined(OS_MACOSX) TEST_F(PPAPITest, FLAKY_FlashFullscreen) { RunTestViaHTTP("FlashFullscreen"); } TEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) { RunTestViaHTTP("FlashFullscreen"); } // New implementation only honors fullscreen requests within a context of // a user gesture. Since we do not yet have an infrastructure for testing // those under ppapi_tests, the tests below time out when run automtically. // To test the code, run them manually following the directions here: // www.chromium.org/developers/design-documents/pepper-plugin-implementation // and click on the plugin area (gray square) to force fullscreen mode and // get the test unstuck. TEST_F(PPAPITest, DISABLED_Fullscreen) { RunTestViaHTTP("Fullscreen"); } TEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) { RunTestViaHTTP("Fullscreen"); } #endif TEST_PPAPI_IN_PROCESS(FlashClipboard) TEST_PPAPI_OUT_OF_PROCESS(FlashClipboard) #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84294 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } TEST_PPAPI_IN_PROCESS(FAILS_NetAddressPrivate) TEST_PPAPI_OUT_OF_PROCESS(FAILS_NetAddressPrivate) <commit_msg>Reenable PPB_NetAddress_Private test.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "content/public/common/content_switches.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Smooth scrolling confuses the scrollbar test. launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // See comment above TestingInstance in ppapi/test/testing_instance.h. // Basically it sets a series of numbered cookies. The value of "..." means // it's still working and we should continue to wait, any other value // indicates completion (in this case it will start with "PASS" or "FAIL"). // This keeps us from timing out on cookie waits for long tests. int progress_number = 0; std::string progress; while (true) { std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d", progress_number); progress = WaitUntilCookieNonEmpty(tab.get(), test_url, cookie_name.c_str(), TestTimeouts::large_test_timeout_ms()); if (progress != "...") break; progress_number++; } if (progress_number == 0) { // Failing the first time probably means the plugin wasn't loaded. ASSERT_FALSE(progress.empty()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; } else { ASSERT_FALSE(progress.empty()) << "Test timed out."; } EXPECT_STREQ("PASS", progress.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) // http://crbug.com/91729 TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 #if defined(OS_WIN) // It often takes too long time (and fails otherwise) on Windows. #define MAYBE_URLLoader DISABLED_URLLoader #else #define MAYBE_URLLoader FAILS_URLLoader #endif TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Crypto) TEST_PPAPI_OUT_OF_PROCESS(Crypto) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) #if !defined(OS_WIN) // Times out on Windows XP: http://crbug.com/95557 TEST_PPAPI_OUT_OF_PROCESS(PostMessage) #endif TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(VideoDecoder) TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } // http://crbug.com/101154 TEST_F(OutOfProcessPPAPITest, DISABLED_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/96767 #if !defined(OS_MACOSX) TEST_F(PPAPITest, FLAKY_FlashFullscreen) { RunTestViaHTTP("FlashFullscreen"); } TEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) { RunTestViaHTTP("FlashFullscreen"); } // New implementation only honors fullscreen requests within a context of // a user gesture. Since we do not yet have an infrastructure for testing // those under ppapi_tests, the tests below time out when run automtically. // To test the code, run them manually following the directions here: // www.chromium.org/developers/design-documents/pepper-plugin-implementation // and click on the plugin area (gray square) to force fullscreen mode and // get the test unstuck. TEST_F(PPAPITest, DISABLED_Fullscreen) { RunTestViaHTTP("Fullscreen"); } TEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) { RunTestViaHTTP("Fullscreen"); } #endif TEST_PPAPI_IN_PROCESS(FlashClipboard) TEST_PPAPI_OUT_OF_PROCESS(FlashClipboard) #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84294 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } TEST_PPAPI_IN_PROCESS(NetAddressPrivate) TEST_PPAPI_OUT_OF_PROCESS(NetAddressPrivate) <|endoftext|>
<commit_before>// // Copyright (C) 2013-2014 mogemimi. // // Distributed under the MIT License. // See accompanying file LICENSE.md or copy at // http://enginetrouble.net/pomdog/LICENSE.md for details. // #include "DebugNavigator.hpp" #include "DrawingContext.hpp" namespace Pomdog { namespace UI { //----------------------------------------------------------------------- DebugNavigator::DebugNavigator(std::shared_ptr<GameClock> const& clockIn) : Control(Matrix3x2::Identity, 150, 40) , clock(clockIn) , duration(DurationSeconds(0)) , frameRateString("-- fps") {} //----------------------------------------------------------------------- void DebugNavigator::Draw(DrawingContext & drawingContext) { constexpr float minFramerate = 15.0f; constexpr float maxFramerate = 61.0f; constexpr std::uint16_t maxHistories = 20; { if (clock->TotalGameTime() - duration > DurationSeconds(0.2)) { auto frameRate = clock->FrameRate(); frameRateString = StringFormat("%4.2f fps", frameRate); frameRates.push_back(MathHelper::Clamp(frameRate, minFramerate, maxFramerate)); if (frameRates.size() > maxHistories) { frameRates.pop_front(); } duration = clock->TotalGameTime(); } } auto transform = Transform() * drawingContext.Top(); { auto graphTransform = Matrix3x2::CreateTranslation(Vector2{0, 16}) * transform; constexpr float maxGraphHeight = 26.0f; constexpr float graphMarginLeft = 1.0f; auto graghWidth = (static_cast<float>(Width()) / maxHistories); std::int32_t graphX = 0; for (auto & frameRate: frameRates) { auto amount = ((frameRate - minFramerate) / (maxFramerate - minFramerate)); auto graphHeight = std::max(1.0f, maxGraphHeight * amount); drawingContext.DrawRectangle(graphTransform, Color::CornflowerBlue, Rectangle(graphX, maxGraphHeight - graphHeight, graghWidth - graphMarginLeft, graphHeight)); graphX += graghWidth; } } drawingContext.DrawString(transform * Matrix3x2::CreateTranslation(Vector2(5, -2.5f)), Color::White, FontWeight::Bold, FontSize::Medium, frameRateString); } //----------------------------------------------------------------------- }// namespace UI }// namespace Pomdog <commit_msg>Fix debug navigator<commit_after>// // Copyright (C) 2013-2014 mogemimi. // // Distributed under the MIT License. // See accompanying file LICENSE.md or copy at // http://enginetrouble.net/pomdog/LICENSE.md for details. // #include "DebugNavigator.hpp" #include "DrawingContext.hpp" namespace Pomdog { namespace UI { //----------------------------------------------------------------------- DebugNavigator::DebugNavigator(std::shared_ptr<GameClock> const& clockIn) : Control(Matrix3x2::Identity, 150, 40) , clock(clockIn) , duration(DurationSeconds(0)) , frameRateString("-- fps") {} //----------------------------------------------------------------------- void DebugNavigator::Draw(DrawingContext & drawingContext) { constexpr float minFramerate = 10.0f; constexpr float maxFramerate = 60.0f; constexpr std::uint16_t maxHistories = 20; { if (clock->TotalGameTime() - duration > DurationSeconds(0.2)) { auto frameRate = clock->FrameRate(); frameRateString = StringFormat("%4.2f fps", frameRate); frameRates.push_back(MathHelper::Clamp(frameRate, minFramerate, maxFramerate)); if (frameRates.size() > maxHistories) { frameRates.pop_front(); } duration = clock->TotalGameTime(); } } auto transform = Transform() * drawingContext.Top(); { auto graphTransform = Matrix3x2::CreateTranslation(Vector2{0, 16}) * transform; constexpr std::uint16_t maxGraphHeight = 26; constexpr float graphMarginLeft = 1.0f; auto graghWidth = (static_cast<float>(Width()) / maxHistories); std::int32_t graphX = 0; for (auto & frameRate: frameRates) { auto amount = ((frameRate - minFramerate) / (maxFramerate - minFramerate)); auto graphHeight = MathHelper::Clamp<std::uint16_t>(maxGraphHeight * amount, 1, maxGraphHeight); drawingContext.DrawRectangle(graphTransform, Color::CornflowerBlue, Rectangle(graphX, maxGraphHeight - graphHeight, graghWidth - graphMarginLeft, graphHeight)); graphX += graghWidth; } } drawingContext.DrawString(transform * Matrix3x2::CreateTranslation(Vector2(5, -2.5f)), Color::White, FontWeight::Bold, FontSize::Medium, frameRateString); } //----------------------------------------------------------------------- }// namespace UI }// namespace Pomdog <|endoftext|>
<commit_before>//===-- lldb.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/lldb-private.h" using namespace lldb; using namespace lldb_private; #if defined (__APPLE__) // Xcode writes this file out in a build step. // cmake builds get this through another mechanism. // Both produce LLDB_REVISION. #include "lldb_revision.h" extern "C" const unsigned char liblldb_coreVersionString[]; #endif #if defined(LLDB_USE_OSS_VERSION_SCHEME) #include "llvm/Support/raw_ostream.h" #include "swift/Basic/Version.h" #endif #if !defined (__APPLE__) || defined(LLDB_USE_OSS_VERSION_SCHEME) #include "clang/Basic/Version.h" static const char * GetLLDBRevision() { #ifdef LLDB_REVISION static const char *s_revision = LLDB_REVISION; #else static const char *s_revision = nullptr; #endif if (s_revision != nullptr) return s_revision; else return ""; } #endif #if !defined (__APPLE__) static const char * GetLLDBRepository() { #ifdef LLDB_REPOSITORY return LLDB_REPOSITORY; #else return NULL; #endif } #endif #if defined(LLDB_USE_OSS_VERSION_SCHEME) // TODO remove this function once swift revision is directly exposed. std::string ExtractSwiftRevision(const std::string &fullVersion) { // Find spot right before Swift revision. const std::string search_prefix = "Swift "; const size_t prefix_start_pos = fullVersion.rfind(search_prefix); if (prefix_start_pos == std::string::npos) return ""; // Find spot where Swift revision ends. const size_t revision_end_pos = fullVersion.rfind(')'); if (revision_end_pos == std::string::npos) return ""; // Return the revision. return fullVersion.substr(prefix_start_pos + search_prefix.length(), revision_end_pos - prefix_start_pos - search_prefix.length()); } static std::string GetBuildDate() { // The following code helps distinguish between a defined preprocessor // value that gets the default value assigned vs. one with an explicit value. #define LLDB_DO_MACRO_EXPAND(macro_value) macro_value ## 1 #define LLDB_MACRO_EXPAND(macro_value) LLDB_DO_MACRO_EXPAND(macro_value) #if defined(LLDB_BUILD_DATE) return std::string(LLDB_BUILD_DATE); #else return std::string(); #endif } static const char* _GetVersionOSS () { static std::string g_version_string; if (g_version_string.empty()) { std::string build_string; llvm::raw_string_ostream out(build_string); std::string build_flavor = "local"; #if defined (LLDB_IS_BUILDBOT_BUILD) # if (LLDB_IS_BUILDBOT_BUILD != 0) build_flavor = "buildbot"; # endif #endif out << "lldb-" << build_flavor; // We only run this code when the build date is both set and non-default. // Otherwise this code doesn't compile. const std::string build_date(GetBuildDate()); if (!build_date.empty()) out << "-" << build_date; out << " ("; std::string lldb_revision = GetLLDBRevision(); if (lldb_revision.length() > 0) { const size_t MAX_REVISION_LENGTH = 10; out << "LLDB "; out << lldb_revision.substr(0, MAX_REVISION_LENGTH); const std::string llvm_revision = clang::getLLVMRevision(); if (!llvm_revision.empty()) out << ", LLVM " << llvm_revision.substr(0, MAX_REVISION_LENGTH); const std::string clang_revision = clang::getClangRevision(); if (!clang_revision.empty()) out << ", Clang " << clang_revision.substr(0, MAX_REVISION_LENGTH); // TODO replace this with a swift::version::GetSwiftRevision() call // once added. const std::string swift_revision = ExtractSwiftRevision(swift::version::getSwiftFullVersion()); if (!swift_revision.empty()) { auto const swift_version = swift::version::getSwiftNumericVersion(); out << ", Swift-" << swift_version.first << "." << swift_version.second << " " << swift_revision.substr(0, MAX_REVISION_LENGTH); } } out << ")"; g_version_string = out.str(); } return g_version_string.c_str(); } #endif #if defined(__APPLE__) && !defined(LLDB_USE_OSS_VERSION_SCHEME) static const char* _GetVersionAppleStandard () { static char g_version_string[32]; if (g_version_string[0] == '\0') { const char *version_string = ::strstr ((const char *)liblldb_coreVersionString, "PROJECT:"); if (version_string) version_string += sizeof("PROJECT:") - 1; else version_string = "unknown"; const char *newline_loc = strchr(version_string, '\n'); size_t version_len = sizeof(g_version_string) - 1; if (newline_loc && (newline_loc - version_string < static_cast<ptrdiff_t>(version_len))) version_len = newline_loc - version_string; ::snprintf(g_version_string, version_len + 1, "%s", version_string); } return g_version_string; } #endif const char * lldb_private::GetVersion () { #if defined (__APPLE__) # if defined(LLDB_USE_OSS_VERSION_SCHEME) return _GetVersionOSS (); # else return _GetVersionAppleStandard (); # endif #else # if defined(LLDB_USE_OSS_VERSION_SCHEME) return _GetVersionOSS (); # else // On platforms other than Darwin, report a version number in the same style as the clang tool. static std::string g_version_str; if (g_version_str.empty()) { g_version_str += "lldb version "; g_version_str += CLANG_VERSION_STRING; const char * lldb_repo = GetLLDBRepository(); if (lldb_repo) { g_version_str += " ("; g_version_str += lldb_repo; } const char *lldb_rev = GetLLDBRevision(); if (lldb_rev) { g_version_str += " revision "; g_version_str += lldb_rev; } std::string clang_rev (clang::getClangRevision()); if (clang_rev.length() > 0) { g_version_str += " clang revision "; g_version_str += clang_rev; } std::string llvm_rev (clang::getLLVMRevision()); if (llvm_rev.length() > 0) { g_version_str += " llvm revision "; g_version_str += llvm_rev; } if (lldb_repo) g_version_str += ")"; } return g_version_str.c_str(); # endif #endif } <commit_msg>added a comment to clarify a check in previous version fixup code<commit_after>//===-- lldb.cpp ------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/lldb-private.h" using namespace lldb; using namespace lldb_private; #if defined (__APPLE__) // Xcode writes this file out in a build step. // cmake builds get this through another mechanism. // Both produce LLDB_REVISION. #include "lldb_revision.h" extern "C" const unsigned char liblldb_coreVersionString[]; #endif #if defined(LLDB_USE_OSS_VERSION_SCHEME) #include "llvm/Support/raw_ostream.h" #include "swift/Basic/Version.h" #endif #if !defined (__APPLE__) || defined(LLDB_USE_OSS_VERSION_SCHEME) #include "clang/Basic/Version.h" static const char * GetLLDBRevision() { #ifdef LLDB_REVISION static const char *s_revision = LLDB_REVISION; #else static const char *s_revision = nullptr; #endif // If LLDB_REVISION is defined but isn't set to a string, it // can still be the equivalent of NULL. Hence we always do // this check below and return an empty string when we don't // otherwise have a valid const string for it. if (s_revision != nullptr) return s_revision; else return ""; } #endif #if !defined (__APPLE__) static const char * GetLLDBRepository() { #ifdef LLDB_REPOSITORY return LLDB_REPOSITORY; #else return NULL; #endif } #endif #if defined(LLDB_USE_OSS_VERSION_SCHEME) // TODO remove this function once swift revision is directly exposed. std::string ExtractSwiftRevision(const std::string &fullVersion) { // Find spot right before Swift revision. const std::string search_prefix = "Swift "; const size_t prefix_start_pos = fullVersion.rfind(search_prefix); if (prefix_start_pos == std::string::npos) return ""; // Find spot where Swift revision ends. const size_t revision_end_pos = fullVersion.rfind(')'); if (revision_end_pos == std::string::npos) return ""; // Return the revision. return fullVersion.substr(prefix_start_pos + search_prefix.length(), revision_end_pos - prefix_start_pos - search_prefix.length()); } static std::string GetBuildDate() { // The following code helps distinguish between a defined preprocessor // value that gets the default value assigned vs. one with an explicit value. #define LLDB_DO_MACRO_EXPAND(macro_value) macro_value ## 1 #define LLDB_MACRO_EXPAND(macro_value) LLDB_DO_MACRO_EXPAND(macro_value) #if defined(LLDB_BUILD_DATE) return std::string(LLDB_BUILD_DATE); #else return std::string(); #endif } static const char* _GetVersionOSS () { static std::string g_version_string; if (g_version_string.empty()) { std::string build_string; llvm::raw_string_ostream out(build_string); std::string build_flavor = "local"; #if defined (LLDB_IS_BUILDBOT_BUILD) # if (LLDB_IS_BUILDBOT_BUILD != 0) build_flavor = "buildbot"; # endif #endif out << "lldb-" << build_flavor; // We only run this code when the build date is both set and non-default. // Otherwise this code doesn't compile. const std::string build_date(GetBuildDate()); if (!build_date.empty()) out << "-" << build_date; out << " ("; std::string lldb_revision = GetLLDBRevision(); if (lldb_revision.length() > 0) { const size_t MAX_REVISION_LENGTH = 10; out << "LLDB "; out << lldb_revision.substr(0, MAX_REVISION_LENGTH); const std::string llvm_revision = clang::getLLVMRevision(); if (!llvm_revision.empty()) out << ", LLVM " << llvm_revision.substr(0, MAX_REVISION_LENGTH); const std::string clang_revision = clang::getClangRevision(); if (!clang_revision.empty()) out << ", Clang " << clang_revision.substr(0, MAX_REVISION_LENGTH); // TODO replace this with a swift::version::GetSwiftRevision() call // once added. const std::string swift_revision = ExtractSwiftRevision(swift::version::getSwiftFullVersion()); if (!swift_revision.empty()) { auto const swift_version = swift::version::getSwiftNumericVersion(); out << ", Swift-" << swift_version.first << "." << swift_version.second << " " << swift_revision.substr(0, MAX_REVISION_LENGTH); } } out << ")"; g_version_string = out.str(); } return g_version_string.c_str(); } #endif #if defined(__APPLE__) && !defined(LLDB_USE_OSS_VERSION_SCHEME) static const char* _GetVersionAppleStandard () { static char g_version_string[32]; if (g_version_string[0] == '\0') { const char *version_string = ::strstr ((const char *)liblldb_coreVersionString, "PROJECT:"); if (version_string) version_string += sizeof("PROJECT:") - 1; else version_string = "unknown"; const char *newline_loc = strchr(version_string, '\n'); size_t version_len = sizeof(g_version_string) - 1; if (newline_loc && (newline_loc - version_string < static_cast<ptrdiff_t>(version_len))) version_len = newline_loc - version_string; ::snprintf(g_version_string, version_len + 1, "%s", version_string); } return g_version_string; } #endif const char * lldb_private::GetVersion () { #if defined (__APPLE__) # if defined(LLDB_USE_OSS_VERSION_SCHEME) return _GetVersionOSS (); # else return _GetVersionAppleStandard (); # endif #else # if defined(LLDB_USE_OSS_VERSION_SCHEME) return _GetVersionOSS (); # else // On platforms other than Darwin, report a version number in the same style as the clang tool. static std::string g_version_str; if (g_version_str.empty()) { g_version_str += "lldb version "; g_version_str += CLANG_VERSION_STRING; const char * lldb_repo = GetLLDBRepository(); if (lldb_repo) { g_version_str += " ("; g_version_str += lldb_repo; } const char *lldb_rev = GetLLDBRevision(); if (lldb_rev) { g_version_str += " revision "; g_version_str += lldb_rev; } std::string clang_rev (clang::getClangRevision()); if (clang_rev.length() > 0) { g_version_str += " clang revision "; g_version_str += clang_rev; } std::string llvm_rev (clang::getLLVMRevision()); if (llvm_rev.length() > 0) { g_version_str += " llvm revision "; g_version_str += llvm_rev; } if (lldb_repo) g_version_str += ")"; } return g_version_str.c_str(); # endif #endif } <|endoftext|>
<commit_before>/* * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others. * * 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. * * Contributors: * Markus Pilman <mpilman@inf.ethz.ch> * Simon Loesing <sloesing@inf.ethz.ch> * Thomas Etter <etterth@gmail.com> * Kevin Bocksrocker <kevin.bocksrocker@gmail.com> * Lucas Braun <braunl@inf.ethz.ch> */ #include "Client.hpp" #include <util/Protocol.hpp> #include "sqlite3.h" #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <vector> #include <thread> namespace mbench { std::string cmdString(Commands cmd) { switch (cmd) { case mbench::Commands::CreateSchema: return "CreateSchema"; case mbench::Commands::Populate: return "Populate"; case mbench::Commands::BatchOp: return "BatchOp"; case mbench::Commands::Q1: return "Q1"; case mbench::Commands::Q2: return "Q2"; case mbench::Commands::Q3: return "Q3"; throw std::runtime_error("Invalid command"); } throw std::runtime_error("This has to be dead code"); } } // namespace mbench #define sqlOk(code) assertSql(code, __FILE__, __LINE__) void assertSql(int code, const char* file, int line) { if (code != SQLITE_OK) { auto msg = (boost::format("ERROR (%1%:%2%): %3%") % file % line % sqlite3_errstr(code)).str(); throw std::runtime_error(msg.c_str()); } } int main(int argc, const char* argv[]) { namespace po = boost::program_options; unsigned numThreads = 1; unsigned sf; unsigned oltpClients; bool populate = false; unsigned time = 5; unsigned numAnalytical; unsigned numOps; double insProb, delProb, updProb; bool noWarmup; bool onlyQ1; std::string hostStr; std::string dbFile("out.db"); po::options_description desc("Allowed options"); desc.add_options() ("help,h", "Show help message") ("hosts,H", po::value<std::string>(&hostStr)->required(), "Adress to servers") ("scaling-factor,s", po::value<unsigned>(&sf)->required(), "Scaling factor") ("clients,c", po::value<unsigned>(&oltpClients)->default_value(29), "Number of get/put clients (in total)") ("analytical,a", po::value<unsigned>(&numAnalytical)->default_value(0), "Number of analytical clients (in total)") ("threads,t", po::value<unsigned>(&numThreads), "Number of network threads") ("populate,P", "Run population instead of benchmark") ("db,o", po::value<std::string>(&dbFile), "Output to write to") ("time", po::value<unsigned>(&time), "Number of minutes to run") ("batch-size,b", po::value<unsigned>(&numOps)->default_value(100), "Number of operations per batch") ("inserts,i", po::value<double>(&insProb)->default_value(0.166), "Fraction of insert operations") ("deletes,d", po::value<double>(&delProb)->default_value(0.166), "Fraction of delete operations") ("update,u", po::value<double>(&updProb)->default_value(0.166), "Fraction of update operations") ("no-warmup", po::bool_switch(&noWarmup)->default_value(false), "No warm up time") ("only-q1,q", po::bool_switch(&onlyQ1)->default_value(false), "Execute only q1") ; po::variables_map vm; store(parse_command_line(argc, argv, desc), vm); if (vm.count("help")) { std::cout << desc << std::endl; return 0; } if (vm.count("populate")) { populate = true; } notify(vm); if (insProb + updProb + delProb > 1.0) { std::cerr << "sum(insert,delete,update) > 1.0\n"; return 1; } if (oltpClients == 0 && populate) { std::cerr << "can not populate without oltp clients\n"; return 1; } if (!noWarmup) time += 2; std::vector<std::string> hosts; boost::split(hosts, hostStr, boost::is_any_of(";,"), boost::token_compress_on); boost::asio::io_service service; boost::asio::io_service::strand ioStrand(service); std::vector<std::unique_ptr<mbench::Client>> clients; clients.reserve(oltpClients + numAnalytical); boost::asio::ip::tcp::resolver resolver(service); std::vector<std::string> hostPort; hostPort.reserve(2); bool allAnalytical = oltpClients == 0; auto hostIter = hosts.begin(); if (populate) numAnalytical = 0; for (unsigned i = 0; i < numAnalytical; ++i) { if (hostIter == hosts.end()) hostIter = hosts.begin(); clients.emplace_back(new mbench::Client(service, ioStrand, sf, oltpClients, 0, true, numOps, insProb, delProb, updProb, onlyQ1)); auto& client = *clients.back(); boost::split(hostPort, *hostIter, boost::is_any_of(":"), boost::token_compress_on); if (hostPort.size() == 1) { boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]})); } else if (hostPort.size() == 2) { boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]})); } else { std::cerr << "Format error while parsing hosts" << std::endl; return 1; } ++hostIter; } for (unsigned clientId = 0; clientId < oltpClients; ++clientId) { if (hostIter == hosts.end()) hostIter = hosts.begin(); clients.emplace_back(new mbench::Client(service, ioStrand, sf, oltpClients, clientId, false, numOps, insProb, delProb, updProb, onlyQ1)); auto& client = *clients.back(); boost::split(hostPort, *hostIter, boost::is_any_of(":"), boost::token_compress_on); if (hostPort.size() == 1) { boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]})); } else if (hostPort.size() == 2) { boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]})); } else { std::cerr << "Format error while parsing hosts" << std::endl; return 1; } ++hostIter; } auto duration = std::chrono::minutes(time); bool timerChosen = true; if (populate) { std::cout << "start population\n"; clients[0]->populate(clients); } else { for (auto& client : clients) { if (timerChosen && allAnalytical) { client->run(duration, true); timerChosen = false; } else if (timerChosen && !client->isAnalytical()) { client->run(duration, true); timerChosen = false; } else { client->run(duration, false); } } } std::cout << "Will run for " << time << " minutes with " << clients.size() << " clients\n"; auto startTime = mbench::Clock::now(); std::vector<std::thread> threads; threads.reserve(numThreads - 1); for (unsigned i = 0; i < numThreads - 1; ++i) { threads.emplace_back([&service](){ service.run(); }); } service.run(); for (auto& t : threads) { t.join(); } if (populate) { std::cout << " \r"; std::cout << "Done\n"; } std::cout << "Done - writing results\n"; sqlOk(sqlite3_config(SQLITE_CONFIG_SINGLETHREAD)); sqlite3* db; sqlOk(sqlite3_open(dbFile.c_str(), &db)); sqlOk(sqlite3_exec(db, "CREATE TABLE results(start int, end int, rt int, tx text, success text, msg text)", nullptr, nullptr, nullptr)); // Insert data sqlOk(sqlite3_exec(db, "BEGIN TRANSACTION", nullptr, nullptr, nullptr)); sqlite3_stmt* stmt; sqlOk(sqlite3_prepare_v2(db, "INSERT INTO results VALUES(?, ?, ?, ?, ?, ?)", -1, &stmt, nullptr)); for (auto& client : clients) { const auto& log = client->log(); for (const auto& e : log) { auto start = int(std::chrono::duration_cast<std::chrono::microseconds>(e.start - startTime).count()); auto end = int(std::chrono::duration_cast<std::chrono::microseconds>(e.end - startTime).count()); std::string trans = cmdString(e.transaction); std::string success = e.success ? "true" : "false"; std::string msg(e.error.data(), e.error.size()); sqlOk(sqlite3_bind_int(stmt, 1, start)); sqlOk(sqlite3_bind_int(stmt, 2, end)); sqlOk(sqlite3_bind_int(stmt, 3, e.responseTime)); sqlOk(sqlite3_bind_text(stmt, 4, trans.data(), trans.size(), nullptr)); sqlOk(sqlite3_bind_text(stmt, 5, success.data(), success.size(), nullptr)); sqlOk(sqlite3_bind_text(stmt, 6, msg.data(), msg.size(), nullptr)); int s; while ((s = sqlite3_step(stmt)) != SQLITE_DONE) { if (s == SQLITE_ERROR) { throw std::runtime_error(sqlite3_errmsg(db)); } } sqlite3_reset(stmt); } } sqlOk(sqlite3_exec(db, "END TRANSACTION", nullptr, nullptr, nullptr)); sqlOk(sqlite3_finalize(stmt)); std::cout << "Inserted data, calculating results...\n"; std::string cutWarmup = noWarmup ? "" : "start >= 60000000 AND end <= 360000000 AND success LIKE 'true'"; std::string getPutTP = (boost::format( "SELECT count(*)/%1% " "FROM results " "WHERE tx LIKE 'BatchOp' " "AND %2%" ) % double((time - 2)*60) % cutWarmup).str(); std::string scanTP = (boost::format( "SELECT count(*)/%1% " "FROM results " "WHERE tx LIKE 'Q%%' " "AND %2%" ) % double((time - 2)) % cutWarmup).str(); std::string responseTime = (boost::format( "SELECT tx, avg(rt) " "FROM results " "WHERE %1% " "GROUP BY tx;" ) % cutWarmup).str(); std::cout << "================\n"; std::cout << "Get/Put throughput:\n"; std::cout << "===================\n"; std::cout << getPutTP << std::endl; std::cout << "---------------------\n"; sqlOk(sqlite3_prepare_v2(db, getPutTP.data(), getPutTP.size() + 1, &stmt, nullptr)); int s; while ((s = sqlite3_step(stmt)) != SQLITE_DONE) { if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db)); double tp = sqlite3_column_double(stmt, 0); std::cout << tp << " / second\n"; } sqlOk(sqlite3_finalize(stmt)); sqlOk(sqlite3_prepare_v2(db, scanTP.data(), scanTP.size() + 1, &stmt, nullptr)); std::cout << "================\n"; std::cout << "Scan throughput:\n"; std::cout << "================\n"; std::cout << scanTP << std::endl; std::cout << "---------------------\n"; while ((s = sqlite3_step(stmt)) != SQLITE_DONE) { if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db)); double tp = sqlite3_column_double(stmt, 0); std::cout << tp << " / minute\n"; } std::cout << "================\n"; std::cout << "Response Times:\n"; std::cout << "================\n"; std::cout << responseTime << std::endl; sqlOk(sqlite3_finalize(stmt)); sqlOk(sqlite3_prepare_v2(db, responseTime.data(), responseTime.size() + 1, &stmt, nullptr)); while ((s = sqlite3_step(stmt)) != SQLITE_DONE) { if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db)); auto name = sqlite3_column_text(stmt, 0); double rt = sqlite3_column_double(stmt, 1); std::cout << name << ": " << rt/1000.0 << " microseconds" << std::endl; } std::cout << "done"; sqlite3_close(db); return 0; } <commit_msg>fixed writing to sqlite - don't print results.<commit_after>/* * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others. * * 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. * * Contributors: * Markus Pilman <mpilman@inf.ethz.ch> * Simon Loesing <sloesing@inf.ethz.ch> * Thomas Etter <etterth@gmail.com> * Kevin Bocksrocker <kevin.bocksrocker@gmail.com> * Lucas Braun <braunl@inf.ethz.ch> */ #include "Client.hpp" #include <util/Protocol.hpp> #include "sqlite3.h" #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <vector> #include <thread> namespace mbench { std::string cmdString(Commands cmd) { switch (cmd) { case mbench::Commands::CreateSchema: return "CreateSchema"; case mbench::Commands::Populate: return "Populate"; case mbench::Commands::BatchOp: return "BatchOp"; case mbench::Commands::Q1: return "Q1"; case mbench::Commands::Q2: return "Q2"; case mbench::Commands::Q3: return "Q3"; throw std::runtime_error("Invalid command"); } throw std::runtime_error("This has to be dead code"); } } // namespace mbench #define sqlOk(code) assertSql(code, __FILE__, __LINE__) void assertSql(int code, const char* file, int line) { if (code != SQLITE_OK) { auto msg = (boost::format("ERROR (%1%:%2%): %3%") % file % line % sqlite3_errstr(code)).str(); throw std::runtime_error(msg.c_str()); } } int main(int argc, const char* argv[]) { namespace po = boost::program_options; unsigned numThreads = 1; unsigned sf; unsigned oltpClients; bool populate = false; unsigned time = 5; unsigned numAnalytical; unsigned numOps; double insProb, delProb, updProb; bool noWarmup; bool onlyQ1; std::string hostStr; std::string dbFile("out.db"); po::options_description desc("Allowed options"); desc.add_options() ("help,h", "Show help message") ("hosts,H", po::value<std::string>(&hostStr)->required(), "Adress to servers") ("scaling-factor,s", po::value<unsigned>(&sf)->required(), "Scaling factor") ("clients,c", po::value<unsigned>(&oltpClients)->default_value(29), "Number of get/put clients (in total)") ("analytical,a", po::value<unsigned>(&numAnalytical)->default_value(0), "Number of analytical clients (in total)") ("threads,t", po::value<unsigned>(&numThreads), "Number of network threads") ("populate,P", "Run population instead of benchmark") ("db,o", po::value<std::string>(&dbFile), "Output to write to") ("time", po::value<unsigned>(&time), "Number of minutes to run") ("batch-size,b", po::value<unsigned>(&numOps)->default_value(100), "Number of operations per batch") ("inserts,i", po::value<double>(&insProb)->default_value(0.166), "Fraction of insert operations") ("deletes,d", po::value<double>(&delProb)->default_value(0.166), "Fraction of delete operations") ("update,u", po::value<double>(&updProb)->default_value(0.166), "Fraction of update operations") ("no-warmup", po::bool_switch(&noWarmup)->default_value(false), "No warm up time") ("only-q1,q", po::bool_switch(&onlyQ1)->default_value(false), "Execute only q1") ; po::variables_map vm; store(parse_command_line(argc, argv, desc), vm); if (vm.count("help")) { std::cout << desc << std::endl; return 0; } if (vm.count("populate")) { populate = true; } notify(vm); if (insProb + updProb + delProb > 1.0) { std::cerr << "sum(insert,delete,update) > 1.0\n"; return 1; } if (oltpClients == 0 && populate) { std::cerr << "can not populate without oltp clients\n"; return 1; } if (!noWarmup) time += 2; std::vector<std::string> hosts; boost::split(hosts, hostStr, boost::is_any_of(";,"), boost::token_compress_on); boost::asio::io_service service; boost::asio::io_service::strand ioStrand(service); std::vector<std::unique_ptr<mbench::Client>> clients; clients.reserve(oltpClients + numAnalytical); boost::asio::ip::tcp::resolver resolver(service); std::vector<std::string> hostPort; hostPort.reserve(2); bool allAnalytical = oltpClients == 0; auto hostIter = hosts.begin(); if (populate) numAnalytical = 0; for (unsigned i = 0; i < numAnalytical; ++i) { if (hostIter == hosts.end()) hostIter = hosts.begin(); clients.emplace_back(new mbench::Client(service, ioStrand, sf, oltpClients, 0, true, numOps, insProb, delProb, updProb, onlyQ1)); auto& client = *clients.back(); boost::split(hostPort, *hostIter, boost::is_any_of(":"), boost::token_compress_on); if (hostPort.size() == 1) { boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]})); } else if (hostPort.size() == 2) { boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]})); } else { std::cerr << "Format error while parsing hosts" << std::endl; return 1; } ++hostIter; } for (unsigned clientId = 0; clientId < oltpClients; ++clientId) { if (hostIter == hosts.end()) hostIter = hosts.begin(); clients.emplace_back(new mbench::Client(service, ioStrand, sf, oltpClients, clientId, false, numOps, insProb, delProb, updProb, onlyQ1)); auto& client = *clients.back(); boost::split(hostPort, *hostIter, boost::is_any_of(":"), boost::token_compress_on); if (hostPort.size() == 1) { boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]})); } else if (hostPort.size() == 2) { boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]})); } else { std::cerr << "Format error while parsing hosts" << std::endl; return 1; } ++hostIter; } auto duration = std::chrono::minutes(time); bool timerChosen = true; if (populate) { std::cout << "start population\n"; clients[0]->populate(clients); } else { for (auto& client : clients) { if (timerChosen && allAnalytical) { client->run(duration, true); timerChosen = false; } else if (timerChosen && !client->isAnalytical()) { client->run(duration, true); timerChosen = false; } else { client->run(duration, false); } } } std::cout << "Will run for " << time << " minutes with " << clients.size() << " clients\n"; auto startTime = mbench::Clock::now(); std::vector<std::thread> threads; threads.reserve(numThreads - 1); for (unsigned i = 0; i < numThreads - 1; ++i) { threads.emplace_back([&service](){ service.run(); }); } service.run(); for (auto& t : threads) { t.join(); } if (populate) { std::cout << " \r"; std::cout << "Done\n"; } std::cout << "Done - writing results\n"; sqlOk(sqlite3_config(SQLITE_CONFIG_SINGLETHREAD)); sqlite3* db; sqlOk(sqlite3_open(dbFile.c_str(), &db)); sqlOk(sqlite3_exec(db, "CREATE TABLE results(start int, end int, rt int, tx text, success text, msg text)", nullptr, nullptr, nullptr)); sqlOk(sqlite3_exec(db, "CREATE TABLE clientArgs(idx int, param text)", nullptr, nullptr, nullptr)); sqlOk(sqlite3_exec(db, "BEGIN TRANSACTION", nullptr, nullptr, nullptr)); // Insert arguments sqlite3_stmt* stmt; sqlOk(sqlite3_prepare_v2(db, "INSERT INTO clientArgs VALUES(?, ?)", -1, &stmt, nullptr)); for (int i = 0; i < argc; ++i) { sqlOk(sqlite3_bind_int(stmt, 1, i)); sqlOk(sqlite3_bind_text(stmt, 2, argv[i], -1, nullptr)); int s; while ((s = sqlite3_step(stmt)) != SQLITE_DONE) { if (s == SQLITE_ERROR) { throw std::runtime_error(sqlite3_errmsg(db)); } } sqlite3_reset(stmt); } sqlOk(sqlite3_finalize(stmt)); sqlOk(sqlite3_exec(db, "END TRANSACTION", nullptr, nullptr, nullptr)); // insert data sqlOk(sqlite3_exec(db, "BEGIN TRANSACTION", nullptr, nullptr, nullptr)); sqlOk(sqlite3_prepare_v2(db, "INSERT INTO results VALUES(?, ?, ?, ?, ?, ?)", -1, &stmt, nullptr)); for (auto& client : clients) { const auto& log = client->log(); for (const auto& e : log) { auto start = int(std::chrono::duration_cast<std::chrono::microseconds>(e.start - startTime).count()); auto end = int(std::chrono::duration_cast<std::chrono::microseconds>(e.end - startTime).count()); std::string trans = cmdString(e.transaction); std::string success = e.success ? "true" : "false"; std::string msg(e.error.data(), e.error.size()); sqlOk(sqlite3_bind_int(stmt, 1, start)); sqlOk(sqlite3_bind_int(stmt, 2, end)); sqlOk(sqlite3_bind_int64(stmt, 3, e.responseTime)); sqlOk(sqlite3_bind_text(stmt, 4, trans.data(), trans.size(), nullptr)); sqlOk(sqlite3_bind_text(stmt, 5, success.data(), success.size(), nullptr)); sqlOk(sqlite3_bind_text(stmt, 6, msg.data(), msg.size(), nullptr)); int s; while ((s = sqlite3_step(stmt)) != SQLITE_DONE) { if (s == SQLITE_ERROR) { throw std::runtime_error(sqlite3_errmsg(db)); } } sqlite3_reset(stmt); } } sqlOk(sqlite3_finalize(stmt)); sqlOk(sqlite3_exec(db, "END TRANSACTION", nullptr, nullptr, nullptr)); std::cout << "done\n"; sqlite3_close(db); return 0; } <|endoftext|>
<commit_before><commit_msg>No need to rotate U/V components returned by qengine<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlgattr.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2007-04-26 07:59:28 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifdef MAC #ifdef ITEMID_NUMBERINFO #undef ITEMID_NUMBERINFO #endif #endif #define ITEMID_NUMBERINFO 0 #ifndef DBAUI_SBATTRDLG_HXX #include "dlgattr.hxx" #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SVX_NUMINF_HXX //autogen #include <svx/numinf.hxx> #endif //CHINA001 #ifndef _SVX_CHARDLG_HXX //autogen //CHINA001 #include <svx/chardlg.hxx> //CHINA001 #endif //CHINA001 #ifndef _SVX_NUMFMT_HXX //autogen //CHINA001 #include <svx/numfmt.hxx> //CHINA001 #endif #ifndef _SVX_NUMINF_HXX #include <svx/numinf.hxx> #endif //CHINA001 #ifndef _SVX_ALIGN_HXX //autogen //CHINA001 #include <svx/align.hxx> //CHINA001 #endif #ifndef _SVX_DIALOGS_HRC #include <svx/dialogs.hrc> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _DBU_DLG_HRC_ #include "dbu_dlg.hrc" #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #define _ZFORLIST_DECLARE_TABLE #ifndef _ZFORLIST_HXX #include <svtools/zforlist.hxx> #endif #include <svx/svxids.hrc> //CHINA001 #include <svx/flagsdef.hxx> //CHINA001 #ifndef _SFXINTITEM_HXX //CHINA001 #include <svtools/intitem.hxx> //CHINA001 #endif //CHINA001 using namespace dbaui; DBG_NAME(SbaSbAttrDlg) //================================================================== SbaSbAttrDlg::SbaSbAttrDlg(Window* pParent, const SfxItemSet* pCellAttrs, SvNumberFormatter* pFormatter, USHORT nFlags, BOOL bRow) : SfxTabDialog(pParent, ModuleRes( DLG_ATTR ), pCellAttrs ) ,aTitle(ModuleRes(ST_ROW)) { DBG_CTOR(SbaSbAttrDlg,NULL); pNumberInfoItem = new SvxNumberInfoItem( pFormatter ); if (bRow) SetText(aTitle); if( nFlags & TP_ATTR_CHAR ) { // AddTabPage( RID_SVXPAGE_CHAR_STD,String(ModuleRes(TP_ATTR_CHAR)),SvxCharStdPage::Create, 0 ); DBG_ERROR( "found flag TP_ATTR_CHAR" ); } if( nFlags & TP_ATTR_NUMBER ) AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)) ); //CHINA001 AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)),SvxNumberFormatTabPage::Create, 0 ); if( nFlags & TP_ATTR_ALIGN ) AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)) );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)),SvxAlignmentTabPage::Create, 0 ); FreeResource(); } // ----------------------------------------------------------------------- SbaSbAttrDlg::~SbaSbAttrDlg() { delete pNumberInfoItem; DBG_DTOR(SbaSbAttrDlg,NULL); } // ----------------------------------------------------------------------- void SbaSbAttrDlg::PageCreated( sal_uInt16 nPageId, SfxTabPage& rTabPage ) { SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool())); switch ( nPageId ) { case RID_SVXPAGE_NUMBERFORMAT: { //CHINA001 ((SvxNumberFormatTabPage&)rTabPage). //CHINA001 SetNumberFormatList( *pNumberInfoItem ); aSet.Put (SvxNumberInfoItem( pNumberInfoItem->GetNumberFormatter(), (const USHORT)SID_ATTR_NUMBERFORMAT_INFO)); rTabPage.PageCreated(aSet); } break; case RID_SVXPAGE_CHAR_STD: { // ((SvxCharStdPage&)rTabPage).SetFontList(SBA_MOD_EXT()->FontListItem()); } break; case RID_SVXPAGE_ALIGNMENT: { //CHINA001 ((SvxAlignmentTabPage&)rTabPage).SetFlags(WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT); // aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT)); // rTabPage.PageCreated(aSet); } break; default: break; } } <commit_msg>INTEGRATION: CWS pchfix04 (1.9.32); FILE MERGED 2007/02/05 08:45:41 os 1.9.32.1: #i73604# usage of ITEMID_* removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlgattr.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: kz $ $Date: 2007-05-10 15:06:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBAUI_SBATTRDLG_HXX #include "dlgattr.hxx" #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SVX_NUMINF_HXX //autogen #include <svx/numinf.hxx> #endif //CHINA001 #ifndef _SVX_CHARDLG_HXX //autogen //CHINA001 #include <svx/chardlg.hxx> //CHINA001 #endif //CHINA001 #ifndef _SVX_NUMFMT_HXX //autogen //CHINA001 #include <svx/numfmt.hxx> //CHINA001 #endif #ifndef _SVX_NUMINF_HXX #include <svx/numinf.hxx> #endif //CHINA001 #ifndef _SVX_ALIGN_HXX //autogen //CHINA001 #include <svx/align.hxx> //CHINA001 #endif #ifndef _SVX_DIALOGS_HRC #include <svx/dialogs.hrc> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _DBU_DLG_HRC_ #include "dbu_dlg.hrc" #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #define _ZFORLIST_DECLARE_TABLE #ifndef _ZFORLIST_HXX #include <svtools/zforlist.hxx> #endif #include <svx/svxids.hrc> //CHINA001 #include <svx/flagsdef.hxx> //CHINA001 #ifndef _SFXINTITEM_HXX //CHINA001 #include <svtools/intitem.hxx> //CHINA001 #endif //CHINA001 using namespace dbaui; DBG_NAME(SbaSbAttrDlg) //================================================================== SbaSbAttrDlg::SbaSbAttrDlg(Window* pParent, const SfxItemSet* pCellAttrs, SvNumberFormatter* pFormatter, USHORT nFlags, BOOL bRow) : SfxTabDialog(pParent, ModuleRes( DLG_ATTR ), pCellAttrs ) ,aTitle(ModuleRes(ST_ROW)) { DBG_CTOR(SbaSbAttrDlg,NULL); pNumberInfoItem = new SvxNumberInfoItem( pFormatter, 0 ); if (bRow) SetText(aTitle); if( nFlags & TP_ATTR_CHAR ) { // AddTabPage( RID_SVXPAGE_CHAR_STD,String(ModuleRes(TP_ATTR_CHAR)),SvxCharStdPage::Create, 0 ); DBG_ERROR( "found flag TP_ATTR_CHAR" ); } if( nFlags & TP_ATTR_NUMBER ) AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)) ); //CHINA001 AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)),SvxNumberFormatTabPage::Create, 0 ); if( nFlags & TP_ATTR_ALIGN ) AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)) );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)),SvxAlignmentTabPage::Create, 0 ); FreeResource(); } // ----------------------------------------------------------------------- SbaSbAttrDlg::~SbaSbAttrDlg() { delete pNumberInfoItem; DBG_DTOR(SbaSbAttrDlg,NULL); } // ----------------------------------------------------------------------- void SbaSbAttrDlg::PageCreated( sal_uInt16 nPageId, SfxTabPage& rTabPage ) { SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool())); switch ( nPageId ) { case RID_SVXPAGE_NUMBERFORMAT: { //CHINA001 ((SvxNumberFormatTabPage&)rTabPage). //CHINA001 SetNumberFormatList( *pNumberInfoItem ); aSet.Put (SvxNumberInfoItem( pNumberInfoItem->GetNumberFormatter(), (const USHORT)SID_ATTR_NUMBERFORMAT_INFO)); rTabPage.PageCreated(aSet); } break; case RID_SVXPAGE_CHAR_STD: { // ((SvxCharStdPage&)rTabPage).SetFontList(SBA_MOD_EXT()->FontListItem()); } break; case RID_SVXPAGE_ALIGNMENT: { //CHINA001 ((SvxAlignmentTabPage&)rTabPage).SetFlags(WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT); // aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT)); // rTabPage.PageCreated(aSet); } break; default: break; } } <|endoftext|>
<commit_before>//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2005 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <base/path_search.h> #include <base/logstream.h> #include <iostream> #include <algorithm> //TODO:[GK] Clean up open functions, reuse code! std::map<std::string, std::vector<std::string> > PathSearch::path_lists; std::map<std::string, std::vector<std::string> > PathSearch::suffix_lists; std::string PathSearch::empty(""); void PathSearch::initialize_classes() { std::vector<std::string> v; v.push_back(empty); path_lists.insert(map_type(std::string("PARAMETER"), v)); v.push_back(std::string(DEAL_II_PATH "/lib/meshes/")); path_lists.insert(map_type(std::string("MESH"), v)); v.clear(); v.push_back(empty); v.push_back(std::string(".prm")); suffix_lists.insert(map_type(std::string("PARAMETER"), v)); v.clear(); v.push_back(empty); v.push_back(std::string(".inp")); v.push_back(std::string(".xda")); v.push_back(std::string(".dbmesh")); suffix_lists.insert(map_type(std::string("MESH"), v)); } std::vector<std::string>& PathSearch::get_path_list(const std::string& cls) { if (path_lists.empty()) initialize_classes(); Assert(path_lists.count(cls) != 0, ExcNoClass(cls)); return path_lists.find(cls)->second; } std::vector<std::string>& PathSearch::get_suffix_list(const std::string& cls) { Assert(suffix_lists.count(cls) != 0, ExcNoClass(cls)); return suffix_lists.find(cls)->second; } PathSearch::PathSearch(const std::string& cls, const unsigned int debug) : cls(cls), my_path_list(get_path_list(cls)), my_suffix_list(get_suffix_list(cls)), debug(debug) {} std::istream& PathSearch::open (const std::string& filename, const std::string& suffix) { std::vector<std::string>::const_iterator path; const std::vector<std::string>::const_iterator endp = my_path_list.end(); if (debug > 2) deallog << "PathSearch[" << cls << "] " << my_path_list.size() << " directories " << std::endl; // Try without suffix first for (path = my_path_list.begin(); path != endp; ++path) { real_name = *path + filename; if (debug > 1) deallog << "PathSearch[" << cls << "] trying " << real_name << std::endl; stream.reset(new std::ifstream(real_name.c_str())); if (stream->is_open()) { if (debug > 0) deallog << "PathSearch[" << cls << "] opened " << real_name << std::endl; return *stream; } } // Now try with given suffix for (path = my_path_list.begin(); path != endp; ++path) { real_name = *path + filename + suffix; if (debug > 1) deallog << "PathSearch[" << cls << "] trying " << real_name << std::endl; stream.reset(new std::ifstream(real_name.c_str())); if (stream->is_open()) { if (debug > 0) deallog << "PathSearch[" << cls << "] opened " << real_name << std::endl; return *stream; } } AssertThrow(false, ExcFileNotFound(filename, cls)); return *stream; } std::istream& PathSearch::open (const std::string& filename) { std::vector<std::string>::const_iterator suffix; std::vector<std::string>::const_iterator path; const std::vector<std::string>::const_iterator ends = my_suffix_list.end(); const std::vector<std::string>::const_iterator endp = my_path_list.end(); if (debug > 2) deallog << "PathSearch[" << cls << "] " << my_path_list.size() << " directories " << my_suffix_list.size() << " suffixes" << std::endl; for (suffix = my_suffix_list.begin(); suffix != ends; ++suffix) { for (path = my_path_list.begin(); path != endp; ++path) { real_name = *path + filename + *suffix; if (debug > 1) deallog << "PathSearch[" << cls << "] trying " << real_name << std::endl; stream.reset(new std::ifstream(real_name.c_str())); if (stream->is_open()) { if (debug > 0) deallog << "PathSearch[" << cls << "] opened " << real_name << std::endl; return *stream; } } } AssertThrow(false, ExcFileNotFound(filename, cls)); return *stream; } void PathSearch::add_class (const std::string& cls) { // Make sure standard classes are // initialized first if (path_lists.empty()) initialize_classes(); // Add empty path and empty suffix // for new class std::vector<std::string> v; v.push_back(empty); path_lists.insert(map_type(cls, v)); suffix_lists.insert(map_type(cls, v)); } void PathSearch::add_path (const std::string& path, Position pos) { if (pos == back) my_path_list.push_back(path); else if (pos == front) my_path_list.insert(my_path_list.begin(), path); else if (pos == after_none) { std::vector<std::string>::iterator i = std::find(my_path_list.begin(), my_path_list.end(), empty); if (i != my_path_list.end()) ++i; my_path_list.insert(i, path); } } void PathSearch::add_suffix (const std::string& suffix, Position pos) { if (pos == back) my_suffix_list.push_back(suffix); else if (pos == front) my_suffix_list.insert(my_suffix_list.begin(), suffix); else if (pos == after_none) { std::vector<std::string>::iterator i = std::find(my_suffix_list.begin(), my_suffix_list.end(), empty); if (i != my_suffix_list.end()) ++i; my_suffix_list.insert(i, suffix); } } <commit_msg>Add a TODO.<commit_after>//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2005 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <base/path_search.h> #include <base/logstream.h> #include <iostream> #include <algorithm> //TODO:[GK] Clean up open functions, reuse code! std::map<std::string, std::vector<std::string> > PathSearch::path_lists; std::map<std::string, std::vector<std::string> > PathSearch::suffix_lists; std::string PathSearch::empty(""); void PathSearch::initialize_classes() { std::vector<std::string> v; v.push_back(empty); path_lists.insert(map_type(std::string("PARAMETER"), v)); v.push_back(std::string(DEAL_II_PATH "/lib/meshes/")); path_lists.insert(map_type(std::string("MESH"), v)); v.clear(); v.push_back(empty); v.push_back(std::string(".prm")); suffix_lists.insert(map_type(std::string("PARAMETER"), v)); //TODO[GK]: instead of listing by hand here, query the GridIn class which formats it can presently read v.clear(); v.push_back(empty); v.push_back(std::string(".inp")); v.push_back(std::string(".xda")); v.push_back(std::string(".dbmesh")); suffix_lists.insert(map_type(std::string("MESH"), v)); } std::vector<std::string>& PathSearch::get_path_list(const std::string& cls) { if (path_lists.empty()) initialize_classes(); Assert(path_lists.count(cls) != 0, ExcNoClass(cls)); return path_lists.find(cls)->second; } std::vector<std::string>& PathSearch::get_suffix_list(const std::string& cls) { Assert(suffix_lists.count(cls) != 0, ExcNoClass(cls)); return suffix_lists.find(cls)->second; } PathSearch::PathSearch(const std::string& cls, const unsigned int debug) : cls(cls), my_path_list(get_path_list(cls)), my_suffix_list(get_suffix_list(cls)), debug(debug) {} std::istream& PathSearch::open (const std::string& filename, const std::string& suffix) { std::vector<std::string>::const_iterator path; const std::vector<std::string>::const_iterator endp = my_path_list.end(); if (debug > 2) deallog << "PathSearch[" << cls << "] " << my_path_list.size() << " directories " << std::endl; // Try without suffix first for (path = my_path_list.begin(); path != endp; ++path) { real_name = *path + filename; if (debug > 1) deallog << "PathSearch[" << cls << "] trying " << real_name << std::endl; stream.reset(new std::ifstream(real_name.c_str())); if (stream->is_open()) { if (debug > 0) deallog << "PathSearch[" << cls << "] opened " << real_name << std::endl; return *stream; } } // Now try with given suffix for (path = my_path_list.begin(); path != endp; ++path) { real_name = *path + filename + suffix; if (debug > 1) deallog << "PathSearch[" << cls << "] trying " << real_name << std::endl; stream.reset(new std::ifstream(real_name.c_str())); if (stream->is_open()) { if (debug > 0) deallog << "PathSearch[" << cls << "] opened " << real_name << std::endl; return *stream; } } AssertThrow(false, ExcFileNotFound(filename, cls)); return *stream; } std::istream& PathSearch::open (const std::string& filename) { std::vector<std::string>::const_iterator suffix; std::vector<std::string>::const_iterator path; const std::vector<std::string>::const_iterator ends = my_suffix_list.end(); const std::vector<std::string>::const_iterator endp = my_path_list.end(); if (debug > 2) deallog << "PathSearch[" << cls << "] " << my_path_list.size() << " directories " << my_suffix_list.size() << " suffixes" << std::endl; for (suffix = my_suffix_list.begin(); suffix != ends; ++suffix) { for (path = my_path_list.begin(); path != endp; ++path) { real_name = *path + filename + *suffix; if (debug > 1) deallog << "PathSearch[" << cls << "] trying " << real_name << std::endl; stream.reset(new std::ifstream(real_name.c_str())); if (stream->is_open()) { if (debug > 0) deallog << "PathSearch[" << cls << "] opened " << real_name << std::endl; return *stream; } } } AssertThrow(false, ExcFileNotFound(filename, cls)); return *stream; } void PathSearch::add_class (const std::string& cls) { // Make sure standard classes are // initialized first if (path_lists.empty()) initialize_classes(); // Add empty path and empty suffix // for new class std::vector<std::string> v; v.push_back(empty); path_lists.insert(map_type(cls, v)); suffix_lists.insert(map_type(cls, v)); } void PathSearch::add_path (const std::string& path, Position pos) { if (pos == back) my_path_list.push_back(path); else if (pos == front) my_path_list.insert(my_path_list.begin(), path); else if (pos == after_none) { std::vector<std::string>::iterator i = std::find(my_path_list.begin(), my_path_list.end(), empty); if (i != my_path_list.end()) ++i; my_path_list.insert(i, path); } } void PathSearch::add_suffix (const std::string& suffix, Position pos) { if (pos == back) my_suffix_list.push_back(suffix); else if (pos == front) my_suffix_list.insert(my_suffix_list.begin(), suffix); else if (pos == after_none) { std::vector<std::string>::iterator i = std::find(my_suffix_list.begin(), my_suffix_list.end(), empty); if (i != my_suffix_list.end()) ++i; my_suffix_list.insert(i, suffix); } } <|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2014 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : field/test/container.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // includes, system #include <glm/gtx/io.hpp> // glm::operator<< // includes, project #include <scene/objects.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal } // namespace { #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(test_scene_object_light_base_rep) { scene::object::light::base::rep const lr; BOOST_CHECK(false == lr.active); BOOST_MESSAGE("object_light_source_rep:" << lr << '\n'); } BOOST_AUTO_TEST_CASE(test_scene_object_light_directional) { scene::object::light::directional const l; BOOST_CHECK(false == l.active); BOOST_MESSAGE(l << '\n'); } BOOST_AUTO_TEST_CASE(test_scene_object_light_positional) { scene::object::light::positional const l; BOOST_CHECK(false == l.active); BOOST_MESSAGE(l << '\n'); } BOOST_AUTO_TEST_CASE(test_scene_object_light_spot) { scene::object::light::spot const l; BOOST_CHECK(false == l.active); BOOST_MESSAGE(l << '\n'); } BOOST_AUTO_TEST_CASE(test_scene_object_light_area) { scene::object::light::area l; l.exponent.set(1); l.cutoff. set(12.5); l.size. set(glm::uvec2(1, 2)); l.samples. set(glm::uvec2(1, 4)); l.size. set(glm::uvec2(2, 1)); l.samples. set(glm::uvec2(4, 1)); l.size. set(glm::uvec2(2, 2)); l.samples. set(glm::uvec2(4, 4)); l.size. set(glm::uvec2( 6, 3)); l.samples. set(glm::uvec2(10, 5)); BOOST_CHECK(false == l.active); BOOST_MESSAGE(l << '\n'); } <commit_msg>fixed: typo<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2014 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : field/test/objects_light.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // includes, system #include <glm/gtx/io.hpp> // glm::operator<< // includes, project #include <scene/objects.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal } // namespace { #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(test_scene_object_light_base_rep) { scene::object::light::base::rep const lr; BOOST_CHECK(false == lr.active); BOOST_MESSAGE("object_light_source_rep:" << lr << '\n'); } BOOST_AUTO_TEST_CASE(test_scene_object_light_directional) { scene::object::light::directional const l; BOOST_CHECK(false == l.active); BOOST_MESSAGE(l << '\n'); } BOOST_AUTO_TEST_CASE(test_scene_object_light_positional) { scene::object::light::positional const l; BOOST_CHECK(false == l.active); BOOST_MESSAGE(l << '\n'); } BOOST_AUTO_TEST_CASE(test_scene_object_light_spot) { scene::object::light::spot const l; BOOST_CHECK(false == l.active); BOOST_MESSAGE(l << '\n'); } BOOST_AUTO_TEST_CASE(test_scene_object_light_area) { scene::object::light::area l; l.exponent.set(1); l.cutoff. set(12.5); l.size. set(glm::uvec2(1, 2)); l.samples. set(glm::uvec2(1, 4)); l.size. set(glm::uvec2(2, 1)); l.samples. set(glm::uvec2(4, 1)); l.size. set(glm::uvec2(2, 2)); l.samples. set(glm::uvec2(4, 4)); l.size. set(glm::uvec2( 6, 3)); l.samples. set(glm::uvec2(10, 5)); BOOST_CHECK(false == l.active); BOOST_MESSAGE(l << '\n'); } <|endoftext|>
<commit_before>/* * BaseProbe.h * * Author: slundquist */ #ifndef BASEPROBE_HPP_ #define BASEPROBE_HPP_ #include <stdio.h> #include <vector> #include "../io/fileio.hpp" namespace PV { class HyPerCol; class HyPerLayer; //typedef enum { // BufV, // BufActivity //} PVBufType; /** * An abstract base class for the common functionality of layer probes and connection probes. */ class BaseProbe { // Methods public: //BaseProbe(const char * probeName, HyPerCol * hc); virtual ~BaseProbe(); int ioParams(enum ParamsIOFlag ioFlag); /** * A pure virtual function called during HyPerCol::run, during the communicateInitInfo stage. * BaseProbe::communicateInitInfo sets up the triggering layer and attaches to the energy probe, * if either triggerFlag or energyProbe are set. */ virtual int communicateInitInfo() = 0; /** * Called during HyPerCol::run, during the allocateDataStructures stage. * BaseProbe::allocateDataStructures returns immediately, but derived classes that * need to allocate storage should override this method. */ virtual int allocateDataStructures(); /** * If there is a triggering layer, needUpdate returns true when the triggering layer's * nextUpdateTime, modified by the probe's triggerOffset parameter, occurs. * If there is not a triggering layer, needUpdate returns false. * This behavior can be overridden if a probe uses some criterion other than triggering * to choose when output its state. */ virtual bool needUpdate(double time, double dt); /** * Returns the number of value indices the probe can compute (typically the value * of the parent HyPerCol's nBatch parameter). * BaseProbe::getNumValues() returns the parent HyPerCol's getNBatch(), which can be overridden. * Probes derived from BaseProbe can set numValues to zero or a negative number to indicate that * getValues() and getNumValues() * are not fully implemented for that probe. */ int getNumValues() { return numValues; } /** * The public interface for calling the outputState method. * BaseConnection::outputStateWrapper calls outputState() if needUpdate() returns true. * This behavior is intended to be general, but the method can be overridden if needed. */ virtual int outputStateWrapper(double timef, double dt); /** * A pure virtual method for writing output to the output file. */ virtual int outputState(double timef) = 0; virtual int writeTimer(FILE* stream) {return PV_SUCCESS;} /** * Returns the keyword of the params group associated with this probe. */ char const * getKeyword(); /** * Returns the name of the probe, specified in the public constructor. */ const char * getName() {return name;} /** * Returns the name of the targetName parameter for this probe. * LayerProbe uses targetName to specify the layer to attach to; * BaseConnectionProbe uses it to specify the connection to attach to. */ const char * getTargetName() {return targetName;} /** * Specifies the object responsible calling the probe's destructor. * BaseProbe sets owner to the parent HyPerCol during initialization. * During the communicateInitInfo stage, layer probes and connection probes * change their owner to the layer or connection they attach to. */ void const * getOwner() { return owner;} /** * getValues(double timevalue, double * values) sets the buffer 'values' with the probe's calculated values. * It assumes that the values buffer is large enough to hold getNumValues() * double-precision values. * If 'values' is NULL, the values are still updated internally if needed, but * those values are not returned. * Internally, getValues() calls calcValues() if needRecalc() is true. It then * copies the probeValues buffer to the input argument buffer 'values'. * Derived classes should not override or hide this method. Instead, they should override calcValues. */ int getValues(double timevalue, double * valuesVector); /** * getValues(double timevalue, vector<double> * valuesVector) is a wrapper around * getValues(double, double *) that uses C++ vectors. It resizes valuesVector * to size getNumValues() and then fills the vector with the values returned by getValues. */ int getValues(double timevalue, std::vector<double> * valuesVector); /** * getValue() is meant for situations where the caller needs one value * that would be returned by getValues(), not the whole buffer. * getValue() returns a signaling NaN if index is out of bounds. If index is valid, * getValue() calls calcValues() if needRecalc() returns true, and then * returns probeValues[index]. * Derived classes should not override or hide this method. Instead, they should override calcValues. */ double getValue(double timevalue, int index); protected: BaseProbe(); int initialize(const char * probeName, HyPerCol * hc); virtual int ioParamsFillGroup(enum ParamsIOFlag ioFlag); /** * List of parameters for the BaseProbe class * @name BaseProbe Parameters * @{ */ /** * @brief targetName: the name of the object that the probe attaches to. * In LayerProbe, targetName is used to define the targetLayer, and in * BaseConnectionProbe, targetName is used to define the targetConn. */ virtual void ioParam_targetName(enum ParamsIOFlag ioFlag); /** * @brief message: A string parameter that is typically included in the lines output by the outputState method */ virtual void ioParam_message(enum ParamsIOFlag ioFlag); /** * @brief probeOutputFile: the name of the file that the outputState method writes to. * If blank, the output is sent to stdout. */ virtual void ioParam_probeOutputFile(enum ParamsIOFlag ioFlag); /** * @brief triggerFlag: If false, the needUpdate method always returns true, * so that outputState is called every timestep. If false, the needUpdate * method uses triggerLayerName and triggerOffset to determine if the probe * should be triggered. */ virtual void ioParam_triggerFlag(enum ParamsIOFlag ioFlag); /** * @brief triggerLayerName: If triggerFlag is true, triggerLayerName specifies the layer * to check for triggering. */ virtual void ioParam_triggerLayerName(enum ParamsIOFlag ioFlag); /** * @brief triggerOffset: If triggerFlag is true, triggerOffset specifies the * time interval *before* the triggerLayer's nextUpdate time that needUpdate() returns true. */ virtual void ioParam_triggerOffset(enum ParamsIOFlag ioFlag); /** * @brief energyProbe: If nonblank, specifies the name of a ColumnEnergyProbe * that this probe contributes an energy term to. */ virtual void ioParam_energyProbe(enum ParamsIOFlag ioFlag); /** * @brief coefficient: If energyProbe is set, the coefficient parameter specifies * that ColumnEnergyProbe multiplies the result of this probe's getValues() method * by coefficient when computing the error. * @details Note that coefficient does not affect the value returned by the getValue() or * getValues() method. */ virtual void ioParam_coefficient(enum ParamsIOFlag ioFlag); /** @} */ virtual int initOutputStream(const char * filename); /** * A pure virtual method for that should return true if the quantities being measured * by the probe have changed since the last time the quantities were calculated. * Typically, an implementation of needRecalc() will check the lastUpdateTime of * the object being probed, and return true if that value is greater than the * lastUpdateTime member variable. * needRecalc() is called by getValues(double) (and hence by getValue() and the other * flavors of getValues). * Note that there is a single needRecalc that applies to all getNumValues() quantities. */ virtual bool needRecalc(double timevalue) = 0; /** * A pure virtual method to calculate the values of the probe. calcValues() can * assume that needRecalc() has been called and returned true. * It should write the computed values into the buffer of member variable 'probeValues'. */ virtual int calcValues(double timevalue) = 0; /** * If needRecalc() returns true, getValues(double) updates the probeValues buffer * (by calling calcValues) and sets lastUpdateTime to the timevalue input argument. */ int getValues(double timevalue); /** * Returns a pointer to parent HyPerCol. */ HyPerCol * getParent() {return parent;} /** * Returns a pointer to the message parameter. */ const char * getMessage() {return msgstring;} /** * The method called by BaseProbe::initialize() to set the message used by * the probe's outputState method. */ virtual int initMessage(const char * msg); /** * Returns a pointer to the PV_Stream used by outputState. */ PV_Stream * getStream() {return outputstream;} /** * initNumValues is called by initialize. * BaseProbe::initNumValues sets numValues to the parent HyPerCol's getNBatch(). * Derived classes can override initNumValues to initialize numValues to a different * value. */ virtual int initNumValues(); /** * Sets the numValues member variable (returned by getNumValues()) and reallocates * the probeValues member variable to hold numValues double-precision values. * If the reallocation fails, the probeValues buffer is left unchanged, errno is * set (by a realloc() call), and PV_FAILURE is returned. * Otherwise, PV_SUCCESS is returned. */ int setNumValues(int n); /** * Returns a pointer to the buffer containing the probeValues. */ double * getValuesBuffer() { return probeValues; } /** * Returns the time that calcValues was last called. * BaseProbe updates the last update time in getValues() and getValue(), * based on the result of needRecalc. */ double getLastUpdateTime() { return lastUpdateTime; } private: int initialize_base(); void setParentCol(HyPerCol * hc) {parent = hc;} int setProbeName(const char * probeName); // Member variables protected: PV_Stream * outputstream; bool triggerFlag; char* triggerLayerName; HyPerLayer * triggerLayer; double triggerOffset; HyPerCol * parent; void * owner; // the object responsible for calling the probe's destructor char * name; char * targetName; char * energyProbe; // the name of the ColumnEnergyProbe to attach to, if any. double coefficient; private: char * msgparams; // the message parameter in the params char * msgstring; // the string that gets printed by outputState ("" if message is empty or null; message + ":" if nonempty char * probeOutputFilename; int numValues; double * probeValues; double lastUpdateTime; // The time of the last time calcValues was called. }; } #endif /* BASEPROBE_HPP_ */ <commit_msg>Fixes comment to ioParam_triggerFlag in BaseProbe<commit_after>/* * BaseProbe.h * * Author: slundquist */ #ifndef BASEPROBE_HPP_ #define BASEPROBE_HPP_ #include <stdio.h> #include <vector> #include "../io/fileio.hpp" namespace PV { class HyPerCol; class HyPerLayer; //typedef enum { // BufV, // BufActivity //} PVBufType; /** * An abstract base class for the common functionality of layer probes and connection probes. */ class BaseProbe { // Methods public: //BaseProbe(const char * probeName, HyPerCol * hc); virtual ~BaseProbe(); int ioParams(enum ParamsIOFlag ioFlag); /** * A pure virtual function called during HyPerCol::run, during the communicateInitInfo stage. * BaseProbe::communicateInitInfo sets up the triggering layer and attaches to the energy probe, * if either triggerFlag or energyProbe are set. */ virtual int communicateInitInfo() = 0; /** * Called during HyPerCol::run, during the allocateDataStructures stage. * BaseProbe::allocateDataStructures returns immediately, but derived classes that * need to allocate storage should override this method. */ virtual int allocateDataStructures(); /** * If there is a triggering layer, needUpdate returns true when the triggering layer's * nextUpdateTime, modified by the probe's triggerOffset parameter, occurs. * If there is not a triggering layer, needUpdate returns false. * This behavior can be overridden if a probe uses some criterion other than triggering * to choose when output its state. */ virtual bool needUpdate(double time, double dt); /** * Returns the number of value indices the probe can compute (typically the value * of the parent HyPerCol's nBatch parameter). * BaseProbe::getNumValues() returns the parent HyPerCol's getNBatch(), which can be overridden. * Probes derived from BaseProbe can set numValues to zero or a negative number to indicate that * getValues() and getNumValues() * are not fully implemented for that probe. */ int getNumValues() { return numValues; } /** * The public interface for calling the outputState method. * BaseConnection::outputStateWrapper calls outputState() if needUpdate() returns true. * This behavior is intended to be general, but the method can be overridden if needed. */ virtual int outputStateWrapper(double timef, double dt); /** * A pure virtual method for writing output to the output file. */ virtual int outputState(double timef) = 0; virtual int writeTimer(FILE* stream) {return PV_SUCCESS;} /** * Returns the keyword of the params group associated with this probe. */ char const * getKeyword(); /** * Returns the name of the probe, specified in the public constructor. */ const char * getName() {return name;} /** * Returns the name of the targetName parameter for this probe. * LayerProbe uses targetName to specify the layer to attach to; * BaseConnectionProbe uses it to specify the connection to attach to. */ const char * getTargetName() {return targetName;} /** * Specifies the object responsible calling the probe's destructor. * BaseProbe sets owner to the parent HyPerCol during initialization. * During the communicateInitInfo stage, layer probes and connection probes * change their owner to the layer or connection they attach to. */ void const * getOwner() { return owner;} /** * getValues(double timevalue, double * values) sets the buffer 'values' with the probe's calculated values. * It assumes that the values buffer is large enough to hold getNumValues() * double-precision values. * If 'values' is NULL, the values are still updated internally if needed, but * those values are not returned. * Internally, getValues() calls calcValues() if needRecalc() is true. It then * copies the probeValues buffer to the input argument buffer 'values'. * Derived classes should not override or hide this method. Instead, they should override calcValues. */ int getValues(double timevalue, double * valuesVector); /** * getValues(double timevalue, vector<double> * valuesVector) is a wrapper around * getValues(double, double *) that uses C++ vectors. It resizes valuesVector * to size getNumValues() and then fills the vector with the values returned by getValues. */ int getValues(double timevalue, std::vector<double> * valuesVector); /** * getValue() is meant for situations where the caller needs one value * that would be returned by getValues(), not the whole buffer. * getValue() returns a signaling NaN if index is out of bounds. If index is valid, * getValue() calls calcValues() if needRecalc() returns true, and then * returns probeValues[index]. * Derived classes should not override or hide this method. Instead, they should override calcValues. */ double getValue(double timevalue, int index); protected: BaseProbe(); int initialize(const char * probeName, HyPerCol * hc); virtual int ioParamsFillGroup(enum ParamsIOFlag ioFlag); /** * List of parameters for the BaseProbe class * @name BaseProbe Parameters * @{ */ /** * @brief targetName: the name of the object that the probe attaches to. * In LayerProbe, targetName is used to define the targetLayer, and in * BaseConnectionProbe, targetName is used to define the targetConn. */ virtual void ioParam_targetName(enum ParamsIOFlag ioFlag); /** * @brief message: A string parameter that is typically included in the lines output by the outputState method */ virtual void ioParam_message(enum ParamsIOFlag ioFlag); /** * @brief probeOutputFile: the name of the file that the outputState method writes to. * If blank, the output is sent to stdout. */ virtual void ioParam_probeOutputFile(enum ParamsIOFlag ioFlag); /** * @brief triggerFlag: If false, the needUpdate method always returns true, * so that outputState is called every timestep. If true, the needUpdate * method uses triggerLayerName and triggerOffset to determine if the probe * should be triggered. */ virtual void ioParam_triggerFlag(enum ParamsIOFlag ioFlag); /** * @brief triggerLayerName: If triggerFlag is true, triggerLayerName specifies the layer * to check for triggering. */ virtual void ioParam_triggerLayerName(enum ParamsIOFlag ioFlag); /** * @brief triggerOffset: If triggerFlag is true, triggerOffset specifies the * time interval *before* the triggerLayer's nextUpdate time that needUpdate() returns true. */ virtual void ioParam_triggerOffset(enum ParamsIOFlag ioFlag); /** * @brief energyProbe: If nonblank, specifies the name of a ColumnEnergyProbe * that this probe contributes an energy term to. */ virtual void ioParam_energyProbe(enum ParamsIOFlag ioFlag); /** * @brief coefficient: If energyProbe is set, the coefficient parameter specifies * that ColumnEnergyProbe multiplies the result of this probe's getValues() method * by coefficient when computing the error. * @details Note that coefficient does not affect the value returned by the getValue() or * getValues() method. */ virtual void ioParam_coefficient(enum ParamsIOFlag ioFlag); /** @} */ virtual int initOutputStream(const char * filename); /** * A pure virtual method for that should return true if the quantities being measured * by the probe have changed since the last time the quantities were calculated. * Typically, an implementation of needRecalc() will check the lastUpdateTime of * the object being probed, and return true if that value is greater than the * lastUpdateTime member variable. * needRecalc() is called by getValues(double) (and hence by getValue() and the other * flavors of getValues). * Note that there is a single needRecalc that applies to all getNumValues() quantities. */ virtual bool needRecalc(double timevalue) = 0; /** * A pure virtual method to calculate the values of the probe. calcValues() can * assume that needRecalc() has been called and returned true. * It should write the computed values into the buffer of member variable 'probeValues'. */ virtual int calcValues(double timevalue) = 0; /** * If needRecalc() returns true, getValues(double) updates the probeValues buffer * (by calling calcValues) and sets lastUpdateTime to the timevalue input argument. */ int getValues(double timevalue); /** * Returns a pointer to parent HyPerCol. */ HyPerCol * getParent() {return parent;} /** * Returns a pointer to the message parameter. */ const char * getMessage() {return msgstring;} /** * The method called by BaseProbe::initialize() to set the message used by * the probe's outputState method. */ virtual int initMessage(const char * msg); /** * Returns a pointer to the PV_Stream used by outputState. */ PV_Stream * getStream() {return outputstream;} /** * initNumValues is called by initialize. * BaseProbe::initNumValues sets numValues to the parent HyPerCol's getNBatch(). * Derived classes can override initNumValues to initialize numValues to a different * value. */ virtual int initNumValues(); /** * Sets the numValues member variable (returned by getNumValues()) and reallocates * the probeValues member variable to hold numValues double-precision values. * If the reallocation fails, the probeValues buffer is left unchanged, errno is * set (by a realloc() call), and PV_FAILURE is returned. * Otherwise, PV_SUCCESS is returned. */ int setNumValues(int n); /** * Returns a pointer to the buffer containing the probeValues. */ double * getValuesBuffer() { return probeValues; } /** * Returns the time that calcValues was last called. * BaseProbe updates the last update time in getValues() and getValue(), * based on the result of needRecalc. */ double getLastUpdateTime() { return lastUpdateTime; } private: int initialize_base(); void setParentCol(HyPerCol * hc) {parent = hc;} int setProbeName(const char * probeName); // Member variables protected: PV_Stream * outputstream; bool triggerFlag; char* triggerLayerName; HyPerLayer * triggerLayer; double triggerOffset; HyPerCol * parent; void * owner; // the object responsible for calling the probe's destructor char * name; char * targetName; char * energyProbe; // the name of the ColumnEnergyProbe to attach to, if any. double coefficient; private: char * msgparams; // the message parameter in the params char * msgstring; // the string that gets printed by outputState ("" if message is empty or null; message + ":" if nonempty char * probeOutputFilename; int numValues; double * probeValues; double lastUpdateTime; // The time of the last time calcValues was called. }; } #endif /* BASEPROBE_HPP_ */ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgstreamercameraexposurecontrol_maemo.h" #include "qgstreamercapturesession_maemo.h" #include <gst/interfaces/photography.h> #include <QDebug> QGstreamerCameraExposureControl::QGstreamerCameraExposureControl(GstElement &camerabin, QGstreamerCaptureSession *session) :QCameraExposureControl(session), m_camerabin(camerabin), m_session(session) { } QGstreamerCameraExposureControl::~QGstreamerCameraExposureControl() { } QCamera::FlashModes QGstreamerCameraExposureControl::flashMode() const { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); GstFlashMode flashMode = config.flash_mode; QCamera::FlashModes modes; switch (flashMode) { case GST_PHOTOGRAPHY_FLASH_MODE_AUTO: modes |= QCamera::FlashAuto; break; case GST_PHOTOGRAPHY_FLASH_MODE_OFF: modes |= QCamera::FlashOff; break; case GST_PHOTOGRAPHY_FLASH_MODE_ON: modes |= QCamera::FlashOn; break; case GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN: modes |= QCamera::FlashFill; break; case GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE: modes |= QCamera::FlashRedEyeReduction; break; default: modes |= QCamera::FlashManual; break; } return modes; } void QGstreamerCameraExposureControl::setFlashMode(QCamera::FlashModes mode) { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); GstFlashMode flashMode = config.flash_mode; if (mode.testFlag(QCamera::FlashAuto)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_AUTO; else if (mode.testFlag(QCamera::FlashOff)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_OFF; else if (mode.testFlag(QCamera::FlashOn)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_ON; else if (mode.testFlag(QCamera::FlashFill)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN; else if (mode.testFlag(QCamera::FlashRedEyeReduction)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE; config.flash_mode = flashMode; gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config); } QCamera::FlashModes QGstreamerCameraExposureControl::supportedFlashModes() const { QCamera::FlashModes modes; modes |= QCamera::FlashOff; modes |= QCamera::FlashOn; modes |= QCamera::FlashAuto; modes |= QCamera::FlashRedEyeReduction; modes |= QCamera::FlashFill; return modes; } qreal QGstreamerCameraExposureControl::flashCompensation() const { return 0; } void QGstreamerCameraExposureControl::setFlashCompensation(qreal ev) { } qreal QGstreamerCameraExposureControl::flashPower() const { } void QGstreamerCameraExposureControl::setFlashPower(qreal power) { } bool QGstreamerCameraExposureControl::isFlashReady() const { } QCamera::ExposureMode QGstreamerCameraExposureControl::exposureMode() const { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); GstSceneMode sceneMode = config.scene_mode; switch (sceneMode) { case GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT: return QCamera::ExposurePortrait; case GST_PHOTOGRAPHY_SCENE_MODE_SPORT: return QCamera::ExposureSports; case GST_PHOTOGRAPHY_SCENE_MODE_NIGHT: return QCamera::ExposureNight; case GST_PHOTOGRAPHY_SCENE_MODE_AUTO: return QCamera::ExposureAuto; case GST_PHOTOGRAPHY_SCENE_MODE_MANUAL: case GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP: //no direct mapping available so mapping to manual mode case GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE: //no direct mapping available so mapping to manual mode default: return QCamera::ExposureManual; } } void QGstreamerCameraExposureControl::setExposureMode(QCamera::ExposureMode mode) { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); GstSceneMode sceneMode = config.scene_mode; if (mode == QCamera::ExposureManual) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_MANUAL; else if (mode == QCamera::ExposurePortrait) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT; else if (mode == QCamera::ExposureSports) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_SPORT; else if (mode == QCamera::ExposureNight) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_NIGHT; else if (mode == QCamera::ExposureAuto) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_AUTO; config.scene_mode = sceneMode; gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config); } QCamera::ExposureModes QGstreamerCameraExposureControl::supportedExposureModes() const { //Similar mode names can be found in gst as GstSceneMode QCamera::ExposureModes modes; modes |= QCamera::ExposureManual; modes |= QCamera::ExposurePortrait; modes |= QCamera::ExposureSports; modes |= QCamera::ExposureNight; modes |= QCamera::ExposureAuto; //No direct mapping available for GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP and //GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE return modes; } qreal QGstreamerCameraExposureControl::exposureCompensation() const { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); return config.ev_compensation; } void QGstreamerCameraExposureControl::setExposureCompensation(qreal ev) { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); config.ev_compensation = ev; gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config); } QCamera::MeteringMode QGstreamerCameraExposureControl::meteringMode() const { } void QGstreamerCameraExposureControl::setMeteringMode(QCamera::MeteringMode mode) { } QCamera::MeteringModes QGstreamerCameraExposureControl::supportedMeteringModes() const { } int QGstreamerCameraExposureControl::isoSensitivity() const { } QList<int> QGstreamerCameraExposureControl::supportedIsoSensitivities(bool *continuous) const { } void QGstreamerCameraExposureControl::setManualIsoSensitivity(int iso) { } void QGstreamerCameraExposureControl::setAutoIsoSensitivity() { } qreal QGstreamerCameraExposureControl::aperture() const { } QList<qreal> QGstreamerCameraExposureControl::supportedApertures(bool *continuous) const { } void QGstreamerCameraExposureControl::setManualAperture(qreal aperture) { } void QGstreamerCameraExposureControl::setAutoAperture() { } qreal QGstreamerCameraExposureControl::shutterSpeed() const { } QList<qreal> QGstreamerCameraExposureControl::supportedShutterSpeeds(bool *continuous) const { } void QGstreamerCameraExposureControl::setManualShutterSpeed(qreal seconds) { } void QGstreamerCameraExposureControl::setAutoShutterSpeed() { } bool QGstreamerCameraExposureControl::isExposureLocked() const { } void QGstreamerCameraExposureControl::lockExposure() { } void QGstreamerCameraExposureControl::unlockExposure() { } <commit_msg>Returning MeteringAverage as an only supported mode<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgstreamercameraexposurecontrol_maemo.h" #include "qgstreamercapturesession_maemo.h" #include <gst/interfaces/photography.h> #include <QDebug> QGstreamerCameraExposureControl::QGstreamerCameraExposureControl(GstElement &camerabin, QGstreamerCaptureSession *session) :QCameraExposureControl(session), m_camerabin(camerabin), m_session(session) { } QGstreamerCameraExposureControl::~QGstreamerCameraExposureControl() { } QCamera::FlashModes QGstreamerCameraExposureControl::flashMode() const { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); GstFlashMode flashMode = config.flash_mode; QCamera::FlashModes modes; switch (flashMode) { case GST_PHOTOGRAPHY_FLASH_MODE_AUTO: modes |= QCamera::FlashAuto; break; case GST_PHOTOGRAPHY_FLASH_MODE_OFF: modes |= QCamera::FlashOff; break; case GST_PHOTOGRAPHY_FLASH_MODE_ON: modes |= QCamera::FlashOn; break; case GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN: modes |= QCamera::FlashFill; break; case GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE: modes |= QCamera::FlashRedEyeReduction; break; default: modes |= QCamera::FlashManual; break; } return modes; } void QGstreamerCameraExposureControl::setFlashMode(QCamera::FlashModes mode) { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); GstFlashMode flashMode = config.flash_mode; if (mode.testFlag(QCamera::FlashAuto)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_AUTO; else if (mode.testFlag(QCamera::FlashOff)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_OFF; else if (mode.testFlag(QCamera::FlashOn)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_ON; else if (mode.testFlag(QCamera::FlashFill)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN; else if (mode.testFlag(QCamera::FlashRedEyeReduction)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE; config.flash_mode = flashMode; gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config); } QCamera::FlashModes QGstreamerCameraExposureControl::supportedFlashModes() const { QCamera::FlashModes modes; modes |= QCamera::FlashOff; modes |= QCamera::FlashOn; modes |= QCamera::FlashAuto; modes |= QCamera::FlashRedEyeReduction; modes |= QCamera::FlashFill; return modes; } qreal QGstreamerCameraExposureControl::flashCompensation() const { return 0; } void QGstreamerCameraExposureControl::setFlashCompensation(qreal ev) { } qreal QGstreamerCameraExposureControl::flashPower() const { } void QGstreamerCameraExposureControl::setFlashPower(qreal power) { } bool QGstreamerCameraExposureControl::isFlashReady() const { } QCamera::ExposureMode QGstreamerCameraExposureControl::exposureMode() const { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); GstSceneMode sceneMode = config.scene_mode; switch (sceneMode) { case GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT: return QCamera::ExposurePortrait; case GST_PHOTOGRAPHY_SCENE_MODE_SPORT: return QCamera::ExposureSports; case GST_PHOTOGRAPHY_SCENE_MODE_NIGHT: return QCamera::ExposureNight; case GST_PHOTOGRAPHY_SCENE_MODE_AUTO: return QCamera::ExposureAuto; case GST_PHOTOGRAPHY_SCENE_MODE_MANUAL: case GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP: //no direct mapping available so mapping to manual mode case GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE: //no direct mapping available so mapping to manual mode default: return QCamera::ExposureManual; } } void QGstreamerCameraExposureControl::setExposureMode(QCamera::ExposureMode mode) { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); GstSceneMode sceneMode = config.scene_mode; if (mode == QCamera::ExposureManual) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_MANUAL; else if (mode == QCamera::ExposurePortrait) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT; else if (mode == QCamera::ExposureSports) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_SPORT; else if (mode == QCamera::ExposureNight) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_NIGHT; else if (mode == QCamera::ExposureAuto) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_AUTO; config.scene_mode = sceneMode; gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config); } QCamera::ExposureModes QGstreamerCameraExposureControl::supportedExposureModes() const { //Similar mode names can be found in gst as GstSceneMode QCamera::ExposureModes modes; modes |= QCamera::ExposureManual; modes |= QCamera::ExposurePortrait; modes |= QCamera::ExposureSports; modes |= QCamera::ExposureNight; modes |= QCamera::ExposureAuto; //No direct mapping available for GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP and //GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE return modes; } qreal QGstreamerCameraExposureControl::exposureCompensation() const { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); return config.ev_compensation; } void QGstreamerCameraExposureControl::setExposureCompensation(qreal ev) { GstPhotoSettings config; gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config); config.ev_compensation = ev; gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config); } QCamera::MeteringMode QGstreamerCameraExposureControl::meteringMode() const { return QCamera::MeteringAverage; } void QGstreamerCameraExposureControl::setMeteringMode(QCamera::MeteringMode mode) { //pass } QCamera::MeteringModes QGstreamerCameraExposureControl::supportedMeteringModes() const { QCamera::MeteringModes modes; modes |= QCamera::MeteringAverage; return modes; } int QGstreamerCameraExposureControl::isoSensitivity() const { } QList<int> QGstreamerCameraExposureControl::supportedIsoSensitivities(bool *continuous) const { } void QGstreamerCameraExposureControl::setManualIsoSensitivity(int iso) { } void QGstreamerCameraExposureControl::setAutoIsoSensitivity() { } qreal QGstreamerCameraExposureControl::aperture() const { } QList<qreal> QGstreamerCameraExposureControl::supportedApertures(bool *continuous) const { } void QGstreamerCameraExposureControl::setManualAperture(qreal aperture) { } void QGstreamerCameraExposureControl::setAutoAperture() { } qreal QGstreamerCameraExposureControl::shutterSpeed() const { } QList<qreal> QGstreamerCameraExposureControl::supportedShutterSpeeds(bool *continuous) const { } void QGstreamerCameraExposureControl::setManualShutterSpeed(qreal seconds) { } void QGstreamerCameraExposureControl::setAutoShutterSpeed() { } bool QGstreamerCameraExposureControl::isExposureLocked() const { } void QGstreamerCameraExposureControl::lockExposure() { } void QGstreamerCameraExposureControl::unlockExposure() { } <|endoftext|>
<commit_before><commit_msg>Обновление библиотек<commit_after><|endoftext|>
<commit_before>// ========================================================================== // NGS: Regions of Interest Analysis // ========================================================================== // Copyright (c) 2012-2013, Bernd Jagla, Institut Pasteur // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: Bernd Jagla <bernd.jagla@pasteur.fr> // Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de> // ========================================================================== #include "project_interval.h" // ---------------------------------------------------------------------------- // Member Functions IntersectBed::pushBed() // ---------------------------------------------------------------------------- void IntersectBed::pushBed(TBedRecord const & bedRecord) { if (options.verbosity >= 2) { std::cerr << "pushBed()\n" << " "; writeRecord(std::cerr, bedRecord, seqan::Bed()); } // Handle contig transition, we can unconditionally update rId. if (bedRecord.ref != ref) finishContig(); ref = bedRecord.ref; // Register new BED record. bedRecords.push_back(bedRecord); } // ---------------------------------------------------------------------------- // Member Function IntersectBed::writeEmptyBed() // ---------------------------------------------------------------------------- void IntersectBed::writeEmptyBed(seqan::BedRecord<seqan::Bed6> const & bedRecord) { seqan::RoiRecord roiRecord; roiRecord.ref = bedRecord.ref; roiRecord.beginPos = bedRecord.beginPos; roiRecord.endPos = bedRecord.endPos; roiRecord.strand = bedRecord.strand; roiRecord.name = bedRecord.name; roiRecord.len = roiRecord.endPos - roiRecord.beginPos; roiRecord.countMax = 0; for (int i = 0; i < (int)roiRecord.len; ++i) appendValue(roiRecord.count, 0); writeRecord(roiFileOut, roiRecord); } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::processFirstBedRecord() // ---------------------------------------------------------------------------- // Return true iff lhs and rhs overlap (both are BED or ROI records). template <typename TLeft, typename TRight> bool overlap(TLeft const & lhs, TRight const & rhs) { return (rhs.beginPos < lhs.endPos) && (lhs.beginPos < rhs.endPos); } void IntersectBed::processFirstBedRecord() { if (options.verbosity >= 2) { std::cerr << "processFirstBedRecord()\n"; if (!bedRecords.empty()) { std::cerr << " "; writeRecord(std::cerr, bedRecords.front(), seqan::Bed()); } } // When computing symmetric difference, we write out the BED record as ROI if there is no overlapping ROI record. if (options.mode == IntersectBedOptions::DIFF) { if (roiRecords.empty() || roiRecords.front().beginPos >= bedRecords.front().endPos) { writeEmptyBed(bedRecords.front()); return; } } if (roiRecords.empty()) return; // When in DIFF mode: Mark all ROI records overlapping with current front BED record as such and stop. typedef std::list<TRoiRecord>::/*const_*/iterator TRoiIter; if (options.mode == IntersectBedOptions::DIFF) { for (TRoiIter it = roiRecords.begin(); it != roiRecords.end(); ++it) if (overlap(*it, bedRecords.front())) back(it->data)[0] = '*'; // Mark as overlapping with BED. return; } // Get range of ROI records overlapping with BED record. TRoiIter rangeBegin = roiRecords.begin(); TRoiIter rangeEnd = rangeBegin; for (; rangeEnd != roiRecords.end() && overlap(*rangeEnd, bedRecords.front()); ++rangeEnd) { if (options.verbosity >= 2) { std::cerr << "ROI RECORD\t"; writeRecord(std::cerr, *rangeEnd, seqan::Roi()); } continue; } // ------------------------------------------------------------------------ // Create a result ROI from that depending on the configuration. // ------------------------------------------------------------------------ // Compute the smallest begin position and the largest end position of BED and all ROI objects. TBedRecord const & bedRecord = bedRecords.front(); int beginPos = bedRecord.beginPos; int endPos = bedRecord.endPos; if (options.verbosity >= 2) std::cerr << "beginPos, endPos == " << beginPos << ", " << endPos << "\n"; for (TRoiIter it = rangeBegin; it != rangeEnd; ++it) { if (options.verbosity >= 2) std::cerr << "it->beginPos, it->endPos == " << it->beginPos << ", " << it->endPos << "\n"; beginPos = std::min(it->beginPos, beginPos); endPos = std::max(it->endPos, endPos); if (options.verbosity >= 2) std::cerr << "beginPos, endPos == " << beginPos << ", " << endPos << "\n"; } // Create bitmap marking positions as connected/covered. seqan::String<bool> connected; resize(connected, endPos - beginPos, false); updateConnectivity(connected, beginPos, bedRecord, rangeBegin, rangeEnd); // Create array with counts. seqan::String<int> counts; resize(counts, endPos - beginPos, 0); for (TRoiIter it = rangeBegin; it != rangeEnd; ++it) for (unsigned j = it->beginPos - beginPos, i = 0; i < length(it->count); ++i, ++j) counts[j] += it->count[i]; // TODO(holtgrew): Increment or simply set? // Write resulting intervals to output file. writeRois(connected, counts, beginPos, bedRecord); } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::cleanRoiRecords() // ---------------------------------------------------------------------------- void IntersectBed::cleanRoiRecords() { if (options.verbosity >= 2) { std::cerr << "cleanRoiRecords()\n"; } while (!roiRecords.empty() && (bedRecords.empty() || roiRecords.front().endPos <= bedRecords.front().beginPos)) { // Remove data from front ROI, write it out, remove it. if (options.mode == IntersectBedOptions::DIFF && back(roiRecords.front().data)[0] == '.') { clear(roiRecords.front().data); writeRecord(roiFileOut, roiRecords.front()); } roiRecords.pop_front(); } } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::pushRoi() // ---------------------------------------------------------------------------- void IntersectBed::pushRoi(TRoiRecord const & roiRecord) { if (options.verbosity >= 2) { std::cerr << "pushRoi()\n" << " "; writeRecord(std::cerr, roiRecord, seqan::Roi()); } // Handle contig transition, we can unconditionally update ref. if (roiRecord.ref != ref) finishContig(); ref = roiRecord.ref; // Complete processing all BED records that cannot overlap with roiRecord. After removing each BED record, remove // all ROI records that do not overlap with first BED record any more. while (!empty(bedRecords) && bedRecords.front().endPos <= roiRecord.beginPos) { processFirstBedRecord(); bedRecords.pop_front(); cleanRoiRecords(); } // Finally, register ROI records. roiRecords.push_back(roiRecord); // Mark ROI record as not touched yet. We do this using the data entry. appendValue(roiRecords.back().data, "."); } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::finishContig() // ---------------------------------------------------------------------------- void IntersectBed::finishContig() { if (options.verbosity >= 2) std::cerr << "finishContig()\n"; while (!empty(bedRecords)) { processFirstBedRecord(); bedRecords.pop_front(); } cleanRoiRecords(); } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::updateConnectivity() // ---------------------------------------------------------------------------- void IntersectBed::updateConnectivity(seqan::String<bool> & bitmap, int beginPos, // position of bitmap[0] seqan::BedRecord<seqan::Bed6> const & bedRecord, std::list<TRoiRecord>::const_iterator const & rangeBegin, std::list<TRoiRecord>::const_iterator const & rangeEnd) { if (options.verbosity >= 2) std::cerr << "updateConnectivity()\n"; typedef std::list<TRoiRecord>::const_iterator TRoiIter; switch (options.mode) { case IntersectBedOptions::PROJECTION: // Mark whole BED record range as covered. for (int pos = bedRecord.beginPos; pos != bedRecord.endPos; ++pos) bitmap[pos - beginPos] = true; break; case IntersectBedOptions::INTERSECTION: // Mark intersection of BED record and ROI records as covered. for (TRoiIter it = rangeBegin; it != rangeEnd; ++it) { for (int pos = it->beginPos; pos != it->endPos; ++pos) if (pos >= bedRecord.beginPos && pos < bedRecord.endPos) bitmap[pos - beginPos] = true; } break; case IntersectBedOptions::UNION: // Mark union of BED and ROI intervals as being covered. for (unsigned i = 0; i < length(bitmap); ++i) bitmap[i] = true; break; case IntersectBedOptions::DIFF: default: SEQAN_FAIL("Cannot reach here!"); } } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::writeRois() // ---------------------------------------------------------------------------- void IntersectBed::writeRois(seqan::String<bool> const & bitmap, seqan::String<int> const & counts, int beginPos, // position of bitmap[0] and counts[0] seqan::BedRecord<seqan::Bed6> const & bedRecord) { // We will build a string of ranges in bitmap/counts for writing out. The bitmap is used depending on the // combination mode. typedef seqan::Pair<int, int> TIntPair; seqan::String<TIntPair> pairs; // We also generate the names of the new regions. seqan::StringSet<seqan::CharString> names; switch (options.mode) { case IntersectBedOptions::PROJECTION: // Use BED range only. appendValue(pairs, TIntPair(bedRecord.beginPos - beginPos, bedRecord.endPos - beginPos)); break; case IntersectBedOptions::INTERSECTION: // Search for 0/1 and 1/0 flanks. { bool state = bitmap[0]; int lastFlank = 0; for (unsigned i = 1; i < length(bitmap); ++i) { if (state) { if (!bitmap[i]) // Found a 1/0 flank. { appendValue(pairs, TIntPair(lastFlank, i)); state = false; lastFlank = i; } } else { if (bitmap[i]) // Found a 0/1 flank. { state = true; lastFlank = i; } } } if (state) appendValue(pairs, TIntPair(lastFlank, length(bitmap))); } break; case IntersectBedOptions::UNION: // Use whole range, including overlaps to the left of right. appendValue(pairs, TIntPair(0, length(counts))); break; case IntersectBedOptions::DIFF: SEQAN_FAIL("Difference does not implemented yet!"); break; default: SEQAN_FAIL("Cannot reach here!"); } if (options.verbosity >= 2) std::cerr << "Adding " << length(pairs) << " for BED " << bedRecord.name << "\n"; for (unsigned i = 0; i < length(pairs); ++i) { std::stringstream ss; ss << bedRecord.name << "_" << i; appendValue(names, ss.str()); } seqan::RoiRecord record; for (unsigned i = 0; i < length(pairs); ++i) { clear(record); record.ref = bedRecord.ref; record.beginPos = beginPos + pairs[i].i1; record.endPos = beginPos + pairs[i].i2; record.len = record.endPos - record.beginPos; record.name = names[i]; record.strand = bedRecord.strand; record.countMax = 0; resize(record.count, pairs[i].i2 - pairs[i].i1, 0); for (int k = 0, j = pairs[i].i1; j != pairs[i].i2; ++j, ++k) { record.countMax = std::max(record.countMax, (unsigned)counts[j]); record.count[k] = counts[j]; } writeRecord(roiFileOut, record); } } <commit_msg>[FIX] Use list member function empty instead of global empty function.<commit_after>// ========================================================================== // NGS: Regions of Interest Analysis // ========================================================================== // Copyright (c) 2012-2013, Bernd Jagla, Institut Pasteur // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: Bernd Jagla <bernd.jagla@pasteur.fr> // Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de> // ========================================================================== #include "project_interval.h" // ---------------------------------------------------------------------------- // Member Functions IntersectBed::pushBed() // ---------------------------------------------------------------------------- void IntersectBed::pushBed(TBedRecord const & bedRecord) { if (options.verbosity >= 2) { std::cerr << "pushBed()\n" << " "; writeRecord(std::cerr, bedRecord, seqan::Bed()); } // Handle contig transition, we can unconditionally update rId. if (bedRecord.ref != ref) finishContig(); ref = bedRecord.ref; // Register new BED record. bedRecords.push_back(bedRecord); } // ---------------------------------------------------------------------------- // Member Function IntersectBed::writeEmptyBed() // ---------------------------------------------------------------------------- void IntersectBed::writeEmptyBed(seqan::BedRecord<seqan::Bed6> const & bedRecord) { seqan::RoiRecord roiRecord; roiRecord.ref = bedRecord.ref; roiRecord.beginPos = bedRecord.beginPos; roiRecord.endPos = bedRecord.endPos; roiRecord.strand = bedRecord.strand; roiRecord.name = bedRecord.name; roiRecord.len = roiRecord.endPos - roiRecord.beginPos; roiRecord.countMax = 0; for (int i = 0; i < (int)roiRecord.len; ++i) appendValue(roiRecord.count, 0); writeRecord(roiFileOut, roiRecord); } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::processFirstBedRecord() // ---------------------------------------------------------------------------- // Return true iff lhs and rhs overlap (both are BED or ROI records). template <typename TLeft, typename TRight> bool overlap(TLeft const & lhs, TRight const & rhs) { return (rhs.beginPos < lhs.endPos) && (lhs.beginPos < rhs.endPos); } void IntersectBed::processFirstBedRecord() { if (options.verbosity >= 2) { std::cerr << "processFirstBedRecord()\n"; if (!bedRecords.empty()) { std::cerr << " "; writeRecord(std::cerr, bedRecords.front(), seqan::Bed()); } } // When computing symmetric difference, we write out the BED record as ROI if there is no overlapping ROI record. if (options.mode == IntersectBedOptions::DIFF) { if (roiRecords.empty() || roiRecords.front().beginPos >= bedRecords.front().endPos) { writeEmptyBed(bedRecords.front()); return; } } if (roiRecords.empty()) return; // When in DIFF mode: Mark all ROI records overlapping with current front BED record as such and stop. typedef std::list<TRoiRecord>::/*const_*/iterator TRoiIter; if (options.mode == IntersectBedOptions::DIFF) { for (TRoiIter it = roiRecords.begin(); it != roiRecords.end(); ++it) if (overlap(*it, bedRecords.front())) back(it->data)[0] = '*'; // Mark as overlapping with BED. return; } // Get range of ROI records overlapping with BED record. TRoiIter rangeBegin = roiRecords.begin(); TRoiIter rangeEnd = rangeBegin; for (; rangeEnd != roiRecords.end() && overlap(*rangeEnd, bedRecords.front()); ++rangeEnd) { if (options.verbosity >= 2) { std::cerr << "ROI RECORD\t"; writeRecord(std::cerr, *rangeEnd, seqan::Roi()); } continue; } // ------------------------------------------------------------------------ // Create a result ROI from that depending on the configuration. // ------------------------------------------------------------------------ // Compute the smallest begin position and the largest end position of BED and all ROI objects. TBedRecord const & bedRecord = bedRecords.front(); int beginPos = bedRecord.beginPos; int endPos = bedRecord.endPos; if (options.verbosity >= 2) std::cerr << "beginPos, endPos == " << beginPos << ", " << endPos << "\n"; for (TRoiIter it = rangeBegin; it != rangeEnd; ++it) { if (options.verbosity >= 2) std::cerr << "it->beginPos, it->endPos == " << it->beginPos << ", " << it->endPos << "\n"; beginPos = std::min(it->beginPos, beginPos); endPos = std::max(it->endPos, endPos); if (options.verbosity >= 2) std::cerr << "beginPos, endPos == " << beginPos << ", " << endPos << "\n"; } // Create bitmap marking positions as connected/covered. seqan::String<bool> connected; resize(connected, endPos - beginPos, false); updateConnectivity(connected, beginPos, bedRecord, rangeBegin, rangeEnd); // Create array with counts. seqan::String<int> counts; resize(counts, endPos - beginPos, 0); for (TRoiIter it = rangeBegin; it != rangeEnd; ++it) for (unsigned j = it->beginPos - beginPos, i = 0; i < length(it->count); ++i, ++j) counts[j] += it->count[i]; // TODO(holtgrew): Increment or simply set? // Write resulting intervals to output file. writeRois(connected, counts, beginPos, bedRecord); } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::cleanRoiRecords() // ---------------------------------------------------------------------------- void IntersectBed::cleanRoiRecords() { if (options.verbosity >= 2) { std::cerr << "cleanRoiRecords()\n"; } while (!roiRecords.empty() && (bedRecords.empty() || roiRecords.front().endPos <= bedRecords.front().beginPos)) { // Remove data from front ROI, write it out, remove it. if (options.mode == IntersectBedOptions::DIFF && back(roiRecords.front().data)[0] == '.') { clear(roiRecords.front().data); writeRecord(roiFileOut, roiRecords.front()); } roiRecords.pop_front(); } } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::pushRoi() // ---------------------------------------------------------------------------- void IntersectBed::pushRoi(TRoiRecord const & roiRecord) { if (options.verbosity >= 2) { std::cerr << "pushRoi()\n" << " "; writeRecord(std::cerr, roiRecord, seqan::Roi()); } // Handle contig transition, we can unconditionally update ref. if (roiRecord.ref != ref) finishContig(); ref = roiRecord.ref; // Complete processing all BED records that cannot overlap with roiRecord. After removing each BED record, remove // all ROI records that do not overlap with first BED record any more. while (!bedRecords.empty() && bedRecords.front().endPos <= roiRecord.beginPos) { processFirstBedRecord(); bedRecords.pop_front(); cleanRoiRecords(); } // Finally, register ROI records. roiRecords.push_back(roiRecord); // Mark ROI record as not touched yet. We do this using the data entry. appendValue(roiRecords.back().data, "."); } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::finishContig() // ---------------------------------------------------------------------------- void IntersectBed::finishContig() { if (options.verbosity >= 2) std::cerr << "finishContig()\n"; while (!bedRecords.empty()) { processFirstBedRecord(); bedRecords.pop_front(); } cleanRoiRecords(); } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::updateConnectivity() // ---------------------------------------------------------------------------- void IntersectBed::updateConnectivity(seqan::String<bool> & bitmap, int beginPos, // position of bitmap[0] seqan::BedRecord<seqan::Bed6> const & bedRecord, std::list<TRoiRecord>::const_iterator const & rangeBegin, std::list<TRoiRecord>::const_iterator const & rangeEnd) { if (options.verbosity >= 2) std::cerr << "updateConnectivity()\n"; typedef std::list<TRoiRecord>::const_iterator TRoiIter; switch (options.mode) { case IntersectBedOptions::PROJECTION: // Mark whole BED record range as covered. for (int pos = bedRecord.beginPos; pos != bedRecord.endPos; ++pos) bitmap[pos - beginPos] = true; break; case IntersectBedOptions::INTERSECTION: // Mark intersection of BED record and ROI records as covered. for (TRoiIter it = rangeBegin; it != rangeEnd; ++it) { for (int pos = it->beginPos; pos != it->endPos; ++pos) if (pos >= bedRecord.beginPos && pos < bedRecord.endPos) bitmap[pos - beginPos] = true; } break; case IntersectBedOptions::UNION: // Mark union of BED and ROI intervals as being covered. for (unsigned i = 0; i < length(bitmap); ++i) bitmap[i] = true; break; case IntersectBedOptions::DIFF: default: SEQAN_FAIL("Cannot reach here!"); } } // ---------------------------------------------------------------------------- // Member Functions IntersectBed::writeRois() // ---------------------------------------------------------------------------- void IntersectBed::writeRois(seqan::String<bool> const & bitmap, seqan::String<int> const & counts, int beginPos, // position of bitmap[0] and counts[0] seqan::BedRecord<seqan::Bed6> const & bedRecord) { // We will build a string of ranges in bitmap/counts for writing out. The bitmap is used depending on the // combination mode. typedef seqan::Pair<int, int> TIntPair; seqan::String<TIntPair> pairs; // We also generate the names of the new regions. seqan::StringSet<seqan::CharString> names; switch (options.mode) { case IntersectBedOptions::PROJECTION: // Use BED range only. appendValue(pairs, TIntPair(bedRecord.beginPos - beginPos, bedRecord.endPos - beginPos)); break; case IntersectBedOptions::INTERSECTION: // Search for 0/1 and 1/0 flanks. { bool state = bitmap[0]; int lastFlank = 0; for (unsigned i = 1; i < length(bitmap); ++i) { if (state) { if (!bitmap[i]) // Found a 1/0 flank. { appendValue(pairs, TIntPair(lastFlank, i)); state = false; lastFlank = i; } } else { if (bitmap[i]) // Found a 0/1 flank. { state = true; lastFlank = i; } } } if (state) appendValue(pairs, TIntPair(lastFlank, length(bitmap))); } break; case IntersectBedOptions::UNION: // Use whole range, including overlaps to the left of right. appendValue(pairs, TIntPair(0, length(counts))); break; case IntersectBedOptions::DIFF: SEQAN_FAIL("Difference does not implemented yet!"); break; default: SEQAN_FAIL("Cannot reach here!"); } if (options.verbosity >= 2) std::cerr << "Adding " << length(pairs) << " for BED " << bedRecord.name << "\n"; for (unsigned i = 0; i < length(pairs); ++i) { std::stringstream ss; ss << bedRecord.name << "_" << i; appendValue(names, ss.str()); } seqan::RoiRecord record; for (unsigned i = 0; i < length(pairs); ++i) { clear(record); record.ref = bedRecord.ref; record.beginPos = beginPos + pairs[i].i1; record.endPos = beginPos + pairs[i].i2; record.len = record.endPos - record.beginPos; record.name = names[i]; record.strand = bedRecord.strand; record.countMax = 0; resize(record.count, pairs[i].i2 - pairs[i].i1, 0); for (int k = 0, j = pairs[i].i1; j != pairs[i].i2; ++j, ++k) { record.countMax = std::max(record.countMax, (unsigned)counts[j]); record.count[k] = counts[j]; } writeRecord(roiFileOut, record); } } <|endoftext|>
<commit_before>#include <Poco/Exception.h> #include <Poco/Data/Statement.h> #include <Poco/Data/RecordSet.h> #include <Poco/Data/Row.h> #include <Poco/Data/RowIterator.h> #include "di/Injectable.h" #include "dao/poco/PocoSQLLocationDao.h" #include "dao/poco/PocoDaoManager.h" #include "transaction/TransactionManager.h" using namespace std; using namespace Poco; using namespace Poco::Data; using namespace Poco::Data::Keywords; using namespace BeeeOn; BEEEON_OBJECT_BEGIN(BeeeOn, PocoSQLLocationDao) BEEEON_OBJECT_CASTABLE(LocationDao) BEEEON_OBJECT_REF("daoManager", &PocoSQLLocationDao::setDaoManager) BEEEON_OBJECT_REF("transactionManager", &PocoSQLLocationDao::setTransactionManager) BEEEON_OBJECT_REF("sqlLoader", &PocoSQLLocationDao::setSQLLoader) BEEEON_OBJECT_HOOK("done", &PocoSQLLocationDao::loadQueries) BEEEON_OBJECT_END(BeeeOn, PocoSQLLocationDao) PocoSQLLocationDao::PocoSQLLocationDao() { registerQuery(m_queryCreate); registerQuery(m_queryUpdate); registerQuery(m_queryRemove); registerQuery(m_queryFetchById); registerQuery(m_queryFetchByIdAndGatewayId); registerQuery(m_queryFetchByGatewayId); } void PocoSQLLocationDao::create(Location &location) { location.setId(LocationID::random()); string id(location.id().toString()); string name(location.name()); string gatewayID(location.gateway().id().toString()); Statement sql = (session() << m_queryCreate(), use(id, "id"), use(name, "name"), use(gatewayID, "gateway_id") ); execute(sql); } bool PocoSQLLocationDao::fetch(Location &location) { assureHasId(location); string id(location.id().toString()); Statement sql = (session() << m_queryFetchById(), use(id, "id") ); if (execute(sql) == 0) return false; RecordSet result(sql); return parseSingle(result, location); } bool PocoSQLLocationDao::fetchFrom(Location &location, const Gateway &gateway) { assureHasId(location); assureHasId(gateway); string id(location.id().toString()); string gatewayID(gateway.id().toString()); Statement sql = (session() << m_queryFetchByIdAndGatewayId(), use(id, "id"), use(gatewayID, "gateway_id") ); if (execute(sql) == 0) return false; RecordSet result(sql); return parseSingle(result, location); } void PocoSQLLocationDao::fetchBy(std::vector<Location> &locations, const Gateway &gateway) { assureHasId(gateway); string gatewayID(gateway.id().toString()); Statement sql = (session() << m_queryFetchByGatewayId(), use(gatewayID, "gateway_id") ); execute(sql); RecordSet result(sql); parseMany(result, locations); } bool PocoSQLLocationDao::update(Location &location) { assureHasId(location); assureHasId(location.gateway()); string id(location.id().toString()); string name(location.name()); Statement sql = (session() << m_queryUpdate(), use(name, "name"), use(id, "id") ); return execute(sql) > 0; } bool PocoSQLLocationDao::remove(const Location &location) { assureHasId(location); string id(location.id().toString()); Statement sql = (session() << m_queryRemove(), use(id, "id") ); return execute(sql) > 0; } bool PocoSQLLocationDao::parseSingle(RecordSet &result, Location &location, const string &prefix) { if (result.begin() == result.end()) return false; return parseSingle(*result.begin(), location, prefix); } bool PocoSQLLocationDao::parseSingle(Row &result, Location &location, const string &prefix) { if (hasColumn(result, prefix + "id")) location.setId(LocationID::parse(result[prefix + "id"])); location.setName(result[prefix + "name"]); Gateway gateway(GatewayID::parse(result[prefix + "gateway_id"])); location.setGateway(gateway); markLoaded(location); return true; } bool PocoSQLLocationDao::parseIfIDNotNull(Row &result, Location &location, const string &prefix) { const string id = emptyWhenNull(result[prefix + "id"]); if (id.empty()) return false; location.setId(LocationID::parse(id)); if (hasColumn(result, prefix + "name")) location.setName(result[prefix + "name"]); markLoaded(location); return true; } <commit_msg>PocoSQLLocationDao: fix order of arguments to locations.update<commit_after>#include <Poco/Exception.h> #include <Poco/Data/Statement.h> #include <Poco/Data/RecordSet.h> #include <Poco/Data/Row.h> #include <Poco/Data/RowIterator.h> #include "di/Injectable.h" #include "dao/poco/PocoSQLLocationDao.h" #include "dao/poco/PocoDaoManager.h" #include "transaction/TransactionManager.h" using namespace std; using namespace Poco; using namespace Poco::Data; using namespace Poco::Data::Keywords; using namespace BeeeOn; BEEEON_OBJECT_BEGIN(BeeeOn, PocoSQLLocationDao) BEEEON_OBJECT_CASTABLE(LocationDao) BEEEON_OBJECT_REF("daoManager", &PocoSQLLocationDao::setDaoManager) BEEEON_OBJECT_REF("transactionManager", &PocoSQLLocationDao::setTransactionManager) BEEEON_OBJECT_REF("sqlLoader", &PocoSQLLocationDao::setSQLLoader) BEEEON_OBJECT_HOOK("done", &PocoSQLLocationDao::loadQueries) BEEEON_OBJECT_END(BeeeOn, PocoSQLLocationDao) PocoSQLLocationDao::PocoSQLLocationDao() { registerQuery(m_queryCreate); registerQuery(m_queryUpdate); registerQuery(m_queryRemove); registerQuery(m_queryFetchById); registerQuery(m_queryFetchByIdAndGatewayId); registerQuery(m_queryFetchByGatewayId); } void PocoSQLLocationDao::create(Location &location) { location.setId(LocationID::random()); string id(location.id().toString()); string name(location.name()); string gatewayID(location.gateway().id().toString()); Statement sql = (session() << m_queryCreate(), use(id, "id"), use(name, "name"), use(gatewayID, "gateway_id") ); execute(sql); } bool PocoSQLLocationDao::fetch(Location &location) { assureHasId(location); string id(location.id().toString()); Statement sql = (session() << m_queryFetchById(), use(id, "id") ); if (execute(sql) == 0) return false; RecordSet result(sql); return parseSingle(result, location); } bool PocoSQLLocationDao::fetchFrom(Location &location, const Gateway &gateway) { assureHasId(location); assureHasId(gateway); string id(location.id().toString()); string gatewayID(gateway.id().toString()); Statement sql = (session() << m_queryFetchByIdAndGatewayId(), use(id, "id"), use(gatewayID, "gateway_id") ); if (execute(sql) == 0) return false; RecordSet result(sql); return parseSingle(result, location); } void PocoSQLLocationDao::fetchBy(std::vector<Location> &locations, const Gateway &gateway) { assureHasId(gateway); string gatewayID(gateway.id().toString()); Statement sql = (session() << m_queryFetchByGatewayId(), use(gatewayID, "gateway_id") ); execute(sql); RecordSet result(sql); parseMany(result, locations); } bool PocoSQLLocationDao::update(Location &location) { assureHasId(location); assureHasId(location.gateway()); string id(location.id().toString()); string name(location.name()); Statement sql = (session() << m_queryUpdate(), use(id, "id"), use(name, "name") ); return execute(sql) > 0; } bool PocoSQLLocationDao::remove(const Location &location) { assureHasId(location); string id(location.id().toString()); Statement sql = (session() << m_queryRemove(), use(id, "id") ); return execute(sql) > 0; } bool PocoSQLLocationDao::parseSingle(RecordSet &result, Location &location, const string &prefix) { if (result.begin() == result.end()) return false; return parseSingle(*result.begin(), location, prefix); } bool PocoSQLLocationDao::parseSingle(Row &result, Location &location, const string &prefix) { if (hasColumn(result, prefix + "id")) location.setId(LocationID::parse(result[prefix + "id"])); location.setName(result[prefix + "name"]); Gateway gateway(GatewayID::parse(result[prefix + "gateway_id"])); location.setGateway(gateway); markLoaded(location); return true; } bool PocoSQLLocationDao::parseIfIDNotNull(Row &result, Location &location, const string &prefix) { const string id = emptyWhenNull(result[prefix + "id"]); if (id.empty()) return false; location.setId(LocationID::parse(id)); if (hasColumn(result, prefix + "name")) location.setName(result[prefix + "name"]); markLoaded(location); return true; } <|endoftext|>
<commit_before>/* Copyright 2007-2015 QReal Research Group * * 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 "trikKitInterpreterCommon/robotModel/real/parts/shell.h" #include <qrutils/inFile.h> using namespace trik::robotModel::real::parts; using namespace kitBase::robotModel; Shell::Shell(const DeviceInfo &info, const PortInfo &port , utils::robotCommunication::TcpRobotCommunicator &tcpRobotCommunicator) : robotModel::parts::TrikShell(info, port) , mRobotCommunicator(tcpRobotCommunicator) { connect(&mRobotCommunicator, &utils::robotCommunication::TcpRobotCommunicator::printText , this, &Shell::textPrinted); } void Shell::say(const QString &text) { const QString pathToCommand = ":/trikQts/templates/say.t"; const QString directCommand = utils::InFile::readAll(pathToCommand) .replace("@@TEXT@@", "\"" + text + "\"") + "script.run();"; mRobotCommunicator.runDirectCommand(directCommand); } void Shell::runCommand(const QString &command) { const QString pathToCommand = ":/trikQts/templates/system.t"; const QString directCommand = utils::InFile::readAll(pathToCommand) .replace("@@COMMAND@@", command) + "script.run();"; mRobotCommunicator.runDirectCommand(directCommand); } void Shell::runCode(const QString &code) { mRobotCommunicator.runDirectCommand(code); } void Shell::writeToFile(const QString &filePath, const QString &text) { const QString pathToCommand = ":/trikQts/templates/files/writeFile.t"; const QString directCommand = utils::InFile::readAll(pathToCommand) .replace("@@FILE@@", filePath).replace("@@TEXT@@", "\"" + text + "\"") + "script.run();"; mRobotCommunicator.runDirectCommand(directCommand); } void Shell::removeFile(const QString &filePath) { const QString pathToCommand = ":/trikQts/templates/files/removeFile.t"; const QString directCommand = utils::InFile::readAll(pathToCommand) .replace("@@FILE@@", filePath) + "script.run();"; mRobotCommunicator.runDirectCommand(directCommand); } void Shell::print(const QString &text) { const QString pathToCommand = ":/trikQts/templates/functions/print.t"; const QString directCommand = utils::InFile::readAll(pathToCommand) .replace("@@ARGUMENT@@", "\"" + text + "\"") + ";script.run();"; mRobotCommunicator.runDirectCommand(directCommand); } void Shell::initVideoStreaming(QString qual, QString blackwhite) { const QString shellToExecute = QString("\"/etc/init.d/mjpg-encoder-ov7670 start --jpeg-qual ") + qual + QString(" --white-black ") + blackwhite + QString(" && /etc/init.d/mjpg-streamer-ov7670.sh start\""); runCommand(shellToExecute); } <commit_msg>JpgEncoder: unnecessary duplicate file deleted<commit_after><|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief cap constraint /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 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 Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "CapConstraint.h" #include "Utils/transactions.h" #include "VocBase/document-collection.h" #include "VocBase/transaction.h" using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- class CapConstraint // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief minimum size //////////////////////////////////////////////////////////////////////////////// int64_t const CapConstraint::MinSize = 16384; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- CapConstraint::CapConstraint (TRI_idx_iid_t iid, TRI_document_collection_t* collection, size_t count, int64_t size) : Index(iid, std::vector<std::string>()), _collection(collection), _count(count), _size(static_cast<int64_t>(size)) { initialize(); } CapConstraint::~CapConstraint () { } // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- size_t CapConstraint::memory () const { return 0; } triagens::basics::Json CapConstraint::toJson (TRI_memory_zone_t* zone) const { auto json = Index::toJson(zone); json("size", triagens::basics::Json(zone, static_cast<double>(_count))) ("byteSize", triagens::basics::Json(zone, static_cast<double>(_size))); return json; } int CapConstraint::insert (TRI_doc_mptr_t const*, bool) { return TRI_ERROR_NO_ERROR; } int CapConstraint::remove (TRI_doc_mptr_t const*, bool) { return TRI_ERROR_NO_ERROR; } int CapConstraint::postInsert (TRI_transaction_collection_t* trxCollection, TRI_doc_mptr_t const*) { TRI_ASSERT(_count > 0 || _size > 0); return apply(trxCollection->_collection->_collection, trxCollection); } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief initialize the cap constraint //////////////////////////////////////////////////////////////////////////////// int CapConstraint::initialize () { TRI_ASSERT(_count > 0 || _size > 0); TRI_headers_t* headers = _collection->_headersPtr; // ONLY IN INDEX (CAP) int64_t currentCount = static_cast<int64_t>(headers->count()); int64_t currentSize = headers->size(); if ((_count > 0 && currentCount <= _count) && (_size > 0 && currentSize <= _size)) { // nothing to do return TRI_ERROR_NO_ERROR; } else { TRI_vocbase_t* vocbase = _collection->_vocbase; TRI_voc_cid_t cid = _collection->_info._cid; triagens::arango::SingleCollectionWriteTransaction<UINT64_MAX> trx(new triagens::arango::StandaloneTransactionContext(), vocbase, cid); trx.addHint(TRI_TRANSACTION_HINT_LOCK_NEVER, false); trx.addHint(TRI_TRANSACTION_HINT_NO_BEGIN_MARKER, false); trx.addHint(TRI_TRANSACTION_HINT_NO_ABORT_MARKER, false); trx.addHint(TRI_TRANSACTION_HINT_SINGLE_OPERATION, false); // this is actually not true, but necessary to create trx id 0 int res = trx.begin(); if (res != TRI_ERROR_NO_ERROR) { return res; } TRI_transaction_collection_t* trxCollection = trx.trxCollection(); res = apply(_collection, trxCollection); res = trx.finish(res); return res; } } //////////////////////////////////////////////////////////////////////////////// /// @brief apply the cap constraint for the collection //////////////////////////////////////////////////////////////////////////////// int CapConstraint::apply (TRI_document_collection_t* document, TRI_transaction_collection_t* trxCollection) { TRI_headers_t* headers = document->_headersPtr; // PROTECTED by trx in trxCollection int64_t currentCount = static_cast<int64_t>(headers->count()); int64_t currentSize = headers->size(); int res = TRI_ERROR_NO_ERROR; // delete while at least one of the constraints is still violated while ((_count > 0 && currentCount > _count) || (_size > 0 && currentSize > _size)) { TRI_doc_mptr_t* oldest = headers->front(); if (oldest != nullptr) { TRI_ASSERT(oldest->getDataPtr() != nullptr); // ONLY IN INDEX, PROTECTED by RUNTIME size_t oldSize = ((TRI_df_marker_t*) (oldest->getDataPtr()))->_size; // ONLY IN INDEX, PROTECTED by RUNTIME TRI_ASSERT(oldSize > 0); if (trxCollection != nullptr) { res = TRI_DeleteDocumentDocumentCollection(trxCollection, nullptr, oldest); if (res != TRI_ERROR_NO_ERROR) { LOG_WARNING("cannot cap collection: %s", TRI_errno_string(res)); break; } } else { headers->unlink(oldest); } currentCount--; currentSize -= (int64_t) oldSize; } else { // we should not get here LOG_WARNING("logic error in %s", __FUNCTION__); break; } } return res; } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <commit_msg>fixed cap constraints<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief cap constraint /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 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 Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "CapConstraint.h" #include "Utils/transactions.h" #include "VocBase/document-collection.h" #include "VocBase/transaction.h" using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- class CapConstraint // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief minimum size //////////////////////////////////////////////////////////////////////////////// int64_t const CapConstraint::MinSize = 16384; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- CapConstraint::CapConstraint (TRI_idx_iid_t iid, TRI_document_collection_t* collection, size_t count, int64_t size) : Index(iid, std::vector<std::string>()), _collection(collection), _count(count), _size(static_cast<int64_t>(size)) { initialize(); } CapConstraint::~CapConstraint () { } // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- size_t CapConstraint::memory () const { return 0; } triagens::basics::Json CapConstraint::toJson (TRI_memory_zone_t* zone) const { auto json = Index::toJson(zone); json("size", triagens::basics::Json(zone, static_cast<double>(_count))) ("byteSize", triagens::basics::Json(zone, static_cast<double>(_size))); return json; } int CapConstraint::insert (TRI_doc_mptr_t const* doc, bool) { if (_size > 0) { // there is a size restriction auto marker = static_cast<TRI_df_marker_t const*>(doc->getDataPtr()); // ONLY IN INDEX, PROTECTED by RUNTIME // check if the document would be too big if (static_cast<int64_t>(marker->_size) > _size) { return TRI_ERROR_ARANGO_DOCUMENT_TOO_LARGE; } } return TRI_ERROR_NO_ERROR; } int CapConstraint::remove (TRI_doc_mptr_t const*, bool) { return TRI_ERROR_NO_ERROR; } int CapConstraint::postInsert (TRI_transaction_collection_t* trxCollection, TRI_doc_mptr_t const*) { TRI_ASSERT(_count > 0 || _size > 0); return apply(trxCollection->_collection->_collection, trxCollection); } // ----------------------------------------------------------------------------- // --SECTION-- private methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief initialize the cap constraint //////////////////////////////////////////////////////////////////////////////// int CapConstraint::initialize () { TRI_ASSERT(_count > 0 || _size > 0); TRI_headers_t* headers = _collection->_headersPtr; // ONLY IN INDEX (CAP) int64_t currentCount = static_cast<int64_t>(headers->count()); int64_t currentSize = headers->size(); if ((_count > 0 && currentCount <= _count) && (_size > 0 && currentSize <= _size)) { // nothing to do return TRI_ERROR_NO_ERROR; } else { TRI_vocbase_t* vocbase = _collection->_vocbase; TRI_voc_cid_t cid = _collection->_info._cid; triagens::arango::SingleCollectionWriteTransaction<UINT64_MAX> trx(new triagens::arango::StandaloneTransactionContext(), vocbase, cid); trx.addHint(TRI_TRANSACTION_HINT_LOCK_NEVER, false); trx.addHint(TRI_TRANSACTION_HINT_NO_BEGIN_MARKER, false); trx.addHint(TRI_TRANSACTION_HINT_NO_ABORT_MARKER, false); trx.addHint(TRI_TRANSACTION_HINT_SINGLE_OPERATION, false); // this is actually not true, but necessary to create trx id 0 int res = trx.begin(); if (res != TRI_ERROR_NO_ERROR) { return res; } TRI_transaction_collection_t* trxCollection = trx.trxCollection(); res = apply(_collection, trxCollection); res = trx.finish(res); return res; } } //////////////////////////////////////////////////////////////////////////////// /// @brief apply the cap constraint for the collection //////////////////////////////////////////////////////////////////////////////// int CapConstraint::apply (TRI_document_collection_t* document, TRI_transaction_collection_t* trxCollection) { TRI_headers_t* headers = document->_headersPtr; // PROTECTED by trx in trxCollection int64_t currentCount = static_cast<int64_t>(headers->count()); int64_t currentSize = headers->size(); int res = TRI_ERROR_NO_ERROR; // delete while at least one of the constraints is still violated while ((_count > 0 && currentCount > _count) || (_size > 0 && currentSize > _size)) { TRI_doc_mptr_t* oldest = headers->front(); if (oldest != nullptr) { TRI_ASSERT(oldest->getDataPtr() != nullptr); // ONLY IN INDEX, PROTECTED by RUNTIME size_t oldSize = ((TRI_df_marker_t*) (oldest->getDataPtr()))->_size; // ONLY IN INDEX, PROTECTED by RUNTIME TRI_ASSERT(oldSize > 0); if (trxCollection != nullptr) { res = TRI_DeleteDocumentDocumentCollection(trxCollection, nullptr, oldest); if (res != TRI_ERROR_NO_ERROR) { LOG_WARNING("cannot cap collection: %s", TRI_errno_string(res)); break; } } else { headers->unlink(oldest); } currentCount--; currentSize -= (int64_t) oldSize; } else { // we should not get here LOG_WARNING("logic error in %s", __FUNCTION__); break; } } return res; } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: systemshell.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:56:46 $ * * 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 _SYSTEMSHELL_HXX_ #include "systemshell.hxx" #endif #include "osl/module.hxx" const rtl::OUString SYM_ADD_TO_RECENTLY_USED_FILE_LIST = rtl::OUString::createFromAscii("add_to_recently_used_file_list"); const rtl::OUString LIB_RECENT_FILE = rtl::OUString::createFromAscii("librecentfile.so"); namespace SystemShell { typedef void (*PFUNC_ADD_TO_RECENTLY_USED_LIST)(const rtl::OUString&, const rtl::OUString&); //############################## rtl::OUString get_absolute_library_url(const rtl::OUString& lib_name) { rtl::OUString url; if (osl::Module::getUrlFromAddress(reinterpret_cast<oslGenericFunction>(AddToRecentDocumentList), url)) { sal_Int32 index = url.lastIndexOf('/'); url = url.copy(0, index + 1); url += LIB_RECENT_FILE; } return url; } //############################## void AddToRecentDocumentList(const rtl::OUString& aFileUrl, const rtl::OUString& aMimeType) { rtl::OUString librecentfile_url = get_absolute_library_url(LIB_RECENT_FILE); if (librecentfile_url.getLength()) { osl::Module module(librecentfile_url); if (module.is()) { // convert from reinterpret_cast<PFUNC_ADD_TO_RECENTLY_USED_LIST> // not allowed in gcc 3.3 without permissive. PFUNC_ADD_TO_RECENTLY_USED_LIST add_to_recently_used_file_list = reinterpret_cast<PFUNC_ADD_TO_RECENTLY_USED_LIST>(module.getFunctionSymbol(SYM_ADD_TO_RECENTLY_USED_FILE_LIST)); if (add_to_recently_used_file_list) add_to_recently_used_file_list(aFileUrl, aMimeType); } } } } // namespace SystemShell <commit_msg>INTEGRATION: CWS warnings01 (1.5.14); FILE MERGED 2005/10/26 15:08:25 pl 1.5.14.1: #i55991# remove warnings for solaris platform<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: systemshell.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-19 14:20:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SYSTEMSHELL_HXX_ #include "systemshell.hxx" #endif #include "osl/module.hxx" const rtl::OUString SYM_ADD_TO_RECENTLY_USED_FILE_LIST = rtl::OUString::createFromAscii("add_to_recently_used_file_list"); const rtl::OUString LIB_RECENT_FILE = rtl::OUString::createFromAscii("librecentfile.so"); namespace SystemShell { typedef void (*PFUNC_ADD_TO_RECENTLY_USED_LIST)(const rtl::OUString&, const rtl::OUString&); //############################## rtl::OUString get_absolute_library_url(const rtl::OUString& /*lib_name*/) { rtl::OUString url; if (osl::Module::getUrlFromAddress(reinterpret_cast<oslGenericFunction>(AddToRecentDocumentList), url)) { sal_Int32 index = url.lastIndexOf('/'); url = url.copy(0, index + 1); url += LIB_RECENT_FILE; } return url; } //############################## void AddToRecentDocumentList(const rtl::OUString& aFileUrl, const rtl::OUString& aMimeType) { rtl::OUString librecentfile_url = get_absolute_library_url(LIB_RECENT_FILE); if (librecentfile_url.getLength()) { osl::Module module(librecentfile_url); if (module.is()) { // convert from reinterpret_cast<PFUNC_ADD_TO_RECENTLY_USED_LIST> // not allowed in gcc 3.3 without permissive. PFUNC_ADD_TO_RECENTLY_USED_LIST add_to_recently_used_file_list = reinterpret_cast<PFUNC_ADD_TO_RECENTLY_USED_LIST>(module.getFunctionSymbol(SYM_ADD_TO_RECENTLY_USED_FILE_LIST)); if (add_to_recently_used_file_list) add_to_recently_used_file_list(aFileUrl, aMimeType); } } } } // namespace SystemShell <|endoftext|>
<commit_before>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <TelepathyQt4/ChannelFactory> #include <TelepathyQt4/Connection> #include <TelepathyQt4/ContactFactory> #include <TelepathyQt4/ContactSearchChannel> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/Debug> #include <telepathy-glib/debug.h> #include <tests/lib/glib/echo/conn.h> #include <tests/lib/glib/contact-search-chan.h> #include <tests/lib/test.h> using namespace Tp; class TestContactSearchChan : public Test { Q_OBJECT public: TestContactSearchChan(QObject *parent = 0) : Test(parent), mConnService(0), mBaseConnService(0), mChan1Service(0) { } protected Q_SLOTS: void onSearchStateChanged(Tp::ChannelContactSearchState state, const QString &errorName, const Tp::ContactSearchChannel::SearchStateChangeDetails &details); void onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &result); private Q_SLOTS: void initTestCase(); void init(); void testContactSearch(); void testContactSearchEmptyResult(); void cleanup(); void cleanupTestCase(); private: ExampleEchoConnection *mConnService; TpBaseConnection *mBaseConnService; TpHandleRepoIface *mContactRepo; QString mConnName; QString mConnPath; ConnectionPtr mConn; ContactSearchChannelPtr mChan; ContactSearchChannelPtr mChan1; ContactSearchChannelPtr mChan2; QString mChan1Path; TpTestsContactSearchChannel *mChan1Service; QString mChan2Path; TpTestsContactSearchChannel *mChan2Service; ContactSearchChannel::SearchResult mSearchResult; struct SearchStateChangeInfo { SearchStateChangeInfo(ChannelContactSearchState state, const QString &errorName, const Tp::ContactSearchChannel::SearchStateChangeDetails &details) : state(state), errorName(errorName), details(details) { } ChannelContactSearchState state; QString errorName; ContactSearchChannel::SearchStateChangeDetails details; }; QList<SearchStateChangeInfo> mSearchStateChangeInfoList; }; void TestContactSearchChan::onSearchStateChanged(Tp::ChannelContactSearchState state, const QString &errorName, const Tp::ContactSearchChannel::SearchStateChangeDetails &details) { mSearchStateChangeInfoList.append(SearchStateChangeInfo(state, errorName, details)); mLoop->exit(0); } void TestContactSearchChan::onSearchResultReceived( const Tp::ContactSearchChannel::SearchResult &result) { QCOMPARE(mChan->searchState(), ChannelContactSearchStateInProgress); mSearchResult = result; mLoop->exit(0); } void TestContactSearchChan::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("contact-search-chan"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); gchar *name; gchar *connPath; GError *error = 0; mConnService = EXAMPLE_ECHO_CONNECTION(g_object_new( EXAMPLE_TYPE_ECHO_CONNECTION, "account", "me@example.com", "protocol", "example", NULL)); QVERIFY(mConnService != 0); mBaseConnService = TP_BASE_CONNECTION(mConnService); QVERIFY(mBaseConnService != 0); QVERIFY(tp_base_connection_register(mBaseConnService, "example", &name, &connPath, &error)); QVERIFY(error == 0); QVERIFY(name != 0); QVERIFY(connPath != 0); mConnName = QLatin1String(name); mConnPath = QLatin1String(connPath); g_free(name); g_free(connPath); mConn = Connection::create(mConnName, mConnPath, ChannelFactory::create(QDBusConnection::sessionBus()), ContactFactory::create()); QCOMPARE(mConn->isReady(), false); QVERIFY(connect(mConn->requestConnect(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mConn->isReady(), true); QCOMPARE(static_cast<uint>(mConn->status()), static_cast<uint>(Connection::StatusConnected)); QByteArray chan1Path; mChan1Path = mConnPath + QLatin1String("/ContactSearchChannel/1"); chan1Path = mChan1Path.toAscii(); mChan1Service = TP_TESTS_CONTACT_SEARCH_CHANNEL(g_object_new( TP_TESTS_TYPE_CONTACT_SEARCH_CHANNEL, "connection", mConnService, "object-path", chan1Path.data(), NULL)); QByteArray chan2Path; mChan2Path = mConnPath + QLatin1String("/ContactSearchChannel/2"); chan2Path = mChan2Path.toAscii(); mChan2Service = TP_TESTS_CONTACT_SEARCH_CHANNEL(g_object_new( TP_TESTS_TYPE_CONTACT_SEARCH_CHANNEL, "connection", mConnService, "object-path", chan2Path.data(), NULL)); } void TestContactSearchChan::init() { initImpl(); mSearchResult.clear(); mSearchStateChangeInfoList.clear(); } void TestContactSearchChan::testContactSearch() { mChan1 = ContactSearchChannel::create(mConn, mChan1Path, QVariantMap()); mChan = mChan1; QVERIFY(connect(mChan1->becomeReady(ContactSearchChannel::FeatureCore), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan1->isReady(), true); QCOMPARE(mChan1->searchState(), ChannelContactSearchStateNotStarted); QCOMPARE(mChan1->limit(), static_cast<uint>(0)); QCOMPARE(mChan1->availableSearchKeys().isEmpty(), false); QCOMPARE(mChan1->availableSearchKeys().count(), 1); QCOMPARE(mChan1->availableSearchKeys().first(), QLatin1String("employer")); QCOMPARE(mChan1->server(), QLatin1String("characters.shakespeare.lit")); QVERIFY(connect(mChan1.data(), SIGNAL(searchStateChanged(Tp::ChannelContactSearchState, const QString &, const Tp::ContactSearchChannel::SearchStateChangeDetails &)), SLOT(onSearchStateChanged(Tp::ChannelContactSearchState, const QString &, const Tp::ContactSearchChannel::SearchStateChangeDetails &)))); QVERIFY(connect(mChan1.data(), SIGNAL(searchResultReceived(const Tp::ContactSearchChannel::SearchResult &)), SLOT(onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &)))); mChan1->search(QLatin1String("employer"), QLatin1String("Collabora")); while (mChan1->searchState() != ChannelContactSearchStateCompleted) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mSearchStateChangeInfoList.count(), 2); SearchStateChangeInfo info = mSearchStateChangeInfoList.at(0); QCOMPARE(info.state, ChannelContactSearchStateInProgress); QCOMPARE(info.errorName, QLatin1String("")); QCOMPARE(info.details.hasDebugMessage(), true); QCOMPARE(info.details.debugMessage(), QLatin1String("in progress")); info = mSearchStateChangeInfoList.at(1); QCOMPARE(info.state, ChannelContactSearchStateCompleted); QCOMPARE(info.errorName, QLatin1String("")); QCOMPARE(info.details.hasDebugMessage(), true); QCOMPARE(info.details.debugMessage(), QLatin1String("completed")); QCOMPARE(mSearchResult.isEmpty(), false); QCOMPARE(mSearchResult.size(), 3); QStringList expectedIds; expectedIds << QLatin1String("oggis") << QLatin1String("andrunko") << QLatin1String("wjt"); expectedIds.sort(); QStringList expectedFns; expectedFns << QLatin1String("Olli Salli") << QLatin1String("Andre Moreira Magalhaes") << QLatin1String("Will Thompson"); expectedFns.sort(); QStringList ids; QStringList fns; for (ContactSearchChannel::SearchResult::const_iterator it = mSearchResult.constBegin(); it != mSearchResult.constEnd(); ++it) { QCOMPARE(it.key().isNull(), false); ids << it.key()->id(); QCOMPARE(it.value().isValid(), true); QCOMPARE(it.value().allFields().isEmpty(), false); Q_FOREACH (const ContactInfoField &contactInfo, it.value().allFields()) { QCOMPARE(contactInfo.fieldName, QLatin1String("fn")); fns.append(contactInfo.fieldValue.first()); } } ids.sort(); QCOMPARE(ids, expectedIds); fns.sort(); QCOMPARE(fns, expectedFns); mChan1.reset(); } void TestContactSearchChan::testContactSearchEmptyResult() { mChan2 = ContactSearchChannel::create(mConn, mChan2Path, QVariantMap()); mChan = mChan2; QVERIFY(connect(mChan2->becomeReady(ContactSearchChannel::FeatureCore), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan2->isReady(), true); QCOMPARE(mChan2->searchState(), ChannelContactSearchStateNotStarted); QCOMPARE(mChan2->limit(), static_cast<uint>(0)); QCOMPARE(mChan2->availableSearchKeys().isEmpty(), false); QCOMPARE(mChan2->availableSearchKeys().count(), 1); QCOMPARE(mChan2->availableSearchKeys().first(), QLatin1String("employer")); QCOMPARE(mChan2->server(), QLatin1String("characters.shakespeare.lit")); QVERIFY(connect(mChan2.data(), SIGNAL(searchStateChanged(Tp::ChannelContactSearchState, const QString &, const Tp::ContactSearchChannel::SearchStateChangeDetails &)), SLOT(onSearchStateChanged(Tp::ChannelContactSearchState, const QString &, const Tp::ContactSearchChannel::SearchStateChangeDetails &)))); QVERIFY(connect(mChan2.data(), SIGNAL(searchResultReceived(const Tp::ContactSearchChannel::SearchResult &)), SLOT(onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &)))); ContactSearchMap searchTerms; searchTerms.insert(QLatin1String("employer"), QLatin1String("FooBar")); mChan2->search(searchTerms); while (mChan2->searchState() != ChannelContactSearchStateCompleted) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mSearchResult.isEmpty(), true); QCOMPARE(mSearchStateChangeInfoList.count(), 2); SearchStateChangeInfo info = mSearchStateChangeInfoList.at(0); QCOMPARE(info.state, ChannelContactSearchStateInProgress); QCOMPARE(info.errorName, QLatin1String("")); QCOMPARE(info.details.hasDebugMessage(), true); QCOMPARE(info.details.debugMessage(), QLatin1String("in progress")); info = mSearchStateChangeInfoList.at(1); QCOMPARE(info.state, ChannelContactSearchStateCompleted); QCOMPARE(info.errorName, QLatin1String("")); QCOMPARE(info.details.hasDebugMessage(), true); QCOMPARE(info.details.debugMessage(), QLatin1String("completed")); mChan2.reset(); } void TestContactSearchChan::cleanup() { cleanupImpl(); } void TestContactSearchChan::cleanupTestCase() { if (mConn) { // Disconnect and wait for the readiness change QVERIFY(connect(mConn->requestDisconnect(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); if (mConn->isValid()) { QVERIFY(connect(mConn.data(), SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)), mLoop, SLOT(quit()))); QCOMPARE(mLoop->exec(), 0); } } if (mChan1Service != 0) { g_object_unref(mChan1Service); mChan1Service = 0; } if (mChan2Service != 0) { g_object_unref(mChan2Service); mChan2Service = 0; } if (mConnService != 0) { mBaseConnService = 0; g_object_unref(mConnService); mConnService = 0; } cleanupTestCaseImpl(); } QTEST_MAIN(TestContactSearchChan) #include "_gen/chan-contact-search.cpp.moc.hpp" <commit_msg>chan-contact-search test: Test that the pending operation returned from search only finishes when the state changes.<commit_after>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <TelepathyQt4/ChannelFactory> #include <TelepathyQt4/Connection> #include <TelepathyQt4/ContactFactory> #include <TelepathyQt4/ContactSearchChannel> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/Debug> #include <telepathy-glib/debug.h> #include <tests/lib/glib/echo/conn.h> #include <tests/lib/glib/contact-search-chan.h> #include <tests/lib/test.h> using namespace Tp; class TestContactSearchChan : public Test { Q_OBJECT public: TestContactSearchChan(QObject *parent = 0) : Test(parent), mConnService(0), mBaseConnService(0), mChan1Service(0), mSearchReturned(false) { } protected Q_SLOTS: void onSearchStateChanged(Tp::ChannelContactSearchState state, const QString &errorName, const Tp::ContactSearchChannel::SearchStateChangeDetails &details); void onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &result); void onSearchReturned(Tp::PendingOperation *op); private Q_SLOTS: void initTestCase(); void init(); void testContactSearch(); void testContactSearchEmptyResult(); void cleanup(); void cleanupTestCase(); private: ExampleEchoConnection *mConnService; TpBaseConnection *mBaseConnService; TpHandleRepoIface *mContactRepo; QString mConnName; QString mConnPath; ConnectionPtr mConn; ContactSearchChannelPtr mChan; ContactSearchChannelPtr mChan1; ContactSearchChannelPtr mChan2; QString mChan1Path; TpTestsContactSearchChannel *mChan1Service; QString mChan2Path; TpTestsContactSearchChannel *mChan2Service; ContactSearchChannel::SearchResult mSearchResult; bool mSearchReturned; struct SearchStateChangeInfo { SearchStateChangeInfo(ChannelContactSearchState state, const QString &errorName, const Tp::ContactSearchChannel::SearchStateChangeDetails &details) : state(state), errorName(errorName), details(details) { } ChannelContactSearchState state; QString errorName; ContactSearchChannel::SearchStateChangeDetails details; }; QList<SearchStateChangeInfo> mSearchStateChangeInfoList; }; void TestContactSearchChan::onSearchStateChanged(Tp::ChannelContactSearchState state, const QString &errorName, const Tp::ContactSearchChannel::SearchStateChangeDetails &details) { mSearchStateChangeInfoList.append(SearchStateChangeInfo(state, errorName, details)); mLoop->exit(0); } void TestContactSearchChan::onSearchResultReceived( const Tp::ContactSearchChannel::SearchResult &result) { QCOMPARE(mChan->searchState(), ChannelContactSearchStateInProgress); mSearchResult = result; mLoop->exit(0); } void TestContactSearchChan::onSearchReturned(Tp::PendingOperation *op) { QCOMPARE(op->isError(), false); QVERIFY(mChan->searchState() != ChannelContactSearchStateNotStarted); mSearchReturned = true; mLoop->exit(0); } void TestContactSearchChan::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("contact-search-chan"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); gchar *name; gchar *connPath; GError *error = 0; mConnService = EXAMPLE_ECHO_CONNECTION(g_object_new( EXAMPLE_TYPE_ECHO_CONNECTION, "account", "me@example.com", "protocol", "example", NULL)); QVERIFY(mConnService != 0); mBaseConnService = TP_BASE_CONNECTION(mConnService); QVERIFY(mBaseConnService != 0); QVERIFY(tp_base_connection_register(mBaseConnService, "example", &name, &connPath, &error)); QVERIFY(error == 0); QVERIFY(name != 0); QVERIFY(connPath != 0); mConnName = QLatin1String(name); mConnPath = QLatin1String(connPath); g_free(name); g_free(connPath); mConn = Connection::create(mConnName, mConnPath, ChannelFactory::create(QDBusConnection::sessionBus()), ContactFactory::create()); QCOMPARE(mConn->isReady(), false); QVERIFY(connect(mConn->requestConnect(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mConn->isReady(), true); QCOMPARE(static_cast<uint>(mConn->status()), static_cast<uint>(Connection::StatusConnected)); QByteArray chan1Path; mChan1Path = mConnPath + QLatin1String("/ContactSearchChannel/1"); chan1Path = mChan1Path.toAscii(); mChan1Service = TP_TESTS_CONTACT_SEARCH_CHANNEL(g_object_new( TP_TESTS_TYPE_CONTACT_SEARCH_CHANNEL, "connection", mConnService, "object-path", chan1Path.data(), NULL)); QByteArray chan2Path; mChan2Path = mConnPath + QLatin1String("/ContactSearchChannel/2"); chan2Path = mChan2Path.toAscii(); mChan2Service = TP_TESTS_CONTACT_SEARCH_CHANNEL(g_object_new( TP_TESTS_TYPE_CONTACT_SEARCH_CHANNEL, "connection", mConnService, "object-path", chan2Path.data(), NULL)); } void TestContactSearchChan::init() { initImpl(); mSearchResult.clear(); mSearchStateChangeInfoList.clear(); mSearchReturned = false; } void TestContactSearchChan::testContactSearch() { mChan1 = ContactSearchChannel::create(mConn, mChan1Path, QVariantMap()); mChan = mChan1; QVERIFY(connect(mChan1->becomeReady(ContactSearchChannel::FeatureCore), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan1->isReady(), true); QCOMPARE(mChan1->searchState(), ChannelContactSearchStateNotStarted); QCOMPARE(mChan1->limit(), static_cast<uint>(0)); QCOMPARE(mChan1->availableSearchKeys().isEmpty(), false); QCOMPARE(mChan1->availableSearchKeys().count(), 1); QCOMPARE(mChan1->availableSearchKeys().first(), QLatin1String("employer")); QCOMPARE(mChan1->server(), QLatin1String("characters.shakespeare.lit")); QVERIFY(connect(mChan1.data(), SIGNAL(searchStateChanged(Tp::ChannelContactSearchState, const QString &, const Tp::ContactSearchChannel::SearchStateChangeDetails &)), SLOT(onSearchStateChanged(Tp::ChannelContactSearchState, const QString &, const Tp::ContactSearchChannel::SearchStateChangeDetails &)))); QVERIFY(connect(mChan1.data(), SIGNAL(searchResultReceived(const Tp::ContactSearchChannel::SearchResult &)), SLOT(onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &)))); QVERIFY(connect(mChan1->search(QLatin1String("employer"), QLatin1String("Collabora")), SIGNAL(finished(Tp::PendingOperation *)), SLOT(onSearchReturned(Tp::PendingOperation *)))); while (!mSearchReturned) { QCOMPARE(mLoop->exec(), 0); } while (mChan1->searchState() != ChannelContactSearchStateCompleted) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mSearchReturned, true); QCOMPARE(mSearchStateChangeInfoList.count(), 2); SearchStateChangeInfo info = mSearchStateChangeInfoList.at(0); QCOMPARE(info.state, ChannelContactSearchStateInProgress); QCOMPARE(info.errorName, QLatin1String("")); QCOMPARE(info.details.hasDebugMessage(), true); QCOMPARE(info.details.debugMessage(), QLatin1String("in progress")); info = mSearchStateChangeInfoList.at(1); QCOMPARE(info.state, ChannelContactSearchStateCompleted); QCOMPARE(info.errorName, QLatin1String("")); QCOMPARE(info.details.hasDebugMessage(), true); QCOMPARE(info.details.debugMessage(), QLatin1String("completed")); QCOMPARE(mSearchResult.isEmpty(), false); QCOMPARE(mSearchResult.size(), 3); QStringList expectedIds; expectedIds << QLatin1String("oggis") << QLatin1String("andrunko") << QLatin1String("wjt"); expectedIds.sort(); QStringList expectedFns; expectedFns << QLatin1String("Olli Salli") << QLatin1String("Andre Moreira Magalhaes") << QLatin1String("Will Thompson"); expectedFns.sort(); QStringList ids; QStringList fns; for (ContactSearchChannel::SearchResult::const_iterator it = mSearchResult.constBegin(); it != mSearchResult.constEnd(); ++it) { QCOMPARE(it.key().isNull(), false); ids << it.key()->id(); QCOMPARE(it.value().isValid(), true); QCOMPARE(it.value().allFields().isEmpty(), false); Q_FOREACH (const ContactInfoField &contactInfo, it.value().allFields()) { QCOMPARE(contactInfo.fieldName, QLatin1String("fn")); fns.append(contactInfo.fieldValue.first()); } } ids.sort(); QCOMPARE(ids, expectedIds); fns.sort(); QCOMPARE(fns, expectedFns); mChan1.reset(); } void TestContactSearchChan::testContactSearchEmptyResult() { mChan2 = ContactSearchChannel::create(mConn, mChan2Path, QVariantMap()); mChan = mChan2; QVERIFY(connect(mChan2->becomeReady(ContactSearchChannel::FeatureCore), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mChan2->isReady(), true); QCOMPARE(mChan2->searchState(), ChannelContactSearchStateNotStarted); QCOMPARE(mChan2->limit(), static_cast<uint>(0)); QCOMPARE(mChan2->availableSearchKeys().isEmpty(), false); QCOMPARE(mChan2->availableSearchKeys().count(), 1); QCOMPARE(mChan2->availableSearchKeys().first(), QLatin1String("employer")); QCOMPARE(mChan2->server(), QLatin1String("characters.shakespeare.lit")); QVERIFY(connect(mChan2.data(), SIGNAL(searchStateChanged(Tp::ChannelContactSearchState, const QString &, const Tp::ContactSearchChannel::SearchStateChangeDetails &)), SLOT(onSearchStateChanged(Tp::ChannelContactSearchState, const QString &, const Tp::ContactSearchChannel::SearchStateChangeDetails &)))); QVERIFY(connect(mChan2.data(), SIGNAL(searchResultReceived(const Tp::ContactSearchChannel::SearchResult &)), SLOT(onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &)))); ContactSearchMap searchTerms; searchTerms.insert(QLatin1String("employer"), QLatin1String("FooBar")); QVERIFY(connect(mChan2->search(searchTerms), SIGNAL(finished(Tp::PendingOperation *)), SLOT(onSearchReturned(Tp::PendingOperation *)))); while (!mSearchReturned) { QCOMPARE(mLoop->exec(), 0); } while (mChan2->searchState() != ChannelContactSearchStateCompleted) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mSearchReturned, true); QCOMPARE(mSearchResult.isEmpty(), true); QCOMPARE(mSearchStateChangeInfoList.count(), 2); SearchStateChangeInfo info = mSearchStateChangeInfoList.at(0); QCOMPARE(info.state, ChannelContactSearchStateInProgress); QCOMPARE(info.errorName, QLatin1String("")); QCOMPARE(info.details.hasDebugMessage(), true); QCOMPARE(info.details.debugMessage(), QLatin1String("in progress")); info = mSearchStateChangeInfoList.at(1); QCOMPARE(info.state, ChannelContactSearchStateCompleted); QCOMPARE(info.errorName, QLatin1String("")); QCOMPARE(info.details.hasDebugMessage(), true); QCOMPARE(info.details.debugMessage(), QLatin1String("completed")); mChan2.reset(); } void TestContactSearchChan::cleanup() { cleanupImpl(); } void TestContactSearchChan::cleanupTestCase() { if (mConn) { // Disconnect and wait for the readiness change QVERIFY(connect(mConn->requestDisconnect(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); if (mConn->isValid()) { QVERIFY(connect(mConn.data(), SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)), mLoop, SLOT(quit()))); QCOMPARE(mLoop->exec(), 0); } } if (mChan1Service != 0) { g_object_unref(mChan1Service); mChan1Service = 0; } if (mChan2Service != 0) { g_object_unref(mChan2Service); mChan2Service = 0; } if (mConnService != 0) { mBaseConnService = 0; g_object_unref(mConnService); mConnService = 0; } cleanupTestCaseImpl(); } QTEST_MAIN(TestContactSearchChan) #include "_gen/chan-contact-search.cpp.moc.hpp" <|endoftext|>
<commit_before>/* * Copyright (c) 2003 [NAMES_GO_HERE] * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "p2psim/network.h" #include "p2psim/topology.h" #include "protocols/protocolfactory.h" #include "euclidean.h" #include <cmath> #include <iostream> using namespace std; Euclidean::Euclidean(vector<string>*) { } Euclidean::~Euclidean() { } Time Euclidean::latency(IPAddress ip1x, IPAddress ip2x, bool reply) { IPAddress ip1 = Network::Instance()->first_ip(ip1x); IPAddress ip2 = Network::Instance()->first_ip(ip2x); assert(ip1 > 0 && ip2 > 0); Coord c1 = _nodes[ip1]; Coord c2 = _nodes[ip2]; if (ip1==ip2) return 0; else { Time t= (Time) hypot(labs(c2.first - c1.first), labs(c2.second - c1.second)); if (t > 1000) fprintf(stderr,"warning! %u,%u -> %u,%u\n",c1.first,c1.second,c2.first,c2.second); return t; } } void Euclidean::parse(ifstream &ifs) { string line; Time max_first, max_second; max_first = max_second = 0; while(getline(ifs,line)) { vector<string> words = split(line); // skip empty lines and commented lines if(words.empty() || words[0][0] == '#') continue; // nodeid, coordinates and at least one protocol if(words.size() < 2) { cerr << "provide nodeid and coordinates per line" << endl; continue; } // node-id IPAddress ipaddr = (IPAddress) strtoull(words[0].c_str(), NULL, 10); if(!ipaddr) cerr << "found node-id 0. you're asking for trouble." << endl; // x,y coordinates vector<string> coords = split(words[1], ","); Coord c; if (coords.size () < 2) { cerr << "malformed coordinates " << endl; exit (-1); } c.first = atoi(coords[0].c_str()); c.second = atoi(coords[1].c_str()); if ((Time) c.first > max_first) max_first = c.first; else if ((Time) c.second > max_second) max_second = c.second; // what kind of node? Node *p = ProtocolFactory::Instance()->create(ipaddr); // add the new node it to the topology if(_nodes.find(p->ip()) != _nodes.end()) cerr << "warning: node " << ipaddr << " already added! (" <<words[0]<<")" << endl; _nodes[p->ip()] = c; // add the node to the network send(Network::Instance()->nodechan(), &p); } _med_lat = (Time) sqrt((double) (max_first * max_first + max_second * max_second))/3; } <commit_msg>get rid of annoying warning message<commit_after>/* * Copyright (c) 2003 [NAMES_GO_HERE] * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "p2psim/network.h" #include "p2psim/topology.h" #include "protocols/protocolfactory.h" #include "euclidean.h" #include <cmath> #include <iostream> using namespace std; Euclidean::Euclidean(vector<string>*) { } Euclidean::~Euclidean() { } Time Euclidean::latency(IPAddress ip1x, IPAddress ip2x, bool reply) { IPAddress ip1 = Network::Instance()->first_ip(ip1x); IPAddress ip2 = Network::Instance()->first_ip(ip2x); assert(ip1 > 0 && ip2 > 0); Coord c1 = _nodes[ip1]; Coord c2 = _nodes[ip2]; if (ip1==ip2) return 0; else { Time t= (Time) hypot(labs(c2.first - c1.first), labs(c2.second - c1.second)); return t; } } void Euclidean::parse(ifstream &ifs) { string line; Time max_first, max_second; max_first = max_second = 0; while(getline(ifs,line)) { vector<string> words = split(line); // skip empty lines and commented lines if(words.empty() || words[0][0] == '#') continue; // nodeid, coordinates and at least one protocol if(words.size() < 2) { cerr << "provide nodeid and coordinates per line" << endl; continue; } // node-id IPAddress ipaddr = (IPAddress) strtoull(words[0].c_str(), NULL, 10); if(!ipaddr) cerr << "found node-id 0. you're asking for trouble." << endl; // x,y coordinates vector<string> coords = split(words[1], ","); Coord c; if (coords.size () < 2) { cerr << "malformed coordinates " << endl; exit (-1); } c.first = atoi(coords[0].c_str()); c.second = atoi(coords[1].c_str()); if ((Time) c.first > max_first) max_first = c.first; else if ((Time) c.second > max_second) max_second = c.second; // what kind of node? Node *p = ProtocolFactory::Instance()->create(ipaddr); // add the new node it to the topology if(_nodes.find(p->ip()) != _nodes.end()) cerr << "warning: node " << ipaddr << " already added! (" <<words[0]<<")" << endl; _nodes[p->ip()] = c; // add the node to the network send(Network::Instance()->nodechan(), &p); } _med_lat = (Time) sqrt((double) (max_first * max_first + max_second * max_second))/3; } <|endoftext|>
<commit_before><commit_msg>Unused return value warning fix<commit_after><|endoftext|>
<commit_before><commit_msg>Allows receivers of nullptr from begin_data to output any quantity of data.<commit_after><|endoftext|>
<commit_before>#include "WhistleControl.h" using namespace naoth; WhistleControl::WhistleControl(): onOffSwitch(0), whistleListFile("whistles.lst"), activeChannels("1010") {} void WhistleControl::print(std::ostream& stream) const { stream << "switch: " << (onOffSwitch == 1 ? "on" : "off") << std::endl; stream << "whistle list file: " << whistleListFile << std::endl; stream << "active channels(Left|Front|Right|Rear): " << activeChannels << std::endl; } WhistleControl::~WhistleControl() {} <commit_msg>initialize whistlecontrol variables<commit_after>#include "WhistleControl.h" using namespace naoth; WhistleControl::WhistleControl(): onOffSwitch(0), whistleListFile("whistles.lst"), activeChannels("1010"), threshold(0.4), checkAllWhistles(true), saveRawAudio(false) {} void WhistleControl::print(std::ostream& stream) const { stream << "switch: " << (onOffSwitch == 1 ? "on" : "off") << std::endl; stream << "whistle list file: " << whistleListFile << std::endl; stream << "active channels(Left|Front|Right|Rear): " << activeChannels << std::endl; } WhistleControl::~WhistleControl() {} <|endoftext|>
<commit_before>#include <string> #include "../include/Account.h" using namespace std; static const string Account::admin = "AA"; static const string Account::sell = "SS"; static const string Account::buy = "BS"; static const string Account::full = "FS"; static const double Account::maxPrice = 999999.99; string Account::getType() { return this->type; } void Account::setType(string type) { this->type = type; } double Account::getBalance() { return this->balance; } void Account::setBalance(double balance) { this->balance = balance; } string Account::getUsername() { return this->username; } void Account::setUsername(string username) { this->username = username; } <commit_msg>FIXED: 'static' may not be used when defining (as opposed to declaring) a static data member<commit_after>#include <string> #include "../include/Account.h" using namespace std; // ‘static’ may not be used when defining (as opposed to declaring) a static data member [-fpermissive] const string Account::admin = "AA"; const string Account::sell = "SS"; const string Account::buy = "BS"; const string Account::full = "FS"; const double Account::maxPrice = 999999.99; string Account::getType() { return this->type; } void Account::setType(string type) { this->type = type; } double Account::getBalance() { return this->balance; } void Account::setBalance(double balance) { this->balance = balance; } string Account::getUsername() { return this->username; } void Account::setUsername(string username) { this->username = username; } <|endoftext|>
<commit_before>#include "LogicController.h" LogicController::LogicController() { logicState = LOGIC_STATE_INTERRUPT; processState = PROCCESS_STATE_SEARCHING; prioritizedControllers = { PrioritizedController{0, (Controller*)(&searchController)}, PrioritizedController{1, (Controller*)(&obstacleController)}, PrioritizedController{2, (Controller*)(&pickUpController)} }; control_queue = priority_queue<PrioritizedController>(); } LogicController::~LogicController() {} void LogicController::Reset() { logicState = LOGIC_STATE_INTERRUPT; processState = PROCCESS_STATE_SEARCHING; prioritizedControllers = { PrioritizedController{0, (Controller*)(&searchController)}, PrioritizedController{1, (Controller*)(&obstacleController)}, PrioritizedController{2, (Controller*)(&pickUpController)} }; control_queue = priority_queue<PrioritizedController>(); } Result LogicController::DoWork() { Result result; if (processState == PROCCESS_STATE_SEARCHING) { } else if (processState == PROCCESS_COLLECTING_TARGET) { } else if (processState == PROCCESS_STATE_TARGET_PICKEDUP) { } switch(logicState) { case LOGIC_STATE_INTERRUPT: { //Reset the control queue control_queue = priority_queue<PrioritizedController>(); for(PrioritizedController cntrlr : prioritizedControllers) { if(cntrlr.controller->ShouldInterrupt()) { control_queue.push(cntrlr); } } if(control_queue.empty()) { result.type = behavior; result.b = wait; return result; } result = control_queue.top().controller->DoWork(); if(result.type == behavior) { if(result.b == nextProcess) { if (processState == _LAST) { processState = _FIRST; } else { processState = (ProcessState)((int)processState + 1); } } else if(result.b == prevProcess) { if (processState == _FIRST) { processState = (ProcessState)((int)_LAST - 1); } else { processState = (ProcessState)((int)processState - 1); } } } else if(result.type == precisionDriving) { logicState = LOGIC_STATE_PRECISION_COMMAND; } else if(result.type == waypoint) { logicState = LOGIC_STATE_WAITING; result = control_queue.top().controller->DoWork(); } break; } case LOGIC_STATE_WAITING: { result = driveController.DoWork(); if (result.type = behavior) { if(driveController.ShouldInterrupt()) { logicState = LOGIC_STATE_INTERRUPT; } else { return result; } } else { return result; } break; } case LOGIC_STATE_PRECISION_COMMAND: { result = control_queue.top().controller->DoWork(); driveController.setResultData(result); result = driveController.DoWork(); break; } } return result; } void LogicController::UpdateData() { } void LogicController::ProcessData() { } bool LogicController::ShouldInterrupt() { ProcessData(); return false; } bool LogicController::HasWork() { return false; } void LogicController::controllerInterconnect() { if(pickUpController.GetIgnoreCenter()) { obstacleController.SetIgnoreCenter(); } } void LogicController::setPositionData(Point currentLocation) { searchController.setCurrentLocation(currentLocation); dropOffController.SetCurrentLocation(currentLocation); obstacleController.SetCurrentLocation(currentLocation); } void LogicController::setMapPositionData(Point currentLocationMap) { } void LogicController::setVelocityData(float linearVelocity, float angularVelocity) { driveController.SetVelocityData(linearVelocity,angularVelocity); } void LogicController::setMapVelocityData(float linearVelocity, float angularVelocity) { } void LogicController::setAprilTags(vector<TagPoint> tags) { pickUpController.SetTagData(tags); obstacleController.SetTagData(tags); dropOffController.setTargetData(tags); } void LogicController::setSonarData(float left, float center, float right) { pickUpController.SetSonarData(center); obstacleController.SetSonarData(left,center,right); } void LogicController::setCenterLocationOdom(Point centerLocationOdom) { searchController.setCenterLocation(centerLocationOdom); dropOffController.SetCenterLocation(centerLocationOdom); } void LogicController::setCenterLocationMap(Point centerLocationMap) { } <commit_msg>Added alternet priorites based upon process loop state<commit_after>#include "LogicController.h" LogicController::LogicController() { logicState = LOGIC_STATE_INTERRUPT; processState = PROCCESS_STATE_SEARCHING; prioritizedControllers = { PrioritizedController{0, (Controller*)(&searchController)}, PrioritizedController{1, (Controller*)(&obstacleController)}, PrioritizedController{2, (Controller*)(&pickUpController)}, PrioritizedController{-1, (Controller*)(&dropOffController)} }; control_queue = priority_queue<PrioritizedController>(); } LogicController::~LogicController() {} void LogicController::Reset() { logicState = LOGIC_STATE_INTERRUPT; processState = PROCCESS_STATE_SEARCHING; prioritizedControllers = { PrioritizedController{0, (Controller*)(&searchController)}, PrioritizedController{1, (Controller*)(&obstacleController)}, PrioritizedController{2, (Controller*)(&pickUpController)} }; control_queue = priority_queue<PrioritizedController>(); } Result LogicController::DoWork() { Result result; if (processState == PROCCESS_STATE_SEARCHING) { prioritizedControllers = { PrioritizedController{0, (Controller*)(&searchController)}, PrioritizedController{1, (Controller*)(&obstacleController)}, PrioritizedController{2, (Controller*)(&pickUpController)}, PrioritizedController{-1, (Controller*)(&dropOffController)} }; } else if (processState == PROCCESS_COLLECTING_TARGET) { prioritizedControllers = { PrioritizedController{-1, (Controller*)(&searchController)}, PrioritizedController{1, (Controller*)(&obstacleController)}, PrioritizedController{2, (Controller*)(&pickUpController)}, PrioritizedController{-1, (Controller*)(&dropOffController)} }; } else if (processState == PROCCESS_STATE_TARGET_PICKEDUP) { prioritizedControllers = { PrioritizedController{-1, (Controller*)(&searchController)}, PrioritizedController{2, (Controller*)(&obstacleController)}, PrioritizedController{-1, (Controller*)(&pickUpController)}, PrioritizedController{1, (Controller*)(&dropOffController)} }; } switch(logicState) { case LOGIC_STATE_INTERRUPT: { //Reset the control queue control_queue = priority_queue<PrioritizedController>(); for(PrioritizedController cntrlr : prioritizedControllers) { if(cntrlr.controller->ShouldInterrupt()) { if (cntrlr.priority < 0) { continue; } else { control_queue.push(cntrlr); } } } if(control_queue.empty()) { result.type = behavior; result.b = wait; return result; } result = control_queue.top().controller->DoWork(); if(result.type == behavior) { if(result.b == nextProcess) { if (processState == _LAST) { processState = _FIRST; } else { processState = (ProcessState)((int)processState + 1); } } else if(result.b == prevProcess) { if (processState == _FIRST) { processState = (ProcessState)((int)_LAST - 1); } else { processState = (ProcessState)((int)processState - 1); } } } else if(result.type == precisionDriving) { logicState = LOGIC_STATE_PRECISION_COMMAND; } else if(result.type == waypoint) { logicState = LOGIC_STATE_WAITING; result = control_queue.top().controller->DoWork(); } break; } case LOGIC_STATE_WAITING: { result = driveController.DoWork(); if (result.type = behavior) { if(driveController.ShouldInterrupt()) { logicState = LOGIC_STATE_INTERRUPT; } else { return result; } } else { return result; } break; } case LOGIC_STATE_PRECISION_COMMAND: { result = control_queue.top().controller->DoWork(); driveController.setResultData(result); result = driveController.DoWork(); break; } } return result; } void LogicController::UpdateData() { } void LogicController::ProcessData() { } bool LogicController::ShouldInterrupt() { ProcessData(); return false; } bool LogicController::HasWork() { return false; } void LogicController::controllerInterconnect() { if(pickUpController.GetIgnoreCenter()) { obstacleController.SetIgnoreCenter(); } } void LogicController::setPositionData(Point currentLocation) { searchController.setCurrentLocation(currentLocation); dropOffController.SetCurrentLocation(currentLocation); obstacleController.SetCurrentLocation(currentLocation); } void LogicController::setMapPositionData(Point currentLocationMap) { } void LogicController::setVelocityData(float linearVelocity, float angularVelocity) { driveController.SetVelocityData(linearVelocity,angularVelocity); } void LogicController::setMapVelocityData(float linearVelocity, float angularVelocity) { } void LogicController::setAprilTags(vector<TagPoint> tags) { pickUpController.SetTagData(tags); obstacleController.SetTagData(tags); dropOffController.setTargetData(tags); } void LogicController::setSonarData(float left, float center, float right) { pickUpController.SetSonarData(center); obstacleController.SetSonarData(left,center,right); } void LogicController::setCenterLocationOdom(Point centerLocationOdom) { searchController.setCenterLocation(centerLocationOdom); dropOffController.SetCenterLocation(centerLocationOdom); } void LogicController::setCenterLocationMap(Point centerLocationMap) { } <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "iodevicereader.h" #include "qasyncreader.h" #include "mediagraph.h" #include <phonon/streaminterface.h> #include <dshow.h> #include <initguid.h> QT_BEGIN_NAMESPACE #ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM namespace Phonon { namespace DS9 { //these mediatypes define a stream, its type will be autodetected by DirectShow static QVector<AM_MEDIA_TYPE> getMediaTypes() { AM_MEDIA_TYPE mt = { MEDIATYPE_Stream, MEDIASUBTYPE_NULL, TRUE, FALSE, 1, GUID_NULL, 0, 0, 0}; QVector<AM_MEDIA_TYPE> ret; //normal auto-detect stream ret << mt; //AVI stream mt.subtype = MEDIASUBTYPE_Avi; ret << mt; //WAVE stream mt.subtype = MEDIASUBTYPE_WAVE; ret << mt; return ret; } class StreamReader : public QAsyncReader, public Phonon::StreamInterface { public: StreamReader(QBaseFilter *parent, const Phonon::MediaSource &source, const MediaGraph *mg) : QAsyncReader(parent, getMediaTypes()), m_seekable(false), m_pos(0), m_size(-1), m_mediaGraph(mg) { connectToSource(source); } //for Phonon::StreamInterface void writeData(const QByteArray &data) { m_pos += data.size(); m_buffer += data; } void endOfData() { } void setStreamSize(qint64 newSize) { QMutexLocker locker(&m_mutex); m_size = newSize; } void setStreamSeekable(bool s) { QMutexLocker locker(&m_mutex); m_seekable = s; } //virtual pure members //implementation from IAsyncReader STDMETHODIMP Length(LONGLONG *total, LONGLONG *available) { QMutexLocker locker(&m_mutex); if (total) { *total = m_size; } if (available) { *available = m_size; } return S_OK; } HRESULT read(LONGLONG pos, LONG length, BYTE *buffer, LONG *actual) { Q_ASSERT(!m_mutex.tryLock()); if (m_mediaGraph->isStopping()) { return VFW_E_WRONG_STATE; } if(m_size != 1 && pos + length > m_size) { //it tries to read outside of the boundaries return E_FAIL; } if (m_pos - m_buffer.size() != pos) { if (!m_seekable) { return S_FALSE; } m_pos = pos; seekStream(pos); m_buffer.clear(); } int oldSize = m_buffer.size(); while (m_buffer.size() < int(length)) { needData(); if (m_mediaGraph->isStopping()) { return VFW_E_WRONG_STATE; } if (oldSize == m_buffer.size()) { break; //we didn't get any data } oldSize = m_buffer.size(); } int bytesRead = qMin(m_buffer.size(), int(length)); qMemCopy(buffer, m_buffer.data(), bytesRead); //truncate the buffer m_buffer = m_buffer.mid(bytesRead); if (actual) { *actual = bytesRead; //initialization } return bytesRead == length ? S_OK : S_FALSE; } public: //for Phonon::StreamInterface QByteArray m_buffer; bool m_seekable; qint64 m_pos; qint64 m_size; const MediaGraph *m_mediaGraph; }; IODeviceReader::IODeviceReader(const Phonon::MediaSource &source, const MediaGraph *mg) : QBaseFilter(CLSID_NULL) { //create the output pin m_streamReader = new StreamReader(this, source, mg); } IODeviceReader::~IODeviceReader() { } } } #endif //QT_NO_PHONON_ABSTRACTMEDIASTREAM QT_END_NAMESPACE <commit_msg>Phonon: allows to stream wave files from QIODevice<commit_after>/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). 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 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "iodevicereader.h" #include "qasyncreader.h" #include "mediagraph.h" #include <phonon/streaminterface.h> #include <dshow.h> #include <initguid.h> QT_BEGIN_NAMESPACE #ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM namespace Phonon { namespace DS9 { //these mediatypes define a stream, its type will be autodetected by DirectShow static QVector<AM_MEDIA_TYPE> getMediaTypes() { //the order here is important because otherwise, //directshow might not be able to detect the stream type correctly AM_MEDIA_TYPE mt = { MEDIATYPE_Stream, MEDIASUBTYPE_Avi, TRUE, FALSE, 1, GUID_NULL, 0, 0, 0}; QVector<AM_MEDIA_TYPE> ret; //AVI stream ret << mt; //WAVE stream mt.subtype = MEDIASUBTYPE_WAVE; ret << mt; //normal auto-detect stream (must be at the end!) mt.subtype = MEDIASUBTYPE_NULL; ret << mt; return ret; } class StreamReader : public QAsyncReader, public Phonon::StreamInterface { public: StreamReader(QBaseFilter *parent, const Phonon::MediaSource &source, const MediaGraph *mg) : QAsyncReader(parent, getMediaTypes()), m_seekable(false), m_pos(0), m_size(-1), m_mediaGraph(mg) { connectToSource(source); } //for Phonon::StreamInterface void writeData(const QByteArray &data) { m_pos += data.size(); m_buffer += data; } void endOfData() { } void setStreamSize(qint64 newSize) { QMutexLocker locker(&m_mutex); m_size = newSize; } void setStreamSeekable(bool s) { QMutexLocker locker(&m_mutex); m_seekable = s; } //virtual pure members //implementation from IAsyncReader STDMETHODIMP Length(LONGLONG *total, LONGLONG *available) { QMutexLocker locker(&m_mutex); if (total) { *total = m_size; } if (available) { *available = m_size; } return S_OK; } HRESULT read(LONGLONG pos, LONG length, BYTE *buffer, LONG *actual) { Q_ASSERT(!m_mutex.tryLock()); if (m_mediaGraph->isStopping()) { return VFW_E_WRONG_STATE; } if(m_size != 1 && pos + length > m_size) { //it tries to read outside of the boundaries return E_FAIL; } if (m_pos - m_buffer.size() != pos) { if (!m_seekable) { return S_FALSE; } m_pos = pos; seekStream(pos); m_buffer.clear(); } int oldSize = m_buffer.size(); while (m_buffer.size() < int(length)) { needData(); if (m_mediaGraph->isStopping()) { return VFW_E_WRONG_STATE; } if (oldSize == m_buffer.size()) { break; //we didn't get any data } oldSize = m_buffer.size(); } int bytesRead = qMin(m_buffer.size(), int(length)); qMemCopy(buffer, m_buffer.data(), bytesRead); //truncate the buffer m_buffer = m_buffer.mid(bytesRead); if (actual) { *actual = bytesRead; //initialization } return bytesRead == length ? S_OK : S_FALSE; } public: //for Phonon::StreamInterface QByteArray m_buffer; bool m_seekable; qint64 m_pos; qint64 m_size; const MediaGraph *m_mediaGraph; }; IODeviceReader::IODeviceReader(const Phonon::MediaSource &source, const MediaGraph *mg) : QBaseFilter(CLSID_NULL) { //create the output pin m_streamReader = new StreamReader(this, source, mg); } IODeviceReader::~IODeviceReader() { } } } #endif //QT_NO_PHONON_ABSTRACTMEDIASTREAM QT_END_NAMESPACE <|endoftext|>
<commit_before>#include "opencv.hpp" #include "utilities.hpp" #include "AspectError.hpp" #include <string> #include <ctime> struct HeaderData { timespec captureTime, captureTimeMono; int cameraID; float cameraTemperature; int cpuTemperature; int i2c_temperatures[8]; long frameCount; int exposure; timespec imageWriteTime; int preampGain; int analogGain; float sunCenter[2]; float sunCenterError[2]; int imageMinMax[2]; float XYinterceptslope[4]; double CTLsolution[2]; float screenCenter[2]; float screenCenterError[2]; int fiducialCount; float fiducialX[10]; float fiducialY[10]; int limbCount; float limbX[10]; float limbY[10]; //float limbXerror[10]; //float limbYerror[10]; int fiducialIDX[10]; int fiducialIDY[10]; float cpuVoltage[5]; bool isTracking; bool isOutputting; AspectCode runResult; float latitude; float longitude; float solarTarget[2]; double northAngle; float clockingAngle; }; int writePNGImage(cv::InputArray _image, const std::string fileName); int writeFITSImage(cv::InputArray, HeaderData keys, const std::string fileName); int readFITSImage(const std::string fileName, cv::OutputArray image); int readFITSHeader(const std::string fileName, HeaderData &keys); <commit_msg>removing utilities.hpp<commit_after>#include "opencv.hpp" #include <string> #include <ctime> struct HeaderData { timespec captureTime, captureTimeMono; int cameraID; float cameraTemperature; int cpuTemperature; int i2c_temperatures[8]; long frameCount; int exposure; timespec imageWriteTime; int preampGain; int analogGain; float sunCenter[2]; float sunCenterError[2]; int imageMinMax[2]; float XYinterceptslope[4]; double CTLsolution[2]; float screenCenter[2]; float screenCenterError[2]; int fiducialCount; float fiducialX[10]; float fiducialY[10]; int limbCount; float limbX[10]; float limbY[10]; //float limbXerror[10]; //float limbYerror[10]; int fiducialIDX[10]; int fiducialIDY[10]; float cpuVoltage[5]; bool isTracking; bool isOutputting; float latitude; float longitude; float solarTarget[2]; double northAngle; float clockingAngle; }; int writePNGImage(cv::InputArray _image, const std::string fileName); int writeFITSImage(cv::InputArray, HeaderData keys, const std::string fileName); int readFITSImage(const std::string fileName, cv::OutputArray image); int readFITSHeader(const std::string fileName, HeaderData &keys); <|endoftext|>
<commit_before>//============================================================================================================= /** * @file realtimemultisamplearraydelegate.cpp * @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date May, 2014 * * @section LICENSE * * Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Implementation of the RealTimeMultiSampleArrayDelegate Class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "realtimemultisamplearraydelegate.h" #include "realtimemultisamplearraymodel.h" //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QPainter> #include <QPainterPath> #include <QDebug> #include <QThread> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace XDISPLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= RealTimeMultiSampleArrayDelegate::RealTimeMultiSampleArrayDelegate(QObject *parent) : QAbstractItemDelegate(parent) { } //************************************************************************************************************* void RealTimeMultiSampleArrayDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { float t_fPlotHeight = option.rect.height(); switch(index.column()) { case 0: { //chnames painter->save(); painter->rotate(-90); painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString()); painter->restore(); break; } case 1: { //data plot painter->save(); //draw special background when channel is marked as bad // QVariant v = index.model()->data(index,Qt::BackgroundRole); // if(v.canConvert<QBrush>() && !(option.state & QStyle::State_Selected)) { // QPointF oldBO = painter->brushOrigin(); // painter->setBrushOrigin(option.rect.topLeft()); // painter->fillRect(option.rect, qvariant_cast<QBrush>(v)); // painter->setBrushOrigin(oldBO); // } // //Highlight selected channels // if(option.state & QStyle::State_Selected) { // QPointF oldBO = painter->brushOrigin(); // painter->setBrushOrigin(option.rect.topLeft()); // painter->fillRect(option.rect, option.palette.highlight()); // painter->setBrushOrigin(oldBO); // } //Get data QVariant variant = index.model()->data(index,Qt::DisplayRole); QList< QVector<float> > data = variant.value< QList< QVector<float> > >(); const RealTimeMultiSampleArrayModel* t_pModel = static_cast<const RealTimeMultiSampleArrayModel*>(index.model()); if(data.size() > 0) { // const RealTimeMultiSampleArrayModel* t_rtmsaModel = (static_cast<const RealTimeMultiSampleArrayModel*>(index.model())); QPainterPath path(QPointF(option.rect.x(),option.rect.y()));//QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor()-1,option.rect.y())); //Plot grid painter->setRenderHint(QPainter::Antialiasing, false); createGridPath(index, option, path, data); painter->save(); QPen pen; pen.setStyle(Qt::DotLine); pen.setWidthF(0.5); painter->setPen(pen); painter->drawPath(path); painter->restore(); //Plot data path path = QPainterPath(QPointF(option.rect.x(),option.rect.y()));//QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor(),option.rect.y())); QPainterPath lastPath(QPointF(option.rect.x(),option.rect.y())); createPlotPath(index, option, path, lastPath, data[0], data[1]); painter->save(); painter->translate(0,t_fPlotHeight/2); painter->setRenderHint(QPainter::Antialiasing, true); if(option.state & QStyle::State_Selected) painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine)); else painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine)); painter->drawPath(path); painter->restore(); //Plot last data path painter->translate(0,t_fPlotHeight/2); painter->setRenderHint(QPainter::Antialiasing, true); if(option.state & QStyle::State_Selected) painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine)); else painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine)); painter->drawPath(lastPath); painter->restore(); } break; } } } //************************************************************************************************************* QSize RealTimeMultiSampleArrayDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QSize size; switch(index.column()) { case 0: size = QSize(20,option.rect.height()); break; case 1: QList< QVector<float> > data = index.model()->data(index).value< QList<QVector<float> > >(); // qint32 nsamples = (static_cast<const RealTimeMultiSampleArrayModel*>(index.model()))->lastSample()-(static_cast<const RealTimeMultiSampleArrayModel*>(index.model()))->firstSample(); // size = QSize(nsamples*m_dDx,m_dPlotHeight); Q_UNUSED(option); break; } return size; } //************************************************************************************************************* void RealTimeMultiSampleArrayDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QPainterPath& lastPath, QVector<float>& data, QVector<float>& lastData) const { const RealTimeMultiSampleArrayModel* t_pModel = static_cast<const RealTimeMultiSampleArrayModel*>(index.model()); //get maximum range of respective channel type (range value in FiffChInfo does not seem to contain a reasonable value) qint32 kind = t_pModel->getKind(index.row()); float fMaxValue = 1e-9f; float Amp = 1e-9f; switch(kind) { case FIFFV_MEG_CH: { qint32 unit =t_pModel->getUnit(index.row()); if(unit == FIFF_UNIT_T_M) { fMaxValue = 1e-10f; if(t_pModel->getScaling().contains(FIFF_UNIT_T_M)) fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T_M]; } else if(unit == FIFF_UNIT_T) { if(t_pModel->getCoil(index.row()) == FIFFV_COIL_BABY_MAG) fMaxValue = 1e-11f; else fMaxValue = 1e-11f; if(t_pModel->getScaling().contains(FIFF_UNIT_T)) fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T]; } Amp = 1e-10f; break; } case FIFFV_REF_MEG_CH: { /*11/04/14 Added by Limin: MEG reference channel */ fMaxValue = 1e-11f; if(t_pModel->getScaling().contains(FIFF_UNIT_T)) fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T]; Amp = 1e-10f; break; } case FIFFV_EEG_CH: { fMaxValue = 1e-4f; if(t_pModel->getScaling().contains(FIFFV_EEG_CH)) fMaxValue = t_pModel->getScaling()[FIFFV_EEG_CH]; Amp = 1e-4f; break; } case FIFFV_EOG_CH: { fMaxValue = 1e-3f; if(t_pModel->getScaling().contains(FIFFV_EOG_CH)) fMaxValue = t_pModel->getScaling()[FIFFV_EOG_CH]; Amp = 1e-3f; break; } case FIFFV_STIM_CH: { fMaxValue = 5; if(t_pModel->getScaling().contains(FIFFV_STIM_CH)) fMaxValue = t_pModel->getScaling()[FIFFV_STIM_CH]; Amp = 1.0f; break; } case FIFFV_MISC_CH: { fMaxValue = 1e-3f; if(t_pModel->getScaling().contains(FIFFV_MISC_CH)) fMaxValue = t_pModel->getScaling()[FIFFV_MISC_CH]; Amp = 1e-3f; break; } } float fValue; //float fScaleY = option.rect.height()/(2*fMaxValue); float fScaleY = Amp / fMaxValue; float y_base = path.currentPosition().y(); QPointF qSamplePosition; float fDx = ((float)option.rect.width()) / t_pModel->getMaxSamples(); //Move to initial starting point if(data.size() > 0) { // float val = data[0]; fValue = 0;//(val-data[0])*fScaleY; float newY = y_base-fValue;//Reverse direction -> plot the right way qSamplePosition.setY(newY); qSamplePosition.setX(path.currentPosition().x()); path.moveTo(qSamplePosition); } //create lines from one to the next sample qint32 i; for(i = 1; i < data.size(); ++i) { float val = data[i] - data[0]; //remove first sample data[0] as offset fValue = val*fScaleY; //qDebug()<<"val"<<val<<"fScaleY"<<fScaleY<<"fValue"<<fValue; float newY = y_base-fValue;//Reverse direction -> plot the right way qSamplePosition.setY(newY); qSamplePosition.setX(path.currentPosition().x()+fDx); path.lineTo(qSamplePosition); } //create lines from one to the next sample for last path qint32 sample_offset = t_pModel->numVLines() + 1; qSamplePosition.setX(qSamplePosition.x() + fDx*sample_offset); lastPath.moveTo(qSamplePosition); for(i += sample_offset; i < lastData.size(); ++i) { float val = lastData[i] - lastData[0]; //remove first sample lastData[0] as offset fValue = val*fScaleY; float newY = y_base-fValue; qSamplePosition.setY(newY); qSamplePosition.setX(lastPath.currentPosition().x()+fDx); lastPath.lineTo(qSamplePosition); } } //************************************************************************************************************* void RealTimeMultiSampleArrayDelegate::createGridPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QList< QVector<float> >& data) const { Q_UNUSED(data) const RealTimeMultiSampleArrayModel* t_pModel = static_cast<const RealTimeMultiSampleArrayModel*>(index.model()); if(t_pModel->numVLines() > 0) { //horizontal lines float distance = option.rect.width()/(t_pModel->numVLines()+1); float yStart = option.rect.topLeft().y(); float yEnd = option.rect.bottomRight().y(); for(qint8 i = 0; i < t_pModel->numVLines(); ++i) { float x = distance*(i+1); path.moveTo(x,yStart); path.lineTo(x,yEnd); } } } <commit_msg>corrected scaling<commit_after>//============================================================================================================= /** * @file realtimemultisamplearraydelegate.cpp * @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date May, 2014 * * @section LICENSE * * Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Implementation of the RealTimeMultiSampleArrayDelegate Class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "realtimemultisamplearraydelegate.h" #include "realtimemultisamplearraymodel.h" //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QPainter> #include <QPainterPath> #include <QDebug> #include <QThread> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace XDISPLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= RealTimeMultiSampleArrayDelegate::RealTimeMultiSampleArrayDelegate(QObject *parent) : QAbstractItemDelegate(parent) { } //************************************************************************************************************* void RealTimeMultiSampleArrayDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { float t_fPlotHeight = option.rect.height(); switch(index.column()) { case 0: { //chnames painter->save(); painter->rotate(-90); painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString()); painter->restore(); break; } case 1: { //data plot painter->save(); //draw special background when channel is marked as bad // QVariant v = index.model()->data(index,Qt::BackgroundRole); // if(v.canConvert<QBrush>() && !(option.state & QStyle::State_Selected)) { // QPointF oldBO = painter->brushOrigin(); // painter->setBrushOrigin(option.rect.topLeft()); // painter->fillRect(option.rect, qvariant_cast<QBrush>(v)); // painter->setBrushOrigin(oldBO); // } // //Highlight selected channels // if(option.state & QStyle::State_Selected) { // QPointF oldBO = painter->brushOrigin(); // painter->setBrushOrigin(option.rect.topLeft()); // painter->fillRect(option.rect, option.palette.highlight()); // painter->setBrushOrigin(oldBO); // } //Get data QVariant variant = index.model()->data(index,Qt::DisplayRole); QList< QVector<float> > data = variant.value< QList< QVector<float> > >(); const RealTimeMultiSampleArrayModel* t_pModel = static_cast<const RealTimeMultiSampleArrayModel*>(index.model()); if(data.size() > 0) { // const RealTimeMultiSampleArrayModel* t_rtmsaModel = (static_cast<const RealTimeMultiSampleArrayModel*>(index.model())); QPainterPath path(QPointF(option.rect.x(),option.rect.y()));//QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor()-1,option.rect.y())); //Plot grid painter->setRenderHint(QPainter::Antialiasing, false); createGridPath(index, option, path, data); painter->save(); QPen pen; pen.setStyle(Qt::DotLine); pen.setWidthF(0.5); painter->setPen(pen); painter->drawPath(path); painter->restore(); //Plot data path path = QPainterPath(QPointF(option.rect.x(),option.rect.y()));//QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor(),option.rect.y())); QPainterPath lastPath(QPointF(option.rect.x(),option.rect.y())); createPlotPath(index, option, path, lastPath, data[0], data[1]); painter->save(); painter->translate(0,t_fPlotHeight/2); painter->setRenderHint(QPainter::Antialiasing, true); if(option.state & QStyle::State_Selected) painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine)); else painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine)); painter->drawPath(path); painter->restore(); //Plot last data path painter->translate(0,t_fPlotHeight/2); painter->setRenderHint(QPainter::Antialiasing, true); if(option.state & QStyle::State_Selected) painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine)); else painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine)); painter->drawPath(lastPath); painter->restore(); } break; } } } //************************************************************************************************************* QSize RealTimeMultiSampleArrayDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QSize size; switch(index.column()) { case 0: size = QSize(20,option.rect.height()); break; case 1: QList< QVector<float> > data = index.model()->data(index).value< QList<QVector<float> > >(); // qint32 nsamples = (static_cast<const RealTimeMultiSampleArrayModel*>(index.model()))->lastSample()-(static_cast<const RealTimeMultiSampleArrayModel*>(index.model()))->firstSample(); // size = QSize(nsamples*m_dDx,m_dPlotHeight); Q_UNUSED(option); break; } return size; } //************************************************************************************************************* void RealTimeMultiSampleArrayDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QPainterPath& lastPath, QVector<float>& data, QVector<float>& lastData) const { const RealTimeMultiSampleArrayModel* t_pModel = static_cast<const RealTimeMultiSampleArrayModel*>(index.model()); //get maximum range of respective channel type (range value in FiffChInfo does not seem to contain a reasonable value) qint32 kind = t_pModel->getKind(index.row()); float fMaxValue = 1e-9f; // float Amp = 1e-9f; switch(kind) { case FIFFV_MEG_CH: { qint32 unit =t_pModel->getUnit(index.row()); if(unit == FIFF_UNIT_T_M) { fMaxValue = 1e-10f; if(t_pModel->getScaling().contains(FIFF_UNIT_T_M)) fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T_M]; } else if(unit == FIFF_UNIT_T) { if(t_pModel->getCoil(index.row()) == FIFFV_COIL_BABY_MAG) fMaxValue = 1e-11f; else fMaxValue = 1e-11f; if(t_pModel->getScaling().contains(FIFF_UNIT_T)) fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T]; } // Amp = 1e-10f; break; } case FIFFV_REF_MEG_CH: { /*11/04/14 Added by Limin: MEG reference channel */ fMaxValue = 1e-11f; if(t_pModel->getScaling().contains(FIFF_UNIT_T)) fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T]; // Amp = 1e-10f; break; } case FIFFV_EEG_CH: { fMaxValue = 1e-4f; if(t_pModel->getScaling().contains(FIFFV_EEG_CH)) fMaxValue = t_pModel->getScaling()[FIFFV_EEG_CH]; // Amp = 1e-4f; break; } case FIFFV_EOG_CH: { fMaxValue = 1e-3f; if(t_pModel->getScaling().contains(FIFFV_EOG_CH)) fMaxValue = t_pModel->getScaling()[FIFFV_EOG_CH]; // Amp = 1e-3f; break; } case FIFFV_STIM_CH: { fMaxValue = 5; if(t_pModel->getScaling().contains(FIFFV_STIM_CH)) fMaxValue = t_pModel->getScaling()[FIFFV_STIM_CH]; // Amp = 1.0f; break; } case FIFFV_MISC_CH: { fMaxValue = 1e-3f; if(t_pModel->getScaling().contains(FIFFV_MISC_CH)) fMaxValue = t_pModel->getScaling()[FIFFV_MISC_CH]; // Amp = 1e-3f; break; } } float fValue; float fScaleY = option.rect.height()/(2*fMaxValue); // float fScaleY = Amp / fMaxValue; float y_base = path.currentPosition().y(); QPointF qSamplePosition; float fDx = ((float)option.rect.width()) / t_pModel->getMaxSamples(); //Move to initial starting point if(data.size() > 0) { // float val = data[0]; fValue = 0;//(val-data[0])*fScaleY; float newY = y_base-fValue;//Reverse direction -> plot the right way qSamplePosition.setY(newY); qSamplePosition.setX(path.currentPosition().x()); path.moveTo(qSamplePosition); } //create lines from one to the next sample qint32 i; for(i = 1; i < data.size(); ++i) { float val = data[i] - data[0]; //remove first sample data[0] as offset fValue = val*fScaleY; //qDebug()<<"val"<<val<<"fScaleY"<<fScaleY<<"fValue"<<fValue; float newY = y_base-fValue;//Reverse direction -> plot the right way qSamplePosition.setY(newY); qSamplePosition.setX(path.currentPosition().x()+fDx); path.lineTo(qSamplePosition); } //create lines from one to the next sample for last path qint32 sample_offset = t_pModel->numVLines() + 1; qSamplePosition.setX(qSamplePosition.x() + fDx*sample_offset); lastPath.moveTo(qSamplePosition); for(i += sample_offset; i < lastData.size(); ++i) { float val = lastData[i] - lastData[0]; //remove first sample lastData[0] as offset fValue = val*fScaleY; float newY = y_base-fValue; qSamplePosition.setY(newY); qSamplePosition.setX(lastPath.currentPosition().x()+fDx); lastPath.lineTo(qSamplePosition); } } //************************************************************************************************************* void RealTimeMultiSampleArrayDelegate::createGridPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QList< QVector<float> >& data) const { Q_UNUSED(data) const RealTimeMultiSampleArrayModel* t_pModel = static_cast<const RealTimeMultiSampleArrayModel*>(index.model()); if(t_pModel->numVLines() > 0) { //horizontal lines float distance = option.rect.width()/(t_pModel->numVLines()+1); float yStart = option.rect.topLeft().y(); float yEnd = option.rect.bottomRight().y(); for(qint8 i = 0; i < t_pModel->numVLines(); ++i) { float x = distance*(i+1); path.moveTo(x,yStart); path.lineTo(x,yEnd); } } } <|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. */ // This file was copied from apache::thrift::server::TThreadedServer.cpp v0.9.0, with the // significant changes noted inline below. #include "rpc/TAcceptQueueServer.h" #include <thrift/concurrency/PlatformThreadFactory.h> #include "util/thread-pool.h" DEFINE_int32(accepted_cnxn_queue_depth, 10000, "(Advanced) The size of the post-accept, pre-setup connection queue for Impala " "internal connections"); namespace apache { namespace thrift { namespace server { using boost::shared_ptr; using namespace std; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::concurrency; using namespace impala; class TAcceptQueueServer::Task : public Runnable { public: Task(TAcceptQueueServer& server, shared_ptr<TProcessor> processor, shared_ptr<TProtocol> input, shared_ptr<TProtocol> output, shared_ptr<TTransport> transport) : server_(server), processor_(std::move(processor)), input_(std::move(input)), output_(std::move(output)), transport_(std::move(transport)) {} ~Task() override = default; void run() override { boost::shared_ptr<TServerEventHandler> eventHandler = server_.getEventHandler(); void* connectionContext = nullptr; if (eventHandler != nullptr) { connectionContext = eventHandler->createContext(input_, output_); } try { for (;;) { if (eventHandler != nullptr) { eventHandler->processContext(connectionContext, transport_); } if (!processor_->process(input_, output_, connectionContext) || !input_->getTransport()->peek()) { break; } } } catch (const TTransportException& ttx) { if (ttx.getType() != TTransportException::END_OF_FILE) { string errStr = string("TAcceptQueueServer client died: ") + ttx.what(); GlobalOutput(errStr.c_str()); } } catch (const std::exception& x) { GlobalOutput.printf( "TAcceptQueueServer exception: %s: %s", typeid(x).name(), x.what()); } catch (...) { GlobalOutput("TAcceptQueueServer uncaught exception."); } if (eventHandler != nullptr) { eventHandler->deleteContext(connectionContext, input_, output_); } try { input_->getTransport()->close(); } catch (TTransportException& ttx) { string errStr = string("TAcceptQueueServer input close failed: ") + ttx.what(); GlobalOutput(errStr.c_str()); } try { output_->getTransport()->close(); } catch (TTransportException& ttx) { string errStr = string("TAcceptQueueServer output close failed: ") + ttx.what(); GlobalOutput(errStr.c_str()); } // Remove this task from parent bookkeeping { Synchronized s(server_.tasksMonitor_); server_.tasks_.erase(this); server_.tasksMonitor_.notify(); } } private: TAcceptQueueServer& server_; friend class TAcceptQueueServer; shared_ptr<TProcessor> processor_; shared_ptr<TProtocol> input_; shared_ptr<TProtocol> output_; shared_ptr<TTransport> transport_; }; TAcceptQueueServer::TAcceptQueueServer(const boost::shared_ptr<TProcessor>& processor, const boost::shared_ptr<TServerTransport>& serverTransport, const boost::shared_ptr<TTransportFactory>& transportFactory, const boost::shared_ptr<TProtocolFactory>& protocolFactory, const boost::shared_ptr<ThreadFactory>& threadFactory, int32_t maxTasks) : TServer(processor, serverTransport, transportFactory, protocolFactory), threadFactory_(threadFactory), maxTasks_(maxTasks) { init(); } void TAcceptQueueServer::init() { stop_ = false; metrics_enabled_ = false; queue_size_metric_ = nullptr; if (!threadFactory_) { threadFactory_.reset(new PlatformThreadFactory); } } // New. void TAcceptQueueServer::SetupConnection(boost::shared_ptr<TTransport> client) { if (metrics_enabled_) queue_size_metric_->Increment(-1); shared_ptr<TTransport> inputTransport; shared_ptr<TTransport> outputTransport; try { inputTransport = inputTransportFactory_->getTransport(client); outputTransport = outputTransportFactory_->getTransport(client); shared_ptr<TProtocol> inputProtocol = inputProtocolFactory_->getProtocol(inputTransport); shared_ptr<TProtocol> outputProtocol = outputProtocolFactory_->getProtocol(outputTransport); shared_ptr<TProcessor> processor = getProcessor(inputProtocol, outputProtocol, client); TAcceptQueueServer::Task* task = new TAcceptQueueServer::Task( *this, processor, inputProtocol, outputProtocol, client); // Create a task shared_ptr<Runnable> runnable = shared_ptr<Runnable>(task); // Create a thread for this task shared_ptr<Thread> thread = shared_ptr<Thread>(threadFactory_->newThread(runnable)); // Insert thread into the set of threads { Synchronized s(tasksMonitor_); while (maxTasks_ > 0 && tasks_.size() >= maxTasks_) { tasksMonitor_.wait(); } tasks_.insert(task); } // Start the thread! thread->start(); } catch (TException& tx) { if (inputTransport != nullptr) { inputTransport->close(); } if (outputTransport != nullptr) { outputTransport->close(); } if (client != nullptr) { client->close(); } string errStr = string("TAcceptQueueServer: Caught TException: ") + tx.what(); GlobalOutput(errStr.c_str()); } catch (string s) { if (inputTransport != nullptr) { inputTransport->close(); } if (outputTransport != nullptr) { outputTransport->close(); } if (client != nullptr) { client->close(); } string errStr = "TAcceptQueueServer: Unknown exception: " + s; GlobalOutput(errStr.c_str()); } } void TAcceptQueueServer::serve() { // Start the server listening serverTransport_->listen(); // Run the preServe event if (eventHandler_ != nullptr) { eventHandler_->preServe(); } // Only using one thread here is sufficient for performance, and it avoids potential // thread safety issues with the thrift code called in SetupConnection. constexpr int CONNECTION_SETUP_POOL_SIZE = 1; // New - this is the thread pool used to process the internal accept queue. ThreadPool<shared_ptr<TTransport>> connection_setup_pool("setup-server", "setup-worker", CONNECTION_SETUP_POOL_SIZE, FLAGS_accepted_cnxn_queue_depth, [this](int tid, const shared_ptr<TTransport>& item) { this->SetupConnection(item); }); // Initialize the thread pool Status status = connection_setup_pool.Init(); if (!status.ok()) { status.AddDetail("TAcceptQueueServer: thread pool could not start."); string errStr = status.GetDetail(); GlobalOutput(errStr.c_str()); stop_ = true; } while (!stop_) { try { // Fetch client from server shared_ptr<TTransport> client = serverTransport_->accept(); // New - the work done to setup the connection has been moved to SetupConnection. if (!connection_setup_pool.Offer(std::move(client))) { string errStr = string("TAcceptQueueServer: thread pool unexpectedly shut down."); GlobalOutput(errStr.c_str()); stop_ = true; break; } if (metrics_enabled_) queue_size_metric_->Increment(1); } catch (TTransportException& ttx) { if (!stop_ || ttx.getType() != TTransportException::INTERRUPTED) { string errStr = string("TAcceptQueueServer: TServerTransport died on accept: ") + ttx.what(); GlobalOutput(errStr.c_str()); } continue; } catch (TException& tx) { string errStr = string("TAcceptQueueServer: Caught TException: ") + tx.what(); GlobalOutput(errStr.c_str()); continue; } catch (string s) { string errStr = "TAcceptQueueServer: Unknown exception: " + s; GlobalOutput(errStr.c_str()); break; } } // If stopped manually, make sure to close server transport if (stop_) { try { serverTransport_->close(); connection_setup_pool.Shutdown(); } catch (TException& tx) { string errStr = string("TAcceptQueueServer: Exception shutting down: ") + tx.what(); GlobalOutput(errStr.c_str()); } try { Synchronized s(tasksMonitor_); while (!tasks_.empty()) { tasksMonitor_.wait(); } } catch (TException& tx) { string errStr = string("TAcceptQueueServer: Exception joining workers: ") + tx.what(); GlobalOutput(errStr.c_str()); } stop_ = false; } } void TAcceptQueueServer::InitMetrics(MetricGroup* metrics, const string& key_prefix) { DCHECK(metrics != nullptr); stringstream queue_size_ss; queue_size_ss << key_prefix << ".connection-setup-queue-size"; queue_size_metric_ = metrics->AddGauge(queue_size_ss.str(), 0); metrics_enabled_ = true; } } // namespace server } // namespace thrift } // namespace apache <commit_msg>IMPALA-7565: Add startup flag to set thrift connection setup thread pool size<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. */ // This file was copied from apache::thrift::server::TThreadedServer.cpp v0.9.0, with the // significant changes noted inline below. #include "rpc/TAcceptQueueServer.h" #include <thrift/concurrency/PlatformThreadFactory.h> #include "util/thread-pool.h" DEFINE_int32(accepted_cnxn_queue_depth, 10000, "(Advanced) The size of the post-accept, pre-setup connection queue in each thrift " "server set up to service Impala internal and external connections."); DEFINE_int32_hidden(accepted_cnxn_setup_thread_pool_size, 1, "(Advanced) The size of the thread pool that is used to process the " "post-accept, pre-setup connection queue in each thrift server set up to service " "Impala internal and external connections. Warning: This is untested for values " "greater than 1 which might exhibit unpredictable behavior and/or cause crashes."); namespace apache { namespace thrift { namespace server { using boost::shared_ptr; using namespace std; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::concurrency; using namespace impala; class TAcceptQueueServer::Task : public Runnable { public: Task(TAcceptQueueServer& server, shared_ptr<TProcessor> processor, shared_ptr<TProtocol> input, shared_ptr<TProtocol> output, shared_ptr<TTransport> transport) : server_(server), processor_(std::move(processor)), input_(std::move(input)), output_(std::move(output)), transport_(std::move(transport)) {} ~Task() override = default; void run() override { boost::shared_ptr<TServerEventHandler> eventHandler = server_.getEventHandler(); void* connectionContext = nullptr; if (eventHandler != nullptr) { connectionContext = eventHandler->createContext(input_, output_); } try { for (;;) { if (eventHandler != nullptr) { eventHandler->processContext(connectionContext, transport_); } if (!processor_->process(input_, output_, connectionContext) || !input_->getTransport()->peek()) { break; } } } catch (const TTransportException& ttx) { if (ttx.getType() != TTransportException::END_OF_FILE) { string errStr = string("TAcceptQueueServer client died: ") + ttx.what(); GlobalOutput(errStr.c_str()); } } catch (const std::exception& x) { GlobalOutput.printf( "TAcceptQueueServer exception: %s: %s", typeid(x).name(), x.what()); } catch (...) { GlobalOutput("TAcceptQueueServer uncaught exception."); } if (eventHandler != nullptr) { eventHandler->deleteContext(connectionContext, input_, output_); } try { input_->getTransport()->close(); } catch (TTransportException& ttx) { string errStr = string("TAcceptQueueServer input close failed: ") + ttx.what(); GlobalOutput(errStr.c_str()); } try { output_->getTransport()->close(); } catch (TTransportException& ttx) { string errStr = string("TAcceptQueueServer output close failed: ") + ttx.what(); GlobalOutput(errStr.c_str()); } // Remove this task from parent bookkeeping { Synchronized s(server_.tasksMonitor_); server_.tasks_.erase(this); server_.tasksMonitor_.notify(); } } private: TAcceptQueueServer& server_; friend class TAcceptQueueServer; shared_ptr<TProcessor> processor_; shared_ptr<TProtocol> input_; shared_ptr<TProtocol> output_; shared_ptr<TTransport> transport_; }; TAcceptQueueServer::TAcceptQueueServer(const boost::shared_ptr<TProcessor>& processor, const boost::shared_ptr<TServerTransport>& serverTransport, const boost::shared_ptr<TTransportFactory>& transportFactory, const boost::shared_ptr<TProtocolFactory>& protocolFactory, const boost::shared_ptr<ThreadFactory>& threadFactory, int32_t maxTasks) : TServer(processor, serverTransport, transportFactory, protocolFactory), threadFactory_(threadFactory), maxTasks_(maxTasks) { init(); } void TAcceptQueueServer::init() { stop_ = false; metrics_enabled_ = false; queue_size_metric_ = nullptr; if (!threadFactory_) { threadFactory_.reset(new PlatformThreadFactory); } } // New. void TAcceptQueueServer::SetupConnection(boost::shared_ptr<TTransport> client) { if (metrics_enabled_) queue_size_metric_->Increment(-1); shared_ptr<TTransport> inputTransport; shared_ptr<TTransport> outputTransport; try { inputTransport = inputTransportFactory_->getTransport(client); outputTransport = outputTransportFactory_->getTransport(client); shared_ptr<TProtocol> inputProtocol = inputProtocolFactory_->getProtocol(inputTransport); shared_ptr<TProtocol> outputProtocol = outputProtocolFactory_->getProtocol(outputTransport); shared_ptr<TProcessor> processor = getProcessor(inputProtocol, outputProtocol, client); TAcceptQueueServer::Task* task = new TAcceptQueueServer::Task( *this, processor, inputProtocol, outputProtocol, client); // Create a task shared_ptr<Runnable> runnable = shared_ptr<Runnable>(task); // Create a thread for this task shared_ptr<Thread> thread = shared_ptr<Thread>(threadFactory_->newThread(runnable)); // Insert thread into the set of threads { Synchronized s(tasksMonitor_); while (maxTasks_ > 0 && tasks_.size() >= maxTasks_) { tasksMonitor_.wait(); } tasks_.insert(task); } // Start the thread! thread->start(); } catch (TException& tx) { if (inputTransport != nullptr) { inputTransport->close(); } if (outputTransport != nullptr) { outputTransport->close(); } if (client != nullptr) { client->close(); } string errStr = string("TAcceptQueueServer: Caught TException: ") + tx.what(); GlobalOutput(errStr.c_str()); } catch (string s) { if (inputTransport != nullptr) { inputTransport->close(); } if (outputTransport != nullptr) { outputTransport->close(); } if (client != nullptr) { client->close(); } string errStr = "TAcceptQueueServer: Unknown exception: " + s; GlobalOutput(errStr.c_str()); } } void TAcceptQueueServer::serve() { // Start the server listening serverTransport_->listen(); // Run the preServe event if (eventHandler_ != nullptr) { eventHandler_->preServe(); } if (FLAGS_accepted_cnxn_setup_thread_pool_size > 1) { LOG(WARNING) << "connection_setup_thread_pool_size is set to " << FLAGS_accepted_cnxn_setup_thread_pool_size << ". Values greater than 1 are untested and might exhibit " "unpredictable behavior and/or cause crashes."; } // New - this is the thread pool used to process the internal accept queue. // TODO: IMPALA-7565: Make sure the related thrift code is thread safe and subsequently // enable multi-threading by default. ThreadPool<shared_ptr<TTransport>> connection_setup_pool("setup-server", "setup-worker", FLAGS_accepted_cnxn_setup_thread_pool_size, FLAGS_accepted_cnxn_queue_depth, [this](int tid, const shared_ptr<TTransport>& item) { this->SetupConnection(item); }); // Initialize the thread pool Status status = connection_setup_pool.Init(); if (!status.ok()) { status.AddDetail("TAcceptQueueServer: thread pool could not start."); string errStr = status.GetDetail(); GlobalOutput(errStr.c_str()); stop_ = true; } while (!stop_) { try { // Fetch client from server shared_ptr<TTransport> client = serverTransport_->accept(); // New - the work done to setup the connection has been moved to SetupConnection. if (!connection_setup_pool.Offer(std::move(client))) { string errStr = string("TAcceptQueueServer: thread pool unexpectedly shut down."); GlobalOutput(errStr.c_str()); stop_ = true; break; } if (metrics_enabled_) queue_size_metric_->Increment(1); } catch (TTransportException& ttx) { if (!stop_ || ttx.getType() != TTransportException::INTERRUPTED) { string errStr = string("TAcceptQueueServer: TServerTransport died on accept: ") + ttx.what(); GlobalOutput(errStr.c_str()); } continue; } catch (TException& tx) { string errStr = string("TAcceptQueueServer: Caught TException: ") + tx.what(); GlobalOutput(errStr.c_str()); continue; } catch (string s) { string errStr = "TAcceptQueueServer: Unknown exception: " + s; GlobalOutput(errStr.c_str()); break; } } // If stopped manually, make sure to close server transport if (stop_) { try { serverTransport_->close(); connection_setup_pool.Shutdown(); } catch (TException& tx) { string errStr = string("TAcceptQueueServer: Exception shutting down: ") + tx.what(); GlobalOutput(errStr.c_str()); } try { Synchronized s(tasksMonitor_); while (!tasks_.empty()) { tasksMonitor_.wait(); } } catch (TException& tx) { string errStr = string("TAcceptQueueServer: Exception joining workers: ") + tx.what(); GlobalOutput(errStr.c_str()); } stop_ = false; } } void TAcceptQueueServer::InitMetrics(MetricGroup* metrics, const string& key_prefix) { DCHECK(metrics != nullptr); stringstream queue_size_ss; queue_size_ss << key_prefix << ".connection-setup-queue-size"; queue_size_metric_ = metrics->AddGauge(queue_size_ss.str(), 0); metrics_enabled_ = true; } } // namespace server } // namespace thrift } // namespace apache <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2008 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * 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., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <boost/uuid/uuid_io.hpp> #endif #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepAdaptor_Curve.hxx> #include <gp_Circ.hxx> #include <Geom_Circle.hxx> #include <App/Material.h> #include <Base/Console.h> #include <Base/Vector3D.h> #include <Base/VectorPy.h> #include <Base/GeometryPyCXX.h> #include "DrawUtil.h" #include "Geometry.h" #include "Cosmetic.h" #include "CosmeticEdgePy.h" #include "CosmeticEdgePy.cpp" using namespace TechDraw; // returns a string which represents the object e.g. when printed in python std::string CosmeticEdgePy::representation(void) const { std::stringstream ss; ss << "<CosmeticEdge object> at " << std::hex << this; return ss.str(); // return "<CosmeticEdge object>"; } PyObject *CosmeticEdgePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper { // never create such objects with the constructor PyErr_SetString(PyExc_RuntimeError, "You cannot create an instance of the abstract class 'CosmeticEdge'."); return 0; } // constructor method int CosmeticEdgePy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) { return 0; } //From Part::GeometryPy.cpp PyObject* CosmeticEdgePy::clone(PyObject *args) { if (!PyArg_ParseTuple(args, "")) return NULL; TechDraw::CosmeticEdge* geom = this->getCosmeticEdgePtr(); PyTypeObject* type = this->GetType(); PyObject* cpy = 0; // let the type object decide if (type->tp_new) cpy = type->tp_new(type, this, 0); if (!cpy) { PyErr_SetString(PyExc_TypeError, "failed to create clone of CosmeticEdge"); return 0; } TechDraw::CosmeticEdgePy* geompy = static_cast<TechDraw::CosmeticEdgePy*>(cpy); // the PyMake function must have created the corresponding instance of the 'CosmeticEdge' subclass // so delete it now to avoid a memory leak if (geompy->_pcTwinPointer) { TechDraw::CosmeticEdge* clone = static_cast<TechDraw::CosmeticEdge*>(geompy->_pcTwinPointer); delete clone; } geompy->_pcTwinPointer = geom->clone(); return cpy; } PyObject* CosmeticEdgePy::copy(PyObject *args) { if (!PyArg_ParseTuple(args, "")) return NULL; TechDraw::CosmeticEdge* geom = this->getCosmeticEdgePtr(); PyTypeObject* type = this->GetType(); PyObject* cpy = 0; // let the type object decide if (type->tp_new) cpy = type->tp_new(type, this, 0); if (!cpy) { PyErr_SetString(PyExc_TypeError, "failed to create copy of CosmeticEdge"); return 0; } TechDraw::CosmeticEdgePy* geompy = static_cast<TechDraw::CosmeticEdgePy*>(cpy); // the PyMake function must have created the corresponding instance of the 'CosmeticEdge' subclass // so delete it now to avoid a memory leak if (geompy->_pcTwinPointer) { TechDraw::CosmeticEdge* copy = static_cast<TechDraw::CosmeticEdge*>(geompy->_pcTwinPointer); delete copy; } geompy->_pcTwinPointer = geom->copy(); return cpy; } void CosmeticEdgePy::setFormat(Py::Object arg) { PyObject* pTuple = arg.ptr(); int style = 1; double weight = 0.50; double red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0; App::Color c(red, blue, green, alpha); bool visible = 1; TechDraw::CosmeticEdge* ce = this->getCosmeticEdgePtr(); if (PyTuple_Check(pTuple)) { int tSize = (int) PyTuple_Size(pTuple); if (tSize > 3) { PyObject* pStyle = PyTuple_GetItem(pTuple,0); style = (int) PyLong_AsLong(pStyle); PyObject* pWeight = PyTuple_GetItem(pTuple,1); weight = PyFloat_AsDouble(pWeight); PyObject* pColor = PyTuple_GetItem(pTuple,2); c = DrawUtil::pyTupleToColor(pColor); PyObject* pVisible = PyTuple_GetItem(pTuple,3); visible = (bool) PyLong_AsLong(pVisible); ce->m_format.m_style = style; ce->m_format.m_weight = weight; ce->m_format.m_color = c; ce->m_format.m_visible = visible; } } else { Base::Console().Error("CEPI::setFormat - not a tuple!\n"); } } Py::Object CosmeticEdgePy::getFormat(void) const { TechDraw::CosmeticEdge* ce = this->getCosmeticEdgePtr(); PyObject* pStyle = PyLong_FromLong((long) ce->m_format.m_style); PyObject* pWeight = PyFloat_FromDouble(ce->m_format.m_weight); PyObject* pColor = DrawUtil::colorToPyTuple(ce->m_format.m_color); PyObject* pVisible = PyBool_FromLong((long) ce->m_format.m_visible); PyObject* result = PyTuple_New(4); PyTuple_SET_ITEM(result, 0, pStyle); PyTuple_SET_ITEM(result, 1, pWeight); PyTuple_SET_ITEM(result, 2, pColor); PyTuple_SET_ITEM(result, 3, pVisible); return Py::asObject(result); } Py::String CosmeticEdgePy::getTag(void) const { std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getTag()); return Py::String(tmp); } //Py::String CosmeticEdgePy::getOwner(void) const //{ //// std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getOwner()); // std::string tmp = "not implemented yet"; // return Py::String(tmp); //} //TODO: make BaseGeom py-aware or convert TD geometry to ??Part::Geometry2d?? or other // py-aware class. //Py::Object CosmeticEdgePy::getGeometry(void) const //{ //// TechDraw::BaseGeom* bg = getCosmeticEdgePtr()->m_geometry; // Base::Console().Message("Not implemented yet"); // return Py::asObject(Py_None); //} //void CosmeticEdgePy::setGeometry(Py::Object arg) //{ // Base::Console().Message("Not implemented yet"); // PyObject* p = arg.ptr(); // if (PyObject_TypeCheck(p, &(TechDraw::BaseGeomPy::Type))) { // //TODO // } else { // std::string error = std::string("type must be 'BaseGeom', not "); // error += p->ob_type->tp_name; // throw Py::TypeError(error); // } //} Py::Object CosmeticEdgePy::getStart(void) const { Base::Vector3d point = getCosmeticEdgePtr()->permaStart; return Py::asObject(new Base::VectorPy(point)); } void CosmeticEdgePy::setStart(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d pNew; if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { pNew = static_cast<Base::VectorPy*>(p)->value(); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { pNew = Base::getVectorFromTuple<double>(p); } else { std::string error = std::string("type must be 'Vector', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); } pNew = DrawUtil::invertY(pNew); Base::Vector3d pEnd = getCosmeticEdgePtr()->permaEnd; pEnd = DrawUtil::invertY(pEnd); gp_Pnt gp1(pNew.x,pNew.y,pNew.z); gp_Pnt gp2(pEnd.x,pEnd.y,pEnd.z); TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); auto oldGeom = getCosmeticEdgePtr()->m_geometry; getCosmeticEdgePtr()->m_geometry = TechDraw::BaseGeom::baseFactory(e); getCosmeticEdgePtr()->permaStart = pNew; delete oldGeom; } Py::Object CosmeticEdgePy::getEnd(void) const { Base::Vector3d point = getCosmeticEdgePtr()->permaEnd; return Py::asObject(new Base::VectorPy(point)); } void CosmeticEdgePy::setEnd(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d pNew; if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { pNew = static_cast<Base::VectorPy*>(p)->value(); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { pNew = Base::getVectorFromTuple<double>(p); } else { std::string error = std::string("type must be 'Vector', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); } pNew = DrawUtil::invertY(pNew); Base::Vector3d pStart = getCosmeticEdgePtr()->permaStart; pStart = DrawUtil::invertY(pStart); gp_Pnt gp1(pNew.x,pNew.y,pNew.z); gp_Pnt gp2(pStart.x,pStart.y,pStart.z); TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp2, gp1); auto oldGeom = getCosmeticEdgePtr()->m_geometry; getCosmeticEdgePtr()->m_geometry = TechDraw::BaseGeom::baseFactory(e); getCosmeticEdgePtr()->permaEnd = pNew; delete oldGeom; } Py::Object CosmeticEdgePy::getRadius(void) const { double r = getCosmeticEdgePtr()->permaRadius; return Py::asObject(PyFloat_FromDouble(r)); } void CosmeticEdgePy::setRadius(Py::Object arg) { //TODO: check if the edge has a radius attrib PyObject* p = arg.ptr(); double r; if (PyObject_TypeCheck(p, &PyFloat_Type)) { r = PyFloat_AsDouble(p); } else if (PyObject_TypeCheck(p, &PyLong_Type)) { r = (double) PyLong_AsLong(p); } else { std::string error = std::string("type must be 'Float' or 'Int', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); } getCosmeticEdgePtr()->permaRadius = r; auto oldGeom = getCosmeticEdgePtr()->m_geometry; getCosmeticEdgePtr()->m_geometry = new TechDraw::Circle(getCosmeticEdgePtr()->permaStart, r); delete oldGeom; } Py::Object CosmeticEdgePy::getCenter(void) const { Base::Vector3d point = getCosmeticEdgePtr()->permaStart; return Py::asObject(new Base::VectorPy(point)); } void CosmeticEdgePy::setCenter(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d pNew; if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { pNew = static_cast<Base::VectorPy*>(p)->value(); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { pNew = Base::getVectorFromTuple<double>(p); } else { std::string error = std::string("type must be 'Vector', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); } pNew = DrawUtil::invertY(pNew); auto oldGeom = getCosmeticEdgePtr()->m_geometry; TechDraw::Circle* oldCircle = dynamic_cast<TechDraw::Circle*>(oldGeom); getCosmeticEdgePtr()->permaStart = pNew; getCosmeticEdgePtr()->permaEnd = pNew; getCosmeticEdgePtr()->permaRadius = oldCircle->radius; getCosmeticEdgePtr()->m_geometry = new TechDraw::Circle(getCosmeticEdgePtr()->permaStart, oldCircle->radius); delete oldGeom; } PyObject *CosmeticEdgePy::getCustomAttributes(const char* /*attr*/) const { return 0; } int CosmeticEdgePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } <commit_msg>[TD]CosmeticEdge type guards<commit_after>/*************************************************************************** * Copyright (c) 2008 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * 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., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <boost/uuid/uuid_io.hpp> #endif #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepAdaptor_Curve.hxx> #include <gp_Circ.hxx> #include <Geom_Circle.hxx> #include <App/Material.h> #include <Base/Console.h> #include <Base/Vector3D.h> #include <Base/VectorPy.h> #include <Base/GeometryPyCXX.h> #include "DrawUtil.h" #include "Geometry.h" #include "Cosmetic.h" #include "CosmeticEdgePy.h" #include "CosmeticEdgePy.cpp" using namespace TechDraw; // returns a string which represents the object e.g. when printed in python std::string CosmeticEdgePy::representation(void) const { std::stringstream ss; ss << "<CosmeticEdge object> at " << std::hex << this; return ss.str(); // return "<CosmeticEdge object>"; } PyObject *CosmeticEdgePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper { // never create such objects with the constructor PyErr_SetString(PyExc_RuntimeError, "You cannot create an instance of the abstract class 'CosmeticEdge'."); return 0; } // constructor method int CosmeticEdgePy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) { return 0; } //From Part::GeometryPy.cpp PyObject* CosmeticEdgePy::clone(PyObject *args) { if (!PyArg_ParseTuple(args, "")) return NULL; TechDraw::CosmeticEdge* geom = this->getCosmeticEdgePtr(); PyTypeObject* type = this->GetType(); PyObject* cpy = 0; // let the type object decide if (type->tp_new) cpy = type->tp_new(type, this, 0); if (!cpy) { PyErr_SetString(PyExc_TypeError, "failed to create clone of CosmeticEdge"); return 0; } TechDraw::CosmeticEdgePy* geompy = static_cast<TechDraw::CosmeticEdgePy*>(cpy); // the PyMake function must have created the corresponding instance of the 'CosmeticEdge' subclass // so delete it now to avoid a memory leak if (geompy->_pcTwinPointer) { TechDraw::CosmeticEdge* clone = static_cast<TechDraw::CosmeticEdge*>(geompy->_pcTwinPointer); delete clone; } geompy->_pcTwinPointer = geom->clone(); return cpy; } PyObject* CosmeticEdgePy::copy(PyObject *args) { if (!PyArg_ParseTuple(args, "")) return NULL; TechDraw::CosmeticEdge* geom = this->getCosmeticEdgePtr(); PyTypeObject* type = this->GetType(); PyObject* cpy = 0; // let the type object decide if (type->tp_new) cpy = type->tp_new(type, this, 0); if (!cpy) { PyErr_SetString(PyExc_TypeError, "failed to create copy of CosmeticEdge"); return 0; } TechDraw::CosmeticEdgePy* geompy = static_cast<TechDraw::CosmeticEdgePy*>(cpy); // the PyMake function must have created the corresponding instance of the 'CosmeticEdge' subclass // so delete it now to avoid a memory leak if (geompy->_pcTwinPointer) { TechDraw::CosmeticEdge* copy = static_cast<TechDraw::CosmeticEdge*>(geompy->_pcTwinPointer); delete copy; } geompy->_pcTwinPointer = geom->copy(); return cpy; } void CosmeticEdgePy::setFormat(Py::Object arg) { PyObject* pTuple = arg.ptr(); int style = 1; double weight = 0.50; double red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0; App::Color c(red, blue, green, alpha); bool visible = 1; TechDraw::CosmeticEdge* ce = this->getCosmeticEdgePtr(); if (PyTuple_Check(pTuple)) { int tSize = (int) PyTuple_Size(pTuple); if (tSize > 3) { PyObject* pStyle = PyTuple_GetItem(pTuple,0); style = (int) PyLong_AsLong(pStyle); PyObject* pWeight = PyTuple_GetItem(pTuple,1); weight = PyFloat_AsDouble(pWeight); PyObject* pColor = PyTuple_GetItem(pTuple,2); c = DrawUtil::pyTupleToColor(pColor); PyObject* pVisible = PyTuple_GetItem(pTuple,3); visible = (bool) PyLong_AsLong(pVisible); ce->m_format.m_style = style; ce->m_format.m_weight = weight; ce->m_format.m_color = c; ce->m_format.m_visible = visible; } } else { Base::Console().Error("CEPI::setFormat - not a tuple!\n"); } } Py::Object CosmeticEdgePy::getFormat(void) const { TechDraw::CosmeticEdge* ce = this->getCosmeticEdgePtr(); PyObject* pStyle = PyLong_FromLong((long) ce->m_format.m_style); PyObject* pWeight = PyFloat_FromDouble(ce->m_format.m_weight); PyObject* pColor = DrawUtil::colorToPyTuple(ce->m_format.m_color); PyObject* pVisible = PyBool_FromLong((long) ce->m_format.m_visible); PyObject* result = PyTuple_New(4); PyTuple_SET_ITEM(result, 0, pStyle); PyTuple_SET_ITEM(result, 1, pWeight); PyTuple_SET_ITEM(result, 2, pColor); PyTuple_SET_ITEM(result, 3, pVisible); return Py::asObject(result); } Py::String CosmeticEdgePy::getTag(void) const { std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getTag()); return Py::String(tmp); } //Py::String CosmeticEdgePy::getOwner(void) const //{ //// std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getOwner()); // std::string tmp = "not implemented yet"; // return Py::String(tmp); //} //TODO: make BaseGeom py-aware or convert TD geometry to ??Part::Geometry2d?? or other // py-aware class. //Py::Object CosmeticEdgePy::getGeometry(void) const //{ //// TechDraw::BaseGeom* bg = getCosmeticEdgePtr()->m_geometry; // Base::Console().Message("Not implemented yet"); // return Py::asObject(Py_None); //} //void CosmeticEdgePy::setGeometry(Py::Object arg) //{ // Base::Console().Message("Not implemented yet"); // PyObject* p = arg.ptr(); // if (PyObject_TypeCheck(p, &(TechDraw::BaseGeomPy::Type))) { // //TODO // } else { // std::string error = std::string("type must be 'BaseGeom', not "); // error += p->ob_type->tp_name; // throw Py::TypeError(error); // } //} Py::Object CosmeticEdgePy::getStart(void) const { Base::Vector3d point = getCosmeticEdgePtr()->permaStart; return Py::asObject(new Base::VectorPy(point)); } void CosmeticEdgePy::setStart(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d pNew; if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { pNew = static_cast<Base::VectorPy*>(p)->value(); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { pNew = Base::getVectorFromTuple<double>(p); } else { std::string error = std::string("type must be 'Vector', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); } pNew = DrawUtil::invertY(pNew); Base::Vector3d pEnd = getCosmeticEdgePtr()->permaEnd; pEnd = DrawUtil::invertY(pEnd); gp_Pnt gp1(pNew.x,pNew.y,pNew.z); gp_Pnt gp2(pEnd.x,pEnd.y,pEnd.z); TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); auto oldGeom = getCosmeticEdgePtr()->m_geometry; getCosmeticEdgePtr()->m_geometry = TechDraw::BaseGeom::baseFactory(e); getCosmeticEdgePtr()->permaStart = pNew; delete oldGeom; } Py::Object CosmeticEdgePy::getEnd(void) const { Base::Vector3d point = getCosmeticEdgePtr()->permaEnd; return Py::asObject(new Base::VectorPy(point)); } void CosmeticEdgePy::setEnd(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d pNew; if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { pNew = static_cast<Base::VectorPy*>(p)->value(); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { pNew = Base::getVectorFromTuple<double>(p); } else { std::string error = std::string("type must be 'Vector', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); } pNew = DrawUtil::invertY(pNew); Base::Vector3d pStart = getCosmeticEdgePtr()->permaStart; pStart = DrawUtil::invertY(pStart); gp_Pnt gp1(pNew.x,pNew.y,pNew.z); gp_Pnt gp2(pStart.x,pStart.y,pStart.z); TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp2, gp1); auto oldGeom = getCosmeticEdgePtr()->m_geometry; getCosmeticEdgePtr()->m_geometry = TechDraw::BaseGeom::baseFactory(e); getCosmeticEdgePtr()->permaEnd = pNew; delete oldGeom; } Py::Object CosmeticEdgePy::getRadius(void) const { TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType; if ( (gt != TechDraw::GeomType::CIRCLE) && (gt != TechDraw::GeomType::ARCOFCIRCLE) ) { std::string error = "not a cirle. Can not set radius"; throw Py::TypeError(error); } double r = getCosmeticEdgePtr()->permaRadius; return Py::asObject(PyFloat_FromDouble(r)); } void CosmeticEdgePy::setRadius(Py::Object arg) { TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType; PyObject* p = arg.ptr(); if ( (gt != TechDraw::GeomType::CIRCLE) && (gt != TechDraw::GeomType::ARCOFCIRCLE) ) { std::string error = std::string(p->ob_type->tp_name); error += " is not a cirle. Can not set radius"; throw Py::TypeError(error); } double r; if (PyObject_TypeCheck(p, &PyFloat_Type)) { r = PyFloat_AsDouble(p); } else if (PyObject_TypeCheck(p, &PyLong_Type)) { r = (double) PyLong_AsLong(p); } else { std::string error = std::string("type must be 'Float' or 'Int', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); } getCosmeticEdgePtr()->permaRadius = r; auto oldGeom = getCosmeticEdgePtr()->m_geometry; getCosmeticEdgePtr()->m_geometry = new TechDraw::Circle(getCosmeticEdgePtr()->permaStart, r); delete oldGeom; } Py::Object CosmeticEdgePy::getCenter(void) const { TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType; if ( (gt != TechDraw::GeomType::CIRCLE) && (gt != TechDraw::GeomType::ARCOFCIRCLE) ) { std::string error = "not a cirle. Can not get center"; throw Py::TypeError(error); } Base::Vector3d point = getCosmeticEdgePtr()->permaStart; return Py::asObject(new Base::VectorPy(point)); } void CosmeticEdgePy::setCenter(Py::Object arg) { TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType; PyObject* p = arg.ptr(); if ( (gt != TechDraw::GeomType::CIRCLE) && (gt != TechDraw::GeomType::ARCOFCIRCLE) ) { std::string error = std::string(p->ob_type->tp_name); error += " is not a cirle. Can not set center"; throw Py::TypeError(error); } // PyObject* p = arg.ptr(); Base::Vector3d pNew; if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { pNew = static_cast<Base::VectorPy*>(p)->value(); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { pNew = Base::getVectorFromTuple<double>(p); } else { std::string error = std::string("type must be 'Vector', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); } pNew = DrawUtil::invertY(pNew); auto oldGeom = getCosmeticEdgePtr()->m_geometry; TechDraw::Circle* oldCircle = dynamic_cast<TechDraw::Circle*>(oldGeom); getCosmeticEdgePtr()->permaStart = pNew; getCosmeticEdgePtr()->permaEnd = pNew; getCosmeticEdgePtr()->permaRadius = oldCircle->radius; getCosmeticEdgePtr()->m_geometry = new TechDraw::Circle(getCosmeticEdgePtr()->permaStart, oldCircle->radius); delete oldGeom; } PyObject *CosmeticEdgePy::getCustomAttributes(const char* /*attr*/) const { return 0; } int CosmeticEdgePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/Formats/MeshLoader.hpp> #include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/Model.hpp> #include <Nazara/Graphics/SkeletalModel.hpp> #include <Nazara/Utility/MaterialData.hpp> #include <Nazara/Utility/Mesh.hpp> #include <memory> #include <Nazara/Graphics/Debug.hpp> namespace Nz { namespace { void LoadMaterials(Model* model, const ModelParameters& parameters) { unsigned int matCount = model->GetMaterialCount(); for (unsigned int i = 0; i < matCount; ++i) { const ParameterList& matData = model->GetMesh()->GetMaterialData(i); String filePath; if (matData.GetStringParameter(MaterialData::FilePath, &filePath)) { MaterialRef material = Material::New(); if (material->LoadFromFile(filePath, parameters.material)) model->SetMaterial(i, std::move(material)); else NazaraWarning("Failed to load material from file " + String::Number(i)); } else if (matData.HasParameter(MaterialData::CustomDefined)) { MaterialRef material = Material::New(); material->BuildFromParameters(matData, parameters.material); model->SetMaterial(i, std::move(material)); } } } Ternary CheckStatic(Stream& stream, const ModelParameters& parameters) { NazaraUnused(stream); bool skip; if (parameters.custom.GetBooleanParameter("SkipNativeMeshLoader", &skip) && skip) return Ternary_False; return Ternary_Unknown; } bool LoadStatic(Model* model, Stream& stream, const ModelParameters& parameters) { NazaraUnused(parameters); MeshRef mesh = Mesh::New(); if (!mesh->LoadFromStream(stream, parameters.mesh)) { NazaraError("Failed to load model mesh"); return false; } if (mesh->IsAnimable()) { NazaraError("Can't load animated mesh into static model"); return false; } model->Reset(); model->SetMesh(mesh); if (parameters.loadMaterials) LoadMaterials(model, parameters); return true; } Ternary CheckAnimated(Stream& stream, const SkeletalModelParameters& parameters) { NazaraUnused(stream); bool skip; if (parameters.custom.GetBooleanParameter("SkipNativeAnimatedMeshLoader", &skip) && skip) return Ternary_False; return Ternary_Unknown; } bool LoadAnimated(SkeletalModel* model, Stream& stream, const SkeletalModelParameters& parameters) { NazaraUnused(parameters); MeshRef mesh = Mesh::New(); if (!mesh->LoadFromStream(stream, parameters.mesh)) { NazaraError("Failed to load model mesh"); return false; } if (!mesh->IsAnimable()) { NazaraError("Can't load static mesh into animated model"); return false; } model->Reset(); model->SetMesh(mesh); if (parameters.loadMaterials) LoadMaterials(model, parameters); return true; } } namespace Loaders { void RegisterMesh() { ModelLoader::RegisterLoader(MeshLoader::IsExtensionSupported, CheckStatic, LoadStatic); SkeletalModelLoader::RegisterLoader(MeshLoader::IsExtensionSupported, CheckAnimated, LoadAnimated); } void UnregisterMesh() { ModelLoader::UnregisterLoader(MeshLoader::IsExtensionSupported, CheckStatic, LoadStatic); SkeletalModelLoader::UnregisterLoader(MeshLoader::IsExtensionSupported, CheckAnimated, LoadAnimated); } } } <commit_msg>Default behaviour without precision on name<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/Formats/MeshLoader.hpp> #include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/Model.hpp> #include <Nazara/Graphics/SkeletalModel.hpp> #include <Nazara/Utility/MaterialData.hpp> #include <Nazara/Utility/Mesh.hpp> #include <memory> #include <Nazara/Graphics/Debug.hpp> namespace Nz { namespace { void LoadMaterials(Model* model, const ModelParameters& parameters) { unsigned int matCount = model->GetMaterialCount(); for (unsigned int i = 0; i < matCount; ++i) { const ParameterList& matData = model->GetMesh()->GetMaterialData(i); String filePath; if (matData.GetStringParameter(MaterialData::FilePath, &filePath)) { if (!File::Exists(filePath)) { NazaraWarning("Shader name does not refer to an existing file, \".tga\" is used by default"); filePath += ".tga"; } MaterialRef material = Material::New(); if (material->LoadFromFile(filePath, parameters.material)) model->SetMaterial(i, std::move(material)); else NazaraWarning("Failed to load material from file " + String::Number(i)); } else if (matData.HasParameter(MaterialData::CustomDefined)) { MaterialRef material = Material::New(); material->BuildFromParameters(matData, parameters.material); model->SetMaterial(i, std::move(material)); } } } Ternary CheckStatic(Stream& stream, const ModelParameters& parameters) { NazaraUnused(stream); bool skip; if (parameters.custom.GetBooleanParameter("SkipNativeMeshLoader", &skip) && skip) return Ternary_False; return Ternary_Unknown; } bool LoadStatic(Model* model, Stream& stream, const ModelParameters& parameters) { NazaraUnused(parameters); MeshRef mesh = Mesh::New(); if (!mesh->LoadFromStream(stream, parameters.mesh)) { NazaraError("Failed to load model mesh"); return false; } if (mesh->IsAnimable()) { NazaraError("Can't load animated mesh into static model"); return false; } model->Reset(); model->SetMesh(mesh); if (parameters.loadMaterials) LoadMaterials(model, parameters); return true; } Ternary CheckAnimated(Stream& stream, const SkeletalModelParameters& parameters) { NazaraUnused(stream); bool skip; if (parameters.custom.GetBooleanParameter("SkipNativeAnimatedMeshLoader", &skip) && skip) return Ternary_False; return Ternary_Unknown; } bool LoadAnimated(SkeletalModel* model, Stream& stream, const SkeletalModelParameters& parameters) { NazaraUnused(parameters); MeshRef mesh = Mesh::New(); if (!mesh->LoadFromStream(stream, parameters.mesh)) { NazaraError("Failed to load model mesh"); return false; } if (!mesh->IsAnimable()) { NazaraError("Can't load static mesh into animated model"); return false; } model->Reset(); model->SetMesh(mesh); if (parameters.loadMaterials) LoadMaterials(model, parameters); return true; } } namespace Loaders { void RegisterMesh() { ModelLoader::RegisterLoader(MeshLoader::IsExtensionSupported, CheckStatic, LoadStatic); SkeletalModelLoader::RegisterLoader(MeshLoader::IsExtensionSupported, CheckAnimated, LoadAnimated); } void UnregisterMesh() { ModelLoader::UnregisterLoader(MeshLoader::IsExtensionSupported, CheckStatic, LoadStatic); SkeletalModelLoader::UnregisterLoader(MeshLoader::IsExtensionSupported, CheckAnimated, LoadAnimated); } } } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "list.h" #include "simplelist.h" #include "extArray.h" #include "stringSpace.h" #include "HashTable.h" #include "condor_classad.h" #include "classad_collection_types.h" #include "MyString.h" #include "Set.h" #include "condor_distribution.h" #include "file_transfer.h" #include "extra_param_info.h" #include "daemon.h" #include "condor_cred_base.h" #include "condor_credential.h" #include "condor_config.h" #include "condor_transfer_request.h" #include "log_transaction.h" #include "killfamily.h" #include "passwd_cache.h" #include "proc_family_direct.h" #include "credential.h" template class ExtArray<ParamValue>; template class SimpleList<ClassAd*>; template class List<char>; template class Item<char>; template class List<int>; template class Item<int>; template class SimpleList<int>; template class SimpleList<float>; template class ExtArray<PROC_ID>; template class ExtArray<char *>; template class ExtArray<int>; template class ExtArray<MyString>; template class ExtArray<StringSpace::SSStringEnt>; template class ExtArray<StringSpace*>; template class ExtArray<KillFamily::a_pid>; template class HashTable<int, BaseCollection*>; template class HashBucket<int, BaseCollection*>; template class Set<MyString>; template class SetElem<MyString>; template class Set<int>; template class SetElem<int>; template class Set<RankedClassAd>; template class SetElem<RankedClassAd>; template class HashTable<MyString, int>; template class HashBucket<MyString,int>; template class HashTable<MyString, MyString>; template class HashBucket<MyString, MyString>; template class HashTable<MyString, KeyCacheEntry*>; template class Queue<char *>; template class HashTable<int, FileTransfer *>; template class HashTable<MyString, FileTransfer *>; template class HashTable<MyString, ExtraParamInfo *>; template class HashTable<MyString, group_entry*>; template class HashTable<MyString, uid_entry*>; template class HashTable<MyString, CatalogEntry*>; template class SimpleList<Daemon*>; template class HashTable<Credential_t, Condor_Credential_B*>; template class SimpleList<MyString>; template class SimpleListIterator<MyString>; template class List<LogRecord>; template class Item<LogRecord>; template class HashTable<YourSensitiveString,LogRecordList *>; template class HashTable<pid_t, ProcFamilyDirectContainer*>; template class SimpleList <Credential*>; #if defined(Solaris) template class ExtArray<long>; #endif <commit_msg>Fix for platforms lacking classad external.<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "list.h" #include "simplelist.h" #include "extArray.h" #include "stringSpace.h" #include "HashTable.h" #include "condor_classad.h" #include "classad_collection_types.h" #include "MyString.h" #include "Set.h" #include "condor_distribution.h" #include "file_transfer.h" #include "extra_param_info.h" #include "daemon.h" #include "condor_cred_base.h" #include "condor_credential.h" #include "condor_config.h" #include "condor_transfer_request.h" #include "log_transaction.h" #include "killfamily.h" #include "passwd_cache.h" #include "proc_family_direct.h" #if HAVE_EXT_CLASSADS #include "credential.h" #endif template class ExtArray<ParamValue>; template class SimpleList<ClassAd*>; template class List<char>; template class Item<char>; template class List<int>; template class Item<int>; template class SimpleList<int>; template class SimpleList<float>; template class ExtArray<PROC_ID>; template class ExtArray<char *>; template class ExtArray<int>; template class ExtArray<MyString>; template class ExtArray<StringSpace::SSStringEnt>; template class ExtArray<StringSpace*>; template class ExtArray<KillFamily::a_pid>; template class HashTable<int, BaseCollection*>; template class HashBucket<int, BaseCollection*>; template class Set<MyString>; template class SetElem<MyString>; template class Set<int>; template class SetElem<int>; template class Set<RankedClassAd>; template class SetElem<RankedClassAd>; template class HashTable<MyString, int>; template class HashBucket<MyString,int>; template class HashTable<MyString, MyString>; template class HashBucket<MyString, MyString>; template class HashTable<MyString, KeyCacheEntry*>; template class Queue<char *>; template class HashTable<int, FileTransfer *>; template class HashTable<MyString, FileTransfer *>; template class HashTable<MyString, ExtraParamInfo *>; template class HashTable<MyString, group_entry*>; template class HashTable<MyString, uid_entry*>; template class HashTable<MyString, CatalogEntry*>; template class SimpleList<Daemon*>; template class HashTable<Credential_t, Condor_Credential_B*>; template class SimpleList<MyString>; template class SimpleListIterator<MyString>; template class List<LogRecord>; template class Item<LogRecord>; template class HashTable<YourSensitiveString,LogRecordList *>; template class HashTable<pid_t, ProcFamilyDirectContainer*>; #if HAVE_EXT_CLASSADS template class SimpleList <Credential*>; #endif #if defined(Solaris) template class ExtArray<long>; #endif <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mthemedaemonprotocol.h" #include <QHash> #include <QtEndian> using namespace M::MThemeDaemonProtocol; const QString M::MThemeDaemonProtocol::ServerAddress = "m.mthemedaemon"; static const int SOCKET_DELAY_MS = 15000; PacketData::~PacketData() {} PixmapIdentifier::~PixmapIdentifier() {} Number::~Number() {} String::~String() {} StringBool::~StringBool() {} PixmapHandle::~PixmapHandle() {} ClientList::~ClientList() {} ThemeChangeInfo::~ThemeChangeInfo() {} MostUsedPixmaps::~MostUsedPixmaps() {} RequestedPixmap::~RequestedPixmap() {} Packet::Packet(PacketType type, quint64 seq, PacketData *data) : m_seq (seq), m_data (data), m_type (type) {} Packet::~Packet() {} void Packet::setData(PacketData *data) { m_data = QSharedPointer<PacketData>(data); } QDataStream &operator<<(QDataStream &stream, const Packet &packet) { Q_ASSERT(packet.type() != Packet::Unknown); QByteArray serializedPackageData; QDataStream serializedPackageDataStream(&serializedPackageData, QIODevice::WriteOnly); writePacketData(serializedPackageDataStream, packet); stream.writeBytes(serializedPackageData.constData(), serializedPackageData.length()); return stream; } void writePacketData(QDataStream &stream, const M::MThemeDaemonProtocol::Packet &packet) { stream << quint32(packet.type()); stream << packet.sequenceNumber(); switch (packet.type()) { // NULL as data case Packet::RequestClearPixmapDirectoriesPacket: case Packet::QueryThemeDaemonStatusPacket: break; // string as data case Packet::ErrorPacket: case Packet::RequestRegistrationPacket: { stream << static_cast<const String *>(packet.data())->string; } break; // two string lists as data case Packet::ThemeChangedPacket: { const ThemeChangeInfo* info = static_cast<const ThemeChangeInfo*>(packet.data()); stream << info->themeInheritance << info->themeLibraryNames; } break; case Packet::ProtocolVersionPacket: case Packet::ThemeChangeAppliedPacket: { stream << static_cast<const Number *>(packet.data())->value; } break; // stringbool as data case Packet::RequestNewPixmapDirectoryPacket: { const StringBool *sb = static_cast<const StringBool *>(packet.data()); stream << sb->string << sb->b; } break; // pixmap identifier as data case Packet::PixmapUsedPacket: case Packet::ReleasePixmapPacket: { const PixmapIdentifier *id = static_cast<const PixmapIdentifier *>(packet.data()); stream << *id; } break; case Packet::RequestPixmapPacket: { const RequestedPixmap *pixmap = static_cast<const RequestedPixmap *>(packet.data()); stream << pixmap->priority; stream << pixmap->id; } break; // pixmap handle as data case Packet::PixmapUpdatedPacket: { const PixmapHandle *h = static_cast<const PixmapHandle *>(packet.data()); stream << *h; } break; case Packet::MostUsedPixmapsPacket: { const MostUsedPixmaps *mostUsedPixmaps = static_cast<const MostUsedPixmaps *>(packet.data()); stream << mostUsedPixmaps->addedHandles; stream << mostUsedPixmaps->removedIdentifiers; } break; // client list as data case Packet::ThemeDaemonStatusPacket: { const ClientList *cl = static_cast<const ClientList *>(packet.data()); quint32 clientCount = cl->clients.count(); stream << clientCount; for (uint i = 0; i < clientCount; ++i) { const ClientInfo &info = cl->clients.at(i); stream << info.name; quint32 pixmapCount = info.pixmaps.count(); stream << pixmapCount; for (quint32 j = 0; j < pixmapCount; ++j) { stream << info.pixmaps.at(j); } quint32 requestedPixmapCount = info.requestedPixmaps.count(); stream << requestedPixmapCount; for (quint32 j = 0; j < requestedPixmapCount; ++j) { stream << info.requestedPixmaps.at(j); } quint32 releasedPixmapCount = info.releasedPixmaps.count(); stream << releasedPixmapCount; for (quint32 j = 0; j < releasedPixmapCount; ++j) { stream << info.releasedPixmaps.at(j); } } } break; default: // print out warning break; } } static bool waitForAvailableBytes(QDataStream &stream, quint32 count) { while (stream.device()->bytesAvailable() < count) { if (!stream.device()->waitForReadyRead(SOCKET_DELAY_MS)) { return false; } } return true; } QDataStream &operator>>(QDataStream &stream, Packet &packet) { if (!waitForAvailableBytes(stream, sizeof(quint32))) { return stream; } quint32 length; stream >> length; if (!waitForAvailableBytes(stream, length)) { return stream; } char *raw = new char[length]; stream.readRawData(raw, length); QByteArray serializedPackageData = QByteArray::fromRawData(raw, length); QDataStream serializedPackageDataStream(serializedPackageData); readPacketData(serializedPackageDataStream, packet); delete[] raw; return stream; } void readPacketData(QDataStream &stream, M::MThemeDaemonProtocol::Packet &packet) { quint32 type = 0; quint64 seq = 0; stream >> type >> seq; packet.setType(Packet::PacketType(type)); packet.setSequenceNumber(seq); switch (packet.type()) { // NULL as data case Packet::RequestClearPixmapDirectoriesPacket: case Packet::QueryThemeDaemonStatusPacket: break; // string as data case Packet::ErrorPacket: case Packet::RequestRegistrationPacket: { QString string; stream >> string; packet.setData(new String(string)); } break; // two string lists as data case Packet::ThemeChangedPacket: { QStringList themeInheritance, themeLibraryNames; stream >> themeInheritance >> themeLibraryNames; packet.setData(new ThemeChangeInfo(themeInheritance, themeLibraryNames)); } break; case Packet::ProtocolVersionPacket: case Packet::ThemeChangeAppliedPacket: { qint32 priority; stream >> priority; packet.setData(new Number(priority)); } break; // stringbool as data case Packet::RequestNewPixmapDirectoryPacket: { QString string; stream >> string; bool b = false; stream >> b; packet.setData(new StringBool(string, b)); } break; // pixmap identifier as data case Packet::PixmapUsedPacket: case Packet::ReleasePixmapPacket: { PixmapIdentifier id; stream >> id; packet.setData(new PixmapIdentifier(id)); } break; case Packet::RequestPixmapPacket: { qint32 priority; stream >> priority; PixmapIdentifier id; stream >> id; packet.setData(new RequestedPixmap(id, priority)); } break; // pixmap handle as data case Packet::PixmapUpdatedPacket: { PixmapHandle h; stream >> h; packet.setData(new PixmapHandle(h)); } break; case Packet::MostUsedPixmapsPacket: { QList<PixmapHandle> addedHandles; stream >> addedHandles; QList<PixmapIdentifier> removedIdentifiers; stream >> removedIdentifiers; packet.setData(new MostUsedPixmaps(addedHandles, removedIdentifiers)); } break; // client list as data case Packet::ThemeDaemonStatusPacket: { QList<ClientInfo> clients; quint32 clientCount = 0; stream >> clientCount; while (clientCount) { ClientInfo info; stream >> info.name; quint32 pixmapCount = 0; stream >> pixmapCount; while (pixmapCount) { PixmapIdentifier id; stream >> id; info.pixmaps.append(id); --pixmapCount; } quint32 requestedPixmapCount = 0; stream >> requestedPixmapCount; while (requestedPixmapCount) { PixmapIdentifier id; stream >> id; info.requestedPixmaps.append(id); --requestedPixmapCount; } quint32 releasedPixmapCount = 0; stream >> releasedPixmapCount; while (releasedPixmapCount) { PixmapIdentifier id; stream >> id; info.releasedPixmaps.append(id); --releasedPixmapCount; } clients.append(info); --clientCount; } packet.setData(new ClientList(clients)); } break; default: // print out warning break; } } QDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapHandle &handle) { stream << handle.identifier; stream << quint64(quintptr(handle.pixmapHandle.xHandle)); stream << quint64(quintptr(handle.pixmapHandle.eglHandle)); stream << handle.pixmapHandle.shmHandle; stream << handle.pixmapHandle.size; stream << (quint64)handle.pixmapHandle.format; stream << handle.pixmapHandle.numBytes; stream << (bool)handle.pixmapHandle.directMap; return stream; } QDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapHandle &handle) { stream >> handle.identifier; quint64 h; stream >> h; handle.pixmapHandle.xHandle = (Qt::HANDLE) quintptr(h); stream >> h; handle.pixmapHandle.eglHandle = (Qt::HANDLE) quintptr(h); stream >> handle.pixmapHandle.shmHandle; stream >> handle.pixmapHandle.size; stream >> h; handle.pixmapHandle.format = QImage::Format(h); stream >> handle.pixmapHandle.numBytes; stream >> handle.pixmapHandle.directMap; return stream; } QDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapIdentifier &id) { stream << id.imageId; stream << id.size; return stream; } QDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapIdentifier &id) { QString imageId; stream >> imageId; QSize size; stream >> size; id.imageId = imageId; id.size = size; return stream; } uint M::MThemeDaemonProtocol::qHash(const PixmapIdentifier &id) { using ::qHash; const uint idHash = qHash(id.imageId); const uint widthHash = qHash(id.size.width()); const uint heightHash = qHash(id.size.height()); // Twiddle the bits a little, taking a cue from Qt's own qHash() overloads return idHash ^ (widthHash << 8) ^ (widthHash >> 24) ^ (heightHash << 24) ^ (heightHash >> 8); } <commit_msg>Revert "Changes: fix mismatched free() / delete / delete []"<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mthemedaemonprotocol.h" #include <QHash> #include <QtEndian> using namespace M::MThemeDaemonProtocol; const QString M::MThemeDaemonProtocol::ServerAddress = "m.mthemedaemon"; static const int SOCKET_DELAY_MS = 15000; PacketData::~PacketData() {} PixmapIdentifier::~PixmapIdentifier() {} Number::~Number() {} String::~String() {} StringBool::~StringBool() {} PixmapHandle::~PixmapHandle() {} ClientList::~ClientList() {} ThemeChangeInfo::~ThemeChangeInfo() {} MostUsedPixmaps::~MostUsedPixmaps() {} RequestedPixmap::~RequestedPixmap() {} Packet::Packet(PacketType type, quint64 seq, PacketData *data) : m_seq (seq), m_data (data), m_type (type) {} Packet::~Packet() {} void Packet::setData(PacketData *data) { m_data = QSharedPointer<PacketData>(data); } QDataStream &operator<<(QDataStream &stream, const Packet &packet) { Q_ASSERT(packet.type() != Packet::Unknown); QByteArray serializedPackageData; QDataStream serializedPackageDataStream(&serializedPackageData, QIODevice::WriteOnly); writePacketData(serializedPackageDataStream, packet); stream.writeBytes(serializedPackageData.constData(), serializedPackageData.length()); return stream; } void writePacketData(QDataStream &stream, const M::MThemeDaemonProtocol::Packet &packet) { stream << quint32(packet.type()); stream << packet.sequenceNumber(); switch (packet.type()) { // NULL as data case Packet::RequestClearPixmapDirectoriesPacket: case Packet::QueryThemeDaemonStatusPacket: break; // string as data case Packet::ErrorPacket: case Packet::RequestRegistrationPacket: { stream << static_cast<const String *>(packet.data())->string; } break; // two string lists as data case Packet::ThemeChangedPacket: { const ThemeChangeInfo* info = static_cast<const ThemeChangeInfo*>(packet.data()); stream << info->themeInheritance << info->themeLibraryNames; } break; case Packet::ProtocolVersionPacket: case Packet::ThemeChangeAppliedPacket: { stream << static_cast<const Number *>(packet.data())->value; } break; // stringbool as data case Packet::RequestNewPixmapDirectoryPacket: { const StringBool *sb = static_cast<const StringBool *>(packet.data()); stream << sb->string << sb->b; } break; // pixmap identifier as data case Packet::PixmapUsedPacket: case Packet::ReleasePixmapPacket: { const PixmapIdentifier *id = static_cast<const PixmapIdentifier *>(packet.data()); stream << *id; } break; case Packet::RequestPixmapPacket: { const RequestedPixmap *pixmap = static_cast<const RequestedPixmap *>(packet.data()); stream << pixmap->priority; stream << pixmap->id; } break; // pixmap handle as data case Packet::PixmapUpdatedPacket: { const PixmapHandle *h = static_cast<const PixmapHandle *>(packet.data()); stream << *h; } break; case Packet::MostUsedPixmapsPacket: { const MostUsedPixmaps *mostUsedPixmaps = static_cast<const MostUsedPixmaps *>(packet.data()); stream << mostUsedPixmaps->addedHandles; stream << mostUsedPixmaps->removedIdentifiers; } break; // client list as data case Packet::ThemeDaemonStatusPacket: { const ClientList *cl = static_cast<const ClientList *>(packet.data()); quint32 clientCount = cl->clients.count(); stream << clientCount; for (uint i = 0; i < clientCount; ++i) { const ClientInfo &info = cl->clients.at(i); stream << info.name; quint32 pixmapCount = info.pixmaps.count(); stream << pixmapCount; for (quint32 j = 0; j < pixmapCount; ++j) { stream << info.pixmaps.at(j); } quint32 requestedPixmapCount = info.requestedPixmaps.count(); stream << requestedPixmapCount; for (quint32 j = 0; j < requestedPixmapCount; ++j) { stream << info.requestedPixmaps.at(j); } quint32 releasedPixmapCount = info.releasedPixmaps.count(); stream << releasedPixmapCount; for (quint32 j = 0; j < releasedPixmapCount; ++j) { stream << info.releasedPixmaps.at(j); } } } break; default: // print out warning break; } } static bool waitForAvailableBytes(QDataStream &stream, quint32 count) { while (stream.device()->bytesAvailable() < count) { if (!stream.device()->waitForReadyRead(SOCKET_DELAY_MS)) { return false; } } return true; } QDataStream &operator>>(QDataStream &stream, Packet &packet) { if (!waitForAvailableBytes(stream, sizeof(quint32))) { return stream; } quint32 length; stream >> length; if (!waitForAvailableBytes(stream, length)) { return stream; } char *raw = new char[length]; stream.readRawData(raw, length); QByteArray serializedPackageData = QByteArray::fromRawData(raw, length); QDataStream serializedPackageDataStream(serializedPackageData); readPacketData(serializedPackageDataStream, packet); delete raw; return stream; } void readPacketData(QDataStream &stream, M::MThemeDaemonProtocol::Packet &packet) { quint32 type = 0; quint64 seq = 0; stream >> type >> seq; packet.setType(Packet::PacketType(type)); packet.setSequenceNumber(seq); switch (packet.type()) { // NULL as data case Packet::RequestClearPixmapDirectoriesPacket: case Packet::QueryThemeDaemonStatusPacket: break; // string as data case Packet::ErrorPacket: case Packet::RequestRegistrationPacket: { QString string; stream >> string; packet.setData(new String(string)); } break; // two string lists as data case Packet::ThemeChangedPacket: { QStringList themeInheritance, themeLibraryNames; stream >> themeInheritance >> themeLibraryNames; packet.setData(new ThemeChangeInfo(themeInheritance, themeLibraryNames)); } break; case Packet::ProtocolVersionPacket: case Packet::ThemeChangeAppliedPacket: { qint32 priority; stream >> priority; packet.setData(new Number(priority)); } break; // stringbool as data case Packet::RequestNewPixmapDirectoryPacket: { QString string; stream >> string; bool b = false; stream >> b; packet.setData(new StringBool(string, b)); } break; // pixmap identifier as data case Packet::PixmapUsedPacket: case Packet::ReleasePixmapPacket: { PixmapIdentifier id; stream >> id; packet.setData(new PixmapIdentifier(id)); } break; case Packet::RequestPixmapPacket: { qint32 priority; stream >> priority; PixmapIdentifier id; stream >> id; packet.setData(new RequestedPixmap(id, priority)); } break; // pixmap handle as data case Packet::PixmapUpdatedPacket: { PixmapHandle h; stream >> h; packet.setData(new PixmapHandle(h)); } break; case Packet::MostUsedPixmapsPacket: { QList<PixmapHandle> addedHandles; stream >> addedHandles; QList<PixmapIdentifier> removedIdentifiers; stream >> removedIdentifiers; packet.setData(new MostUsedPixmaps(addedHandles, removedIdentifiers)); } break; // client list as data case Packet::ThemeDaemonStatusPacket: { QList<ClientInfo> clients; quint32 clientCount = 0; stream >> clientCount; while (clientCount) { ClientInfo info; stream >> info.name; quint32 pixmapCount = 0; stream >> pixmapCount; while (pixmapCount) { PixmapIdentifier id; stream >> id; info.pixmaps.append(id); --pixmapCount; } quint32 requestedPixmapCount = 0; stream >> requestedPixmapCount; while (requestedPixmapCount) { PixmapIdentifier id; stream >> id; info.requestedPixmaps.append(id); --requestedPixmapCount; } quint32 releasedPixmapCount = 0; stream >> releasedPixmapCount; while (releasedPixmapCount) { PixmapIdentifier id; stream >> id; info.releasedPixmaps.append(id); --releasedPixmapCount; } clients.append(info); --clientCount; } packet.setData(new ClientList(clients)); } break; default: // print out warning break; } } QDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapHandle &handle) { stream << handle.identifier; stream << quint64(quintptr(handle.pixmapHandle.xHandle)); stream << quint64(quintptr(handle.pixmapHandle.eglHandle)); stream << handle.pixmapHandle.shmHandle; stream << handle.pixmapHandle.size; stream << (quint64)handle.pixmapHandle.format; stream << handle.pixmapHandle.numBytes; stream << (bool)handle.pixmapHandle.directMap; return stream; } QDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapHandle &handle) { stream >> handle.identifier; quint64 h; stream >> h; handle.pixmapHandle.xHandle = (Qt::HANDLE) quintptr(h); stream >> h; handle.pixmapHandle.eglHandle = (Qt::HANDLE) quintptr(h); stream >> handle.pixmapHandle.shmHandle; stream >> handle.pixmapHandle.size; stream >> h; handle.pixmapHandle.format = QImage::Format(h); stream >> handle.pixmapHandle.numBytes; stream >> handle.pixmapHandle.directMap; return stream; } QDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapIdentifier &id) { stream << id.imageId; stream << id.size; return stream; } QDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapIdentifier &id) { QString imageId; stream >> imageId; QSize size; stream >> size; id.imageId = imageId; id.size = size; return stream; } uint M::MThemeDaemonProtocol::qHash(const PixmapIdentifier &id) { using ::qHash; const uint idHash = qHash(id.imageId); const uint widthHash = qHash(id.size.width()); const uint heightHash = qHash(id.size.height()); // Twiddle the bits a little, taking a cue from Qt's own qHash() overloads return idHash ^ (widthHash << 8) ^ (widthHash >> 24) ^ (heightHash << 24) ^ (heightHash >> 8); } <|endoftext|>
<commit_before>/* * FileLogDestination.cpp * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement * with RStudio, then this program is licensed to you under the following terms: * * 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 <shared_core/FileLogDestination.hpp> #include <boost/thread.hpp> #include <vector> #include <shared_core/Error.hpp> #include <shared_core/Logger.hpp> namespace rstudio { namespace core { namespace log { // FileLogOptions ====================================================================================================== FileLogOptions::FileLogOptions(FilePath in_directory) : m_directory(std::move(in_directory)), m_fileMode(s_defaultFileMode), m_maxSizeMb(s_defaultMaxSizeMb), m_doRotation(s_defaultDoRotation), m_includePid(s_defaultIncludePid) { } FileLogOptions::FileLogOptions( FilePath in_directory, std::string in_fileMode, double in_maxSizeMb, bool in_doRotation, bool in_includePid) : m_directory(std::move(in_directory)), m_fileMode(std::move(in_fileMode)), m_maxSizeMb(in_maxSizeMb), m_doRotation(in_doRotation), m_includePid(in_includePid) { } const FilePath& FileLogOptions::getDirectory() const { return m_directory; } const std::string& FileLogOptions::getFileMode() const { return m_fileMode; } double FileLogOptions::getMaxSizeMb() const { return m_maxSizeMb; } bool FileLogOptions::doRotation() const { return m_doRotation; } bool FileLogOptions::includePid() const { return m_includePid; } // FileLogDestination ================================================================================================== struct FileLogDestination::Impl { Impl(unsigned int in_id, const std::string& in_name, FileLogOptions in_options) : LogOptions(std::move(in_options)), LogName(in_name + ".log"), RotatedLogName(in_name + ".old.log"), Id(in_id) { LogOptions.getDirectory().ensureDirectory(); }; ~Impl() { closeLogFile(); } void closeLogFile() { if (LogOutputStream) { LogOutputStream->flush(); LogOutputStream.reset(); } } // Returns true if the log file was opened, false otherwise. bool openLogFile() { // We can't safely log in this function. Error error = LogOptions.getDirectory().completeChildPath(LogName, LogFile); if (error) return false; error = LogFile.ensureFile(); if (error) return false; error = LogFile.openForWrite(LogOutputStream, false); if (error) return false; return true; } // Returns true if it is safe to log; false otherwise. bool rotateLogFile() { // Calculate the maximum size in bytes. const uintmax_t maxSize = 1048576.0 * LogOptions.getMaxSizeMb(); // Only rotate if we're configured to rotate. if (LogOptions.doRotation()) { // Convert MB to B for comparison. if (LogFile.getSize() >= maxSize) { FilePath rotatedLogFile = FilePath(LogOptions.getDirectory()).completeChildPath(RotatedLogName); // We can't safely log errors in this function because we'll end up in an infinitely recursive // rotateLogFile() call. Error error = rotatedLogFile.remove(); if (error) return false; // Close the existing log file and then move it. closeLogFile(); error = LogFile.move(rotatedLogFile); if (error) return false; // Now re-open the log file. openLogFile(); } } return LogFile.getSize() < maxSize; } FileLogOptions LogOptions; FilePath LogFile; std::string LogName; std::string RotatedLogName; boost::mutex Mutex; unsigned int Id; std::shared_ptr<std::ostream> LogOutputStream; }; FileLogDestination::FileLogDestination( unsigned int in_id, LogLevel in_logLevel, const std::string& in_programId, FileLogOptions in_logOptions) : ILogDestination(in_logLevel), m_impl(new Impl(in_id, in_programId, std::move(in_logOptions))) { } FileLogDestination::~FileLogDestination() { if (m_impl->LogOutputStream.get()) m_impl->LogOutputStream->flush(); } unsigned int FileLogDestination::getId() const { return m_impl->Id; } void FileLogDestination::writeLog(LogLevel in_logLevel, const std::string& in_message) { // Don't write logs that are more detailed than the configured maximum. if (in_logLevel > m_logLevel) return; // Lock the mutex before attempting to write. boost::unique_lock<boost::mutex> lock(m_impl->Mutex); // Open the log file if it's not open. If it fails to open, log nothing. if (!m_impl->LogOutputStream && !m_impl->openLogFile()) return; // Rotate the log file if necessary. m_impl->rotateLogFile(); (*m_impl->LogOutputStream) << in_message; m_impl->LogOutputStream->flush(); } } // namespace log } // namespace core } // namespace rstudio <commit_msg>Fix bug where failure to rotate a log file could cause a segfault. Fixes https://github.com/rstudio/rstudio-pro/issues/1779<commit_after>/* * FileLogDestination.cpp * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement * with RStudio, then this program is licensed to you under the following terms: * * 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 <shared_core/FileLogDestination.hpp> #include <boost/thread.hpp> #include <vector> #include <shared_core/Error.hpp> #include <shared_core/Logger.hpp> namespace rstudio { namespace core { namespace log { // FileLogOptions ====================================================================================================== FileLogOptions::FileLogOptions(FilePath in_directory) : m_directory(std::move(in_directory)), m_fileMode(s_defaultFileMode), m_maxSizeMb(s_defaultMaxSizeMb), m_doRotation(s_defaultDoRotation), m_includePid(s_defaultIncludePid) { } FileLogOptions::FileLogOptions( FilePath in_directory, std::string in_fileMode, double in_maxSizeMb, bool in_doRotation, bool in_includePid) : m_directory(std::move(in_directory)), m_fileMode(std::move(in_fileMode)), m_maxSizeMb(in_maxSizeMb), m_doRotation(in_doRotation), m_includePid(in_includePid) { } const FilePath& FileLogOptions::getDirectory() const { return m_directory; } const std::string& FileLogOptions::getFileMode() const { return m_fileMode; } double FileLogOptions::getMaxSizeMb() const { return m_maxSizeMb; } bool FileLogOptions::doRotation() const { return m_doRotation; } bool FileLogOptions::includePid() const { return m_includePid; } // FileLogDestination ================================================================================================== struct FileLogDestination::Impl { Impl(unsigned int in_id, const std::string& in_name, FileLogOptions in_options) : LogOptions(std::move(in_options)), LogName(in_name + ".log"), RotatedLogName(in_name + ".old.log"), Id(in_id) { LogOptions.getDirectory().ensureDirectory(); }; ~Impl() { closeLogFile(); } void closeLogFile() { if (LogOutputStream) { LogOutputStream->flush(); LogOutputStream.reset(); } } // Returns true if the log file was opened, false otherwise. bool openLogFile() { // We can't safely log in this function. Error error = LogOptions.getDirectory().completeChildPath(LogName, LogFile); if (error) return false; error = LogFile.ensureFile(); if (error) return false; error = LogFile.openForWrite(LogOutputStream, false); if (error) return false; return true; } // Returns true if it is safe to log; false otherwise. bool rotateLogFile() { // Calculate the maximum size in bytes. const uintmax_t maxSize = 1048576.0 * LogOptions.getMaxSizeMb(); // Only rotate if we're configured to rotate. if (LogOptions.doRotation()) { // Convert MB to B for comparison. if (LogFile.getSize() >= maxSize) { FilePath rotatedLogFile = FilePath(LogOptions.getDirectory()).completeChildPath(RotatedLogName); // We can't safely log errors in this function because we'll end up in an infinitely recursive // rotateLogFile() call. Error error = rotatedLogFile.remove(); if (error) return false; // Close the existing log file and then move it. closeLogFile(); error = LogFile.move(rotatedLogFile); if (error) return false; // Now re-open the log file. if (!openLogFile()) return false; } // we only sucessfully rotated (and thus are safe to log) if the // file size is now lower than the limit return LogFile.getSize() < maxSize; } else { // we are configured not to rotate logs, which means the log file can grow unboundedly large // thus, we are safe to log return true; } } FileLogOptions LogOptions; FilePath LogFile; std::string LogName; std::string RotatedLogName; boost::mutex Mutex; unsigned int Id; std::shared_ptr<std::ostream> LogOutputStream; }; FileLogDestination::FileLogDestination( unsigned int in_id, LogLevel in_logLevel, const std::string& in_programId, FileLogOptions in_logOptions) : ILogDestination(in_logLevel), m_impl(new Impl(in_id, in_programId, std::move(in_logOptions))) { } FileLogDestination::~FileLogDestination() { if (m_impl->LogOutputStream.get()) m_impl->LogOutputStream->flush(); } unsigned int FileLogDestination::getId() const { return m_impl->Id; } void FileLogDestination::writeLog(LogLevel in_logLevel, const std::string& in_message) { // Don't write logs that are more detailed than the configured maximum. if (in_logLevel > m_logLevel) return; // Lock the mutex before attempting to write. boost::unique_lock<boost::mutex> lock(m_impl->Mutex); // Open the log file if it's not open. If it fails to open, log nothing. if (!m_impl->LogOutputStream && !m_impl->openLogFile()) return; // Rotate the log file if necessary. If it fails to rotate, log nothing. if (!m_impl->rotateLogFile()) return; (*m_impl->LogOutputStream) << in_message; m_impl->LogOutputStream->flush(); } } // namespace log } // namespace core } // namespace rstudio <|endoftext|>
<commit_before>#include <iostream> #include "RelativeDetector.h" #include <list> #include <opencv_workbench/utils/ColorMaps.h> #include <opencv_workbench/wb/WB.h> #include <opencv_workbench/wb/Cluster.h> #include <opencv_workbench/wb/ClusterProcess.h> #include <opencv_workbench/wb/NDT.h> #include <opencv_workbench/utils/OpenCV_Helpers.h> using std::cout; using std::endl; RelativeDetector::RelativeDetector() { cout << "RelativeDetector Constructor" << endl; thresh_value_ = 255; grad_thresh_value_ = 255; cluster_process_.set_threshold(0); cluster_process_.set_gate(25); // 15, 50, 100 cluster_process_.set_min_cluster_size(30); int erosionElem = cv::MORPH_ELLIPSE; int erosionSize = 1; int dilationElem = cv::MORPH_ELLIPSE; // MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE int dilationSize = 1; erosionConfig_ = cv::getStructuringElement( erosionElem, cv::Size(2*erosionSize+1, 2*erosionSize+1), cv::Point(erosionSize, erosionSize) ); dilationConfig_ = cv::getStructuringElement( dilationElem, cv::Size(2*dilationSize+1, 2*dilationSize+1), cv::Point(dilationSize, dilationSize) ); } RelativeDetector::~RelativeDetector() { cout << "RelativeDetector Destructor" << endl; } void RelativeDetector::print() { cout << "I am the Relative Detector" << endl; } void RelativeDetector::set_stream(syllo::Stream *stream) { stream_ = stream; } double RelativeDetector::trajectory_diff(std::list<cv::Point2d> &t1, std::list<cv::Point2d> &t2) { // Calculate differences in trajectories double total_diff = 0; std::vector<cv::Point2d> diffs; int frame = 0; std::list<cv::Point2d>::iterator it1 = t1.begin(); std::list<cv::Point2d>::iterator it2 = t2.begin(); for(; it1 != t1.end() && it2 != t2.end(); it1++, it2++) { double diff = pow(it1->x - it2->x, 2) + pow(it1->y - it2->y, 2); diffs.push_back(cv::Point2d(frame,diff)); total_diff += diff; frame++; } //vectors.push_back(diffs); //labels.push_back("Diff"); //styles.push_back("linespoints"); //vectors.push_back(costs); //labels.push_back("Cost"); //styles.push_back("linespoints"); //plot.plot(vectors, title2, labels, styles); double mean = total_diff / (double)diffs.size(); double RMSE = sqrt(mean); return RMSE; } void RelativeDetector::trajectory_polar_diff(std::list<wb::Entity> &traj, std::list<cv::Point2d> &diffs) { std::list<wb::Entity>::reverse_iterator it = traj.rbegin(); cv::Point2d prev; for(; it != traj.rend(); it++) { if (it == traj.rbegin()) { prev = it->undistorted_centroid(); continue; } cv::Point2d p = it->undistorted_centroid(); // Convert to polar double range = sqrt( pow(p.x,2) + pow(p.y,2) ); double range_prev = sqrt( pow(prev.x,2) + pow(prev.y,2) ); double theta = atan(p.y / p.x); double theta_prev = atan(prev.y / prev.x); // cv::Point2d polar(range,theta); cv::Point2d polar_prev(range_prev, theta_prev); double range_diff = range - range_prev; double theta_diff = theta - theta_prev; cv::Point2d temp; temp.x = range_diff; temp.y = theta_diff; diffs.push_back(temp); prev = it->undistorted_centroid(); } } struct TrajRMSE { int ID1; int ID2; double RMSE; }; void RelativeDetector::trajectory_similarity(int frame_number, cv::Mat &img) { //cout << "==========================================" << endl; std::map<int, std::list<cv::Point2d> > trajectories; for (std::map<int, std::list<wb::Entity> >::iterator it = tracks_history_.begin(); it != tracks_history_.end(); ) { if (it->second.back().frame() < frame_number) { // Clear out track IDs that are dead tracks_history_.erase(it++); } else { if (it->second.back().is_tracked()) { //cout << "Tracked: " << it->first << endl; // Compute derivative of each current track's trajectory trajectory_polar_diff(it->second, trajectories[it->first]); } it++; } } std::map<std::string, struct TrajRMSE> RMSEs; // Store RMSE between each trajectory in a map/hash. A string will be used // to hash the values. The string is of the form "n:m", where n and m are // the trajectory IDs and n is less than m. // Calculate differences between trajectory derivatives std::map<int, std::list<cv::Point2d> >::iterator it_1 = trajectories.begin(); for(; it_1 != trajectories.end(); it_1++) { std::map<int, std::list<cv::Point2d> >::iterator it_2 = trajectories.begin(); for(; it_2 != trajectories.end(); it_2++) { // Determine if this trajectory difference has already been // calculated std::string key; struct TrajRMSE traj; if (it_1->first == it_2->first) { // Don't calculate trajectory diff between two trajectories // with the same ID. This is the same trajectory. continue; } else if (it_1->first < it_2->first) { key = syllo::int2str(it_1->first) + ":" + syllo::int2str(it_2->first); traj.ID1 = it_1->first; traj.ID2 = it_2->first; } else { key = syllo::int2str(it_2->first) + ":" + syllo::int2str(it_1->first); traj.ID1 = it_2->first; traj.ID2 = it_1->first; } if (RMSEs.count(key) == 0) { double RMSE = trajectory_diff(it_1->second, it_2->second); traj.RMSE = RMSE; RMSEs[key] = traj; //cout << "--------------" << endl; //cout << it_1->first << " - " << it_2->first << " : " << RMSE << endl; } } } // Print out the RMSEs for this frame: //cout << "-----------------" << endl; for(std::map<std::string, struct TrajRMSE>::iterator it = RMSEs.begin(); it != RMSEs.end(); it++) { //cout << it->first << ": " << it->second.RMSE << endl; // If the RMSE between two trajectories is less than a threshold, // circle the trajectories if (it->second.RMSE < 0.017) { // Get the two IDs in the track history and circle them cv::Point p1 = tracks_history_[it->second.ID1].back().centroid(); cv::Point p2 = tracks_history_[it->second.ID2].back().centroid(); //cv::circle(img, p1, 10, cv::Scalar(0,255,255), 1, 8, 0); //cv::circle(img, p2, 10, cv::Scalar(0,255,255), 1, 8, 0); cv::line(img, p1, p2, cv::Scalar(0,255,255), 1, 8, 0); } } cv::imshow("SimTraj", img); } int RelativeDetector::set_frame(int frame_number, const cv::Mat &original) { cv::Mat original_w_tracks, original_copy; original_w_tracks = original; original_copy = original; //cv::cvtColor(original_copy, original_copy, CV_RGBA2BGR); //wb::show_nonzero(original_copy); //cv::Mat bad_gray; //cv::applyColorMap(original, bad_gray, CV_BGR2GRAY); //cv::cvtColor(original, bad_gray, CV_BGR2GRAY); //cv::imshow("bad", bad_gray); cv::Mat gray; if (original.channels() != 1) { Jet2Gray_matlab(original,gray); } else { gray = original.clone(); } cv::imshow("Gray", gray); //cv::Mat ndt_img; //ndt_.set_frame(gray, ndt_img); //cv::imshow("ndt", ndt_img); // Compute median cv::Mat median; cv::medianBlur(gray, median,5); cv::imshow("median", median); /// // Compute estimated gradient /// cv::Mat grad; /// wb::gradient_sobel(median, grad); /// cv::imshow("gradient", grad); /// ///cv::Mat thresh_grad; ///wb::adaptive_threshold(grad, thresh_grad, grad_thresh_value_, 0.001, 0.002, 10, 5); /// cv::imshow("grad thresh", thresh_grad); cv::Mat thresh_amp; #if 1 wb::adaptive_threshold(median, thresh_amp, thresh_value_, 0.001, 0.002, 10, 5); #else // TODO: For some reason, using this static threshold kills regular sonar // images, (vs. simulated sonar images), it might have to do with the // number of detected blobs Used for thresholding simulated sonar data // from Gazebo cv::threshold(median, thresh_amp, 100, 255, cv::THRESH_TOZERO); #endif cv::imshow("thresh amp", thresh_amp); /// cv::Mat thresh_and_grad = thresh_amp + thresh_grad; /// cv::imshow("thresh and grad", thresh_and_grad); cv::Mat erode; cv::erode(thresh_amp, erode, erosionConfig_); //cv::imshow("erode", erode); cv::Mat dilate; cv::dilate(erode, dilate, dilationConfig_); cv::imshow("Erode/Dilate", dilate); //dilate = thresh_amp; cv::Mat blob_consolidate; blob_process_.consolidate_tracks(gray, blob_consolidate); cv::imshow("Consolidate", blob_consolidate); //if (found_overlap) { // cv::waitKey(0); //} blob_process_.process_frame(dilate, median, thresh_value_); cv::Mat blob_img; blob_process_.overlay_blobs(gray, blob_img); blob_process_.overlay_tracks(blob_img, blob_img); cv::imshow("Blobs", blob_img); ////////////////////////////////////////////////////////////// /// Tracking //////////////////////////////////////////////////// tracks_.clear(); // clear out the tracks from previous loop std::vector<wb::Blob> blobs = blob_process_.blobs(); std::vector<wb::Blob>::iterator it = blobs.begin(); for (; it != blobs.end(); it++) { // Have to transform tracks from distorted cartesian // to polar, then to undistorted cartesian cv::Point p = it->estimated_centroid(); double x, y; if (stream_->type() == syllo::SonarType) { double range = stream_->pixel_range(p.y, p.x); //row, col double bearing = stream_->pixel_bearing(p.y, p.x) * 0.017453293; // pi/180 y = -range*cos(bearing); x = range*sin(bearing); } else { x = p.x; y = p.y; } //it->set_undistorted_centroid(cv::Point2f(p.x,p.y)); it->set_undistorted_centroid(cv::Point2f(x,y)); it->set_frame(frame_number); tracks_history_[it->id()].push_back((wb::Entity)*it); tracks_.push_back((wb::Entity)*it); } // Calculate Similarity between current tracks this->trajectory_similarity(frame_number, blob_img); /////////////////////////////////////////////////// // Display images /////////////////////////////////////////////////// if (!hide_windows_) { } return 0; } extern "C" { Detector *maker(){ return new RelativeDetector; } class proxy { public: proxy(){ // register the maker with the factory // causes static initialization error plugin_manager_.factory["blank_detector"] = maker; plugin_manager_.factory["relative_detector"] = maker; } }; // our one instance of the proxy proxy p; } /// Color map tests ///cv::Mat grad; ///create_gradient(grad, 100, 255); ///cv::imshow("gradient", grad); /// ///cv::Mat jet_matlab; ///Gray2Jet_matlab(grad,jet_matlab); ///cv::imshow("jet matlab", jet_matlab); /// ///cv::Mat gray_2; ///Jet2Gray_matlab(jet_matlab,gray_2); ///cv::imshow("gray_2",gray_2); /// ///cv::Mat diff = gray_2 - grad; ///cv::imshow("diff",diff); /// ///if (!equal(gray_2, grad)) { /// cout << "Grays are unequal" << endl; ///} <commit_msg>moved track consolidation after assignment algorithm<commit_after>#include <iostream> #include "RelativeDetector.h" #include <list> #include <opencv_workbench/utils/ColorMaps.h> #include <opencv_workbench/wb/WB.h> #include <opencv_workbench/wb/Cluster.h> #include <opencv_workbench/wb/ClusterProcess.h> #include <opencv_workbench/wb/NDT.h> #include <opencv_workbench/utils/OpenCV_Helpers.h> using std::cout; using std::endl; RelativeDetector::RelativeDetector() { cout << "RelativeDetector Constructor" << endl; thresh_value_ = 255; grad_thresh_value_ = 255; cluster_process_.set_threshold(0); cluster_process_.set_gate(25); // 15, 50, 100 cluster_process_.set_min_cluster_size(30); int erosionElem = cv::MORPH_ELLIPSE; int erosionSize = 1; int dilationElem = cv::MORPH_ELLIPSE; // MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE int dilationSize = 1; erosionConfig_ = cv::getStructuringElement( erosionElem, cv::Size(2*erosionSize+1, 2*erosionSize+1), cv::Point(erosionSize, erosionSize) ); dilationConfig_ = cv::getStructuringElement( dilationElem, cv::Size(2*dilationSize+1, 2*dilationSize+1), cv::Point(dilationSize, dilationSize) ); } RelativeDetector::~RelativeDetector() { cout << "RelativeDetector Destructor" << endl; } void RelativeDetector::print() { cout << "I am the Relative Detector" << endl; } void RelativeDetector::set_stream(syllo::Stream *stream) { stream_ = stream; } double RelativeDetector::trajectory_diff(std::list<cv::Point2d> &t1, std::list<cv::Point2d> &t2) { // Calculate differences in trajectories double total_diff = 0; std::vector<cv::Point2d> diffs; int frame = 0; std::list<cv::Point2d>::iterator it1 = t1.begin(); std::list<cv::Point2d>::iterator it2 = t2.begin(); for(; it1 != t1.end() && it2 != t2.end(); it1++, it2++) { double diff = pow(it1->x - it2->x, 2) + pow(it1->y - it2->y, 2); diffs.push_back(cv::Point2d(frame,diff)); total_diff += diff; frame++; } //vectors.push_back(diffs); //labels.push_back("Diff"); //styles.push_back("linespoints"); //vectors.push_back(costs); //labels.push_back("Cost"); //styles.push_back("linespoints"); //plot.plot(vectors, title2, labels, styles); double mean = total_diff / (double)diffs.size(); double RMSE = sqrt(mean); return RMSE; } void RelativeDetector::trajectory_polar_diff(std::list<wb::Entity> &traj, std::list<cv::Point2d> &diffs) { std::list<wb::Entity>::reverse_iterator it = traj.rbegin(); cv::Point2d prev; for(; it != traj.rend(); it++) { if (it == traj.rbegin()) { prev = it->undistorted_centroid(); continue; } cv::Point2d p = it->undistorted_centroid(); // Convert to polar double range = sqrt( pow(p.x,2) + pow(p.y,2) ); double range_prev = sqrt( pow(prev.x,2) + pow(prev.y,2) ); double theta = atan(p.y / p.x); double theta_prev = atan(prev.y / prev.x); // cv::Point2d polar(range,theta); cv::Point2d polar_prev(range_prev, theta_prev); double range_diff = range - range_prev; double theta_diff = theta - theta_prev; cv::Point2d temp; temp.x = range_diff; temp.y = theta_diff; diffs.push_back(temp); prev = it->undistorted_centroid(); } } struct TrajRMSE { int ID1; int ID2; double RMSE; }; void RelativeDetector::trajectory_similarity(int frame_number, cv::Mat &img) { //cout << "==========================================" << endl; std::map<int, std::list<cv::Point2d> > trajectories; for (std::map<int, std::list<wb::Entity> >::iterator it = tracks_history_.begin(); it != tracks_history_.end(); ) { if (it->second.back().frame() < frame_number) { // Clear out track IDs that are dead tracks_history_.erase(it++); } else { if (it->second.back().is_tracked()) { //cout << "Tracked: " << it->first << endl; // Compute derivative of each current track's trajectory trajectory_polar_diff(it->second, trajectories[it->first]); } it++; } } std::map<std::string, struct TrajRMSE> RMSEs; // Store RMSE between each trajectory in a map/hash. A string will be used // to hash the values. The string is of the form "n:m", where n and m are // the trajectory IDs and n is less than m. // Calculate differences between trajectory derivatives std::map<int, std::list<cv::Point2d> >::iterator it_1 = trajectories.begin(); for(; it_1 != trajectories.end(); it_1++) { std::map<int, std::list<cv::Point2d> >::iterator it_2 = trajectories.begin(); for(; it_2 != trajectories.end(); it_2++) { // Determine if this trajectory difference has already been // calculated std::string key; struct TrajRMSE traj; if (it_1->first == it_2->first) { // Don't calculate trajectory diff between two trajectories // with the same ID. This is the same trajectory. continue; } else if (it_1->first < it_2->first) { key = syllo::int2str(it_1->first) + ":" + syllo::int2str(it_2->first); traj.ID1 = it_1->first; traj.ID2 = it_2->first; } else { key = syllo::int2str(it_2->first) + ":" + syllo::int2str(it_1->first); traj.ID1 = it_2->first; traj.ID2 = it_1->first; } if (RMSEs.count(key) == 0) { double RMSE = trajectory_diff(it_1->second, it_2->second); traj.RMSE = RMSE; RMSEs[key] = traj; //cout << "--------------" << endl; //cout << it_1->first << " - " << it_2->first << " : " << RMSE << endl; } } } // Print out the RMSEs for this frame: //cout << "-----------------" << endl; for(std::map<std::string, struct TrajRMSE>::iterator it = RMSEs.begin(); it != RMSEs.end(); it++) { //cout << it->first << ": " << it->second.RMSE << endl; // If the RMSE between two trajectories is less than a threshold, // circle the trajectories if (it->second.RMSE < 0.017) { // Get the two IDs in the track history and circle them cv::Point p1 = tracks_history_[it->second.ID1].back().centroid(); cv::Point p2 = tracks_history_[it->second.ID2].back().centroid(); //cv::circle(img, p1, 10, cv::Scalar(0,255,255), 1, 8, 0); //cv::circle(img, p2, 10, cv::Scalar(0,255,255), 1, 8, 0); cv::line(img, p1, p2, cv::Scalar(0,255,255), 1, 8, 0); } } cv::imshow("SimTraj", img); } int RelativeDetector::set_frame(int frame_number, const cv::Mat &original) { cv::Mat original_w_tracks, original_copy; original_w_tracks = original; original_copy = original; //cv::cvtColor(original_copy, original_copy, CV_RGBA2BGR); //wb::show_nonzero(original_copy); //cv::Mat bad_gray; //cv::applyColorMap(original, bad_gray, CV_BGR2GRAY); //cv::cvtColor(original, bad_gray, CV_BGR2GRAY); //cv::imshow("bad", bad_gray); cv::Mat gray; if (original.channels() != 1) { Jet2Gray_matlab(original,gray); } else { gray = original.clone(); } cv::imshow("Gray", gray); //cv::Mat ndt_img; //ndt_.set_frame(gray, ndt_img); //cv::imshow("ndt", ndt_img); // Compute median cv::Mat median; cv::medianBlur(gray, median,5); cv::imshow("median", median); /// // Compute estimated gradient /// cv::Mat grad; /// wb::gradient_sobel(median, grad); /// cv::imshow("gradient", grad); /// ///cv::Mat thresh_grad; ///wb::adaptive_threshold(grad, thresh_grad, grad_thresh_value_, 0.001, 0.002, 10, 5); /// cv::imshow("grad thresh", thresh_grad); cv::Mat thresh_amp; #if 1 wb::adaptive_threshold(median, thresh_amp, thresh_value_, 0.001, 0.002, 10, 5); #else // TODO: For some reason, using this static threshold kills regular sonar // images, (vs. simulated sonar images), it might have to do with the // number of detected blobs Used for thresholding simulated sonar data // from Gazebo cv::threshold(median, thresh_amp, 100, 255, cv::THRESH_TOZERO); #endif cv::imshow("thresh amp", thresh_amp); /// cv::Mat thresh_and_grad = thresh_amp + thresh_grad; /// cv::imshow("thresh and grad", thresh_and_grad); cv::Mat erode; cv::erode(thresh_amp, erode, erosionConfig_); //cv::imshow("erode", erode); cv::Mat dilate; cv::dilate(erode, dilate, dilationConfig_); cv::imshow("Erode/Dilate", dilate); blob_process_.process_frame(dilate, median, thresh_value_); cv::Mat blob_img; blob_process_.overlay_blobs(gray, blob_img); blob_process_.overlay_tracks(blob_img, blob_img); cv::imshow("Blobs", blob_img); cv::Mat blob_consolidate; blob_process_.consolidate_tracks(gray, blob_consolidate); cv::imshow("Consolidate", blob_consolidate); ////////////////////////////////////////////////////////////// /// Tracking //////////////////////////////////////////////////// tracks_.clear(); // clear out the tracks from previous loop std::vector<wb::Blob> blobs = blob_process_.blobs(); std::vector<wb::Blob>::iterator it = blobs.begin(); for (; it != blobs.end(); it++) { // Have to transform tracks from distorted cartesian // to polar, then to undistorted cartesian cv::Point p = it->estimated_centroid(); double x, y; if (stream_->type() == syllo::SonarType) { double range = stream_->pixel_range(p.y, p.x); //row, col double bearing = stream_->pixel_bearing(p.y, p.x) * 0.017453293; // pi/180 y = -range*cos(bearing); x = range*sin(bearing); } else { x = p.x; y = p.y; } //it->set_undistorted_centroid(cv::Point2f(p.x,p.y)); it->set_undistorted_centroid(cv::Point2f(x,y)); it->set_frame(frame_number); tracks_history_[it->id()].push_back((wb::Entity)*it); tracks_.push_back((wb::Entity)*it); } // Calculate Similarity between current tracks this->trajectory_similarity(frame_number, blob_img); /////////////////////////////////////////////////// // Display images /////////////////////////////////////////////////// if (!hide_windows_) { } return 0; } extern "C" { Detector *maker(){ return new RelativeDetector; } class proxy { public: proxy(){ // register the maker with the factory // causes static initialization error plugin_manager_.factory["blank_detector"] = maker; plugin_manager_.factory["relative_detector"] = maker; } }; // our one instance of the proxy proxy p; } /// Color map tests ///cv::Mat grad; ///create_gradient(grad, 100, 255); ///cv::imshow("gradient", grad); /// ///cv::Mat jet_matlab; ///Gray2Jet_matlab(grad,jet_matlab); ///cv::imshow("jet matlab", jet_matlab); /// ///cv::Mat gray_2; ///Jet2Gray_matlab(jet_matlab,gray_2); ///cv::imshow("gray_2",gray_2); /// ///cv::Mat diff = gray_2 - grad; ///cv::imshow("diff",diff); /// ///if (!equal(gray_2, grad)) { /// cout << "Grays are unequal" << endl; ///} <|endoftext|>
<commit_before>#include <iostream> #include "RelativeDetector.h" #include <list> #include <opencv_workbench/utils/ColorMaps.h> #include <opencv_workbench/wb/WB.h> #include <opencv_workbench/wb/Cluster.h> #include <opencv_workbench/wb/ClusterProcess.h> #include <opencv_workbench/wb/NDT.h> #include <opencv_workbench/utils/OpenCV_Helpers.h> using std::cout; using std::endl; RelativeDetector::RelativeDetector() { cout << "RelativeDetector Constructor" << endl; thresh_value_ = 255; grad_thresh_value_ = 255; cluster_process_.set_threshold(0); cluster_process_.set_gate(25); // 15, 50, 100 cluster_process_.set_min_cluster_size(30); int erosionElem = cv::MORPH_ELLIPSE; int erosionSize = 2; int dilationElem = cv::MORPH_ELLIPSE; // MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE int dilationSize = 1; erosionConfig_ = cv::getStructuringElement( erosionElem, cv::Size(2*erosionSize+1, 2*erosionSize+1), cv::Point(erosionSize, erosionSize) ); dilationConfig_ = cv::getStructuringElement( dilationElem, cv::Size(2*dilationSize+1, 2*dilationSize+1), cv::Point(dilationSize, dilationSize) ); } RelativeDetector::~RelativeDetector() { cout << "RelativeDetector Destructor" << endl; } void RelativeDetector::print() { cout << "I am the Relative Detector" << endl; } void RelativeDetector::set_stream(syllo::Stream *stream) { stream_ = stream; } int RelativeDetector::set_frame(int frame_number, const cv::Mat &original) { cv::Mat original_w_tracks, original_copy; original_w_tracks = original; original_copy = original; //cv::cvtColor(original_copy, original_copy, CV_RGBA2BGR); //wb::show_nonzero(original_copy); //cv::Mat bad_gray; //cv::applyColorMap(original, bad_gray, CV_BGR2GRAY); //cv::cvtColor(original, bad_gray, CV_BGR2GRAY); //cv::imshow("bad", bad_gray); cv::Mat gray; if (original.channels() != 1) { Jet2Gray_matlab(original,gray); } else { gray = original.clone(); } cv::imshow("Gray", gray); //cv::Mat ndt_img; //ndt_.set_frame(gray, ndt_img); //cv::imshow("ndt", ndt_img); // Compute median cv::Mat median; cv::medianBlur(gray, median,5); cv::imshow("median", median); /// // Compute estimated gradient /// cv::Mat grad; /// wb::gradient_sobel(median, grad); /// cv::imshow("gradient", grad); /// ///cv::Mat thresh_grad; ///wb::adaptive_threshold(grad, thresh_grad, grad_thresh_value_, 0.001, 0.002, 10, 5); /// cv::imshow("grad thresh", thresh_grad); cv::Mat thresh_amp; #if 0 wb::adaptive_threshold(median, thresh_amp, thresh_value_, 0.001, 0.002, 10, 5); #else // Used for thresholding simulated sonar data from Gazebo cv::threshold(median, thresh_amp, 100, 255, cv::THRESH_TOZERO); #endif cv::imshow("thresh amp", thresh_amp); /// cv::Mat thresh_and_grad = thresh_amp + thresh_grad; /// cv::imshow("thresh and grad", thresh_and_grad); /// cv::Mat erode; /// cv::erode(thresh_amp, erode, erosionConfig_); /// cv::imshow("erode", erode); /// //cv::Mat dilate; /// cv::dilate(erode, dilate, dilationConfig_); /// cv::imshow("dilate", dilate); //dilate = thresh_amp; blob_process_.process_frame(thresh_amp, median, thresh_value_); cv::Mat blob_img; blob_process_.overlay_blobs(gray, blob_img); blob_process_.overlay_tracks(blob_img, blob_img); cv::imshow("Blobs", blob_img); ////////////////////////////////////////////////////////////// /// Tracking //////////////////////////////////////////////////// tracks_.clear(); // clear out the tracks from previous loop std::vector<wb::Blob> blobs = blob_process_.blobs(); std::vector<wb::Blob>::iterator it = blobs.begin(); for (; it != blobs.end(); it++) { // Have to transform tracks from distorted cartesian // to polar, then to undistorted cartesian cv::Point p = it->estimated_centroid(); double x, y; if (stream_->type() == syllo::SonarType) { double range = stream_->pixel_range(p.y, p.x); //row, col double bearing = stream_->pixel_bearing(p.y, p.x) * 0.017453293; // pi/180 y = -range*cos(bearing); x = range*sin(bearing); } else { x = p.x; y = p.y; } //it->set_undistorted_centroid(cv::Point2f(p.x,p.y)); it->set_undistorted_centroid(cv::Point2f(x,y)); tracks_.push_back((wb::Entity)*it); } /////////////////////////////////////////////////// // Display images /////////////////////////////////////////////////// if (!hide_windows_) { } return 0; } extern "C" { Detector *maker(){ return new RelativeDetector; } class proxy { public: proxy(){ // register the maker with the factory // causes static initialization error plugin_manager_.factory["blank_detector"] = maker; plugin_manager_.factory["relative_detector"] = maker; } }; // our one instance of the proxy proxy p; } /// Color map tests ///cv::Mat grad; ///create_gradient(grad, 100, 255); ///cv::imshow("gradient", grad); /// ///cv::Mat jet_matlab; ///Gray2Jet_matlab(grad,jet_matlab); ///cv::imshow("jet matlab", jet_matlab); /// ///cv::Mat gray_2; ///Jet2Gray_matlab(jet_matlab,gray_2); ///cv::imshow("gray_2",gray_2); /// ///cv::Mat diff = gray_2 - grad; ///cv::imshow("diff",diff); /// ///if (!equal(gray_2, grad)) { /// cout << "Grays are unequal" << endl; ///} <commit_msg>changed sim/real switch<commit_after>#include <iostream> #include "RelativeDetector.h" #include <list> #include <opencv_workbench/utils/ColorMaps.h> #include <opencv_workbench/wb/WB.h> #include <opencv_workbench/wb/Cluster.h> #include <opencv_workbench/wb/ClusterProcess.h> #include <opencv_workbench/wb/NDT.h> #include <opencv_workbench/utils/OpenCV_Helpers.h> using std::cout; using std::endl; RelativeDetector::RelativeDetector() { cout << "RelativeDetector Constructor" << endl; thresh_value_ = 255; grad_thresh_value_ = 255; cluster_process_.set_threshold(0); cluster_process_.set_gate(25); // 15, 50, 100 cluster_process_.set_min_cluster_size(30); int erosionElem = cv::MORPH_ELLIPSE; int erosionSize = 2; int dilationElem = cv::MORPH_ELLIPSE; // MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE int dilationSize = 1; erosionConfig_ = cv::getStructuringElement( erosionElem, cv::Size(2*erosionSize+1, 2*erosionSize+1), cv::Point(erosionSize, erosionSize) ); dilationConfig_ = cv::getStructuringElement( dilationElem, cv::Size(2*dilationSize+1, 2*dilationSize+1), cv::Point(dilationSize, dilationSize) ); } RelativeDetector::~RelativeDetector() { cout << "RelativeDetector Destructor" << endl; } void RelativeDetector::print() { cout << "I am the Relative Detector" << endl; } void RelativeDetector::set_stream(syllo::Stream *stream) { stream_ = stream; } int RelativeDetector::set_frame(int frame_number, const cv::Mat &original) { cv::Mat original_w_tracks, original_copy; original_w_tracks = original; original_copy = original; //cv::cvtColor(original_copy, original_copy, CV_RGBA2BGR); //wb::show_nonzero(original_copy); //cv::Mat bad_gray; //cv::applyColorMap(original, bad_gray, CV_BGR2GRAY); //cv::cvtColor(original, bad_gray, CV_BGR2GRAY); //cv::imshow("bad", bad_gray); cv::Mat gray; if (original.channels() != 1) { Jet2Gray_matlab(original,gray); } else { gray = original.clone(); } cv::imshow("Gray", gray); //cv::Mat ndt_img; //ndt_.set_frame(gray, ndt_img); //cv::imshow("ndt", ndt_img); // Compute median cv::Mat median; cv::medianBlur(gray, median,5); cv::imshow("median", median); /// // Compute estimated gradient /// cv::Mat grad; /// wb::gradient_sobel(median, grad); /// cv::imshow("gradient", grad); /// ///cv::Mat thresh_grad; ///wb::adaptive_threshold(grad, thresh_grad, grad_thresh_value_, 0.001, 0.002, 10, 5); /// cv::imshow("grad thresh", thresh_grad); cv::Mat thresh_amp; #if 1 wb::adaptive_threshold(median, thresh_amp, thresh_value_, 0.001, 0.002, 10, 5); #else // TODO: For some reason, using this static threshold kills regular sonar // images, (vs. simulated sonar images), it might have to do with the // number of detected blobs Used for thresholding simulated sonar data // from Gazebo cv::threshold(median, thresh_amp, 100, 255, cv::THRESH_TOZERO); #endif cv::imshow("thresh amp", thresh_amp); /// cv::Mat thresh_and_grad = thresh_amp + thresh_grad; /// cv::imshow("thresh and grad", thresh_and_grad); /// cv::Mat erode; /// cv::erode(thresh_amp, erode, erosionConfig_); /// cv::imshow("erode", erode); /// //cv::Mat dilate; /// cv::dilate(erode, dilate, dilationConfig_); /// cv::imshow("dilate", dilate); //dilate = thresh_amp; blob_process_.process_frame(thresh_amp, median, thresh_value_); cv::Mat blob_img; blob_process_.overlay_blobs(gray, blob_img); blob_process_.overlay_tracks(blob_img, blob_img); cv::imshow("Blobs", blob_img); ////////////////////////////////////////////////////////////// /// Tracking //////////////////////////////////////////////////// tracks_.clear(); // clear out the tracks from previous loop std::vector<wb::Blob> blobs = blob_process_.blobs(); std::vector<wb::Blob>::iterator it = blobs.begin(); for (; it != blobs.end(); it++) { // Have to transform tracks from distorted cartesian // to polar, then to undistorted cartesian cv::Point p = it->estimated_centroid(); double x, y; if (stream_->type() == syllo::SonarType) { double range = stream_->pixel_range(p.y, p.x); //row, col double bearing = stream_->pixel_bearing(p.y, p.x) * 0.017453293; // pi/180 y = -range*cos(bearing); x = range*sin(bearing); } else { x = p.x; y = p.y; } //it->set_undistorted_centroid(cv::Point2f(p.x,p.y)); it->set_undistorted_centroid(cv::Point2f(x,y)); tracks_.push_back((wb::Entity)*it); } /////////////////////////////////////////////////// // Display images /////////////////////////////////////////////////// if (!hide_windows_) { } return 0; } extern "C" { Detector *maker(){ return new RelativeDetector; } class proxy { public: proxy(){ // register the maker with the factory // causes static initialization error plugin_manager_.factory["blank_detector"] = maker; plugin_manager_.factory["relative_detector"] = maker; } }; // our one instance of the proxy proxy p; } /// Color map tests ///cv::Mat grad; ///create_gradient(grad, 100, 255); ///cv::imshow("gradient", grad); /// ///cv::Mat jet_matlab; ///Gray2Jet_matlab(grad,jet_matlab); ///cv::imshow("jet matlab", jet_matlab); /// ///cv::Mat gray_2; ///Jet2Gray_matlab(jet_matlab,gray_2); ///cv::imshow("gray_2",gray_2); /// ///cv::Mat diff = gray_2 - grad; ///cv::imshow("diff",diff); /// ///if (!equal(gray_2, grad)) { /// cout << "Grays are unequal" << endl; ///} <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * 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 * *****************************************************************************/ //$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $ #include <boost/python.hpp> #include <boost/get_pointer.hpp> #include <boost/python/detail/api_placeholder.hpp> #include <boost/python/exception_translator.hpp> void register_cairo(); void export_color(); void export_coord(); void export_layer(); void export_parameters(); void export_envelope(); void export_query(); void export_geometry(); void export_image(); void export_image_view(); void export_map(); void export_python(); void export_filter(); void export_rule(); void export_style(); void export_stroke(); void export_feature(); void export_featureset(); void export_datasource(); void export_datasource_cache(); void export_point_symbolizer(); void export_line_symbolizer(); void export_line_pattern_symbolizer(); void export_polygon_symbolizer(); void export_polygon_pattern_symbolizer(); void export_raster_symbolizer(); void export_text_symbolizer(); void export_shield_symbolizer(); void export_font_engine(); void export_projection(); void export_proj_transform(); void export_view_transform(); #include <mapnik/version.hpp> #include <mapnik/map.hpp> #include <mapnik/agg_renderer.hpp> #ifdef HAVE_CAIRO #include <mapnik/cairo_renderer.hpp> #endif #include <mapnik/graphics.hpp> #include <mapnik/image_util.hpp> #include <mapnik/load_map.hpp> #include <mapnik/config_error.hpp> #include <mapnik/save_map.hpp> #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) #include <pycairo.h> #endif void render(const mapnik::Map& map,mapnik::Image32& image, unsigned offset_x = 0, unsigned offset_y = 0) { Py_BEGIN_ALLOW_THREADS try { mapnik::agg_renderer<mapnik::Image32> ren(map,image,offset_x, offset_y); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } void render2(const mapnik::Map& map,mapnik::Image32& image) { Py_BEGIN_ALLOW_THREADS try { mapnik::agg_renderer<mapnik::Image32> ren(map,image); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) void render3(const mapnik::Map& map,PycairoSurface* surface, unsigned offset_x = 0, unsigned offset_y = 0) { Py_BEGIN_ALLOW_THREADS try { Cairo::RefPtr<Cairo::Surface> s(new Cairo::Surface(surface->surface)); mapnik::cairo_renderer<Cairo::Surface> ren(map,s,offset_x, offset_y); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } void render4(const mapnik::Map& map,PycairoSurface* surface) { Py_BEGIN_ALLOW_THREADS try { Cairo::RefPtr<Cairo::Surface> s(new Cairo::Surface(surface->surface)); mapnik::cairo_renderer<Cairo::Surface> ren(map,s); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } void render5(const mapnik::Map& map,PycairoContext* context, unsigned offset_x = 0, unsigned offset_y = 0) { Py_BEGIN_ALLOW_THREADS try { Cairo::RefPtr<Cairo::Context> c(new Cairo::Context(context->ctx)); mapnik::cairo_renderer<Cairo::Context> ren(map,c,offset_x, offset_y); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } void render6(const mapnik::Map& map,PycairoContext* context) { Py_BEGIN_ALLOW_THREADS try { Cairo::RefPtr<Cairo::Context> c(new Cairo::Context(context->ctx)); mapnik::cairo_renderer<Cairo::Context> ren(map,c); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } #endif void render_tile_to_file(const mapnik::Map& map, unsigned offset_x, unsigned offset_y, unsigned width, unsigned height, const std::string& file, const std::string& format) { mapnik::Image32 image(width,height); render(map,image,offset_x, offset_y); mapnik::save_to_file(image.data(),file,format); } void render_to_file1(const mapnik::Map& map, const std::string& filename, const std::string& format) { mapnik::Image32 image(map.getWidth(),map.getHeight()); render(map,image,0,0); mapnik::save_to_file(image,filename,format); } void render_to_file2(const mapnik::Map& map, const std::string& filename) { mapnik::Image32 image(map.getWidth(),map.getHeight()); render(map,image,0,0); mapnik::save_to_file(image,filename); } double scale_denominator(mapnik::Map const &map, bool geographic) { return mapnik::scale_denominator(map, geographic); } void translator(mapnik::config_error const & ex) { PyErr_SetString(PyExc_UserWarning, ex.what()); } unsigned mapnik_version() { return MAPNIK_VERSION; } BOOST_PYTHON_FUNCTION_OVERLOADS(load_map_overloads, load_map, 2, 3); BOOST_PYTHON_FUNCTION_OVERLOADS(load_map_string_overloads, load_map_string, 2, 3); BOOST_PYTHON_MODULE(_mapnik) { using namespace boost::python; using mapnik::load_map; using mapnik::load_map_string; using mapnik::save_map; register_exception_translator<mapnik::config_error>(translator); register_cairo(); export_query(); export_geometry(); export_feature(); export_featureset(); export_datasource(); export_parameters(); export_color(); export_envelope(); export_image(); export_image_view(); export_filter(); export_rule(); export_style(); export_layer(); export_stroke(); export_datasource_cache(); export_point_symbolizer(); export_line_symbolizer(); export_line_pattern_symbolizer(); export_polygon_symbolizer(); export_polygon_pattern_symbolizer(); export_raster_symbolizer(); export_text_symbolizer(); export_shield_symbolizer(); export_font_engine(); export_projection(); export_proj_transform(); export_view_transform(); export_coord(); export_map(); def("render_to_file",&render_to_file1, "\n" "Render Map to file using explicit image type\n" "\n" "Usage:\n" ">>> from mapnik import Map, render_to_file, load_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> render_to_file(m,'image32bit.png','png')\n" "\n" "Format Options:\n" "\n" "8 bit (paletted) PNG can be requested with 'png256':\n" ">>> render_to_file(m,'image8bit.png','png256')\n" "JPEG quality can be controlled by adding a suffix to\n" "'jpeg' between 0 and 100 (default is 85):\n" ">>> render_to_file(m,'top_quality.jpeg','jpeg100')\n" ">>> render_to_file(m,'medium_quality.jpeg','jpeg50')\n" ); def("render_to_file",&render_to_file2, "\n" "Render Map to file (type taken from file extension)\n" "\n" "Usage:\n" ">>> from mapnik import Map, render_to_file, load_map\n" ">>> m = Map(256,256)\n" ">>> render_to_file(m,'image.jpeg')\n" "\n" ); def("render_tile_to_file",&render_tile_to_file, "\n" "TODO\n" "\n" ); def("render",&render, "\n" "Render Map to an AGG Image32 using offsets\n" "\n" "Usage:\n" ">>> from mapnik import Map, Image, render, load_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> im = Image(m.width,m.height)\n" ">>> render(m,im,1,1)\n" "\n" ); def("render",&render2, "\n" "Render Map to an AGG Image32\n" "\n" "Usage:\n" ">>> from mapnik import Map, Image, render, load_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> im = Image(m.width,m.height)\n" ">>> render(m,im)\n" "\n" ); #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) def("render",&render3, "\n" "Render Map to Cairo Surface using offsets\n" "\n" "Usage:\n" ">>> from mapnik import Map, render, load_map\n" ">>> from cairo import SVGSurface\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> surface = SVGSurface('image.svg', m.width, m.height)\n" ">>> render(m,surface,1,1)\n" "\n" ); def("render",&render4, "\n" "Render Map to Cairo Surface\n" "\n" "Usage:\n" ">>> from mapnik import Map, render, load_map\n" ">>> from cairo import SVGSurface\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> surface = SVGSurface('image.svg', m.width, m.height)\n" ">>> render(m,surface)\n" "\n" ); def("render",&render5, "\n" "Render Map to Cairo Context using offsets\n" "\n" "Usage:\n" ">>> from mapnik import Map, render, load_map\n" ">>> from cairo import SVGSurface, Context\n" ">>> surface = SVGSurface('image.svg', m.width, m.height)\n" ">>> ctx = Context(surface)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> render(m,context,1,1)\n" "\n" ); def("render",&render6, "\n" "Render Map to Cairo Context\n" "\n" "Usage:\n" ">>> from mapnik import Map, render, load_map\n" ">>> from cairo import SVGSurface, Context\n" ">>> surface = SVGSurface('image.svg', m.width, m.height)\n" ">>> ctx = Context(surface)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> render(m,context)\n" "\n" ); #endif def("scale_denominator", &scale_denominator, "\n" "Return the Map Scale Denominator.\n" "Also available as Map.scale_denominator()\n" "\n" "Usage:\n" "\n" ">>> from mapnik import Map, Projection, scale_denominator, load_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> scale_denominator(m,Projection(m.srs).geographic)\n" "\n" ); def("load_map", & load_map, load_map_overloads()); def("load_map_from_string", & load_map_string, load_map_string_overloads()); def("save_map", & save_map, "\n" "Save Map object to XML file\n" "\n" "Usage:\n" ">>> from mapnik import Map, load_map, save_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile_wgs84.xml')\n" ">>> m.srs\n" "'+proj=latlong +datum=WGS84'\n" ">>> m.srs = '+init=espg:3395'\n" ">>> save_map(m,'mapfile_mercator.xml')\n" "\n" ); def("mapnik_version", &mapnik_version,"Get the Mapnik version number"); using mapnik::symbolizer; class_<symbolizer>("Symbolizer",no_init) ; register_ptr_to_python<mapnik::filter_ptr>(); } <commit_msg>minor formatting to render_to_file docstring<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * 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 * *****************************************************************************/ //$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $ #include <boost/python.hpp> #include <boost/get_pointer.hpp> #include <boost/python/detail/api_placeholder.hpp> #include <boost/python/exception_translator.hpp> void register_cairo(); void export_color(); void export_coord(); void export_layer(); void export_parameters(); void export_envelope(); void export_query(); void export_geometry(); void export_image(); void export_image_view(); void export_map(); void export_python(); void export_filter(); void export_rule(); void export_style(); void export_stroke(); void export_feature(); void export_featureset(); void export_datasource(); void export_datasource_cache(); void export_point_symbolizer(); void export_line_symbolizer(); void export_line_pattern_symbolizer(); void export_polygon_symbolizer(); void export_polygon_pattern_symbolizer(); void export_raster_symbolizer(); void export_text_symbolizer(); void export_shield_symbolizer(); void export_font_engine(); void export_projection(); void export_proj_transform(); void export_view_transform(); #include <mapnik/version.hpp> #include <mapnik/map.hpp> #include <mapnik/agg_renderer.hpp> #ifdef HAVE_CAIRO #include <mapnik/cairo_renderer.hpp> #endif #include <mapnik/graphics.hpp> #include <mapnik/image_util.hpp> #include <mapnik/load_map.hpp> #include <mapnik/config_error.hpp> #include <mapnik/save_map.hpp> #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) #include <pycairo.h> #endif void render(const mapnik::Map& map,mapnik::Image32& image, unsigned offset_x = 0, unsigned offset_y = 0) { Py_BEGIN_ALLOW_THREADS try { mapnik::agg_renderer<mapnik::Image32> ren(map,image,offset_x, offset_y); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } void render2(const mapnik::Map& map,mapnik::Image32& image) { Py_BEGIN_ALLOW_THREADS try { mapnik::agg_renderer<mapnik::Image32> ren(map,image); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) void render3(const mapnik::Map& map,PycairoSurface* surface, unsigned offset_x = 0, unsigned offset_y = 0) { Py_BEGIN_ALLOW_THREADS try { Cairo::RefPtr<Cairo::Surface> s(new Cairo::Surface(surface->surface)); mapnik::cairo_renderer<Cairo::Surface> ren(map,s,offset_x, offset_y); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } void render4(const mapnik::Map& map,PycairoSurface* surface) { Py_BEGIN_ALLOW_THREADS try { Cairo::RefPtr<Cairo::Surface> s(new Cairo::Surface(surface->surface)); mapnik::cairo_renderer<Cairo::Surface> ren(map,s); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } void render5(const mapnik::Map& map,PycairoContext* context, unsigned offset_x = 0, unsigned offset_y = 0) { Py_BEGIN_ALLOW_THREADS try { Cairo::RefPtr<Cairo::Context> c(new Cairo::Context(context->ctx)); mapnik::cairo_renderer<Cairo::Context> ren(map,c,offset_x, offset_y); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } void render6(const mapnik::Map& map,PycairoContext* context) { Py_BEGIN_ALLOW_THREADS try { Cairo::RefPtr<Cairo::Context> c(new Cairo::Context(context->ctx)); mapnik::cairo_renderer<Cairo::Context> ren(map,c); ren.apply(); } catch (...) { Py_BLOCK_THREADS throw; } Py_END_ALLOW_THREADS } #endif void render_tile_to_file(const mapnik::Map& map, unsigned offset_x, unsigned offset_y, unsigned width, unsigned height, const std::string& file, const std::string& format) { mapnik::Image32 image(width,height); render(map,image,offset_x, offset_y); mapnik::save_to_file(image.data(),file,format); } void render_to_file1(const mapnik::Map& map, const std::string& filename, const std::string& format) { mapnik::Image32 image(map.getWidth(),map.getHeight()); render(map,image,0,0); mapnik::save_to_file(image,filename,format); } void render_to_file2(const mapnik::Map& map, const std::string& filename) { mapnik::Image32 image(map.getWidth(),map.getHeight()); render(map,image,0,0); mapnik::save_to_file(image,filename); } double scale_denominator(mapnik::Map const &map, bool geographic) { return mapnik::scale_denominator(map, geographic); } void translator(mapnik::config_error const & ex) { PyErr_SetString(PyExc_UserWarning, ex.what()); } unsigned mapnik_version() { return MAPNIK_VERSION; } BOOST_PYTHON_FUNCTION_OVERLOADS(load_map_overloads, load_map, 2, 3); BOOST_PYTHON_FUNCTION_OVERLOADS(load_map_string_overloads, load_map_string, 2, 3); BOOST_PYTHON_MODULE(_mapnik) { using namespace boost::python; using mapnik::load_map; using mapnik::load_map_string; using mapnik::save_map; register_exception_translator<mapnik::config_error>(translator); register_cairo(); export_query(); export_geometry(); export_feature(); export_featureset(); export_datasource(); export_parameters(); export_color(); export_envelope(); export_image(); export_image_view(); export_filter(); export_rule(); export_style(); export_layer(); export_stroke(); export_datasource_cache(); export_point_symbolizer(); export_line_symbolizer(); export_line_pattern_symbolizer(); export_polygon_symbolizer(); export_polygon_pattern_symbolizer(); export_raster_symbolizer(); export_text_symbolizer(); export_shield_symbolizer(); export_font_engine(); export_projection(); export_proj_transform(); export_view_transform(); export_coord(); export_map(); def("render_to_file",&render_to_file1, "\n" "Render Map to file using explicit image type.\n" "\n" "Usage:\n" ">>> from mapnik import Map, render_to_file, load_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> render_to_file(m,'image32bit.png','png')\n" "\n" "8 bit (paletted) PNG can be requested with 'png256':\n" ">>> render_to_file(m,'8bit_image.png','png256')\n" "\n" "JPEG quality can be controlled by adding a suffix to\n" "'jpeg' between 0 and 100 (default is 85):\n" ">>> render_to_file(m,'top_quality.jpeg','jpeg100')\n" ">>> render_to_file(m,'medium_quality.jpeg','jpeg50')\n" ); def("render_to_file",&render_to_file2, "\n" "Render Map to file (type taken from file extension)\n" "\n" "Usage:\n" ">>> from mapnik import Map, render_to_file, load_map\n" ">>> m = Map(256,256)\n" ">>> render_to_file(m,'image.jpeg')\n" "\n" ); def("render_tile_to_file",&render_tile_to_file, "\n" "TODO\n" "\n" ); def("render",&render, "\n" "Render Map to an AGG Image32 using offsets\n" "\n" "Usage:\n" ">>> from mapnik import Map, Image, render, load_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> im = Image(m.width,m.height)\n" ">>> render(m,im,1,1)\n" "\n" ); def("render",&render2, "\n" "Render Map to an AGG Image32\n" "\n" "Usage:\n" ">>> from mapnik import Map, Image, render, load_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> im = Image(m.width,m.height)\n" ">>> render(m,im)\n" "\n" ); #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) def("render",&render3, "\n" "Render Map to Cairo Surface using offsets\n" "\n" "Usage:\n" ">>> from mapnik import Map, render, load_map\n" ">>> from cairo import SVGSurface\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> surface = SVGSurface('image.svg', m.width, m.height)\n" ">>> render(m,surface,1,1)\n" "\n" ); def("render",&render4, "\n" "Render Map to Cairo Surface\n" "\n" "Usage:\n" ">>> from mapnik import Map, render, load_map\n" ">>> from cairo import SVGSurface\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> surface = SVGSurface('image.svg', m.width, m.height)\n" ">>> render(m,surface)\n" "\n" ); def("render",&render5, "\n" "Render Map to Cairo Context using offsets\n" "\n" "Usage:\n" ">>> from mapnik import Map, render, load_map\n" ">>> from cairo import SVGSurface, Context\n" ">>> surface = SVGSurface('image.svg', m.width, m.height)\n" ">>> ctx = Context(surface)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> render(m,context,1,1)\n" "\n" ); def("render",&render6, "\n" "Render Map to Cairo Context\n" "\n" "Usage:\n" ">>> from mapnik import Map, render, load_map\n" ">>> from cairo import SVGSurface, Context\n" ">>> surface = SVGSurface('image.svg', m.width, m.height)\n" ">>> ctx = Context(surface)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> render(m,context)\n" "\n" ); #endif def("scale_denominator", &scale_denominator, "\n" "Return the Map Scale Denominator.\n" "Also available as Map.scale_denominator()\n" "\n" "Usage:\n" "\n" ">>> from mapnik import Map, Projection, scale_denominator, load_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile.xml')\n" ">>> scale_denominator(m,Projection(m.srs).geographic)\n" "\n" ); def("load_map", & load_map, load_map_overloads()); def("load_map_from_string", & load_map_string, load_map_string_overloads()); def("save_map", & save_map, "\n" "Save Map object to XML file\n" "\n" "Usage:\n" ">>> from mapnik import Map, load_map, save_map\n" ">>> m = Map(256,256)\n" ">>> load_map(m,'mapfile_wgs84.xml')\n" ">>> m.srs\n" "'+proj=latlong +datum=WGS84'\n" ">>> m.srs = '+init=espg:3395'\n" ">>> save_map(m,'mapfile_mercator.xml')\n" "\n" ); def("mapnik_version", &mapnik_version,"Get the Mapnik version number"); using mapnik::symbolizer; class_<symbolizer>("Symbolizer",no_init) ; register_ptr_to_python<mapnik::filter_ptr>(); } <|endoftext|>
<commit_before>/** @copyright * Copyright (c) 2017 Stuart W Baker * 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. * * @file MCP2515Can.cxx * This file implements the CAN driver for the MCP2515 CAN Controller. * * @author Stuart W. Baker * @date 3 January 2017 */ #include "MCP2515Can.hxx" #include <fcntl.h> const MCP2515Can::MCP2515Baud MCP2515Can::baudTable[] = { /* 20 MHz clock source * TQ = (2 * BRP) / freq = (2 * 4) / 20 MHz = 400 nsec * Baud = 125 kHz * bit time = 1 / 125 kHz = 8 usec = 20 TQ * SyncSeg = 1 TQ * PropSeg = 7 TQ * PS1 = 8 TQ * PS2 = 4 TQ * sample time = (1 TQ + 7 TQ + 8 TQ) / 20 TQ = 80% * SJW = PS2 - 1 = 4 - 1 = 3 * SJW = 3 * 400 nsec = 1.2 usec */ {20000000, 125000, {(4 - 1), (2 - 1)}, {(7 - 1), (8 - 1), 0, 1}, {(4 - 1), 0, 0}}, /* 8 MHz clock source * TQ = (2 * BRP) / freq = (2 * 2) / 8 MHz = 500 nsec * Baud = 125 kHz * bit time = 1 / 125 kHz = 8 usec = 16 TQ * SyncSeg = 1 TQ * PropSeg = 4 TQ * PS1 = 8 TQ * PS2 = 3 TQ * sample time = (1 TQ + 4 TQ + 8 TQ) / 16 TQ = 81.25% * SJW = PS2 - 1 = 3 - 1 = 2 * SJW = 2 * 500 nsec = 1 usec */ {8000000, 125000, {(2 - 1), (2 - 1)}, {(4 - 1), (8 - 1), 0, 1}, {(3 - 1), 0, 0}} }; /* * init() */ void MCP2515Can::init(const char *spi_name, uint32_t freq, uint32_t baud) { spi = ::open(spi_name, O_RDWR); HASSERT(spi >= 0); /* reset device */ reset(); /* wait until device is in configuration mode */ while ((register_read(CANSTAT) & 0xE0) != 0x80); /* find valid timing settings for the requested frequency and buad rates */ for (size_t i = 0; i < (sizeof(baudTable) / sizeof(baudTable[0])); ++i) { if (baudTable[i].freq == freq && baudTable[i].baud == baud) { register_write(CNF1, baudTable[i].cnf1.data); register_write(CNF2, baudTable[i].cnf2.data); register_write(CNF3, baudTable[i].cnf3.data); /* setup RX Buf 0 and 1 to receive any message */ register_write(RXB0CTRL, 0x60); register_write(RXB1CTRL, 0x60); /* enable error and receive interrupts */ register_write(CANINTE, MERR | ERRI | RX1I | RX0I); /* put the device into normal operation mode */ register_write(CANCTRL, 0x00); /* wait until device is in normal mode */ while ((register_read(CANSTAT) & 0xE0) != 0x00); return; } } /* unsupported frequency */ HASSERT(0); } /* * enable() */ void MCP2515Can::enable() { /* there is a mutex lock above us, so the following sequence is atomic */ if (!is_created()) { /* start the thread */ /** @todo make this the highest possible thread priority */ start(name, 0, 1024); } /* reset device */ //reset(); interrupt_enable(); } /* * disable() */ void MCP2515Can::disable() { interrupt_disable(); register_write(TXB0CTRL, 0x00); register_write(TXB1CTRL, 0x00); portENTER_CRITICAL(); /* flush out any transmit data in the pipleline */ txBuf->flush(); txPending = 0; portEXIT_CRITICAL(); } /* * tx_msg_locked() */ void MCP2515Can::tx_msg_locked() { /* the node lock_ will be locked by the caller */ if (txPending < 3) { struct can_frame *can_frame; /* find an empty buffer */ int index = 0; if (txPending & 0x1) { /* buffer 0 already in use */ index = 1; } portENTER_CRITICAL(); if (txBuf->data_read_pointer(&can_frame)) { Buffer tx_buf(can_frame); txBuf->consume(1); txBuf->signal_condition(); portEXIT_CRITICAL(); txPending |= (0x1 << index); /* bump up priority of the other buffer so it will transmit first * if it is pending */ bit_modify(index == 0 ? TXB1CTRL : TXB0CTRL, 0x01, 0x03); /* load the tranmsit buffer */ buffer_write(index, tx_buf.get_payload()); /* request to send at lowest priority */ bit_modify(index == 0 ? TXB0CTRL : TXB1CTRL, 0x08, 0x0B); /* enable transmit interrupt */ bit_modify(CANINTE, TX0I << index, TX0I << index); } else { portEXIT_CRITICAL(); } } } /* * rx_msg() */ void MCP2515Can::rx_msg(int index) { Buffer rx_buf; buffer_read(index, rx_buf.get_payload()); struct can_frame *can_frame; portENTER_CRITICAL(); if (rxBuf->data_write_pointer(&can_frame)) { rx_buf.build_struct_can_frame(can_frame); rxBuf->advance(1); ++numReceivedPackets_; rxBuf->signal_condition(); } else { /* receive overrun occured */ ++overrunCount; } portEXIT_CRITICAL(); } /* * entry() */ void *MCP2515Can::entry() { for ( ; /* forever */ ; ) { #if MCP2515_DEBUG int result = sem.timedwait(SEC_TO_NSEC(1)); lock_.lock(); if (result != 0) { spi_ioc_transfer xfer[2]; memset(xfer, 0, sizeof(xfer)); uint8_t wr_data[2] = {READ, 0}; xfer[0].tx_buf = (unsigned long)wr_data; xfer[0].len = sizeof(wr_data); xfer[1].rx_buf = (unsigned long)regs; xfer[1].len = sizeof(regs); xfer[1].cs_change = 1; ::ioctl(spi, SPI_IOC_MESSAGE(2), xfer); lock_.unlock(); continue; } #else sem.wait(); lock_.lock(); #endif /* read status flags */ uint8_t canintf = register_read(CANINTF); if (canintf & MERR) { /* message error interrupt active */ } if (canintf & ERRI) { /* error interrupt active */ register_write(TXB0CTRL, 0x00); register_write(TXB1CTRL, 0x00); portENTER_CRITICAL(); ++softErrorCount; /* flush out any transmit data in the pipleline */ txBuf->flush(); txBuf->signal_condition(); portEXIT_CRITICAL(); txPending = 0; } if (canintf & RX0I) { /* receive interrupt active */ rx_msg(0); } if (txPending) { /* transmit interrupt active and transmission complete */ if (canintf & TX0I) { txPending &= ~0x1; bit_modify(CANINTE, 0, TX0I); bit_modify(CANINTF, 0, TX0I); ++numTransmittedPackets_; } if (canintf & TX1I) { txPending &= ~0x2; bit_modify(CANINTE, 0, TX1I); bit_modify(CANINTF, 0, TX1I); ++numTransmittedPackets_; } tx_msg_locked(); } /* Refresh status flags just in case RX1 buffer became active * before we could finish reading out RX0 buffer. This ussually * won't happen because we should be able to respond to incoming * messages fast enough to only use RX0 buffer. */ canintf = register_read(CANINTF); if (canintf & RX1I) { /* receive interrupt active */ rx_msg(1); } lock_.unlock(); interrupt_enable(); } return NULL; } /* * interrupt_handler() */ void MCP2515Can::interrupt_handler() { int woken = false; interrupt_disable(); sem.post_from_isr(&woken); os_isr_exit_yield_test(woken); } <commit_msg>Update MCP2515 driver to configure the SPI bus settings.<commit_after>/** @copyright * Copyright (c) 2017 Stuart W Baker * 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. * * @file MCP2515Can.cxx * This file implements the CAN driver for the MCP2515 CAN Controller. * * @author Stuart W. Baker * @date 3 January 2017 */ #include "MCP2515Can.hxx" #include <fcntl.h> const MCP2515Can::MCP2515Baud MCP2515Can::baudTable[] = { /* 20 MHz clock source * TQ = (2 * BRP) / freq = (2 * 4) / 20 MHz = 400 nsec * Baud = 125 kHz * bit time = 1 / 125 kHz = 8 usec = 20 TQ * SyncSeg = 1 TQ * PropSeg = 7 TQ * PS1 = 8 TQ * PS2 = 4 TQ * sample time = (1 TQ + 7 TQ + 8 TQ) / 20 TQ = 80% * SJW = PS2 - 1 = 4 - 1 = 3 * SJW = 3 * 400 nsec = 1.2 usec */ {20000000, 125000, {(4 - 1), (2 - 1)}, {(7 - 1), (8 - 1), 0, 1}, {(4 - 1), 0, 0}}, /* 8 MHz clock source * TQ = (2 * BRP) / freq = (2 * 2) / 8 MHz = 500 nsec * Baud = 125 kHz * bit time = 1 / 125 kHz = 8 usec = 16 TQ * SyncSeg = 1 TQ * PropSeg = 4 TQ * PS1 = 8 TQ * PS2 = 3 TQ * sample time = (1 TQ + 4 TQ + 8 TQ) / 16 TQ = 81.25% * SJW = PS2 - 1 = 3 - 1 = 2 * SJW = 2 * 500 nsec = 1 usec */ {8000000, 125000, {(2 - 1), (2 - 1)}, {(4 - 1), (8 - 1), 0, 1}, {(3 - 1), 0, 0}} }; /* * init() */ void MCP2515Can::init(const char *spi_name, uint32_t freq, uint32_t baud) { spi = ::open(spi_name, O_RDWR); HASSERT(spi >= 0); /* configure SPI bus settings */ uint8_t spi_mode = SPI_MODE_0; uint8_t spi_bpw = 8; uint32_t spi_max_speed_hz = freq / 4; ::ioctl(spi, SPI_IOC_WR_MODE, &spi_mode); ::ioctl(spi, SPI_IOC_WR_BITS_PER_WORD, &spi_bpw); ::ioctl(spi, SPI_IOC_WR_MAX_SPEED_HZ, &spi_max_speed_hz); /* reset device */ reset(); /* wait until device is in configuration mode */ while ((register_read(CANSTAT) & 0xE0) != 0x80); /* find valid timing settings for the requested frequency and buad rates */ for (size_t i = 0; i < (sizeof(baudTable) / sizeof(baudTable[0])); ++i) { if (baudTable[i].freq == freq && baudTable[i].baud == baud) { register_write(CNF1, baudTable[i].cnf1.data); register_write(CNF2, baudTable[i].cnf2.data); register_write(CNF3, baudTable[i].cnf3.data); /* setup RX Buf 0 and 1 to receive any message */ register_write(RXB0CTRL, 0x60); register_write(RXB1CTRL, 0x60); /* enable error and receive interrupts */ register_write(CANINTE, MERR | ERRI | RX1I | RX0I); /* put the device into normal operation mode */ register_write(CANCTRL, 0x00); /* wait until device is in normal mode */ while ((register_read(CANSTAT) & 0xE0) != 0x00); return; } } /* unsupported frequency */ HASSERT(0); } /* * enable() */ void MCP2515Can::enable() { /* there is a mutex lock above us, so the following sequence is atomic */ if (!is_created()) { /* start the thread */ /** @todo make this the highest possible thread priority */ start(name, 0, 1024); } /* reset device */ //reset(); interrupt_enable(); } /* * disable() */ void MCP2515Can::disable() { interrupt_disable(); register_write(TXB0CTRL, 0x00); register_write(TXB1CTRL, 0x00); portENTER_CRITICAL(); /* flush out any transmit data in the pipleline */ txBuf->flush(); txPending = 0; portEXIT_CRITICAL(); } /* * tx_msg_locked() */ void MCP2515Can::tx_msg_locked() { /* the node lock_ will be locked by the caller */ if (txPending < 3) { struct can_frame *can_frame; /* find an empty buffer */ int index = 0; if (txPending & 0x1) { /* buffer 0 already in use */ index = 1; } portENTER_CRITICAL(); if (txBuf->data_read_pointer(&can_frame)) { Buffer tx_buf(can_frame); txBuf->consume(1); txBuf->signal_condition(); portEXIT_CRITICAL(); txPending |= (0x1 << index); /* bump up priority of the other buffer so it will transmit first * if it is pending */ bit_modify(index == 0 ? TXB1CTRL : TXB0CTRL, 0x01, 0x03); /* load the tranmsit buffer */ buffer_write(index, tx_buf.get_payload()); /* request to send at lowest priority */ bit_modify(index == 0 ? TXB0CTRL : TXB1CTRL, 0x08, 0x0B); /* enable transmit interrupt */ bit_modify(CANINTE, TX0I << index, TX0I << index); } else { portEXIT_CRITICAL(); } } } /* * rx_msg() */ void MCP2515Can::rx_msg(int index) { Buffer rx_buf; buffer_read(index, rx_buf.get_payload()); struct can_frame *can_frame; portENTER_CRITICAL(); if (rxBuf->data_write_pointer(&can_frame)) { rx_buf.build_struct_can_frame(can_frame); rxBuf->advance(1); ++numReceivedPackets_; rxBuf->signal_condition(); } else { /* receive overrun occured */ ++overrunCount; } portEXIT_CRITICAL(); } /* * entry() */ void *MCP2515Can::entry() { for ( ; /* forever */ ; ) { #if MCP2515_DEBUG int result = sem.timedwait(SEC_TO_NSEC(1)); lock_.lock(); if (result != 0) { spi_ioc_transfer xfer[2]; memset(xfer, 0, sizeof(xfer)); uint8_t wr_data[2] = {READ, 0}; xfer[0].tx_buf = (unsigned long)wr_data; xfer[0].len = sizeof(wr_data); xfer[1].rx_buf = (unsigned long)regs; xfer[1].len = sizeof(regs); xfer[1].cs_change = 1; ::ioctl(spi, SPI_IOC_MESSAGE(2), xfer); lock_.unlock(); continue; } #else sem.wait(); lock_.lock(); #endif /* read status flags */ uint8_t canintf = register_read(CANINTF); if (canintf & MERR) { /* message error interrupt active */ } if (canintf & ERRI) { /* error interrupt active */ register_write(TXB0CTRL, 0x00); register_write(TXB1CTRL, 0x00); portENTER_CRITICAL(); ++softErrorCount; /* flush out any transmit data in the pipleline */ txBuf->flush(); txBuf->signal_condition(); portEXIT_CRITICAL(); txPending = 0; } if (canintf & RX0I) { /* receive interrupt active */ rx_msg(0); } if (txPending) { /* transmit interrupt active and transmission complete */ if (canintf & TX0I) { txPending &= ~0x1; bit_modify(CANINTE, 0, TX0I); bit_modify(CANINTF, 0, TX0I); ++numTransmittedPackets_; } if (canintf & TX1I) { txPending &= ~0x2; bit_modify(CANINTE, 0, TX1I); bit_modify(CANINTF, 0, TX1I); ++numTransmittedPackets_; } tx_msg_locked(); } /* Refresh status flags just in case RX1 buffer became active * before we could finish reading out RX0 buffer. This ussually * won't happen because we should be able to respond to incoming * messages fast enough to only use RX0 buffer. */ canintf = register_read(CANINTF); if (canintf & RX1I) { /* receive interrupt active */ rx_msg(1); } lock_.unlock(); interrupt_enable(); } return NULL; } /* * interrupt_handler() */ void MCP2515Can::interrupt_handler() { int woken = false; interrupt_disable(); sem.post_from_isr(&woken); os_isr_exit_yield_test(woken); } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdafx.h" #include "common/shared_types.h" #include "types/typeops.h" #include "functions/function.h" #include "functions/function_impl.h" #include "functions/func_parse_fragment.h" #include "system/globalenv.h" #include "compiler/expression/expr_consts.h" namespace zorba { /******************************************************************************* ********************************************************************************/ void populate_context_parse_fragment_impl(static_context* sctx) { xqtref_t lParseOptType = GENV_TYPESYSTEM.create_node_type( store::StoreConsts::elementNode, createQName("http://www.zorba-xquery.com/modules/xml-options","","options"), NULL, TypeConstants::QUANT_ONE, false, false ); { DECL_WITH_KIND(sctx, fn_zorba_xml_parse, (createQName("http://www.zorba-xquery.com/modules/xml","","parse"), GENV_TYPESYSTEM.STRING_TYPE_QUESTION, lParseOptType, GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR), FunctionConsts::FN_ZORBA_XML_PARSE_2); } } } /* vim:set et sw=2 ts=2: */ <commit_msg>Fixed the quantity of the options parameter from ONE to QUESTION.<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdafx.h" #include "common/shared_types.h" #include "types/typeops.h" #include "functions/function.h" #include "functions/function_impl.h" #include "functions/func_parse_fragment.h" #include "system/globalenv.h" #include "compiler/expression/expr_consts.h" namespace zorba { /******************************************************************************* ********************************************************************************/ void populate_context_parse_fragment_impl(static_context* sctx) { xqtref_t lParseOptType = GENV_TYPESYSTEM.create_node_type( store::StoreConsts::elementNode, createQName("http://www.zorba-xquery.com/modules/xml-options","","options"), NULL, TypeConstants::QUANT_QUESTION, false, false ); { DECL_WITH_KIND(sctx, fn_zorba_xml_parse, (createQName("http://www.zorba-xquery.com/modules/xml","","parse"), GENV_TYPESYSTEM.STRING_TYPE_QUESTION, lParseOptType, GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR), FunctionConsts::FN_ZORBA_XML_PARSE_2); } } } /* vim:set et sw=2 ts=2: */ <|endoftext|>
<commit_before>// Copyright 2017 Massachusetts Institute of Technology #include <csignal> #include <memory> #include <utility> #include <algorithm> #include <ros/ros.h> #include <pcl_ros/transforms.h> #include <pcl/conversions.h> #include <tf2_sensor_msgs/tf2_sensor_msgs.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/TransformStamped.h> #include <visualization_msgs/MarkerArray.h> #include <visualization_msgs/MarkerArray.h> #include <nav_msgs/OccupancyGrid.h> #include <fla_utils/param_utils.h> #include "global_mapper_ros/global_mapper_ros.h" #include "global_mapper/global_mapper.h" #include "global_mapper/params.h" namespace global_mapper { GlobalMapperRos::GlobalMapperRos(volatile std::sig_atomic_t* stop_signal_ptr) : stop_signal_ptr_(stop_signal_ptr), publish_voxel_map_(false), nh_(), pnh_("~"), tf_listener_(tf_buffer_) { tf_buffer_.setUsingDedicatedThread(true); GetParams(); InitSubscribers(); InitPublishers(); } void GlobalMapperRos::GetParams() { fla_utils::SafeGetParam(pnh_, "map_frame", params_.map_frame); // pixel map params std::vector<double> pixel_xy_min(2, 0.0); fla_utils::SafeGetParam(pnh_, "pixel_map/xy_min", pixel_xy_min); std::copy(pixel_xy_min.begin(), pixel_xy_min.end(), params_.pixel_xy_min); std::vector<double> pixel_xy_max(2, 0.0); fla_utils::SafeGetParam(pnh_, "pixel_map/xy_max", pixel_xy_max); std::copy(pixel_xy_max.begin(), pixel_xy_max.end(), params_.pixel_xy_max); fla_utils::SafeGetParam(pnh_, "pixel_map/resolution", params_.pixel_resolution); fla_utils::SafeGetParam(pnh_, "pixel_map/init_value", params_.pixel_init_value); fla_utils::SafeGetParam(pnh_, "pixel_map/bound_min", params_.pixel_bound_min); fla_utils::SafeGetParam(pnh_, "pixel_map/bound_max", params_.pixel_bound_max); fla_utils::SafeGetParam(pnh_, "pixel_map/min_z_abs", params_.pixel_min_z_abs); fla_utils::SafeGetParam(pnh_, "pixel_map/max_z_abs", params_.pixel_max_z_abs); fla_utils::SafeGetParam(pnh_, "pixel_map/use_rel_flatten", params_.pixel_use_rel_flatten); fla_utils::SafeGetParam(pnh_, "pixel_map/min_z_rel", params_.pixel_min_z_rel); fla_utils::SafeGetParam(pnh_, "pixel_map/max_z_rel", params_.pixel_max_z_rel); fla_utils::SafeGetParam(pnh_, "pixel_map/publish_map", publish_pixel_map_); // voxel map params std::vector<double> voxel_xyz_min(3, 0.0); fla_utils::SafeGetParam(pnh_, "voxel_map/xyz_min", voxel_xyz_min); std::copy(voxel_xyz_min.begin(), voxel_xyz_min.end(), params_.voxel_xyz_min); std::vector<double> voxel_xyz_max(3, 0.0); fla_utils::SafeGetParam(pnh_, "voxel_map/xyz_max", voxel_xyz_max); std::copy(voxel_xyz_max.begin(), voxel_xyz_max.end(), params_.voxel_xyz_max); fla_utils::SafeGetParam(pnh_, "voxel_map/resolution", params_.voxel_resolution); fla_utils::SafeGetParam(pnh_, "voxel_map/init_value", params_.voxel_init_value); fla_utils::SafeGetParam(pnh_, "voxel_map/bound_min", params_.voxel_bound_min); fla_utils::SafeGetParam(pnh_, "voxel_map/bound_max", params_.voxel_bound_max); fla_utils::SafeGetParam(pnh_, "voxel_map/min_z_abs", params_.voxel_min_z_abs); fla_utils::SafeGetParam(pnh_, "voxel_map/max_z_abs", params_.voxel_max_z_abs); fla_utils::SafeGetParam(pnh_, "voxel_map/use_rel_cropping", params_.voxel_use_rel_cropping); fla_utils::SafeGetParam(pnh_, "voxel_map/min_z_rel", params_.voxel_min_z_rel); fla_utils::SafeGetParam(pnh_, "voxel_map/max_z_rel", params_.voxel_max_z_rel); fla_utils::SafeGetParam(pnh_, "voxel_map/hit_inc", params_.voxel_hit_inc); fla_utils::SafeGetParam(pnh_, "voxel_map/miss_inc", params_.voxel_miss_inc); fla_utils::SafeGetParam(pnh_, "voxel_map/publish_map", publish_voxel_map_); } void GlobalMapperRos::InitSubscribers() { point_cloud_sub_ = pnh_.subscribe("cloud_topic", 10, &GlobalMapperRos::PointCloudCallback, this); } void GlobalMapperRos::InitPublishers() { pixel_map_pub_ = pnh_.advertise<nav_msgs::OccupancyGrid>("pixel_map_topic", 1); voxel_map_pub_ = pnh_.advertise<visualization_msgs::MarkerArray>("voxel_map_topic", 1); map_pub_timer_ = nh_.createTimer(ros::Duration(1.0), &GlobalMapperRos::PublishMap, this); } /* Return a RGB colour value given a scalar v in the range [vmin,vmax] In this case each colour component ranges from 0 (no contribution) to 1 (fully saturated). The colour is clipped at the end of the scales if v is outside the range [vmin,vmax] */ void GlobalMapperRos::GrayscaleToRGBJet(double v, double vmin, double vmax, std::vector<double>* rgb) { double dv; if (v < vmin) v = vmin; if (v > vmax) v = vmax; dv = vmax - vmin; if (v < (vmin + 0.25 * dv)) { rgb->at(0) = 0; rgb->at(1) = 4 * (v - vmin) / dv; } else if (v < (vmin + 0.5 * dv)) { rgb->at(0) = 0; rgb->at(2) = 1 + 4 * (vmin + 0.25 * dv - v) / dv; } else if (v < (vmin + 0.75 * dv)) { rgb->at(0) = 4 * (v - vmin - 0.5 * dv) / dv; rgb->at(2) = 0; } else { rgb->at(1) = 1 + 4 * (vmin + 0.75 * dv - v) / dv; rgb->at(2) = 0; } } void GlobalMapperRos::PopulateVoxelMapMsg(visualization_msgs::MarkerArray* marker_array) { // check for bad input if (marker_array == nullptr) { return; } geometry_msgs::TransformStamped transform_stamped; Eigen::Vector3d transform; try { transform_stamped = tf_buffer_.lookupTransform("world", "body", ros::Time(0), ros::Duration(1.0)); transform(0) = transform_stamped.transform.translation.x; transform(1) = transform_stamped.transform.translation.y; transform(2) = transform_stamped.transform.translation.z; } catch (tf2::TransformException &ex) { ROS_WARN("[world_database_master_ros] OnGetTransform failed with %s", ex.what()); transform(0) = std::numeric_limits<double>::quiet_NaN(); transform(1) = std::numeric_limits<double>::quiet_NaN(); transform(2) = std::numeric_limits<double>::quiet_NaN(); } // get occuppied voxels double xyz[3] = {0.0}; Eigen::Map<Eigen::Vector3d> xyz_map(&xyz[0]); std::vector<int> occ_inds; for (int i = 0; i < global_mapper_ptr_->voxel_map_ptr_->num_cells; ++i) { global_mapper_ptr_->voxel_map_ptr_->indToLoc(i, xyz); if (global_mapper_ptr_->voxel_map_ptr_->readValue(xyz) > 0.6) { if((xyz_map - transform).norm() < 20.0) { occ_inds.push_back(i); } } } marker_array->markers.resize(occ_inds.size()); std::vector<double> rgb(3, 1.0); for (int i = 0; i < occ_inds.size(); ++i) { visualization_msgs::Marker& marker = marker_array->markers[i]; // create voxel marker marker.header.frame_id = params_.map_frame; marker.header.stamp = ros::Time::now(); marker.id = i; marker.type = visualization_msgs::Marker::CUBE; marker.action = visualization_msgs::Marker::ADD; // orientation marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; // scale marker.scale.x = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[0]; marker.scale.y = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[1]; marker.scale.z = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[2]; // position global_mapper_ptr_->voxel_map_ptr_->indToLoc(occ_inds[i], xyz); marker.pose.position.x = xyz[0]; marker.pose.position.y = xyz[1]; marker.pose.position.z = xyz[2]; // color GrayscaleToRGBJet(marker.pose.position.z, global_mapper_ptr_->voxel_map_ptr_->xyz0[2], global_mapper_ptr_->voxel_map_ptr_->xyz1[2], &rgb); marker.color.r = static_cast<float>(rgb[0]); marker.color.g = static_cast<float>(rgb[1]); marker.color.b = static_cast<float>(rgb[2]); marker.color.a = 1.0f; } } void GlobalMapperRos::PopulatePixelMapMsg(nav_msgs::OccupancyGrid* occupancy_grid) { // check for bad input if (occupancy_grid == nullptr) { return; } // header occupancy_grid->header.frame_id = params_.map_frame; occupancy_grid->header.stamp = ros::Time::now(); // metadata occupancy_grid->info.resolution = global_mapper_ptr_->pixel_map_ptr_->metersPerPixel; occupancy_grid->info.width = global_mapper_ptr_->pixel_map_ptr_->dimensions[0]; occupancy_grid->info.height = global_mapper_ptr_->pixel_map_ptr_->dimensions[1]; occupancy_grid->info.origin.position.x = 0.0; occupancy_grid->info.origin.position.y = 0.0; occupancy_grid->info.origin.position.z = 0.0; // data float occ_value = 0.0; double xy[2] = {0.0}; occupancy_grid->data.resize(global_mapper_ptr_->pixel_map_ptr_->num_cells); for (int i = 0; i < global_mapper_ptr_->pixel_map_ptr_->num_cells; ++i) { // get xy location global_mapper_ptr_->pixel_map_ptr_->indToLoc(i, xy); // get pixel value and scale occ_value = global_mapper_ptr_->pixel_map_ptr_->readValue(xy); occ_value *= 100.0; occupancy_grid->data[i] = static_cast<uint8_t>(occ_value + 0.5); } } void GlobalMapperRos::PublishMap(const ros::TimerEvent& event) { // lock std::lock_guard<std::mutex> map_lock(global_mapper_ptr_->map_mutex()); // voxel map if (publish_voxel_map_) { visualization_msgs::MarkerArray marker_array; PopulateVoxelMapMsg(&marker_array); voxel_map_pub_.publish(marker_array); } // pixel_map if (publish_pixel_map_) { nav_msgs::OccupancyGrid occupancy_grid; PopulatePixelMapMsg(&occupancy_grid); pixel_map_pub_.publish(occupancy_grid); } } void GlobalMapperRos::PointCloudCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_ptr) { // get transform const std::string target_frame = params_.map_frame; geometry_msgs::TransformStamped transform_stamped; // try to get correct transform try { transform_stamped = tf_buffer_.lookupTransform(target_frame, cloud_ptr->header.frame_id, ros::Time(cloud_ptr->header.stamp), ros::Duration(0.02)); } catch (tf2::TransformException &ex) { ROS_WARN("%s", ex.what()); return; } sensor_msgs::PointCloud2 cloud_out; tf2::doTransform(*cloud_ptr, cloud_out, transform_stamped); pcl::PointCloud<pcl::PointXYZ> cloud; pcl::fromROSMsg(cloud_out, cloud); // // push to mapper global_mapper_ptr_->PushPointCloud(cloud.makeShared()); } void GlobalMapperRos::Run() { // start mapping thread global_mapper_ptr_ = std::unique_ptr<GlobalMapper>(new GlobalMapper(stop_signal_ptr_, params_)); global_mapper_ptr_->Run(); // handle ros callbacks ros::spin(); } } // namespace global_mapper <commit_msg>Cleanup voxel visualization code.<commit_after>// Copyright 2017 Massachusetts Institute of Technology #include <csignal> #include <memory> #include <utility> #include <algorithm> #include <ros/ros.h> #include <pcl_ros/transforms.h> #include <pcl/conversions.h> #include <tf2_sensor_msgs/tf2_sensor_msgs.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/TransformStamped.h> #include <visualization_msgs/MarkerArray.h> #include <visualization_msgs/MarkerArray.h> #include <nav_msgs/OccupancyGrid.h> #include <fla_utils/param_utils.h> #include "global_mapper_ros/global_mapper_ros.h" #include "global_mapper/global_mapper.h" #include "global_mapper/params.h" namespace global_mapper { GlobalMapperRos::GlobalMapperRos(volatile std::sig_atomic_t* stop_signal_ptr) : stop_signal_ptr_(stop_signal_ptr), publish_voxel_map_(false), nh_(), pnh_("~"), tf_listener_(tf_buffer_) { tf_buffer_.setUsingDedicatedThread(true); GetParams(); InitSubscribers(); InitPublishers(); } void GlobalMapperRos::GetParams() { fla_utils::SafeGetParam(pnh_, "map_frame", params_.map_frame); // pixel map params std::vector<double> pixel_xy_min(2, 0.0); fla_utils::SafeGetParam(pnh_, "pixel_map/xy_min", pixel_xy_min); std::copy(pixel_xy_min.begin(), pixel_xy_min.end(), params_.pixel_xy_min); std::vector<double> pixel_xy_max(2, 0.0); fla_utils::SafeGetParam(pnh_, "pixel_map/xy_max", pixel_xy_max); std::copy(pixel_xy_max.begin(), pixel_xy_max.end(), params_.pixel_xy_max); fla_utils::SafeGetParam(pnh_, "pixel_map/resolution", params_.pixel_resolution); fla_utils::SafeGetParam(pnh_, "pixel_map/init_value", params_.pixel_init_value); fla_utils::SafeGetParam(pnh_, "pixel_map/bound_min", params_.pixel_bound_min); fla_utils::SafeGetParam(pnh_, "pixel_map/bound_max", params_.pixel_bound_max); fla_utils::SafeGetParam(pnh_, "pixel_map/min_z_abs", params_.pixel_min_z_abs); fla_utils::SafeGetParam(pnh_, "pixel_map/max_z_abs", params_.pixel_max_z_abs); fla_utils::SafeGetParam(pnh_, "pixel_map/use_rel_flatten", params_.pixel_use_rel_flatten); fla_utils::SafeGetParam(pnh_, "pixel_map/min_z_rel", params_.pixel_min_z_rel); fla_utils::SafeGetParam(pnh_, "pixel_map/max_z_rel", params_.pixel_max_z_rel); fla_utils::SafeGetParam(pnh_, "pixel_map/publish_map", publish_pixel_map_); // voxel map params std::vector<double> voxel_xyz_min(3, 0.0); fla_utils::SafeGetParam(pnh_, "voxel_map/xyz_min", voxel_xyz_min); std::copy(voxel_xyz_min.begin(), voxel_xyz_min.end(), params_.voxel_xyz_min); std::vector<double> voxel_xyz_max(3, 0.0); fla_utils::SafeGetParam(pnh_, "voxel_map/xyz_max", voxel_xyz_max); std::copy(voxel_xyz_max.begin(), voxel_xyz_max.end(), params_.voxel_xyz_max); fla_utils::SafeGetParam(pnh_, "voxel_map/resolution", params_.voxel_resolution); fla_utils::SafeGetParam(pnh_, "voxel_map/init_value", params_.voxel_init_value); fla_utils::SafeGetParam(pnh_, "voxel_map/bound_min", params_.voxel_bound_min); fla_utils::SafeGetParam(pnh_, "voxel_map/bound_max", params_.voxel_bound_max); fla_utils::SafeGetParam(pnh_, "voxel_map/min_z_abs", params_.voxel_min_z_abs); fla_utils::SafeGetParam(pnh_, "voxel_map/max_z_abs", params_.voxel_max_z_abs); fla_utils::SafeGetParam(pnh_, "voxel_map/use_rel_cropping", params_.voxel_use_rel_cropping); fla_utils::SafeGetParam(pnh_, "voxel_map/min_z_rel", params_.voxel_min_z_rel); fla_utils::SafeGetParam(pnh_, "voxel_map/max_z_rel", params_.voxel_max_z_rel); fla_utils::SafeGetParam(pnh_, "voxel_map/hit_inc", params_.voxel_hit_inc); fla_utils::SafeGetParam(pnh_, "voxel_map/miss_inc", params_.voxel_miss_inc); fla_utils::SafeGetParam(pnh_, "voxel_map/publish_map", publish_voxel_map_); } void GlobalMapperRos::InitSubscribers() { point_cloud_sub_ = pnh_.subscribe("cloud_topic", 10, &GlobalMapperRos::PointCloudCallback, this); } void GlobalMapperRos::InitPublishers() { pixel_map_pub_ = pnh_.advertise<nav_msgs::OccupancyGrid>("pixel_map_topic", 1); voxel_map_pub_ = pnh_.advertise<visualization_msgs::MarkerArray>("voxel_map_topic", 1); map_pub_timer_ = nh_.createTimer(ros::Duration(0.2), &GlobalMapperRos::PublishMap, this); } /* Return a RGB colour value given a scalar v in the range [vmin,vmax] In this case each colour component ranges from 0 (no contribution) to 1 (fully saturated). The colour is clipped at the end of the scales if v is outside the range [vmin,vmax] */ void GlobalMapperRos::GrayscaleToRGBJet(double v, double vmin, double vmax, std::vector<double>* rgb) { double dv; if (v < vmin) v = vmin; if (v > vmax) v = vmax; dv = vmax - vmin; if (v < (vmin + 0.25 * dv)) { rgb->at(0) = 0; rgb->at(1) = 4 * (v - vmin) / dv; } else if (v < (vmin + 0.5 * dv)) { rgb->at(0) = 0; rgb->at(2) = 1 + 4 * (vmin + 0.25 * dv - v) / dv; } else if (v < (vmin + 0.75 * dv)) { rgb->at(0) = 4 * (v - vmin - 0.5 * dv) / dv; rgb->at(2) = 0; } else { rgb->at(1) = 1 + 4 * (vmin + 0.75 * dv - v) / dv; rgb->at(2) = 0; } } void GlobalMapperRos::PopulateVoxelMapMsg(visualization_msgs::MarkerArray* marker_array) { // check for bad input if (marker_array == nullptr) { return; } geometry_msgs::TransformStamped transform_stamped; Eigen::Vector3d transform; try { transform_stamped = tf_buffer_.lookupTransform("world", "body", ros::Time(0), ros::Duration(1.0)); transform(0) = transform_stamped.transform.translation.x; transform(1) = transform_stamped.transform.translation.y; transform(2) = transform_stamped.transform.translation.z; } catch (tf2::TransformException &ex) { ROS_WARN("[world_database_master_ros] OnGetTransform failed with %s", ex.what()); transform(0) = std::numeric_limits<double>::quiet_NaN(); transform(1) = std::numeric_limits<double>::quiet_NaN(); transform(2) = std::numeric_limits<double>::quiet_NaN(); } // get occuppied voxels double xyz[3] = {0.0}; Eigen::Map<Eigen::Vector3d> xyz_map(&xyz[0]); std::vector<int> occ_inds; int min_ixyz[3]; int max_ixyz[3]; const double subgrid_half_size[3] = {10,10,3}; const double min_xyz[3] = {transform[0] - subgrid_half_size[0], transform[1] - subgrid_half_size[1], transform[2] - subgrid_half_size[2]}; const double max_xyz[3] = {transform[0] + subgrid_half_size[0], transform[1] + subgrid_half_size[1], transform[2] + subgrid_half_size[2]}; global_mapper_ptr_->voxel_map_ptr_->worldToTable(min_xyz, min_ixyz); global_mapper_ptr_->voxel_map_ptr_->worldToTable(max_xyz, max_ixyz); int voxel_index = 0; for (int x = min_ixyz[0]; x < max_ixyz[0]; x++) { for (int y = min_ixyz[1]; y < max_ixyz[1]; y++) { for (int z = min_ixyz[2]; z < max_ixyz[2]; z++) { int ixyz[3] = {x, y, z}; if(global_mapper_ptr_->voxel_map_ptr_->readValue(ixyz) > 0.6) { voxel_index = global_mapper_ptr_->voxel_map_ptr_->getInd(ixyz); occ_inds.push_back(voxel_index); } } } } marker_array->markers.resize(occ_inds.size()); std::vector<double> rgb(3, 1.0); for (int i = 0; i < occ_inds.size(); ++i) { visualization_msgs::Marker& marker = marker_array->markers[i]; // create voxel marker marker.header.frame_id = params_.map_frame; marker.header.stamp = ros::Time::now(); marker.id = i; marker.type = visualization_msgs::Marker::CUBE; marker.action = visualization_msgs::Marker::ADD; // orientation marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; // scale marker.scale.x = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[0]; marker.scale.y = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[1]; marker.scale.z = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[2]; // position global_mapper_ptr_->voxel_map_ptr_->indToLoc(occ_inds[i], xyz); marker.pose.position.x = xyz[0]; marker.pose.position.y = xyz[1]; marker.pose.position.z = xyz[2]; // color GrayscaleToRGBJet(marker.pose.position.z, global_mapper_ptr_->voxel_map_ptr_->xyz0[2], global_mapper_ptr_->voxel_map_ptr_->xyz1[2], &rgb); marker.color.r = static_cast<float>(rgb[0]); marker.color.g = static_cast<float>(rgb[1]); marker.color.b = static_cast<float>(rgb[2]); marker.color.a = 1.0f; } } void GlobalMapperRos::PopulatePixelMapMsg(nav_msgs::OccupancyGrid* occupancy_grid) { // check for bad input if (occupancy_grid == nullptr) { return; } // header occupancy_grid->header.frame_id = params_.map_frame; occupancy_grid->header.stamp = ros::Time::now(); // metadata occupancy_grid->info.resolution = global_mapper_ptr_->pixel_map_ptr_->metersPerPixel; occupancy_grid->info.width = global_mapper_ptr_->pixel_map_ptr_->dimensions[0]; occupancy_grid->info.height = global_mapper_ptr_->pixel_map_ptr_->dimensions[1]; occupancy_grid->info.origin.position.x = 0.0; occupancy_grid->info.origin.position.y = 0.0; occupancy_grid->info.origin.position.z = 0.0; // data float occ_value = 0.0; double xy[2] = {0.0}; occupancy_grid->data.resize(global_mapper_ptr_->pixel_map_ptr_->num_cells); for (int i = 0; i < global_mapper_ptr_->pixel_map_ptr_->num_cells; ++i) { // get xy location global_mapper_ptr_->pixel_map_ptr_->indToLoc(i, xy); // get pixel value and scale occ_value = global_mapper_ptr_->pixel_map_ptr_->readValue(xy); occ_value *= 100.0; occupancy_grid->data[i] = static_cast<uint8_t>(occ_value + 0.5); } } void GlobalMapperRos::PublishMap(const ros::TimerEvent& event) { // lock // std::lock_guard<std::mutex> map_lock(global_mapper_ptr_->map_mutex()); // voxel map if (publish_voxel_map_) { double start_time = ros::Time::now().toSec(); visualization_msgs::MarkerArray marker_array; PopulateVoxelMapMsg(&marker_array); std::cout << "(global_mapper) PopulateVoxelMapMsg took " << ros::Time::now().toSec() - start_time << " seconds" << std::endl; voxel_map_pub_.publish(marker_array); } // pixel_map if (publish_pixel_map_) { nav_msgs::OccupancyGrid occupancy_grid; PopulatePixelMapMsg(&occupancy_grid); pixel_map_pub_.publish(occupancy_grid); } } void GlobalMapperRos::PointCloudCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_ptr) { // get transform const std::string target_frame = params_.map_frame; geometry_msgs::TransformStamped transform_stamped; // try to get correct transform try { transform_stamped = tf_buffer_.lookupTransform(target_frame, cloud_ptr->header.frame_id, ros::Time(cloud_ptr->header.stamp), ros::Duration(0.02)); } catch (tf2::TransformException &ex) { ROS_WARN("%s", ex.what()); return; } sensor_msgs::PointCloud2 cloud_out; tf2::doTransform(*cloud_ptr, cloud_out, transform_stamped); pcl::PointCloud<pcl::PointXYZ> cloud; pcl::fromROSMsg(cloud_out, cloud); // push to mapper global_mapper_ptr_->PushPointCloud(cloud.makeShared()); } void GlobalMapperRos::Run() { // start mapping thread global_mapper_ptr_ = std::unique_ptr<GlobalMapper>(new GlobalMapper(stop_signal_ptr_, params_)); global_mapper_ptr_->Run(); // handle ros callbacks ros::spin(); } } // namespace global_mapper <|endoftext|>
<commit_before>// Print each number in the range specified by two integers. #include <iostream> using std::cout; using std::cin; void print_range(int lo, int hi) { if (lo > hi) print_range(hi, lo); for (int i = lo; i != hi; ++i) cout << i << " "; } int main() { int low = 0, high = 0; cout << "please input two integers:\n"; cin >> low >> high; print_range(low, high); return 0; } <commit_msg>Fixed #438<commit_after>// Print each number in the range specified by two integers. #include <iostream> using std::cout; using std::cin; void print_range(int lo, int hi) { if (lo > hi) { print_range(hi, lo); return; } for (int i = lo; i != hi; ++i) cout << i << " "; } int main() { int low = 0, high = 0; cout << "please input two integers:\n"; cin >> low >> high; print_range(low, high); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "include/Sales_item.h" int main() { Sales_item currItem, valItem; if (std::cin >> currItem) { int cnt = 1; while (std::cin >> valItem) { if (valItem.isbn() == currItem.isbn()) ++cnt; else { std::cout << currItem << " occurs " << cnt << " times " << std::endl; currItem = valItem; cnt = 1; } } std::cout << currItem << " occurs " << cnt << " times " << std::endl; } return 0; } <commit_msg>Update ex1_23.cpp<commit_after>#include <iostream> #include "include/Sales_item.h" int main() { Sales_item currItem, valItem; if (std::cin >> currItem) { int cnt = 1; while (std::cin >> valItem) { if (valItem.isbn() == currItem.isbn()) { ++cnt; } else { std::cout << currItem << " occurs " << cnt << " times " << std::endl; currItem = valItem; cnt = 1; } } std::cout << currItem << " occurs "<< cnt << " times " << std::endl; } return 0; } <|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/bug_report_util.h" #include "app/l10n_util.h" #include "base/file_version_info.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_version_info.h" #include "chrome/browser/browser_process_impl.h" #include "chrome/browser/profile.h" #include "chrome/browser/safe_browsing/safe_browsing_util.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/net/url_fetcher.h" #include "googleurl/src/gurl.h" #include "grit/locale_settings.h" #include "net/url_request/url_request_status.h" #include "unicode/locid.h" #include <string> namespace { const int kBugReportVersion = 1; const char kReportPhishingUrl[] = "http://www.google.com/safebrowsing/report_phish/"; // URL to post bug reports to. const char* const kBugReportPostUrl = "https://feedback2-test.corp.google.com/tools/feedback/chrome/__submit"; const char* const kProtBufMimeType = "application/x-protobuf"; const char* const kPngMimeType = "image/png"; // Tags we use in product specific data const char* const kPageTitleTag = "PAGE TITLE"; const char* const kProblemTypeTag = "PROBLEM TYPE"; const char* const kChromeVersionTag = "CHROME VERSION"; const char* const kOsVersionTag = "OS VERSION"; } // namespace // Simple URLFetcher::Delegate to clean up URLFetcher on completion. class BugReportUtil::PostCleanup : public URLFetcher::Delegate { public: PostCleanup(); // Overridden from URLFetcher::Delegate. virtual void OnURLFetchComplete(const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data); private: DISALLOW_COPY_AND_ASSIGN(PostCleanup); }; BugReportUtil::PostCleanup::PostCleanup() { } void BugReportUtil::PostCleanup::OnURLFetchComplete( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { // if not 204, something went wrong if (response_code != 204) LOG(WARNING) << "Submission to feedback server failed. Response code: " << response_code << std::endl; // Delete the URLFetcher. delete source; // And then delete ourselves. delete this; } // static void BugReportUtil::SetOSVersion(std::string *os_version) { #if defined(OS_WIN) OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (GetVersionEx(&osvi)) { *os_version = StringPrintf("%d.%d.%d %S", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber, osvi.szCSDVersion); } else { *os_version = "unknown"; } #elif defined(OS_MACOSX) int32 major; int32 minor; int32 bugFix; base::SysInfo::OperatingSystemVersionNumbers(&major, &minor, &bugFix); *os_version = StringPrintf("%d.%d.%d", major, minor, bugFix); #else *os_version = "unknown"; #endif } // static void BugReportUtil::AddFeedbackData( userfeedback::ExternalExtensionSubmit* feedback_data, const std::string& key, const std::string& value) { // Create log_value object and add it to the web_data object userfeedback::ProductSpecificData log_value; log_value.set_key(key); log_value.set_value(value); userfeedback::WebData* web_data = feedback_data->mutable_web_data(); *(web_data->add_product_specific_data()) = log_value; } // static void BugReportUtil::SendReport(Profile* profile, const std::string& page_title_text, int problem_type, const std::string& page_url_text, const std::string& user_email_text, const std::string& description, const char* png_data, int png_data_length, int png_width, #if defined(OS_CHROMEOS) int png_height, const chromeos::LogDictionaryType* const sys_info) { #else int png_height) { #endif GURL post_url(kBugReportPostUrl); // Create google feedback protocol buffer objects userfeedback::ExternalExtensionSubmit feedback_data; // type id set to 0, unused field but needs to be initialized to 0 feedback_data.set_type_id(0); userfeedback::CommonData* common_data = feedback_data.mutable_common_data(); userfeedback::WebData* web_data = feedback_data.mutable_web_data(); // Set GAIA id to 0. We're not using gaia id's for recording // use feedback - we're using the e-mail field, allows users to // submit feedback from incognito mode and specify any mail id // they wish common_data->set_gaia_id(0); // Add the page title. AddFeedbackData(&feedback_data, std::string(kPageTitleTag), page_title_text); AddFeedbackData(&feedback_data, std::string(kProblemTypeTag), StringPrintf("%d\r\n", problem_type)); // Add the user e-mail to the feedback object common_data->set_user_email(user_email_text); // Add the description to the feedback object common_data->set_description(description); // Add the language std::string chrome_locale = g_browser_process->GetApplicationLocale(); common_data->set_source_descripton_language(chrome_locale); // Set the url web_data->set_url(page_url_text); // Add the Chrome version std::string chrome_version; scoped_ptr<FileVersionInfo> version_info( chrome_app::GetChromeVersionInfo()); if (version_info.get()) { chrome_version = WideToUTF8(version_info->product_name()) + " - " + WideToUTF8(version_info->file_version()) + " (" + WideToUTF8(version_info->last_change()) + ")"; } if (!chrome_version.empty()) AddFeedbackData(&feedback_data, std::string(kChromeVersionTag), chrome_version); // Add OS version (eg, for WinXP SP2: "5.1.2600 Service Pack 2"). std::string os_version = ""; SetOSVersion(&os_version); AddFeedbackData(&feedback_data, std::string(kOsVersionTag), os_version); #if defined(OS_CHROMEOS) for (chromeos::LogDictionaryType::const_iterator i = sys_info->begin(); i != sys_info->end(); ++i) AddFeedbackData(&feedback_data, i->first, i->second); #endif // Include the page image if we have one. if (png_data) { userfeedback::PostedScreenshot screenshot; screenshot.set_mime_type(kPngMimeType); // Set the dimensions of the screenshot userfeedback::Dimensions dimensions; dimensions.set_width(static_cast<float>(png_width)); dimensions.set_height(static_cast<float>(png_height)); *(screenshot.mutable_dimensions()) = dimensions; screenshot.set_binary_content(std::string(png_data, png_data_length)); // Set the screenshot object in feedback *(feedback_data.mutable_screenshot()) = screenshot; } // We have the body of our POST, so send it off to the server. URLFetcher* fetcher = new URLFetcher(post_url, URLFetcher::POST, new BugReportUtil::PostCleanup); fetcher->set_request_context(profile->GetRequestContext()); std::string post_body; feedback_data.SerializeToString(&post_body); fetcher->set_upload_data(std::string(kProtBufMimeType), post_body); fetcher->Start(); } // static void BugReportUtil::ReportPhishing(TabContents* currentTab, const std::string& phishing_url) { currentTab->controller().LoadURL( safe_browsing_util::GeneratePhishingReportUrl( kReportPhishingUrl, phishing_url), GURL(), PageTransition::LINK); } <commit_msg>Flipped feedback URL to production servers.<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/bug_report_util.h" #include "app/l10n_util.h" #include "base/file_version_info.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_version_info.h" #include "chrome/browser/browser_process_impl.h" #include "chrome/browser/profile.h" #include "chrome/browser/safe_browsing/safe_browsing_util.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/net/url_fetcher.h" #include "googleurl/src/gurl.h" #include "grit/locale_settings.h" #include "net/url_request/url_request_status.h" #include "unicode/locid.h" #include <string> namespace { const int kBugReportVersion = 1; const char kReportPhishingUrl[] = "http://www.google.com/safebrowsing/report_phish/"; // URL to post bug reports to. const char* const kBugReportPostUrl = "https://www.google.com/tools/feedback/chrome/__submit"; const char* const kProtBufMimeType = "application/x-protobuf"; const char* const kPngMimeType = "image/png"; // Tags we use in product specific data const char* const kPageTitleTag = "PAGE TITLE"; const char* const kProblemTypeTag = "PROBLEM TYPE"; const char* const kChromeVersionTag = "CHROME VERSION"; const char* const kOsVersionTag = "OS VERSION"; } // namespace // Simple URLFetcher::Delegate to clean up URLFetcher on completion. class BugReportUtil::PostCleanup : public URLFetcher::Delegate { public: PostCleanup(); // Overridden from URLFetcher::Delegate. virtual void OnURLFetchComplete(const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data); private: DISALLOW_COPY_AND_ASSIGN(PostCleanup); }; BugReportUtil::PostCleanup::PostCleanup() { } void BugReportUtil::PostCleanup::OnURLFetchComplete( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { // if not 204, something went wrong if (response_code != 204) LOG(WARNING) << "Submission to feedback server failed. Response code: " << response_code << std::endl; // Delete the URLFetcher. delete source; // And then delete ourselves. delete this; } // static void BugReportUtil::SetOSVersion(std::string *os_version) { #if defined(OS_WIN) OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (GetVersionEx(&osvi)) { *os_version = StringPrintf("%d.%d.%d %S", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber, osvi.szCSDVersion); } else { *os_version = "unknown"; } #elif defined(OS_MACOSX) int32 major; int32 minor; int32 bugFix; base::SysInfo::OperatingSystemVersionNumbers(&major, &minor, &bugFix); *os_version = StringPrintf("%d.%d.%d", major, minor, bugFix); #else *os_version = "unknown"; #endif } // static void BugReportUtil::AddFeedbackData( userfeedback::ExternalExtensionSubmit* feedback_data, const std::string& key, const std::string& value) { // Create log_value object and add it to the web_data object userfeedback::ProductSpecificData log_value; log_value.set_key(key); log_value.set_value(value); userfeedback::WebData* web_data = feedback_data->mutable_web_data(); *(web_data->add_product_specific_data()) = log_value; } // static void BugReportUtil::SendReport(Profile* profile, const std::string& page_title_text, int problem_type, const std::string& page_url_text, const std::string& user_email_text, const std::string& description, const char* png_data, int png_data_length, int png_width, #if defined(OS_CHROMEOS) int png_height, const chromeos::LogDictionaryType* const sys_info) { #else int png_height) { #endif GURL post_url(kBugReportPostUrl); // Create google feedback protocol buffer objects userfeedback::ExternalExtensionSubmit feedback_data; // type id set to 0, unused field but needs to be initialized to 0 feedback_data.set_type_id(0); userfeedback::CommonData* common_data = feedback_data.mutable_common_data(); userfeedback::WebData* web_data = feedback_data.mutable_web_data(); // Set GAIA id to 0. We're not using gaia id's for recording // use feedback - we're using the e-mail field, allows users to // submit feedback from incognito mode and specify any mail id // they wish common_data->set_gaia_id(0); // Add the page title. AddFeedbackData(&feedback_data, std::string(kPageTitleTag), page_title_text); AddFeedbackData(&feedback_data, std::string(kProblemTypeTag), StringPrintf("%d\r\n", problem_type)); // Add the user e-mail to the feedback object common_data->set_user_email(user_email_text); // Add the description to the feedback object common_data->set_description(description); // Add the language std::string chrome_locale = g_browser_process->GetApplicationLocale(); common_data->set_source_descripton_language(chrome_locale); // Set the url web_data->set_url(page_url_text); // Add the Chrome version std::string chrome_version; scoped_ptr<FileVersionInfo> version_info( chrome_app::GetChromeVersionInfo()); if (version_info.get()) { chrome_version = WideToUTF8(version_info->product_name()) + " - " + WideToUTF8(version_info->file_version()) + " (" + WideToUTF8(version_info->last_change()) + ")"; } if (!chrome_version.empty()) AddFeedbackData(&feedback_data, std::string(kChromeVersionTag), chrome_version); // Add OS version (eg, for WinXP SP2: "5.1.2600 Service Pack 2"). std::string os_version = ""; SetOSVersion(&os_version); AddFeedbackData(&feedback_data, std::string(kOsVersionTag), os_version); #if defined(OS_CHROMEOS) for (chromeos::LogDictionaryType::const_iterator i = sys_info->begin(); i != sys_info->end(); ++i) AddFeedbackData(&feedback_data, i->first, i->second); #endif // Include the page image if we have one. if (png_data) { userfeedback::PostedScreenshot screenshot; screenshot.set_mime_type(kPngMimeType); // Set the dimensions of the screenshot userfeedback::Dimensions dimensions; dimensions.set_width(static_cast<float>(png_width)); dimensions.set_height(static_cast<float>(png_height)); *(screenshot.mutable_dimensions()) = dimensions; screenshot.set_binary_content(std::string(png_data, png_data_length)); // Set the screenshot object in feedback *(feedback_data.mutable_screenshot()) = screenshot; } // We have the body of our POST, so send it off to the server. URLFetcher* fetcher = new URLFetcher(post_url, URLFetcher::POST, new BugReportUtil::PostCleanup); fetcher->set_request_context(profile->GetRequestContext()); std::string post_body; feedback_data.SerializeToString(&post_body); fetcher->set_upload_data(std::string(kProtBufMimeType), post_body); fetcher->Start(); } // static void BugReportUtil::ReportPhishing(TabContents* currentTab, const std::string& phishing_url) { currentTab->controller().LoadURL( safe_browsing_util::GeneratePhishingReportUrl( kReportPhishingUrl, phishing_url), GURL(), PageTransition::LINK); } <|endoftext|>
<commit_before>#include "selfdrive/ui/replay/camera.h" #include <cassert> #include <iostream> const int YUV_BUF_COUNT = 50; CameraServer::CameraServer() { camera_thread_ = std::thread(&CameraServer::thread, this); } CameraServer::~CameraServer() { queue_.push({}); camera_thread_.join(); vipc_server_.reset(nullptr); } void CameraServer::startVipcServer() { std::cout << (vipc_server_ ? "start" : "restart") << " vipc server" << std::endl; vipc_server_.reset(new VisionIpcServer("camerad")); for (auto &cam : cameras_) { if (cam.width > 0 && cam.height > 0) { vipc_server_->create_buffers(cam.rgb_type, UI_BUF_COUNT, true, cam.width, cam.height); vipc_server_->create_buffers(cam.yuv_type, YUV_BUF_COUNT, false, cam.width, cam.height); } } vipc_server_->start_listener(); } void CameraServer::thread() { while (true) { const auto [type, fr, eidx] = queue_.pop(); if (!fr) break; auto &cam = cameras_[type]; // start|restart the vipc server if frame size changed if (cam.width != fr->width || cam.height != fr->height) { cam.width = fr->width; cam.height = fr->height; std::cout << "camera[" << type << "] frame size " << cam.width << "x" << cam.height << std::endl; startVipcServer(); } // send frame if (auto dat = fr->get(eidx.getSegmentId())) { auto [rgb_dat, yuv_dat] = *dat; VisionIpcBufExtra extra = { .frame_id = eidx.getFrameId(), .timestamp_sof = eidx.getTimestampSof(), .timestamp_eof = eidx.getTimestampEof(), }; VisionBuf *rgb_buf = vipc_server_->get_buffer(cam.rgb_type); memcpy(rgb_buf->addr, rgb_dat, fr->getRGBSize()); VisionBuf *yuv_buf = vipc_server_->get_buffer(cam.yuv_type); memcpy(yuv_buf->addr, yuv_dat, fr->getYUVSize()); vipc_server_->send(rgb_buf, &extra, false); vipc_server_->send(yuv_buf, &extra, false); } else { std::cout << "camera[" << type << "] failed to get frame:" << eidx.getSegmentId() << std::endl; } } } <commit_msg>replay/camera: fix incorrect console output (#22491)<commit_after>#include "selfdrive/ui/replay/camera.h" #include <cassert> #include <iostream> const int YUV_BUF_COUNT = 50; CameraServer::CameraServer() { camera_thread_ = std::thread(&CameraServer::thread, this); } CameraServer::~CameraServer() { queue_.push({}); camera_thread_.join(); vipc_server_.reset(nullptr); } void CameraServer::startVipcServer() { std::cout << (vipc_server_ ? "restart" : "start") << " vipc server" << std::endl; vipc_server_.reset(new VisionIpcServer("camerad")); for (auto &cam : cameras_) { if (cam.width > 0 && cam.height > 0) { vipc_server_->create_buffers(cam.rgb_type, UI_BUF_COUNT, true, cam.width, cam.height); vipc_server_->create_buffers(cam.yuv_type, YUV_BUF_COUNT, false, cam.width, cam.height); } } vipc_server_->start_listener(); } void CameraServer::thread() { while (true) { const auto [type, fr, eidx] = queue_.pop(); if (!fr) break; auto &cam = cameras_[type]; // start|restart the vipc server if frame size changed if (cam.width != fr->width || cam.height != fr->height) { cam.width = fr->width; cam.height = fr->height; std::cout << "camera[" << type << "] frame size " << cam.width << "x" << cam.height << std::endl; startVipcServer(); } // send frame if (auto dat = fr->get(eidx.getSegmentId())) { auto [rgb_dat, yuv_dat] = *dat; VisionIpcBufExtra extra = { .frame_id = eidx.getFrameId(), .timestamp_sof = eidx.getTimestampSof(), .timestamp_eof = eidx.getTimestampEof(), }; VisionBuf *rgb_buf = vipc_server_->get_buffer(cam.rgb_type); memcpy(rgb_buf->addr, rgb_dat, fr->getRGBSize()); VisionBuf *yuv_buf = vipc_server_->get_buffer(cam.yuv_type); memcpy(yuv_buf->addr, yuv_dat, fr->getYUVSize()); vipc_server_->send(rgb_buf, &extra, false); vipc_server_->send(yuv_buf, &extra, false); } else { std::cout << "camera[" << type << "] failed to get frame:" << eidx.getSegmentId() << std::endl; } } } <|endoftext|>
<commit_before>#pragma once #include "beast.hpp" #include "server_core.hpp" namespace msrv { class BeastConnectionContext; class BeastListener : public std::enable_shared_from_this<BeastListener> { public: BeastListener( asio::io_context* ioContext, BeastConnectionContext* connectionContext, const asio::ip::tcp::endpoint& endpoint); ~BeastListener(); void run(); private: void accept(); void handleAccept(const boost::system::error_code& error); asio::io_context* ioContext_; BeastConnectionContext* connectionContext_; asio::ip::tcp::acceptor acceptor_; asio::ip::tcp::socket peerSocket_; asio::ip::tcp::endpoint peerEndpoint_; }; } <commit_msg>fix compilation with clang<commit_after>#pragma once #include "beast.hpp" #include "server_core.hpp" namespace msrv { struct BeastConnectionContext; class BeastListener : public std::enable_shared_from_this<BeastListener> { public: BeastListener( asio::io_context* ioContext, BeastConnectionContext* connectionContext, const asio::ip::tcp::endpoint& endpoint); ~BeastListener(); void run(); private: void accept(); void handleAccept(const boost::system::error_code& error); asio::io_context* ioContext_; BeastConnectionContext* connectionContext_; asio::ip::tcp::acceptor acceptor_; asio::ip::tcp::socket peerSocket_; asio::ip::tcp::endpoint peerEndpoint_; }; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: brokenpackageint.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 16:46:10 $ * * 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 _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef INCLUDED_SFX2_DLLAPI_H #include "sfx2/dllapi.h" #endif #ifndef _COM_SUN_STAR_DOCUMENT_BROKENPACKAGEREQUEST_HPP_ #include <com/sun/star/document/BrokenPackageRequest.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONAPPROVE_HPP_ #include <com/sun/star/task/XInteractionApprove.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONDISAPPROVE_HPP_ #include <com/sun/star/task/XInteractionDisapprove.hpp> #endif #ifndef __FRAMEWORK_DISPATCH_INTERACTION_HXX_ #include <framework/interaction.hxx> #endif using namespace ::framework; typedef ContinuationBase< ::com::sun::star::task::XInteractionApprove > SfxContinuationApprove; typedef ContinuationBase< ::com::sun::star::task::XInteractionDisapprove > SfxContinuationDisapprove; class SFX2_DLLPUBLIC RequestPackageReparation : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest > { ::com::sun::star::uno::Any m_aRequest; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations; SfxContinuationApprove* m_pApprove; SfxContinuationDisapprove* m_pDisapprove; public: RequestPackageReparation( ::rtl::OUString aName ); sal_Bool isApproved() { return m_pApprove->isSelected(); } virtual ::com::sun::star::uno::Any SAL_CALL getRequest() throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException ); }; class SFX2_DLLPUBLIC NotifyBrokenPackage : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest > { ::com::sun::star::uno::Any m_aRequest; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations; ContinuationAbort* m_pAbort; public: NotifyBrokenPackage( ::rtl::OUString aName ); sal_Bool isAborted() { return m_pAbort->isSelected(); } virtual ::com::sun::star::uno::Any SAL_CALL getRequest() throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException ); }; <commit_msg>INTEGRATION: CWS changefileheader (1.4.732); FILE MERGED 2008/04/01 15:38:14 thb 1.4.732.3: #i85898# Stripping all external header guards 2008/04/01 12:40:32 thb 1.4.732.2: #i85898# Stripping all external header guards 2008/03/31 13:37:53 rt 1.4.732.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: brokenpackageint.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "sal/config.h" #include "sfx2/dllapi.h" #include <com/sun/star/document/BrokenPackageRequest.hpp> #include <com/sun/star/task/XInteractionApprove.hpp> #include <com/sun/star/task/XInteractionDisapprove.hpp> #include <framework/interaction.hxx> using namespace ::framework; typedef ContinuationBase< ::com::sun::star::task::XInteractionApprove > SfxContinuationApprove; typedef ContinuationBase< ::com::sun::star::task::XInteractionDisapprove > SfxContinuationDisapprove; class SFX2_DLLPUBLIC RequestPackageReparation : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest > { ::com::sun::star::uno::Any m_aRequest; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations; SfxContinuationApprove* m_pApprove; SfxContinuationDisapprove* m_pDisapprove; public: RequestPackageReparation( ::rtl::OUString aName ); sal_Bool isApproved() { return m_pApprove->isSelected(); } virtual ::com::sun::star::uno::Any SAL_CALL getRequest() throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException ); }; class SFX2_DLLPUBLIC NotifyBrokenPackage : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest > { ::com::sun::star::uno::Any m_aRequest; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > m_lContinuations; ContinuationAbort* m_pAbort; public: NotifyBrokenPackage( ::rtl::OUString aName ); sal_Bool isAborted() { return m_pAbort->isSelected(); } virtual ::com::sun::star::uno::Any SAL_CALL getRequest() throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException ); }; <|endoftext|>
<commit_before>// // Set.h // Set // // Created by Antonio Seprano on 10/08/14. // Copyright (c) 2014 Antonio Seprano. All rights reserved. // #include <vector> #include <functional> #include <utility> #include <algorithm> #ifndef _SET_HPP #define _SET_HPP template<class _T, class _Allocator = std::allocator<_T> > class Set { public: typedef _T value_type; typedef _Allocator allocator_type; private: typedef Set<value_type,allocator_type> _SET; public: typedef typename std::vector<value_type,allocator_type>::iterator iterator; typedef typename std::vector<value_type,allocator_type>::const_iterator const_iterator; // Empty set Set() {}; // Set with initializer list Set(const std::initializer_list<value_type>& l) { _set.reserve(l.size()); for (const auto& value : l) { insert(value); } } Set(std::initializer_list<value_type>&& l) { _set.reserve(l.size()); for (auto& value : l) { insert(std::move(value)); } } // Copy constructor Set(const _SET& s) { _set = s._set; } // Move constructor Set(_SET&& s) { _set = std::move(s._set); } // Copy assignment _SET& operator=(const _SET& s) noexcept { _set = s._set; return *this; } // Move assignment _SET& operator=(_SET&& s) noexcept { _set = std::move(s._set); return *this; } iterator begin() noexcept { return _set.begin(); } const_iterator begin() const noexcept { return _set.begin(); } iterator end() noexcept { return _set.end(); }; const_iterator end() const noexcept { return _set.end(); } size_t size() const noexcept { return _set.size(); } bool empty() const noexcept { return _set.empty(); } void clear() noexcept { _set.clear(); } iterator find(const value_type& value) noexcept { for (auto it = _set.begin(); it != _set.end(); it++) { if (*it == value) return it; } return _set.end(); } const_iterator find(const value_type& value) const noexcept { return (const_iterator)find(value); } size_t count(const value_type& value) const noexcept { size_t ret{}; for (const auto& v : _set) { if (v == value) { ret++; } } return ret; } bool operator==(const _SET& s) const noexcept { return this->contains(s, false) && s.contains(*this, false); } bool operator!=(const _SET& s) const noexcept { return !(*this == s); }; bool operator<(const _SET& s) const noexcept { if (size() != s.size()) { return size() < s.size(); } auto it1=begin(), it2=s.begin(); while (it1 != end() && it2 != s.end()) { if (*it1 < *it2) { return true; } else if (*it1 > *it2) { return false; } it1++; it2++; }; return false; } // Insert new value // unique = true => values must be unique (no duplicate values allowed) _SET& insert(const value_type& value, bool unique = false) noexcept { if (!unique || find(value) == _set.end()) { auto it = begin(); while (it != end() && *it < value) { it++; } _set.insert(it, value); } return *this; } _SET& insert(value_type&& value, bool unique = false) noexcept { if (!unique || find(value) == _set.end()) { auto it = begin(); while (it != end() && *it < value) { it++; } _set.insert(it, std::move(value)); } return *this; } _SET operator+(const value_type& value) const noexcept { return _SET{*this}+_SET{value}; } _SET operator+(value_type&& value) const noexcept { return _SET{*this}+_SET{std::move(value)}; } _SET operator+(const _SET& s) const noexcept { _SET ret{*this}; for (const auto& value : s) { ret.insert(value); } return ret; } _SET operator+(_SET&& s) const noexcept { _SET ret{*this}; for (auto& value : s) { ret.insert(std::move(value)); } return ret; } _SET& operator+=(const value_type& value) noexcept { insert(value); return *this; } _SET& operator+=(value_type&& value) noexcept { insert(std::move(value)); return *this; } _SET& operator+=(const _SET& s) noexcept { for (const auto& value : s) { insert(value); } return *this; } _SET& operator+=(_SET&& s) noexcept { for (auto& value : s) { insert(std::move(value)); } return *this; } _SET operator-(const value_type& value) const noexcept { _SET ret{*this}; ret.erase(value); return ret; } _SET operator-(const _SET& s) const noexcept { _SET ret{*this}; for (const auto& v : s) { ret.erase(v); } return ret; } _SET& operator-=(const value_type& value) noexcept { _set.erase(value); return *this; } _SET& operator-=(const _SET& s) noexcept { for (const auto& value : s) { _set.erase(value); } return *this; } Set<_SET> operator*(const _SET& other) noexcept { Set<_SET> ret; if (!this->empty() && !other.empty()) { for (const auto& v1 : _set) { for (const auto& v2 : other) { ret.insert(_SET{v1,v2}); } } } return ret; } _SET intersection(const _SET& s) noexcept { _SET s1, s2; if (s.size() <= size()) { s1 = s; s2 = *this; } else { s1 = *this; s2 = s; } for (const auto &v : s1) { if (!s2.contains(v)) s1.erase(v); } return s1; } bool contains(const value_type& value) const noexcept { return contains(_SET{value}); } bool contains(const _SET& s, bool strict = false) const noexcept { for (const auto& value : s) { bool found{false}; for (const auto& v : _set) { if (v == value) { found = true; break; } } if (!found) { return false; } } return strict ? (s.size() != size()) : true; } template<class InputIterator> void insert(InputIterator first, InputIterator last) { for (auto it = first; it != last; it++) { _set.insert(*it); } }; iterator erase(const_iterator position) { return _set.erase(position); } iterator erase(const_iterator first, const_iterator last) { return _set.erase(first,last); } size_t erase(const value_type& value, bool all = false) { size_t ret{}; if (!all) { auto it = find(value); if (it != end()) { erase(it); ret++; } return ret; } for (auto it = _set.begin(); it != _set.end(); it++) { if (*it == value) { _set.erase(it); ++ret; } } return ret; } _SET& unique() noexcept { for (auto i = begin(); i != end(); i++) { auto j = i+1; while (j != end()) { if (*i == *j) { _set.erase(j); } else { j++; } } } return *this; } private: std::vector<value_type,allocator_type> _set; }; #endif /* defined(_SET_HPP) */ <commit_msg>[add] Changed Set::intersection() to Set::intersectionWith()<commit_after>// // Set.h // Set // // Created by Antonio Seprano on 10/08/14. // Copyright (c) 2014 Antonio Seprano. All rights reserved. // #include <vector> #include <functional> #include <utility> #include <algorithm> #ifndef _SET_HPP #define _SET_HPP template<class _T, class _Compare = std::less<_T>, class _Allocator = std::allocator<_T>> class Set { public: typedef _T value_type; typedef _Allocator allocator_type; typedef _Compare value_compare; private: typedef Set<value_type,value_compare,allocator_type> _SET; public: typedef typename std::vector<value_type,allocator_type>::iterator iterator; typedef typename std::vector<value_type,allocator_type>::const_iterator const_iterator; // Empty set Set() {}; // Set with initializer list Set(const std::initializer_list<value_type>& l) { _set.reserve(l.size()); for (const auto& value : l) { insert(value); } } Set(std::initializer_list<value_type>&& l) { _set.reserve(l.size()); for (auto& value : l) { insert(std::move(value)); } } // Copy constructor Set(const _SET& s) { _set = s._set; } // Move constructor Set(_SET&& s) { _set = std::move(s._set); } // Copy assignment _SET& operator=(const _SET& s) noexcept { _set = s._set; return *this; } // Move assignment _SET& operator=(_SET&& s) noexcept { _set = std::move(s._set); return *this; } iterator begin() noexcept { return _set.begin(); } const_iterator begin() const noexcept { return _set.begin(); } iterator end() noexcept { return _set.end(); }; const_iterator end() const noexcept { return _set.end(); } size_t size() const noexcept { return _set.size(); } bool empty() const noexcept { return _set.empty(); } void clear() noexcept { _set.clear(); } iterator find(const value_type& value) noexcept { for (auto it = _set.begin(); it != _set.end(); it++) { if (*it == value) return it; } return _set.end(); } const_iterator find(const value_type& value) const noexcept { return (const_iterator)find(value); } size_t count(const value_type& value) const noexcept { size_t ret{}; for (const auto& v : _set) { if (v == value) { ret++; } } return ret; } bool operator==(const _SET& s) const noexcept { return this->contains(s, false) && s.contains(*this, false); } bool operator!=(const _SET& s) const noexcept { return !(*this == s); }; bool operator<(const _SET& s) const noexcept { if (size() != s.size()) { return size() < s.size(); } auto it1=begin(), it2=s.begin(); while (it1 != end() && it2 != s.end()) { if (*it1 < *it2) { return true; } else if (*it1 > *it2) { return false; } it1++; it2++; }; return false; } // Insert new value // unique = true => values must be unique (no duplicate values allowed) _SET& insert(const value_type& value, bool unique = false) noexcept { if (!unique || this->find(value) == _set.end()) { auto it = begin(); while (it != end() && value_compare()(*it, value)) { it++; } _set.insert(it, value); } return *this; } _SET& insert(value_type&& value, bool unique = false) noexcept { if (!unique || find(value) == _set.end()) { auto it = begin(); while (it != end() && value_compare()(*it, value)) { it++; } _set.insert(it, std::move(value)); } return *this; } _SET operator+(const value_type& value) const noexcept { return _SET{*this}+_SET{value}; } _SET operator+(value_type&& value) const noexcept { return _SET{*this}+_SET{std::move(value)}; } _SET operator+(const _SET& s) const noexcept { _SET ret{*this}; for (const auto& value : s) { ret.insert(value); } return ret; } _SET operator+(_SET&& s) const noexcept { _SET ret{*this}; for (auto& value : s) { ret.insert(std::move(value)); } return ret; } _SET& operator+=(const value_type& value) noexcept { insert(value); return *this; } _SET& operator+=(value_type&& value) noexcept { insert(std::move(value)); return *this; } _SET& operator+=(const _SET& s) noexcept { for (const auto& value : s) { insert(value); } return *this; } _SET& operator+=(_SET&& s) noexcept { for (auto& value : s) { insert(std::move(value)); } return *this; } _SET operator-(const value_type& value) const noexcept { _SET ret{*this}; ret.erase(value); return ret; } _SET operator-(const _SET& s) const noexcept { _SET ret{*this}; for (const auto& v : s) { ret.erase(v); } return ret; } _SET& operator-=(const value_type& value) noexcept { _set.erase(value); return *this; } _SET& operator-=(const _SET& s) noexcept { for (const auto& value : s) { _set.erase(value); } return *this; } Set<_SET> operator*(const _SET& other) noexcept { Set<_SET> ret; if (!this->empty() && !other.empty()) { for (const auto& v1 : _set) { for (const auto& v2 : other) { ret.insert(_SET{v1,v2}); } } } return ret; } _SET intersectionWith(const _SET& s) noexcept { _SET s1, s2; if (s.size() <= size()) { s1 = s; s2 = *this; } else { s1 = *this; s2 = s; } for (const auto &v : s1) { if (!s2.contains(v)) s1.erase(v); } return s1; } bool contains(const value_type& value) const noexcept { return contains(_SET{value}); } bool contains(const _SET& s, bool strict = false) const noexcept { for (const auto& value : s) { bool found{false}; for (const auto& v : _set) { if (v == value) { found = true; break; } } if (!found) { return false; } } return strict ? (s.size() != size()) : true; } template<class InputIterator> void insert(InputIterator first, InputIterator last) { for (auto it = first; it != last; it++) { _set.insert(*it); } }; iterator erase(const_iterator position) { return _set.erase(position); } iterator erase(const_iterator first, const_iterator last) { return _set.erase(first,last); } size_t erase(const value_type& value, bool all = false) { size_t ret{}; if (!all) { auto it = find(value); if (it != end()) { erase(it); ret++; } return ret; } for (auto it = _set.begin(); it != _set.end(); it++) { if (*it == value) { _set.erase(it); ++ret; } } return ret; } _SET& unique() noexcept { for (auto i = begin(); i != end(); i++) { auto j = i+1; while (j != end()) { if (*i == *j) { _set.erase(j); } else { j++; } } } return *this; } private: std::vector<value_type,allocator_type> _set; }; #endif /* defined(_SET_HPP) */ <|endoftext|>
<commit_before>#include <cli/Session.h> #include <cli/CommandLine.h> #include <cli/PosixStreams.h> #include <cli/Tokenizer.h> #include <mtp/make_function.h> #include <stdio.h> namespace cli { Session::Session(const mtp::DevicePtr &device): _device(device), _session(_device->OpenSession(1)), _gdi(_session->GetDeviceInfo()), _cd(mtp::Session::Root), _running(true) { using namespace mtp; using namespace std::placeholders; printf("%s\n", _gdi.VendorExtensionDesc.c_str()); printf("%s ", _gdi.Manufacturer.c_str()); printf("%s ", _gdi.Model.c_str()); printf("%s ", _gdi.DeviceVersion.c_str()); //printf("%s", _gdi.SerialNumber.c_str()); printf("\n"); printf("supported op codes: "); for(OperationCode code : _gdi.OperationsSupported) { printf("%04x ", (unsigned)code); } printf("\n"); printf("supported properties: "); for(u16 code : _gdi.DevicePropertiesSupported) { printf("%04x ", (unsigned)code); } printf("\n"); AddCommand("help", make_function([this]() -> void { Help(); })); AddCommand("ls", make_function([this]() -> void { List(); })); AddCommand("list", make_function([this]() -> void { List(); })); AddCommand("list", make_function([this](mtp::u32 parent) -> void { List(parent); })); AddCommand("quit", make_function([this]() -> void { Quit(); })); AddCommand("exit", make_function([this]() -> void { Quit(); })); AddCommand("cd", make_function([this](const Path &path) -> void { ChangeDirectory(path); })); AddCommand("rm", make_function([this](const LocalPath &path) -> void { Delete(path); })); AddCommand("get", make_function([this](const LocalPath &path) -> void { Get(path); })); AddCommand("storages", make_function([this]() -> void { ListStorages(); })); AddCommand("device-properties", make_function([this]() -> void { ListDeviceProperties(); })); } char ** Session::CompletionCallback(const char *text, int start, int end) { if (start == 0) { char **comp = static_cast<char **>(calloc(sizeof(char *), _commands.size() + 1)); auto it = _commands.begin(); size_t i = 0, n = _commands.size(); for(; n--; ++it) { if (end != 0 && it->first.compare(0, end, text) != 0) continue; comp[i++] = strdup(it->first.c_str()); } if (i == 0) //readline silently dereference matches[0] { free(comp); comp = NULL; }; return comp; } return NULL; } void Session::InteractiveInput() { using namespace mtp; std::string prompt(_gdi.Manufacturer + " " + _gdi.Model + "> "), input; cli::CommandLine::Get().SetCallback([this](const char *text, int start, int end) -> char ** { return CompletionCallback(text, start, end); }); while (_running && cli::CommandLine::Get().ReadLine(prompt, input)) { try { Tokens tokens; Tokenizer(input, tokens); if (tokens.empty()) continue; std::string cmdName = tokens.front(); tokens.pop_front(); auto cmd = _commands.find(cmdName); if (cmd == _commands.end()) throw std::runtime_error("invalid command " + cmdName); cmd->second->Execute(tokens); } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } } mtp::u32 Session::Resolve(const Path &path) { mtp::u32 id = _cd; for(size_t p = 0; p < path.size(); ) { size_t next = path.find('/', p); if (next == path.npos) next = path.size(); std::string entity(path.substr(p, next - p)); auto objectList = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, id); bool found = false; for(auto object : objectList.ObjectHandles) { std::string name = _session->GetObjectStringProperty(object, mtp::ObjectProperty::ObjectFilename); if (name == entity) { id = object; found = true; break; } } if (!found) throw std::runtime_error("could not find " + entity + " in path " + path.substr(0, p)); p = next + 1; } return id; } void Session::List(mtp::u32 parent) { using namespace mtp; msg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent); for(u32 objectId : handles.ObjectHandles) { try { msg::ObjectInfo info = _session->GetObjectInfo(objectId); printf("%-10u %04hx %s %u %ux%u, %s\n", objectId, info.ObjectFormat, info.Filename.c_str(), info.ObjectCompressedSize, info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str()); } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } } void Session::ListStorages() { using namespace mtp; msg::StorageIDs list = _session->GetStorageIDs(); for(size_t i = 0; i < list.StorageIDs.size(); ++i) { msg::StorageInfo si = _session->GetStorageInfo(list.StorageIDs[i]); printf("%08d volume: %s, description: %s\n", list.StorageIDs[i], si.VolumeLabel.c_str(), si.StorageDescription.c_str()); } } void Session::Help() { printf("Available commands are:\n"); for(auto i : _commands) { printf("\t%s\n", i.first.c_str()); } } void Session::Get(const LocalPath &dst, mtp::u32 srcId) { _session->GetObject(srcId, std::make_shared<ObjectOutputStream>(dst)); } void Session::Get(mtp::u32 srcId) { auto info = _session->GetObjectInfo(srcId); printf("filename = %s\n", info.Filename.c_str()); Get(LocalPath(info.Filename), srcId); } void Session::Put(mtp::u32 parentId, const LocalPath &src) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = src; oi.ObjectFormat = ObjectFormatFromFilename(src); std::shared_ptr<ObjectInputStream> objectInput(new ObjectInputStream(src)); oi.SetSize(objectInput->GetSize()); auto noi = _session->SendObjectInfo(oi, 0, parentId); printf("new object id = %u\n", noi.ObjectId); _session->SendObject(objectInput); printf("done\n"); } void Session::MakeDirectory(mtp::u32 parentId, const std::string & name) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = name; oi.ObjectFormat = ObjectFormat::Association; _session->SendObjectInfo(oi, 0, parentId); } void Session::Delete(mtp::u32 id) { _session->DeleteObject(id); } void Session::ListProperties(mtp::u32 id) { auto ops = _session->GetObjectPropsSupported(id); printf("properties supported: "); for(mtp::u16 prop: ops.ObjectPropCodes) { printf("%02x ", prop); } printf("\n"); } void Session::ListDeviceProperties() { using namespace mtp; for(u16 code : _gdi.DevicePropertiesSupported) { if ((code & 0xff00) != 0x5000 ) continue; printf("property code: %04x\n", (unsigned)code); ByteArray data = _session->GetDeviceProperty((mtp::DeviceProperty)code); HexDump("value", data); } } } <commit_msg>put newline only for ctrl-d exit<commit_after>#include <cli/Session.h> #include <cli/CommandLine.h> #include <cli/PosixStreams.h> #include <cli/Tokenizer.h> #include <mtp/make_function.h> #include <stdio.h> namespace cli { Session::Session(const mtp::DevicePtr &device): _device(device), _session(_device->OpenSession(1)), _gdi(_session->GetDeviceInfo()), _cd(mtp::Session::Root), _running(true) { using namespace mtp; using namespace std::placeholders; printf("%s\n", _gdi.VendorExtensionDesc.c_str()); printf("%s ", _gdi.Manufacturer.c_str()); printf("%s ", _gdi.Model.c_str()); printf("%s ", _gdi.DeviceVersion.c_str()); //printf("%s", _gdi.SerialNumber.c_str()); printf("\n"); printf("supported op codes: "); for(OperationCode code : _gdi.OperationsSupported) { printf("%04x ", (unsigned)code); } printf("\n"); printf("supported properties: "); for(u16 code : _gdi.DevicePropertiesSupported) { printf("%04x ", (unsigned)code); } printf("\n"); AddCommand("help", make_function([this]() -> void { Help(); })); AddCommand("ls", make_function([this]() -> void { List(); })); AddCommand("list", make_function([this]() -> void { List(); })); AddCommand("list", make_function([this](mtp::u32 parent) -> void { List(parent); })); AddCommand("quit", make_function([this]() -> void { Quit(); })); AddCommand("exit", make_function([this]() -> void { Quit(); })); AddCommand("cd", make_function([this](const Path &path) -> void { ChangeDirectory(path); })); AddCommand("rm", make_function([this](const LocalPath &path) -> void { Delete(path); })); AddCommand("get", make_function([this](const LocalPath &path) -> void { Get(path); })); AddCommand("storages", make_function([this]() -> void { ListStorages(); })); AddCommand("device-properties", make_function([this]() -> void { ListDeviceProperties(); })); } char ** Session::CompletionCallback(const char *text, int start, int end) { if (start == 0) { char **comp = static_cast<char **>(calloc(sizeof(char *), _commands.size() + 1)); auto it = _commands.begin(); size_t i = 0, n = _commands.size(); for(; n--; ++it) { if (end != 0 && it->first.compare(0, end, text) != 0) continue; comp[i++] = strdup(it->first.c_str()); } if (i == 0) //readline silently dereference matches[0] { free(comp); comp = NULL; }; return comp; } return NULL; } void Session::InteractiveInput() { using namespace mtp; std::string prompt(_gdi.Manufacturer + " " + _gdi.Model + "> "), input; cli::CommandLine::Get().SetCallback([this](const char *text, int start, int end) -> char ** { return CompletionCallback(text, start, end); }); while (cli::CommandLine::Get().ReadLine(prompt, input)) { try { Tokens tokens; Tokenizer(input, tokens); if (tokens.empty()) continue; std::string cmdName = tokens.front(); tokens.pop_front(); auto cmd = _commands.find(cmdName); if (cmd == _commands.end()) throw std::runtime_error("invalid command " + cmdName); cmd->second->Execute(tokens); if (!_running) //do not put newline return; } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } printf("\n"); } mtp::u32 Session::Resolve(const Path &path) { mtp::u32 id = _cd; for(size_t p = 0; p < path.size(); ) { size_t next = path.find('/', p); if (next == path.npos) next = path.size(); std::string entity(path.substr(p, next - p)); auto objectList = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, id); bool found = false; for(auto object : objectList.ObjectHandles) { std::string name = _session->GetObjectStringProperty(object, mtp::ObjectProperty::ObjectFilename); if (name == entity) { id = object; found = true; break; } } if (!found) throw std::runtime_error("could not find " + entity + " in path " + path.substr(0, p)); p = next + 1; } return id; } void Session::List(mtp::u32 parent) { using namespace mtp; msg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent); for(u32 objectId : handles.ObjectHandles) { try { msg::ObjectInfo info = _session->GetObjectInfo(objectId); printf("%-10u %04hx %s %u %ux%u, %s\n", objectId, info.ObjectFormat, info.Filename.c_str(), info.ObjectCompressedSize, info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str()); } catch(const std::exception &ex) { printf("error: %s\n", ex.what()); } } } void Session::ListStorages() { using namespace mtp; msg::StorageIDs list = _session->GetStorageIDs(); for(size_t i = 0; i < list.StorageIDs.size(); ++i) { msg::StorageInfo si = _session->GetStorageInfo(list.StorageIDs[i]); printf("%08d volume: %s, description: %s\n", list.StorageIDs[i], si.VolumeLabel.c_str(), si.StorageDescription.c_str()); } } void Session::Help() { printf("Available commands are:\n"); for(auto i : _commands) { printf("\t%s\n", i.first.c_str()); } } void Session::Get(const LocalPath &dst, mtp::u32 srcId) { _session->GetObject(srcId, std::make_shared<ObjectOutputStream>(dst)); } void Session::Get(mtp::u32 srcId) { auto info = _session->GetObjectInfo(srcId); printf("filename = %s\n", info.Filename.c_str()); Get(LocalPath(info.Filename), srcId); } void Session::Put(mtp::u32 parentId, const LocalPath &src) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = src; oi.ObjectFormat = ObjectFormatFromFilename(src); std::shared_ptr<ObjectInputStream> objectInput(new ObjectInputStream(src)); oi.SetSize(objectInput->GetSize()); auto noi = _session->SendObjectInfo(oi, 0, parentId); printf("new object id = %u\n", noi.ObjectId); _session->SendObject(objectInput); printf("done\n"); } void Session::MakeDirectory(mtp::u32 parentId, const std::string & name) { using namespace mtp; msg::ObjectInfo oi; oi.Filename = name; oi.ObjectFormat = ObjectFormat::Association; _session->SendObjectInfo(oi, 0, parentId); } void Session::Delete(mtp::u32 id) { _session->DeleteObject(id); } void Session::ListProperties(mtp::u32 id) { auto ops = _session->GetObjectPropsSupported(id); printf("properties supported: "); for(mtp::u16 prop: ops.ObjectPropCodes) { printf("%02x ", prop); } printf("\n"); } void Session::ListDeviceProperties() { using namespace mtp; for(u16 code : _gdi.DevicePropertiesSupported) { if ((code & 0xff00) != 0x5000 ) continue; printf("property code: %04x\n", (unsigned)code); ByteArray data = _session->GetDeviceProperty((mtp::DeviceProperty)code); HexDump("value", data); } } } <|endoftext|>
<commit_before>#include "cmainwindow.h" #include "ui_cmainwindow.h" #include <QCameraInfo> #include <QImageReader> #include <QPainter> #include <QTime> #include <QTimer> inline bool analyzeFrame(const QImage& frame, unsigned int threshold) { if (frame.depth() != 32) return true; const int w = frame.width(), h = frame.height(); const int sampleSquareSize = 20; const int sampleStrideW = w / sampleSquareSize, sampleStrideH = h / sampleSquareSize; uint64_t pixelsValueSum = 0; for (int y = 0; y < h; y += sampleStrideH) { const uint32_t* scanLine = (const uint32_t*) frame.scanLine(y); for (int x = 0; x < w; x += sampleStrideW) { // TODO: support non-32 bpp images // TODO: vectorization const uint32_t pixel = scanLine[y]; pixelsValueSum += ((pixel & 0x00FF0000) >> 16) + ((pixel & 0x0000FF00) >> 8) + (pixel & 0x000000FF); } } const auto avgValue = pixelsValueSum / ((uint64_t) w / sampleStrideW * (uint64_t) h / sampleStrideH * 3ull); qDebug() << "Frame metric:" << avgValue; return avgValue >= threshold; } CMainWindow::CMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::CMainWindow) { ui->setupUi(this); ui->_displayWidget->installEventFilter(this); connect(&_frameGrabber, &ProxyVideoSurface::frameReceived, [this](QImage frame) { if (!frame.isNull() && ui->_btnEnableProbing->isChecked()) { // This is the first frame upon connecting to the camera if (_frame.isNull()) { if (!analyzeFrame(frame, ui->_threshold->value())) { // Disconnect and schedule re-check stopCamera(); QTimer::singleShot(10000, [this](){ startCamera(); }); } } else // Not the first frame - apparently, we're streaming a live picture // Avoid checking every single frame { static uint32_t frameCounter = 0; ++frameCounter; if (frameCounter > 30) { frameCounter = 0; if (!analyzeFrame(frame, ui->_threshold->value())) { // Diisconnect and schedule re-check stopCamera(); QTimer::singleShot(10000, [this](){ startCamera(); }); } } } } _frame = frame; ui->_displayWidget->update(); }); connect(ui->_btnConnect, &QPushButton::clicked, [this](bool connect){ ui->_btnConnect->setChecked(!connect); if (connect) startCamera(); else stopCamera(); }); startCamera(); } CMainWindow::~CMainWindow() { stopCamera(); delete ui; } bool CMainWindow::eventFilter(QObject* /*object*/, QEvent* event) { if (event->type() == QEvent::Paint) { QWidget * widget = ui->_displayWidget; QPainter painter(widget); if (!_frame.isNull()) painter.drawImage(widget->geometry(), _frame); else painter.fillRect(widget->geometry(), Qt::darkGray); painter.end(); return true; } return false; } void CMainWindow::startCamera() { if (!_camera) { const auto cameras = QCameraInfo::availableCameras(); if (cameras.empty()) return; const auto& cameraInfo = cameras.front(); if (cameraInfo.isNull()) return; qDebug() << "Creating the camera" << cameraInfo.description(); _camera = std::make_shared<QCamera>(cameraInfo); _camera->setViewfinder(&_frameGrabber); qDebug() << "Connecting to the camera"; connect(_camera.get(), &QCamera::stateChanged, [this](const QCamera::State state){ if (state == QCamera::ActiveState) { ui->_btnConnect->setChecked(true); setWindowTitle("Connected"); } else { ui->_btnConnect->setChecked(false); setWindowTitle("Not Connected"); } }); } _camera->load(); _camera->start(); } void CMainWindow::stopCamera() { if (_camera) { _camera->stop(); _camera->unload(); _frame = QImage(); } setWindowTitle("Not Connected"); } <commit_msg>Minor fixes<commit_after>#include "cmainwindow.h" #include "ui_cmainwindow.h" #include <QCameraInfo> #include <QImageReader> #include <QPainter> #include <QTime> #include <QTimer> inline bool analyzeFrame(const QImage& frame, unsigned int threshold) { if (frame.depth() != 32) return true; const int w = frame.width(), h = frame.height(); const int sampleSquareSize = 20; const int sampleStrideW = w / sampleSquareSize, sampleStrideH = h / sampleSquareSize; uint64_t pixelsValueSum = 0; for (int y = 0; y < h; y += sampleStrideH) { const uint32_t* scanLine = (const uint32_t*) frame.scanLine(y); for (int x = 0; x < w; x += sampleStrideW) { // TODO: support non-32 bpp images // TODO: vectorization const uint32_t pixel = scanLine[y]; pixelsValueSum += ((pixel & 0x00FF0000) >> 16) + ((pixel & 0x0000FF00) >> 8) + (pixel & 0x000000FF); } } const auto avgValue = pixelsValueSum / ((uint64_t) w / sampleStrideW * (uint64_t) h / sampleStrideH * 3ull); qDebug() << "Frame metric:" << avgValue; return avgValue >= threshold; } CMainWindow::CMainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::CMainWindow) { ui->setupUi(this); ui->_displayWidget->installEventFilter(this); connect(&_frameGrabber, &ProxyVideoSurface::frameReceived, [this](QImage frame) { if (!frame.isNull() && ui->_btnEnableProbing->isChecked()) { // This is the first frame upon connecting to the camera if (_frame.isNull()) { if (!analyzeFrame(frame, ui->_threshold->value())) { // Disconnect and schedule re-check stopCamera(); QTimer::singleShot(10000, [this](){ startCamera(); }); } } else // Not the first frame - apparently, we're streaming a live picture // Avoid checking every single frame { static uint32_t frameCounter = 0; ++frameCounter; if (frameCounter > 30) { frameCounter = 0; if (!analyzeFrame(frame, ui->_threshold->value())) { // Diisconnect and schedule re-check stopCamera(); QTimer::singleShot(10000, [this](){ startCamera(); }); } } } } _frame = frame; ui->_displayWidget->update(); }); connect(ui->_btnConnect, &QPushButton::clicked, [this](bool connect){ ui->_btnConnect->setChecked(!connect); if (connect) startCamera(); else stopCamera(); }); startCamera(); } CMainWindow::~CMainWindow() { stopCamera(); delete ui; } bool CMainWindow::eventFilter(QObject* /*object*/, QEvent* event) { if (event->type() == QEvent::Paint) { QWidget * widget = ui->_displayWidget; QPainter painter(widget); if (!_frame.isNull()) painter.drawImage(widget->geometry(), _frame); else painter.fillRect(widget->geometry(), Qt::darkGray); painter.end(); return true; } return false; } void CMainWindow::startCamera() { if (!_camera) { const auto cameras = QCameraInfo::availableCameras(); for (const QCameraInfo& cameraInfo : cameras) { if (cameraInfo.isNull()) continue; qDebug() << "Creating the camera" << cameraInfo.description(); _camera = std::make_shared<QCamera>(cameraInfo); if (!_camera->isAvailable()) { _camera.reset(); continue; } _camera->setViewfinder(&_frameGrabber); connect(_camera.get(), &QCamera::stateChanged, [this](const QCamera::State state){ if (state == QCamera::ActiveState) { ui->_btnConnect->setChecked(true); setWindowTitle("Connected"); } else { ui->_btnConnect->setChecked(false); setWindowTitle("Not Connected"); } }); break; } } if (_camera) { qDebug() << "Connecting to the camera"; _camera->load(); _camera->start(); } } void CMainWindow::stopCamera() { if (_camera) { qDebug() << "Disconnecting from the camera"; _camera->stop(); _camera->unload(); _frame = QImage(); } setWindowTitle("Not Connected"); } <|endoftext|>
<commit_before>/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #include "engine/engine.h" #include "server/zone/managers/resource/ResourceManager.h" #include "ResourceShiftTask.h" #include "resourcespawner/SampleTask.h" #include "resourcespawner/SampleResultsTask.h" #include "server/zone/managers/resource/InterplanetarySurvey.h" #include "server/zone/managers/resource/InterplanetarySurveyTask.h" #include "server/zone/objects/resource/ResourceContainer.h" #include "server/zone/packets/resource/ResourceContainerObjectDeltaMessage3.h" #include "server/zone/objects/player/sui/listbox/SuiListBox.h" void ResourceManagerImplementation::initialize() { lua = new Lua(); lua->init(); if(!loadConfigData()) { loadDefaultConfig(); info("***** ERROR in configuration, using default values"); } resourceSpawner->init(); startResourceSpawner(); loadSurveyData(); } bool ResourceManagerImplementation::loadConfigFile() { return lua->runFile("scripts/managers/resource_manager.lua"); } void ResourceManagerImplementation::loadSurveyData() { info("Loading survey data form surveys.db"); ObjectDatabaseManager* dbManager = ObjectDatabaseManager::instance(); ObjectDatabase* surveyDatabase = ObjectDatabaseManager::instance()->loadObjectDatabase("surveys", true); if (surveyDatabase == NULL) { error("Could not load the survey database."); return; } int i = 0; try { ObjectDatabaseIterator iterator(surveyDatabase); uint64 objectID; while (iterator.getNextKey(objectID)) { Core::getObjectBroker()->lookUp(objectID); ++i; } } catch (DatabaseException& e) { error("Database exception in DirectorManager::loadSurveyData(): " + e.getMessage()); } info(String::valueOf(i) + " surveys loaded.", true); } int ResourceManagerImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { if (eventType == ObserverEventType::POSTURECHANGED) { CreatureObject* creature = cast<CreatureObject*>( observable); // Cancel Sampling on posture change Reference<SampleTask*> task = creature->getPendingTask("sample").castTo<SampleTask*>( ); Reference<SampleResultsTask*> sampleResultsTask = creature->getPendingTask("sampleresults").castTo<SampleResultsTask*>( ); if (task != NULL) { task->stopSampling(); //creature->removePendingTask("sample"); if(sampleResultsTask != NULL) { sampleResultsTask->cancel(); creature->removePendingTask("sampleresults"); } creature->sendSystemMessage("@survey:sample_cancel"); } } return 1; } bool ResourceManagerImplementation::loadConfigData() { if (!loadConfigFile()) return false; bool loadFromScript = lua->getGlobalInt("buildInitialResourcesFromScript"); String zonesString = lua->getGlobalString("activeZones"); StringTokenizer zonesTokens(zonesString); zonesTokens.setDelimeter(","); while(zonesTokens.hasMoreTokens()) { String zoneName; zonesTokens.getStringToken(zoneName); resourceSpawner->addZone(zoneName); } shiftInterval = lua->getGlobalInt("averageShiftTime"); int aveduration = lua->getGlobalInt("aveduration"); float spawnThrottling = float(lua->getGlobalInt("spawnThrottling")) / 100.0f; int lowerGateOverride = lua->getGlobalInt("lowerGateOverride"); int maxSpawnQuantity = lua->getGlobalInt("maxSpawnQuantity"); resourceSpawner->setSpawningParameters(loadFromScript, aveduration, spawnThrottling, lowerGateOverride, maxSpawnQuantity); String jtlResources = lua->getGlobalString("jtlresources"); StringTokenizer jtlTokens(jtlResources); jtlTokens.setDelimeter(","); while(jtlTokens.hasMoreTokens()) { String token; jtlTokens.getStringToken(token); resourceSpawner->addJtlResource(token); } LuaObject minpoolinc = lua->getGlobalObject("minimumpoolincludes"); String minpoolexc = lua->getGlobalString("minimumpoolexcludes"); resourceSpawner->initializeMinimumPool(minpoolinc, minpoolexc); LuaObject randpoolinc = lua->getGlobalObject("randompoolincludes"); String randpoolexc = lua->getGlobalString("randompoolexcludes"); int randpoolsize = lua->getGlobalInt("randompoolsize"); resourceSpawner->initializeRandomPool(randpoolinc, randpoolexc, randpoolsize); LuaObject fixedpoolinc = lua->getGlobalObject("fixedpoolincludes"); String fixedpoolexc = lua->getGlobalString("fixedpoolexcludes"); resourceSpawner->initializeFixedPool(fixedpoolinc, fixedpoolexc); String natpoolinc = lua->getGlobalString("nativepoolincludes"); String natpoolexc = lua->getGlobalString("nativepoolexcludes"); resourceSpawner->initializeNativePool(natpoolinc, natpoolexc); return true; } void ResourceManagerImplementation::loadDefaultConfig() { resourceSpawner->addZone("corellia"); resourceSpawner->addZone("lok"); resourceSpawner->addZone("yavin4"); resourceSpawner->addZone("dantooine"); resourceSpawner->addZone("dathomir"); resourceSpawner->addZone("naboo"); resourceSpawner->addZone("rori"); resourceSpawner->addZone("talus"); resourceSpawner->addZone("tatooine"); resourceSpawner->addZone("endor"); shiftInterval = 7200000; resourceSpawner->setSpawningParameters(1, 86400, 90, 1000, 0); } void ResourceManagerImplementation::stop() { } void ResourceManagerImplementation::startResourceSpawner() { Locker _locker(_this.get()); resourceSpawner->start(); Reference<ResourceShiftTask*> resourceShift = new ResourceShiftTask(_this.get().get()); resourceShift->schedule(shiftInterval); } void ResourceManagerImplementation::shiftResources() { Locker _locker(_this.get()); resourceSpawner->shiftResources(); Reference<ResourceShiftTask*> resourceShift = new ResourceShiftTask(_this.get().get()); resourceShift->schedule(shiftInterval); } int ResourceManagerImplementation::getResourceRecycleType(ResourceSpawn* resource) { return resourceSpawner->sendResourceRecycleType(resource); } void ResourceManagerImplementation::sendResourceListForSurvey(CreatureObject* playerCreature, const int toolType, const String& surveyType) { ReadLocker locker(_this.get()); resourceSpawner->sendResourceListForSurvey(playerCreature, toolType, surveyType); } ResourceContainer* ResourceManagerImplementation::harvestResource(CreatureObject* player, const String& type, const int quantity) { return resourceSpawner->harvestResource(player, type, quantity); } bool ResourceManagerImplementation::harvestResourceToPlayer(CreatureObject* player, ResourceSpawn* resourceSpawn, const int quantity) { return resourceSpawner->harvestResource(player, resourceSpawn, quantity); } void ResourceManagerImplementation::sendSurvey(CreatureObject* playerCreature, const String& resname) { resourceSpawner->sendSurvey(playerCreature, resname); } void ResourceManagerImplementation::sendSample(CreatureObject* playerCreature, const String& resname, const String& sampleAnimation) { resourceSpawner->sendSample(playerCreature, resname, sampleAnimation); playerCreature->registerObserver(ObserverEventType::POSTURECHANGED, _this.get()); } void ResourceManagerImplementation::createResourceSpawn(CreatureObject* playerCreature, const String& restype) { Locker _locker(_this.get()); ResourceSpawn* resourceSpawn = resourceSpawner->manualCreateResourceSpawn(restype); if (resourceSpawn != NULL) { StringBuffer buffer; buffer << "Spawned " << resourceSpawn->getName() << " of type " << resourceSpawn->getType(); playerCreature->sendSystemMessage(buffer.toString()); } else { playerCreature->sendSystemMessage("Could not create spawn " + restype); } } ResourceSpawn* ResourceManagerImplementation::getResourceSpawn(const String& spawnName) { ResourceSpawn* spawn = NULL; ReadLocker locker(_this.get()); ResourceMap* resourceMap = resourceSpawner->getResourceMap(); spawn = resourceMap->get(spawnName.toLowerCase()); return spawn; } ResourceSpawn* ResourceManagerImplementation::getCurrentSpawn(const String& restype, const String& zoneName) { return resourceSpawner->getCurrentSpawn(restype, zoneName); } void ResourceManagerImplementation::getResourceListByType(Vector<ManagedReference<ResourceSpawn*> >& list, int type, const String& zoneName) { list.removeAll(); ReadLocker locker(_this.get()); ManagedReference<ResourceSpawn*> resourceSpawn; try { ResourceMap* resourceMap = resourceSpawner->getResourceMap(); ZoneResourceMap* zoneMap = resourceMap->getZoneResourceList(zoneName); if (zoneMap != NULL) { for (int i = 0; i < zoneMap->size(); ++i) { resourceSpawn = zoneMap->get(i); if (!resourceSpawn->inShift()) continue; if (type == 9){ if (resourceSpawn->isType("radioactive")) list.add(resourceSpawn); } else if (resourceSpawn->getSurveyToolType() == type) { list.add(resourceSpawn); } } } } catch (Exception& e) { error(e.getMessage()); e.printStackTrace(); } } uint32 ResourceManagerImplementation::getAvailablePowerFromPlayer(CreatureObject* player) { SceneObject* inventory = player->getSlottedObject("inventory"); uint32 power = 0; for (int i = 0; i < inventory->getContainerObjectsSize(); i++) { Reference<SceneObject*> obj = inventory->getContainerObject(i).castTo<SceneObject*>(); if (obj == NULL || !obj->isResourceContainer()) continue; ResourceContainer* rcno = cast<ResourceContainer*>( obj.get()); ManagedReference<ResourceSpawn*> spawn = rcno->getSpawnObject(); if (spawn == NULL || !spawn->isEnergy()) continue; int quantity = rcno->getQuantity(); int pe = spawn->getValueOf(CraftingManager::PE); // potential energy float modifier = MAX(1.0f, pe / 500.0f); power += (uint32) (modifier * quantity); } return power; } void ResourceManagerImplementation::removePowerFromPlayer(CreatureObject* player, uint32 power) { if (power == 0) return; SceneObject* inventory = player->getSlottedObject("inventory"); uint32 containerPower = 0; for (int i = 0; i < inventory->getContainerObjectsSize() && power > 0; ++i) { ManagedReference<SceneObject*> obj = inventory->getContainerObject(i); if (obj == NULL || !obj->isResourceContainer()) continue; ResourceContainer* rcno = cast<ResourceContainer*>( obj.get()); ManagedReference<ResourceSpawn*> spawn = rcno->getSpawnObject(); if (spawn == NULL || !spawn->isEnergy()) continue; int quantity = rcno->getQuantity(); int pe = spawn->getValueOf(CraftingManager::PE); // potential energy float modifier = MAX(1.0f, pe / 500.0f); containerPower = modifier * quantity; if (containerPower > power) { uint32 consumedUnits = (uint64) power / modifier; rcno->setQuantity(quantity - consumedUnits); ResourceContainerObjectDeltaMessage3* drcno3 = new ResourceContainerObjectDeltaMessage3(rcno); drcno3->updateQuantity(); drcno3->close(); player->sendMessage(drcno3); return; } else { rcno->destroyObjectFromWorld(true); rcno->destroyObjectFromDatabase(true); } power -= containerPower; } } void ResourceManagerImplementation::givePlayerResource(CreatureObject* playerCreature, const String& restype, const int quantity) { ManagedReference<ResourceSpawn* > spawn = getResourceSpawn(restype); if(spawn == NULL) { playerCreature->sendSystemMessage("Selected spawn does not exist."); return; } ManagedReference<SceneObject*> inventory = playerCreature->getSlottedObject("inventory"); if(inventory != NULL && !inventory->hasFullContainerObjects()) { ResourceContainer* newResource = spawn->createResource(quantity); if(newResource != NULL) { spawn->extractResource("", quantity); if (inventory->transferObject(newResource, -1, true)) { inventory->broadcastObject(newResource, true); } else { newResource->destroyObjectFromDatabase(true); } } } } bool ResourceManagerImplementation::isRecycledResource(ResourceSpawn* resource) { return resourceSpawner->isRecycledResource(resource); } ResourceSpawn* ResourceManagerImplementation::getRecycledVersion(ResourceSpawn* resource) { return resourceSpawner->getRecycledVersion(resource); } /// Resource Deed Methods void ResourceManagerImplementation::addNodeToListBox(SuiListBox* sui, const String& nodeName) { resourceSpawner->addNodeToListBox(sui, nodeName); } void ResourceManagerImplementation::addPlanetsToListBox(SuiListBox* sui) { resourceSpawner->addPlanetsToListBox(sui); } String ResourceManagerImplementation::getPlanetByIndex(int idx) { return resourceSpawner->getPlanetByIndex(idx); } String ResourceManagerImplementation::addParentNodeToListBox(SuiListBox* sui, const String& currentNode) { return resourceSpawner->addParentNodeToListBox(sui, currentNode); } void ResourceManagerImplementation::listResourcesForPlanetOnScreen(CreatureObject* creature, const String& planet) { Locker locker(_this.get()); resourceSpawner->listResourcesForPlanetOnScreen(creature, planet); } String ResourceManagerImplementation::healthCheck() { return resourceSpawner->healthCheck(); } String ResourceManagerImplementation::dumpResources() { Locker locker(_this.get()); return resourceSpawner->dumpResources(); } String ResourceManagerImplementation::despawnResource(String& resourceName) { ManagedReference<ResourceSpawn*> spawn = getResourceSpawn(resourceName); if(spawn == NULL) { return "Spawn not Found"; } spawn->setDespawned(time(0) - 1); resourceSpawner->shiftResources(); return resourceName + " despawned."; } <commit_msg>[Fixed] stability issue<commit_after>/* Copyright <SWGEmu> See file COPYING for copying conditions.*/ #include "engine/engine.h" #include "server/zone/managers/resource/ResourceManager.h" #include "ResourceShiftTask.h" #include "resourcespawner/SampleTask.h" #include "resourcespawner/SampleResultsTask.h" #include "server/zone/managers/resource/InterplanetarySurvey.h" #include "server/zone/managers/resource/InterplanetarySurveyTask.h" #include "server/zone/objects/resource/ResourceContainer.h" #include "server/zone/packets/resource/ResourceContainerObjectDeltaMessage3.h" #include "server/zone/objects/player/sui/listbox/SuiListBox.h" void ResourceManagerImplementation::initialize() { lua = new Lua(); lua->init(); if(!loadConfigData()) { loadDefaultConfig(); info("***** ERROR in configuration, using default values"); } resourceSpawner->init(); startResourceSpawner(); loadSurveyData(); } bool ResourceManagerImplementation::loadConfigFile() { return lua->runFile("scripts/managers/resource_manager.lua"); } void ResourceManagerImplementation::loadSurveyData() { info("Loading survey data form surveys.db"); ObjectDatabaseManager* dbManager = ObjectDatabaseManager::instance(); ObjectDatabase* surveyDatabase = ObjectDatabaseManager::instance()->loadObjectDatabase("surveys", true); if (surveyDatabase == NULL) { error("Could not load the survey database."); return; } int i = 0; try { ObjectDatabaseIterator iterator(surveyDatabase); uint64 objectID; while (iterator.getNextKey(objectID)) { Core::getObjectBroker()->lookUp(objectID); ++i; } } catch (DatabaseException& e) { error("Database exception in DirectorManager::loadSurveyData(): " + e.getMessage()); } info(String::valueOf(i) + " surveys loaded.", true); } int ResourceManagerImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { if (eventType == ObserverEventType::POSTURECHANGED) { CreatureObject* creature = cast<CreatureObject*>( observable); // Cancel Sampling on posture change Reference<SampleTask*> task = creature->getPendingTask("sample").castTo<SampleTask*>( ); Reference<SampleResultsTask*> sampleResultsTask = creature->getPendingTask("sampleresults").castTo<SampleResultsTask*>( ); if (task != NULL) { task->stopSampling(); //creature->removePendingTask("sample"); if(sampleResultsTask != NULL) { sampleResultsTask->cancel(); creature->removePendingTask("sampleresults"); } creature->sendSystemMessage("@survey:sample_cancel"); } } return 1; } bool ResourceManagerImplementation::loadConfigData() { if (!loadConfigFile()) return false; bool loadFromScript = lua->getGlobalInt("buildInitialResourcesFromScript"); String zonesString = lua->getGlobalString("activeZones"); StringTokenizer zonesTokens(zonesString); zonesTokens.setDelimeter(","); while(zonesTokens.hasMoreTokens()) { String zoneName; zonesTokens.getStringToken(zoneName); resourceSpawner->addZone(zoneName); } shiftInterval = lua->getGlobalInt("averageShiftTime"); int aveduration = lua->getGlobalInt("aveduration"); float spawnThrottling = float(lua->getGlobalInt("spawnThrottling")) / 100.0f; int lowerGateOverride = lua->getGlobalInt("lowerGateOverride"); int maxSpawnQuantity = lua->getGlobalInt("maxSpawnQuantity"); resourceSpawner->setSpawningParameters(loadFromScript, aveduration, spawnThrottling, lowerGateOverride, maxSpawnQuantity); String jtlResources = lua->getGlobalString("jtlresources"); StringTokenizer jtlTokens(jtlResources); jtlTokens.setDelimeter(","); while(jtlTokens.hasMoreTokens()) { String token; jtlTokens.getStringToken(token); resourceSpawner->addJtlResource(token); } LuaObject minpoolinc = lua->getGlobalObject("minimumpoolincludes"); String minpoolexc = lua->getGlobalString("minimumpoolexcludes"); resourceSpawner->initializeMinimumPool(minpoolinc, minpoolexc); LuaObject randpoolinc = lua->getGlobalObject("randompoolincludes"); String randpoolexc = lua->getGlobalString("randompoolexcludes"); int randpoolsize = lua->getGlobalInt("randompoolsize"); resourceSpawner->initializeRandomPool(randpoolinc, randpoolexc, randpoolsize); LuaObject fixedpoolinc = lua->getGlobalObject("fixedpoolincludes"); String fixedpoolexc = lua->getGlobalString("fixedpoolexcludes"); resourceSpawner->initializeFixedPool(fixedpoolinc, fixedpoolexc); String natpoolinc = lua->getGlobalString("nativepoolincludes"); String natpoolexc = lua->getGlobalString("nativepoolexcludes"); resourceSpawner->initializeNativePool(natpoolinc, natpoolexc); return true; } void ResourceManagerImplementation::loadDefaultConfig() { resourceSpawner->addZone("corellia"); resourceSpawner->addZone("lok"); resourceSpawner->addZone("yavin4"); resourceSpawner->addZone("dantooine"); resourceSpawner->addZone("dathomir"); resourceSpawner->addZone("naboo"); resourceSpawner->addZone("rori"); resourceSpawner->addZone("talus"); resourceSpawner->addZone("tatooine"); resourceSpawner->addZone("endor"); shiftInterval = 7200000; resourceSpawner->setSpawningParameters(1, 86400, 90, 1000, 0); } void ResourceManagerImplementation::stop() { } void ResourceManagerImplementation::startResourceSpawner() { Locker _locker(_this.get()); resourceSpawner->start(); Reference<ResourceShiftTask*> resourceShift = new ResourceShiftTask(_this.get().get()); resourceShift->schedule(shiftInterval); } void ResourceManagerImplementation::shiftResources() { Locker _locker(_this.get()); resourceSpawner->shiftResources(); Reference<ResourceShiftTask*> resourceShift = new ResourceShiftTask(_this.get().get()); resourceShift->schedule(shiftInterval); } int ResourceManagerImplementation::getResourceRecycleType(ResourceSpawn* resource) { return resourceSpawner->sendResourceRecycleType(resource); } void ResourceManagerImplementation::sendResourceListForSurvey(CreatureObject* playerCreature, const int toolType, const String& surveyType) { ReadLocker locker(_this.get()); resourceSpawner->sendResourceListForSurvey(playerCreature, toolType, surveyType); } ResourceContainer* ResourceManagerImplementation::harvestResource(CreatureObject* player, const String& type, const int quantity) { return resourceSpawner->harvestResource(player, type, quantity); } bool ResourceManagerImplementation::harvestResourceToPlayer(CreatureObject* player, ResourceSpawn* resourceSpawn, const int quantity) { return resourceSpawner->harvestResource(player, resourceSpawn, quantity); } void ResourceManagerImplementation::sendSurvey(CreatureObject* playerCreature, const String& resname) { resourceSpawner->sendSurvey(playerCreature, resname); } void ResourceManagerImplementation::sendSample(CreatureObject* playerCreature, const String& resname, const String& sampleAnimation) { resourceSpawner->sendSample(playerCreature, resname, sampleAnimation); playerCreature->registerObserver(ObserverEventType::POSTURECHANGED, _this.get()); } void ResourceManagerImplementation::createResourceSpawn(CreatureObject* playerCreature, const String& restype) { Locker _locker(_this.get()); ResourceSpawn* resourceSpawn = resourceSpawner->manualCreateResourceSpawn(restype); if (resourceSpawn != NULL) { StringBuffer buffer; buffer << "Spawned " << resourceSpawn->getName() << " of type " << resourceSpawn->getType(); playerCreature->sendSystemMessage(buffer.toString()); } else { playerCreature->sendSystemMessage("Could not create spawn " + restype); } } ResourceSpawn* ResourceManagerImplementation::getResourceSpawn(const String& spawnName) { ResourceSpawn* spawn = NULL; ReadLocker locker(_this.get()); ResourceMap* resourceMap = resourceSpawner->getResourceMap(); spawn = resourceMap->get(spawnName.toLowerCase()); return spawn; } ResourceSpawn* ResourceManagerImplementation::getCurrentSpawn(const String& restype, const String& zoneName) { return resourceSpawner->getCurrentSpawn(restype, zoneName); } void ResourceManagerImplementation::getResourceListByType(Vector<ManagedReference<ResourceSpawn*> >& list, int type, const String& zoneName) { list.removeAll(); ReadLocker locker(_this.get()); ManagedReference<ResourceSpawn*> resourceSpawn; try { ResourceMap* resourceMap = resourceSpawner->getResourceMap(); ZoneResourceMap* zoneMap = resourceMap->getZoneResourceList(zoneName); if (zoneMap != NULL) { for (int i = 0; i < zoneMap->size(); ++i) { resourceSpawn = zoneMap->get(i); if (!resourceSpawn->inShift()) continue; if (type == 9){ if (resourceSpawn->isType("radioactive")) list.add(resourceSpawn); } else if (resourceSpawn->getSurveyToolType() == type) { list.add(resourceSpawn); } } } } catch (Exception& e) { error(e.getMessage()); e.printStackTrace(); } } uint32 ResourceManagerImplementation::getAvailablePowerFromPlayer(CreatureObject* player) { SceneObject* inventory = player->getSlottedObject("inventory"); uint32 power = 0; for (int i = 0; i < inventory->getContainerObjectsSize(); i++) { Reference<SceneObject*> obj = inventory->getContainerObject(i).castTo<SceneObject*>(); if (obj == NULL || !obj->isResourceContainer()) continue; ResourceContainer* rcno = cast<ResourceContainer*>( obj.get()); ManagedReference<ResourceSpawn*> spawn = rcno->getSpawnObject(); if (spawn == NULL || !spawn->isEnergy()) continue; int quantity = rcno->getQuantity(); int pe = spawn->getValueOf(CraftingManager::PE); // potential energy float modifier = MAX(1.0f, pe / 500.0f); power += (uint32) (modifier * quantity); } return power; } void ResourceManagerImplementation::removePowerFromPlayer(CreatureObject* player, uint32 power) { if (power == 0) return; SceneObject* inventory = player->getSlottedObject("inventory"); uint32 containerPower = 0; for (int i = 0; i < inventory->getContainerObjectsSize() && power > 0; ++i) { ManagedReference<SceneObject*> obj = inventory->getContainerObject(i); if (obj == NULL || !obj->isResourceContainer()) continue; ResourceContainer* rcno = cast<ResourceContainer*>( obj.get()); Locker locker(rcno); ManagedReference<ResourceSpawn*> spawn = rcno->getSpawnObject(); if (spawn == NULL || !spawn->isEnergy()) continue; int quantity = rcno->getQuantity(); int pe = spawn->getValueOf(CraftingManager::PE); // potential energy float modifier = MAX(1.0f, pe / 500.0f); containerPower = modifier * quantity; if (containerPower > power) { uint32 consumedUnits = (uint64) power / modifier; rcno->setQuantity(quantity - consumedUnits); ResourceContainerObjectDeltaMessage3* drcno3 = new ResourceContainerObjectDeltaMessage3(rcno); drcno3->updateQuantity(); drcno3->close(); player->sendMessage(drcno3); return; } else { rcno->destroyObjectFromWorld(true); rcno->destroyObjectFromDatabase(true); } power -= containerPower; } } void ResourceManagerImplementation::givePlayerResource(CreatureObject* playerCreature, const String& restype, const int quantity) { ManagedReference<ResourceSpawn* > spawn = getResourceSpawn(restype); if(spawn == NULL) { playerCreature->sendSystemMessage("Selected spawn does not exist."); return; } ManagedReference<SceneObject*> inventory = playerCreature->getSlottedObject("inventory"); if(inventory != NULL && !inventory->hasFullContainerObjects()) { ResourceContainer* newResource = spawn->createResource(quantity); if(newResource != NULL) { spawn->extractResource("", quantity); if (inventory->transferObject(newResource, -1, true)) { inventory->broadcastObject(newResource, true); } else { newResource->destroyObjectFromDatabase(true); } } } } bool ResourceManagerImplementation::isRecycledResource(ResourceSpawn* resource) { return resourceSpawner->isRecycledResource(resource); } ResourceSpawn* ResourceManagerImplementation::getRecycledVersion(ResourceSpawn* resource) { return resourceSpawner->getRecycledVersion(resource); } /// Resource Deed Methods void ResourceManagerImplementation::addNodeToListBox(SuiListBox* sui, const String& nodeName) { resourceSpawner->addNodeToListBox(sui, nodeName); } void ResourceManagerImplementation::addPlanetsToListBox(SuiListBox* sui) { resourceSpawner->addPlanetsToListBox(sui); } String ResourceManagerImplementation::getPlanetByIndex(int idx) { return resourceSpawner->getPlanetByIndex(idx); } String ResourceManagerImplementation::addParentNodeToListBox(SuiListBox* sui, const String& currentNode) { return resourceSpawner->addParentNodeToListBox(sui, currentNode); } void ResourceManagerImplementation::listResourcesForPlanetOnScreen(CreatureObject* creature, const String& planet) { Locker locker(_this.get()); resourceSpawner->listResourcesForPlanetOnScreen(creature, planet); } String ResourceManagerImplementation::healthCheck() { return resourceSpawner->healthCheck(); } String ResourceManagerImplementation::dumpResources() { Locker locker(_this.get()); return resourceSpawner->dumpResources(); } String ResourceManagerImplementation::despawnResource(String& resourceName) { ManagedReference<ResourceSpawn*> spawn = getResourceSpawn(resourceName); if(spawn == NULL) { return "Spawn not Found"; } spawn->setDespawned(time(0) - 1); resourceSpawner->shiftResources(); return resourceName + " despawned."; } <|endoftext|>
<commit_before>#include "specter/ViewResources.hpp" namespace specter { static logvisor::Module Log("specter::ViewResources"); void ViewResources::init(boo::IGraphicsDataFactory* factory, FontCache* fcache, const IThemeData* theme, float pf) { if (!factory || !fcache || !theme) Log.report(logvisor::Fatal, "all arguments of ViewResources::init() must be non-null"); m_pixelFactor = pf; m_factory = factory; m_theme = theme; m_fcache = fcache; unsigned dpi = 72.f * m_pixelFactor; m_curveFont = fcache->prepCurvesFont(factory, AllCharFilter, false, 8.f, dpi); m_resData = factory->commitTransaction( [&](boo::IGraphicsDataFactory::Context& ctx) -> bool { switch (ctx.platform()) { case boo::IGraphicsDataFactory::Platform::OGL: init<boo::GLDataFactory::Context>(static_cast<boo::GLDataFactory::Context&>(ctx), *theme, fcache); break; #if _WIN32 case boo::IGraphicsDataFactory::Platform::D3D11: case boo::IGraphicsDataFactory::Platform::D3D12: init<boo::ID3DDataFactory::Context>(static_cast<boo::ID3DDataFactory::Context&>(ctx), *theme, fcache); break; #endif #if BOO_HAS_METAL case boo::IGraphicsDataFactory::Platform::Metal: init<boo::MetalDataFactory::Context>(static_cast<boo::MetalDataFactory::Context&>(ctx), *theme, fcache); break; #endif #if BOO_HAS_VULKAN case boo::IGraphicsDataFactory::Platform::Vulkan: init<boo::VulkanDataFactory::Context>(static_cast<boo::VulkanDataFactory::Context&>(ctx), *theme, fcache); break; #endif default: Log.report(logvisor::Fatal, _S("unable to init view system for %s"), ctx.platformName()); } return true; }); } void ViewResources::prepFontCacheSync() { unsigned dpi = 72.f * m_pixelFactor; if (m_fcacheInterrupt) return; m_mainFont = m_fcache->prepMainFont(m_factory, AllCharFilter, false, 10.f, dpi); if (m_fcacheInterrupt) return; m_monoFont = m_fcache->prepMonoFont(m_factory, AllCharFilter, false, 10.f, dpi); if (m_fcacheInterrupt) return; m_heading14 = m_fcache->prepMainFont(m_factory, LatinAndJapaneseCharFilter, false, 14.f, dpi); if (m_fcacheInterrupt) return; m_heading18 = m_fcache->prepMainFont(m_factory, LatinAndJapaneseCharFilter, false, 18.f, dpi); if (m_fcacheInterrupt) return; m_titleFont = m_fcache->prepMainFont(m_factory, LatinCharFilter, false, 36.f, dpi); if (m_fcacheInterrupt) return; m_fcache->closeBuiltinFonts(); m_fcacheReady = true; } void ViewResources::prepFontCacheAsync(boo::IWindow* window) { m_fcacheReady = false; m_fcacheThread = std::thread([this, window]() { window->getLoadContextDataFactory(); prepFontCacheSync(); }); } void ViewResources::resetPixelFactor(float pf) { m_pixelFactor = pf; unsigned dpi = 72.f * m_pixelFactor; m_curveFont = m_fcache->prepCurvesFont(m_factory, AllCharFilter, false, 8.f, dpi); prepFontCacheSync(); } void ViewResources::resetTheme(const IThemeData* theme) { m_theme = theme; } } <commit_msg>OpenGL enum change<commit_after>#include "specter/ViewResources.hpp" namespace specter { static logvisor::Module Log("specter::ViewResources"); void ViewResources::init(boo::IGraphicsDataFactory* factory, FontCache* fcache, const IThemeData* theme, float pf) { if (!factory || !fcache || !theme) Log.report(logvisor::Fatal, "all arguments of ViewResources::init() must be non-null"); m_pixelFactor = pf; m_factory = factory; m_theme = theme; m_fcache = fcache; unsigned dpi = 72.f * m_pixelFactor; m_curveFont = fcache->prepCurvesFont(factory, AllCharFilter, false, 8.f, dpi); m_resData = factory->commitTransaction( [&](boo::IGraphicsDataFactory::Context& ctx) -> bool { switch (ctx.platform()) { case boo::IGraphicsDataFactory::Platform::OpenGL: init<boo::GLDataFactory::Context>(static_cast<boo::GLDataFactory::Context&>(ctx), *theme, fcache); break; #if _WIN32 case boo::IGraphicsDataFactory::Platform::D3D11: case boo::IGraphicsDataFactory::Platform::D3D12: init<boo::ID3DDataFactory::Context>(static_cast<boo::ID3DDataFactory::Context&>(ctx), *theme, fcache); break; #endif #if BOO_HAS_METAL case boo::IGraphicsDataFactory::Platform::Metal: init<boo::MetalDataFactory::Context>(static_cast<boo::MetalDataFactory::Context&>(ctx), *theme, fcache); break; #endif #if BOO_HAS_VULKAN case boo::IGraphicsDataFactory::Platform::Vulkan: init<boo::VulkanDataFactory::Context>(static_cast<boo::VulkanDataFactory::Context&>(ctx), *theme, fcache); break; #endif default: Log.report(logvisor::Fatal, _S("unable to init view system for %s"), ctx.platformName()); } return true; }); } void ViewResources::prepFontCacheSync() { unsigned dpi = 72.f * m_pixelFactor; if (m_fcacheInterrupt) return; m_mainFont = m_fcache->prepMainFont(m_factory, AllCharFilter, false, 10.f, dpi); if (m_fcacheInterrupt) return; m_monoFont = m_fcache->prepMonoFont(m_factory, AllCharFilter, false, 10.f, dpi); if (m_fcacheInterrupt) return; m_heading14 = m_fcache->prepMainFont(m_factory, LatinAndJapaneseCharFilter, false, 14.f, dpi); if (m_fcacheInterrupt) return; m_heading18 = m_fcache->prepMainFont(m_factory, LatinAndJapaneseCharFilter, false, 18.f, dpi); if (m_fcacheInterrupt) return; m_titleFont = m_fcache->prepMainFont(m_factory, LatinCharFilter, false, 36.f, dpi); if (m_fcacheInterrupt) return; m_fcache->closeBuiltinFonts(); m_fcacheReady = true; } void ViewResources::prepFontCacheAsync(boo::IWindow* window) { m_fcacheReady = false; m_fcacheThread = std::thread([this, window]() { window->getLoadContextDataFactory(); prepFontCacheSync(); }); } void ViewResources::resetPixelFactor(float pf) { m_pixelFactor = pf; unsigned dpi = 72.f * m_pixelFactor; m_curveFont = m_fcache->prepCurvesFont(m_factory, AllCharFilter, false, 8.f, dpi); prepFontCacheSync(); } void ViewResources::resetTheme(const IThemeData* theme) { m_theme = theme; } } <|endoftext|>
<commit_before>#include "chimera/visitor.h" #include <algorithm> #include <boost/algorithm/string/join.hpp> #include <iostream> #include <llvm/Support/raw_ostream.h> #include <string> using namespace chimera; using namespace clang; using boost::algorithm::join; // TODO: Support template functions. // TODO: Detect missing copy constructors, possibly using: // hasUserDeclaredCopyConstructor() // hasCopyConstructorWithConstParam () // TODO: Mark abstract classes as noncopyable? chimera::Visitor::Visitor(clang::CompilerInstance *ci, std::unique_ptr<CompiledConfiguration> cc) : context_(&(ci->getASTContext())) , printing_policy_(ci->getLangOpts()) , config_(std::move(cc)) { // Do nothing. } bool chimera::Visitor::VisitDecl(Decl *decl) { // Only visit declarations in namespaces we are configured to read. if (!IsEnclosed(decl)) return true; if (isa<ClassTemplateDecl>(decl)) GenerateClassTemplate(cast<ClassTemplateDecl>(decl)); else if (isa<CXXRecordDecl>(decl)) GenerateCXXRecord(cast<CXXRecordDecl>(decl)); else if (isa<EnumDecl>(decl)) GenerateEnum(cast<EnumDecl>(decl)); else if (isa<VarDecl>(decl)) GenerateGlobalVar(cast<VarDecl>(decl)); else if (isa<FunctionDecl>(decl)) GenerateGlobalFunction(cast<FunctionDecl>(decl)); return true; } bool chimera::Visitor::GenerateCXXRecord(CXXRecordDecl *const decl) { // Only traverse CXX records that contain the actual class definition. if (!decl->hasDefinition() || decl->getDefinition() != decl) return false; // Open a stream object unique to this CXX record's mangled name. auto stream = config_->GetOutputFile(decl); if (!stream) return false; // Get configuration, and use any overrides if they exist. if (config_->DumpOverride(decl, *stream)) return true; const YAML::Node &node = config_->GetDeclaration(decl); if (node.IsNull()) return false; // Explicitly suppressed. *stream << "::boost::python::class_<" << decl->getTypeForDecl()->getCanonicalTypeInternal().getAsString(printing_policy_); const YAML::Node &noncopyable_node = node["noncopyable"]; if (noncopyable_node && noncopyable_node.as<bool>(false)) *stream << ", ::boost::noncopyable"; if (const YAML::Node &held_type_node = node["held_type"]) *stream << ", " << held_type_node.as<std::string>(); std::vector<std::string> base_names; if (const YAML::Node &bases_node = node["bases"]) base_names = bases_node.as<std::vector<std::string> >(); else base_names = GetBaseClassNames(decl); if (!base_names.empty()) { *stream << ", ::boost::python::bases<" << join(base_names, ", ") << " >"; } *stream << " >(\"" << decl->getNameAsString() << "\", boost::python::no_init)\n"; // Methods std::set<std::string> overloaded_method_names; for (CXXMethodDecl *const method_decl : decl->methods()) { if (method_decl->getAccess() != AS_public) continue; // skip protected and private members if (isa<CXXConversionDecl>(method_decl)) ; // do nothing else if (isa<CXXDestructorDecl>(method_decl)) ; // do nothing else if (isa<CXXConstructorDecl>(method_decl)) { GenerateCXXConstructor( *stream, decl, cast<CXXConstructorDecl>(method_decl)); } else if (method_decl->isOverloadedOperator()) ; // TODO: Wrap overloaded operators. else if (method_decl->isStatic()) { // TODO: Missing the dot. if (GenerateFunction(*stream, decl, method_decl)) overloaded_method_names.insert(method_decl->getNameAsString()); } else { // TODO: Missing the dot. GenerateFunction(*stream, decl, method_decl); } } // Static methods MUST be declared after overloads are defined. for (const std::string &method_name : overloaded_method_names) *stream << ".staticmethod(\"" << method_name << "\")\n"; // Fields for (FieldDecl *const field_decl : decl->fields()) { if (field_decl->getAccess() != AS_public) continue; // skip protected and private fields GenerateField(*stream, decl, field_decl); } for (Decl *const child_decl : decl->decls()) { if (isa<VarDecl>(child_decl)) GenerateStaticField(*stream, decl, cast<VarDecl>(child_decl)); } *stream << ";\n"; return true; } bool chimera::Visitor::GenerateCXXConstructor( chimera::Stream &stream, CXXRecordDecl *class_decl, CXXConstructorDecl *decl) { decl = decl->getCanonicalDecl(); if (decl->isDeleted()) return false; std::vector<std::string> argument_types; for (ParmVarDecl *param_decl : decl->params()) argument_types.push_back(param_decl->getType().getAsString(printing_policy_)); stream << ".def(::boost::python::init<" << join(argument_types, ", ") << ">())\n"; return true; } bool chimera::Visitor::GenerateFunction( chimera::Stream &stream, CXXRecordDecl *class_decl, FunctionDecl *decl) { decl = decl->getCanonicalDecl(); if (decl->isDeleted()) return false; // Get configuration, and use any overrides if they exist. if (config_->DumpOverride(decl, stream)) return true; const YAML::Node &node = config_->GetDeclaration(decl); if (node.IsNull()) return false; // Explicitly suppressed. // Extract the pointer type of this function declaration. QualType pointer_type; if (class_decl && !cast<CXXMethodDecl>(decl)->isStatic()) { pointer_type = context_->getMemberPointerType( decl->getType(), class_decl->getTypeForDecl()); } else { pointer_type = context_->getPointerType(decl->getType()); } pointer_type = pointer_type.getCanonicalType(); // Extract the return type of this function declaration. const QualType return_qual_type = decl->getReturnType(); const Type *return_type = return_qual_type.getTypePtr(); // First, check if a return_value_policy was specified for this function. std::string return_value_policy = node["return_value_policy"].as<std::string>(""); // Next, check if a return_value_policy is defined on the return type. if (return_value_policy.empty()) { const YAML::Node &type_node = config_->GetType(return_qual_type); return_value_policy = type_node["return_value_policy"].as<std::string>(""); } // Finally, try the default return_value_policy. This is only acceptable if // the output is copy constructable. if (return_value_policy.empty()) { if (return_type->isReferenceType()) { std::cerr << "Warning: Skipped method '" << decl->getQualifiedNameAsString() << "' with signature '" << decl->getType().getAsString(printing_policy_) << "' because it returns a reference and no" " 'return_value_policy' was specified.\n"; return false; } else if (return_type->isPointerType()) { std::cerr << "Warning: Skipped method '" << decl->getQualifiedNameAsString() << "' with signature '" << decl->getType().getAsString(printing_policy_) << "' because it returns a pointer and no" " 'return_value_policy' was specified.\n"; return false; } // TODO: Check if return_type is non-copyable. } // If we are inside a class declaration, this is being called within a // builder pattern and will start with '.' since it is a member function. if (class_decl) stream << "."; // Create the actual function declaration here using its name and its // full pointer reference. stream << "def(\"" << decl->getNameAsString() << "\"" << ", static_cast<" << pointer_type.getAsString(printing_policy_) << ">(&" << decl->getQualifiedNameAsString() << ")"; // If a return value policy was specified, insert it after the function. if (!return_value_policy.empty()) { stream << ", ::boost::python::return_value_policy<" << return_value_policy << " >"; } // Construct a list of the arguments that are provided to this function, // and define named arguments for them based on their c++ names. const auto params = GetParameterNames(decl); if (!params.empty()) { // TODO: Suppress any default parameters that occur after the first // non-default to default transition. This can only occur if evaluating // the default value of one or more parameters failed. // TODO: Assign names to unnamed arguments. std::vector<std::string> python_args; for (const auto &param : params) { std::stringstream python_arg; python_arg << "::boost::python::arg(\"" << param.first << "\")"; if (!param.second.empty()) python_arg << " = " << param.second; python_args.push_back(python_arg.str()); } stream << ", (" << join(python_args, ", ") << ")"; } stream << ")\n"; return true; } bool chimera::Visitor::GenerateField( chimera::Stream &stream, clang::CXXRecordDecl *class_decl, clang::FieldDecl *decl) { if (decl->getType().isConstQualified()) stream << ".def_readonly"; else stream << ".def_readwrite"; // TODO: Check if a copy constructor is defined for this type. stream << "(\"" << decl->getNameAsString() << "\"," << " &" << decl->getQualifiedNameAsString() << ")\n"; return true; } bool chimera::Visitor::GenerateStaticField( chimera::Stream &stream, clang::CXXRecordDecl *class_decl, clang::VarDecl *decl) { if (decl->getAccess() != AS_public) return false; else if (!decl->isStaticDataMember()) return false; stream << ".add_static_property(\"" << decl->getNameAsString() << "\", " << "[]() { return " << decl->getQualifiedNameAsString() << "; }"; if (!decl->getType().isConstQualified()) { stream << "[](" << decl->getType().getAsString(printing_policy_) << " value) { " << decl->getQualifiedNameAsString() << " = value; }"; } stream << ")\n"; return true; } bool chimera::Visitor::GenerateClassTemplate(clang::ClassTemplateDecl *decl) { if (decl != decl->getCanonicalDecl()) return false; for (ClassTemplateSpecializationDecl *spec_decl : decl->specializations()) { if (spec_decl->getSpecializationKind() == TSK_Undeclared) continue; CXXRecordDecl *decl = spec_decl->getTypeForDecl()->getAsCXXRecordDecl(); GenerateCXXRecord(decl); } return true; } bool chimera::Visitor::GenerateEnum(clang::EnumDecl *decl) { auto stream = config_->GetOutputFile(decl); if (!stream) return false; *stream << "::boost::python::enum_<" << decl->getQualifiedNameAsString() << ">(\"" << decl->getNameAsString() << "\")\n"; for (EnumConstantDecl *constant_decl : decl->enumerators()) { *stream << ".value(\"" << constant_decl->getNameAsString() << "\", " << constant_decl->getQualifiedNameAsString() << ")\n"; } *stream << ";\n"; return true; } bool chimera::Visitor::GenerateGlobalVar(clang::VarDecl *decl) { if (!decl->isFileVarDecl()) return false; else if (!decl->isThisDeclarationADefinition()) return false; auto stream = config_->GetOutputFile(decl); if (!stream) return false; *stream << "::boost::python::scope().attr(\"" << decl->getNameAsString() << "\") = " << decl->getQualifiedNameAsString() << ";\n"; return true; } bool chimera::Visitor::GenerateGlobalFunction(clang::FunctionDecl *decl) { if (isa<clang::CXXMethodDecl>(decl)) return false; else if (decl->isOverloadedOperator()) return false; // TODO: Wrap overloaded operators. auto stream = config_->GetOutputFile(decl); if (!stream) return false; return GenerateFunction(*stream, nullptr, decl); } std::vector<std::string> chimera::Visitor::GetBaseClassNames( CXXRecordDecl *decl) const { std::vector<std::string> base_names; for (CXXBaseSpecifier &base_decl : decl->bases()) { if (base_decl.getAccessSpecifier() != AS_public) continue; // TODO: Filter out transitive base classes. CXXRecordDecl *const base_record_decl = base_decl.getType()->getAsCXXRecordDecl(); const QualType base_record_type = base_record_decl->getTypeForDecl()->getCanonicalTypeInternal(); base_names.push_back(base_record_type.getAsString(printing_policy_)); } return base_names; } std::vector<std::pair<std::string, std::string>> chimera::Visitor::GetParameterNames(clang::FunctionDecl *decl) const { std::vector<std::pair<std::string, std::string>> params; for (ParmVarDecl *param_decl : decl->params()) { const std::string param_name = param_decl->getNameAsString(); const Type *param_type = param_decl->getType().getTypePtr(); std::string param_value; if (param_decl->hasDefaultArg() && !param_decl->hasUninstantiatedDefaultArg() && !param_decl->hasUnparsedDefaultArg()) { Expr *default_expr = param_decl->getDefaultArg(); assert(default_expr); Expr::EvalResult result; bool success; if (param_type->isReferenceType()) success = default_expr->EvaluateAsLValue(result, *context_); else success = default_expr->EvaluateAsRValue(result, *context_); if (success) { param_value = result.Val.getAsString( *context_, param_decl->getType()); } else if (default_expr->hasNonTrivialCall(*context_)) { // TODO: How do we print the decl with argument + return types? std::cerr << "Warning: Unable to evaluate non-trivial call in default" " value for parameter" << " '" << param_name << "' of method" << " '" << decl->getQualifiedNameAsString() << "'.\n"; } else { // TODO: How do we print the decl with argument + return types? std::cerr << "Warning: Failed to evaluate default value for parameter" << " '" << param_name << "' of method" << " '" << decl->getQualifiedNameAsString() << "'.\n"; } } params.push_back(std::make_pair(param_name, param_value)); } return params; } bool chimera::Visitor::IsEnclosed(Decl *decl) const { // Filter over the namespaces and only traverse ones that are enclosed // by one of the configuration namespaces. for (const auto &it : config_->GetNamespaces()) { if (decl->getDeclContext() && it->Encloses(decl->getDeclContext())) { return true; } } return false; } <commit_msg>Fixed whitespace and printing method pointer_type.<commit_after>#include "chimera/visitor.h" #include <algorithm> #include <boost/algorithm/string/join.hpp> #include <iostream> #include <llvm/Support/raw_ostream.h> #include <string> using namespace chimera; using namespace clang; using boost::algorithm::join; // TODO: Support template functions. // TODO: Detect missing copy constructors, possibly using: // hasUserDeclaredCopyConstructor() // hasCopyConstructorWithConstParam () // TODO: Mark abstract classes as noncopyable? chimera::Visitor::Visitor(clang::CompilerInstance *ci, std::unique_ptr<CompiledConfiguration> cc) : context_(&(ci->getASTContext())) , printing_policy_(ci->getLangOpts()) , config_(std::move(cc)) { // Do nothing. } bool chimera::Visitor::VisitDecl(Decl *decl) { // Only visit declarations in namespaces we are configured to read. if (!IsEnclosed(decl)) return true; if (isa<ClassTemplateDecl>(decl)) GenerateClassTemplate(cast<ClassTemplateDecl>(decl)); else if (isa<CXXRecordDecl>(decl)) GenerateCXXRecord(cast<CXXRecordDecl>(decl)); else if (isa<EnumDecl>(decl)) GenerateEnum(cast<EnumDecl>(decl)); else if (isa<VarDecl>(decl)) GenerateGlobalVar(cast<VarDecl>(decl)); else if (isa<FunctionDecl>(decl)) GenerateGlobalFunction(cast<FunctionDecl>(decl)); return true; } bool chimera::Visitor::GenerateCXXRecord(CXXRecordDecl *const decl) { // Only traverse CXX records that contain the actual class definition. if (!decl->hasDefinition() || decl->getDefinition() != decl) return false; // Open a stream object unique to this CXX record's mangled name. auto stream = config_->GetOutputFile(decl); if (!stream) return false; // Get configuration, and use any overrides if they exist. if (config_->DumpOverride(decl, *stream)) return true; const YAML::Node &node = config_->GetDeclaration(decl); if (node.IsNull()) return false; // Explicitly suppressed. *stream << "::boost::python::class_<" << decl->getTypeForDecl()->getCanonicalTypeInternal().getAsString(printing_policy_); const YAML::Node &noncopyable_node = node["noncopyable"]; if (noncopyable_node && noncopyable_node.as<bool>(false)) *stream << ", ::boost::noncopyable"; if (const YAML::Node &held_type_node = node["held_type"]) *stream << ", " << held_type_node.as<std::string>(); std::vector<std::string> base_names; if (const YAML::Node &bases_node = node["bases"]) base_names = bases_node.as<std::vector<std::string> >(); else base_names = GetBaseClassNames(decl); if (!base_names.empty()) { *stream << ", ::boost::python::bases<" << join(base_names, ", ") << " >"; } *stream << " >(\"" << decl->getNameAsString() << "\", boost::python::no_init)\n"; // Methods std::set<std::string> overloaded_method_names; for (CXXMethodDecl *const method_decl : decl->methods()) { if (method_decl->getAccess() != AS_public) continue; // skip protected and private members if (isa<CXXConversionDecl>(method_decl)) ; // do nothing else if (isa<CXXDestructorDecl>(method_decl)) ; // do nothing else if (isa<CXXConstructorDecl>(method_decl)) { GenerateCXXConstructor( *stream, decl, cast<CXXConstructorDecl>(method_decl)); } else if (method_decl->isOverloadedOperator()) ; // TODO: Wrap overloaded operators. else if (method_decl->isStatic()) { // TODO: Missing the dot. if (GenerateFunction(*stream, decl, method_decl)) overloaded_method_names.insert(method_decl->getNameAsString()); } else { // TODO: Missing the dot. GenerateFunction(*stream, decl, method_decl); } } // Static methods MUST be declared after overloads are defined. for (const std::string &method_name : overloaded_method_names) *stream << ".staticmethod(\"" << method_name << "\")\n"; // Fields for (FieldDecl *const field_decl : decl->fields()) { if (field_decl->getAccess() != AS_public) continue; // skip protected and private fields GenerateField(*stream, decl, field_decl); } for (Decl *const child_decl : decl->decls()) { if (isa<VarDecl>(child_decl)) GenerateStaticField(*stream, decl, cast<VarDecl>(child_decl)); } *stream << ";\n"; return true; } bool chimera::Visitor::GenerateCXXConstructor( chimera::Stream &stream, CXXRecordDecl *class_decl, CXXConstructorDecl *decl) { decl = decl->getCanonicalDecl(); if (decl->isDeleted()) return false; std::vector<std::string> argument_types; for (ParmVarDecl *param_decl : decl->params()) argument_types.push_back(param_decl->getType().getAsString(printing_policy_)); stream << ".def(::boost::python::init<" << join(argument_types, ", ") << ">())\n"; return true; } bool chimera::Visitor::GenerateFunction( chimera::Stream &stream, CXXRecordDecl *class_decl, FunctionDecl *decl) { decl = decl->getCanonicalDecl(); if (decl->isDeleted()) return false; // Get configuration, and use any overrides if they exist. if (config_->DumpOverride(decl, stream)) return true; const YAML::Node &node = config_->GetDeclaration(decl); if (node.IsNull()) return false; // Explicitly suppressed. // Extract the pointer type of this function declaration. QualType pointer_type; if (class_decl && !cast<CXXMethodDecl>(decl)->isStatic()) { pointer_type = context_->getMemberPointerType( decl->getType(), class_decl->getTypeForDecl()); } else { pointer_type = context_->getPointerType(decl->getType()); } pointer_type = pointer_type.getCanonicalType(); // Extract the return type of this function declaration. const QualType return_qual_type = decl->getReturnType(); const Type *return_type = return_qual_type.getTypePtr(); // First, check if a return_value_policy was specified for this function. std::string return_value_policy = node["return_value_policy"].as<std::string>(""); // Next, check if a return_value_policy is defined on the return type. if (return_value_policy.empty()) { const YAML::Node &type_node = config_->GetType(return_qual_type); return_value_policy = type_node["return_value_policy"].as<std::string>(""); } // Finally, try the default return_value_policy. This is only acceptable if // the output is copy constructable. if (return_value_policy.empty()) { if (return_type->isReferenceType()) { std::cerr << "Warning: Skipped method '" << pointer_type.getAsString(printing_policy_) << "' because it returns a reference and no" " 'return_value_policy' was specified.\n"; return false; } else if (return_type->isPointerType()) { std::cerr << "Warning: Skipped method '" << pointer_type.getAsString(printing_policy_) << "' because it returns a pointer and no" " 'return_value_policy' was specified.\n"; return false; } // TODO: Check if return_type is non-copyable. } // If we are inside a class declaration, this is being called within a // builder pattern and will start with '.' since it is a member function. if (class_decl) stream << "."; // Create the actual function declaration here using its name and its // full pointer reference. stream << "def(\"" << decl->getNameAsString() << "\"" << ", static_cast<" << pointer_type.getAsString(printing_policy_) << ">(&" << decl->getQualifiedNameAsString() << ")"; // If a return value policy was specified, insert it after the function. if (!return_value_policy.empty()) { stream << ", ::boost::python::return_value_policy<" << return_value_policy << " >"; } // Construct a list of the arguments that are provided to this function, // and define named arguments for them based on their c++ names. const auto params = GetParameterNames(decl); if (!params.empty()) { // TODO: Suppress any default parameters that occur after the first // non-default to default transition. This can only occur if evaluating // the default value of one or more parameters failed. // TODO: Assign names to unnamed arguments. std::vector<std::string> python_args; for (const auto &param : params) { std::stringstream python_arg; python_arg << "::boost::python::arg(\"" << param.first << "\")"; if (!param.second.empty()) python_arg << " = " << param.second; python_args.push_back(python_arg.str()); } stream << ", (" << join(python_args, ", ") << ")"; } stream << ")\n"; return true; } bool chimera::Visitor::GenerateField( chimera::Stream &stream, clang::CXXRecordDecl *class_decl, clang::FieldDecl *decl) { if (decl->getType().isConstQualified()) stream << ".def_readonly"; else stream << ".def_readwrite"; // TODO: Check if a copy constructor is defined for this type. stream << "(\"" << decl->getNameAsString() << "\"," << " &" << decl->getQualifiedNameAsString() << ")\n"; return true; } bool chimera::Visitor::GenerateStaticField( chimera::Stream &stream, clang::CXXRecordDecl *class_decl, clang::VarDecl *decl) { if (decl->getAccess() != AS_public) return false; else if (!decl->isStaticDataMember()) return false; stream << ".add_static_property(\"" << decl->getNameAsString() << "\", " << "[]() { return " << decl->getQualifiedNameAsString() << "; }"; if (!decl->getType().isConstQualified()) { stream << "[](" << decl->getType().getAsString(printing_policy_) << " value) { " << decl->getQualifiedNameAsString() << " = value; }"; } stream << ")\n"; return true; } bool chimera::Visitor::GenerateClassTemplate(clang::ClassTemplateDecl *decl) { if (decl != decl->getCanonicalDecl()) return false; for (ClassTemplateSpecializationDecl *spec_decl : decl->specializations()) { if (spec_decl->getSpecializationKind() == TSK_Undeclared) continue; CXXRecordDecl *decl = spec_decl->getTypeForDecl()->getAsCXXRecordDecl(); GenerateCXXRecord(decl); } return true; } bool chimera::Visitor::GenerateEnum(clang::EnumDecl *decl) { auto stream = config_->GetOutputFile(decl); if (!stream) return false; *stream << "::boost::python::enum_<" << decl->getQualifiedNameAsString() << ">(\"" << decl->getNameAsString() << "\")\n"; for (EnumConstantDecl *constant_decl : decl->enumerators()) { *stream << ".value(\"" << constant_decl->getNameAsString() << "\", " << constant_decl->getQualifiedNameAsString() << ")\n"; } *stream << ";\n"; return true; } bool chimera::Visitor::GenerateGlobalVar(clang::VarDecl *decl) { if (!decl->isFileVarDecl()) return false; else if (!decl->isThisDeclarationADefinition()) return false; auto stream = config_->GetOutputFile(decl); if (!stream) return false; *stream << "::boost::python::scope().attr(\"" << decl->getNameAsString() << "\") = " << decl->getQualifiedNameAsString() << ";\n"; return true; } bool chimera::Visitor::GenerateGlobalFunction(clang::FunctionDecl *decl) { if (isa<clang::CXXMethodDecl>(decl)) return false; else if (decl->isOverloadedOperator()) return false; // TODO: Wrap overloaded operators. auto stream = config_->GetOutputFile(decl); if (!stream) return false; return GenerateFunction(*stream, nullptr, decl); } std::vector<std::string> chimera::Visitor::GetBaseClassNames( CXXRecordDecl *decl) const { std::vector<std::string> base_names; for (CXXBaseSpecifier &base_decl : decl->bases()) { if (base_decl.getAccessSpecifier() != AS_public) continue; // TODO: Filter out transitive base classes. CXXRecordDecl *const base_record_decl = base_decl.getType()->getAsCXXRecordDecl(); const QualType base_record_type = base_record_decl->getTypeForDecl()->getCanonicalTypeInternal(); base_names.push_back(base_record_type.getAsString(printing_policy_)); } return base_names; } std::vector<std::pair<std::string, std::string>> chimera::Visitor::GetParameterNames(clang::FunctionDecl *decl) const { std::vector<std::pair<std::string, std::string>> params; for (ParmVarDecl *param_decl : decl->params()) { const std::string param_name = param_decl->getNameAsString(); const Type *param_type = param_decl->getType().getTypePtr(); std::string param_value; if (param_decl->hasDefaultArg() && !param_decl->hasUninstantiatedDefaultArg() && !param_decl->hasUnparsedDefaultArg()) { Expr *default_expr = param_decl->getDefaultArg(); assert(default_expr); Expr::EvalResult result; bool success; if (param_type->isReferenceType()) success = default_expr->EvaluateAsLValue(result, *context_); else success = default_expr->EvaluateAsRValue(result, *context_); if (success) { param_value = result.Val.getAsString( *context_, param_decl->getType()); } else if (default_expr->hasNonTrivialCall(*context_)) { // TODO: How do we print the decl with argument + return types? std::cerr << "Warning: Unable to evaluate non-trivial call in default" " value for parameter" << " '" << param_name << "' of method" << " '" << decl->getQualifiedNameAsString() << "'.\n"; } else { // TODO: How do we print the decl with argument + return types? std::cerr << "Warning: Failed to evaluate default value for parameter" << " '" << param_name << "' of method" << " '" << decl->getQualifiedNameAsString() << "'.\n"; } } params.push_back(std::make_pair(param_name, param_value)); } return params; } bool chimera::Visitor::IsEnclosed(Decl *decl) const { // Filter over the namespaces and only traverse ones that are enclosed // by one of the configuration namespaces. for (const auto &it : config_->GetNamespaces()) { if (decl->getDeclContext() && it->Encloses(decl->getDeclContext())) { return true; } } return false; } <|endoftext|>
<commit_before>// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: * Caner Candan <caner.candan@univ-angers.fr> */ #include <boost/algorithm/string.hpp> #include <boost/mpi.hpp> #include <eo> #include <eoSwapMutation.h> #include <eoShiftMutation.h> #include <eoInversionMutation.h> #include <eoTwoOptMutation.h> #include <dim/dim> #include <dim/algo/Easy.h> #include <dim/evolver/Easy.h> #include <dim/feedbacker/Easy.h> #include <dim/migrator/Easy.h> #include <dim/vectorupdater/Easy.h> #include <dim/core/State.h> #if __cplusplus > 199711L namespace std_or_boost = std; #include <mutex> #include <condition_variable> #else #include <boost/thread/thread.hpp> #include <boost/chrono/chrono_io.hpp> #include <boost/thread/mutex.hpp> namespace std_or_boost = boost; #endif typedef dim::representation::Route<double> EOT; int main (int argc, char *argv[]) { /************************* * Initialisation de MPI * *************************/ // boost::mpi::environment env(argc, argv, MPI_THREAD_MULTIPLE, true); // boost::mpi::communicator world; /**************************** * Il faut au moins 4 nœuds * ****************************/ // const size_t ALL = world.size(); // const size_t RANK = world.rank(); /************************ * Initialisation de EO * ************************/ eoParser parser(argc, argv); eoState state; // keeps all things allocated dim::core::State state_dim; // keeps all things allocated /***************************** * Definition des paramètres * *****************************/ // N unsigned nislands = parser.createParam(unsigned(4), "nislands", "Number of islands (see --smp)", 'N', "Islands Model").value(); // a double alphaP = parser.createParam(double(0.2), "alpha", "Alpha Probability", 'a', "Islands Model").value(); // A double alphaF = parser.createParam(double(0.01), "alphaF", "Alpha Fitness", 'A', "Islands Model").value(); // b double betaP = parser.createParam(double(0.01), "beta", "Beta Probability", 'b', "Islands Model").value(); // d double probaSame = parser.createParam(double(100./nislands), "probaSame", "Probability for an individual to stay in the same island", 'd', "Islands Model").value(); // I bool initG = parser.createParam(bool(true), "initG", "initG", 'I', "Islands Model").value(); unsigned nmigrations = parser.createParam(unsigned(1), "nmigrations", "Number of migrations to do at each generation (0=all individuals are migrated)", 0, "Islands Model").value(); unsigned stepTimer = parser.createParam(unsigned(0), "stepTimer", "stepTimer", 0, "Islands Model").value(); bool deltaUpdate = parser.createParam(bool(true), "deltaUpdate", "deltaUpdate", 0, "Islands Model").value(); bool deltaFeedback = parser.createParam(bool(true), "deltaFeedback", "deltaFeedback", 0, "Islands Model").value(); double sensitivity = 1 / parser.createParam(double(1.), "sensitivity", "sensitivity of delta{t} (1/sensitivity)", 0, "Islands Model").value(); std::string rewardStrategy = parser.createParam(std::string("best"), "rewardStrategy", "Strategy of rewarding: best or avg", 0, "Islands Model").value(); /********************************* * Déclaration des composants EO * *********************************/ std::string tspInstance = parser.getORcreateParam(std::string("benchs/ali535.xml"), "tspInstance", "filename of the instance for TSP problem", 0, "Problem").value(); dim::evaluation::Route<double> mainEval; eoEvalFuncCounter<EOT> eval(mainEval); unsigned popSize = parser.getORcreateParam(unsigned(100), "popSize", "Population Size", 'P', "Evolution Engine").value(); double targetFitness = parser.getORcreateParam(double(0), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion").value(); unsigned maxGen = parser.getORcreateParam(unsigned(10000), "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion").value(); std::string monitorPrefix = parser.getORcreateParam(std::string("result"), "monitorPrefix", "Monitor prefix filenames", '\0', "Output").value(); std::map< std::string, eoMonOp<EOT>* > mapOperators; std::vector< std::string > operatorsOrder; mapOperators["swap"] = new eoSwapMutation<EOT>; operatorsOrder.push_back("swap"); mapOperators["shift"] = new eoShiftMutation<EOT>; operatorsOrder.push_back("shift"); mapOperators["inversion"] = new eoInversionMutation<EOT>; operatorsOrder.push_back("inversion"); mapOperators["first_improve_swap"] = new eoFirstImprovementSwapMutation<EOT>(eval); operatorsOrder.push_back("first_improve_swap"); mapOperators["first_improve_shift"] = new eoFirstImprovementShiftMutation<EOT>(eval); operatorsOrder.push_back("first_improve_shift"); mapOperators["first_improve_inversion"] = new eoFirstImprovementInversionMutation<EOT>(eval); operatorsOrder.push_back("first_improve_inversion"); mapOperators["relative_best_improve_swap"] = new eoRelativeBestImprovementSwapMutation<EOT>(eval); operatorsOrder.push_back("relative_best_improve_swap"); mapOperators["relative_best_improve_shift"] = new eoRelativeBestImprovementShiftMutation<EOT>(eval); operatorsOrder.push_back("relative_best_improve_shift"); mapOperators["relative_best_improve_inversion"] = new eoRelativeBestImprovementInversionMutation<EOT>(eval); operatorsOrder.push_back("relative_best_improve_inversion"); mapOperators["best_improve_swap"] = new eoBestImprovementSwapMutation<EOT>(eval); operatorsOrder.push_back("best_improve_swap"); mapOperators["best_improve_shift"] = new eoBestImprovementShiftMutation<EOT>(eval); operatorsOrder.push_back("best_improve_shift"); mapOperators["best_improve_inversion"] = new eoBestImprovementInversionMutation<EOT>(eval); operatorsOrder.push_back("best_improve_inversion"); mapOperators["2swap"] = new eoSwapMutation<EOT>(2); operatorsOrder.push_back("2swap"); mapOperators["2opt"] = new eoTwoOptMutation<EOT>; operatorsOrder.push_back("2opt"); std::ostringstream ssOrder, ssOrder2; ssOrder << "Set an operator between " << operatorsOrder[0]; ssOrder2 << "List of operators separeted by a comma. Select operators between " << operatorsOrder[0]; for ( size_t k = 1; k < operatorsOrder.size(); ++k ) { ssOrder << "," << operatorsOrder[k]; ssOrder2 << "," << operatorsOrder[k]; } std::vector<std::string> operatorsVec(nislands, ""); for (size_t i = 0; i < nislands; ++i) { std::ostringstream ss; ss << "operator" << i; operatorsVec[i] = parser.createParam(std::string(operatorsOrder[ i % operatorsOrder.size() ]), ss.str(), ssOrder.str(), 0, "Islands Model").value(); } // O std::string operators = parser.createParam(std::string(""), "operators", ssOrder2.str(), 'O', "Islands Model").value(); if (!operators.empty()) { boost::split(operatorsVec, operators, boost::is_any_of(",")); } /************** * EO routine * **************/ make_parallel(parser); make_verbose(parser); make_help(parser); dim::initialization::TSPLibGraph::load( tspInstance ); // Instance dim::initialization::Route<double> init ; // Sol. Random Init. dim::core::Pop<EOT>& pop = dim::do_make::detail::pop(parser, state, init); // smp /********************************** * Déclaration des composants DIM * **********************************/ dim::core::ThreadsRunner< EOT > tr; std::vector< dim::core::Pop<EOT>* > islandPop(nislands); std::vector< dim::core::IslandData<EOT>* > islandData(nislands); dim::core::MigrationMatrix probabilities( nislands ); dim::core::InitMatrix initmatrix( initG, probaSame ); initmatrix( probabilities ); std::cout << probabilities; std::cout << "size: " << dim::initialization::TSPLibGraph::size() << std::endl; for (size_t i = 0; i < nislands; ++i) { std::cout << "island " << i << std::endl; islandPop[i] = new dim::core::Pop<EOT>(popSize, init); islandData[i] = new dim::core::IslandData<EOT>(nislands, i); std::cout << islandData[i]->size() << " " << islandData[i]->rank() << " " << operatorsVec[ islandData[i]->rank() ] << std::endl; islandData[i]->proba = probabilities(i); apply<EOT>(eval, *(islandPop[i])); /**************************************** * Distribution des opérateurs aux iles * ****************************************/ eoMonOp<EOT>* ptMon = mapOperators[ operatorsVec[ islandData[i]->rank() ] ]; dim::evolver::Base<EOT>* ptEvolver = new dim::evolver::Easy<EOT>( /*eval*/mainEval, *ptMon ); state_dim.storeFunctor(ptEvolver); dim::feedbacker::Base<EOT>* ptFeedbacker = new dim::feedbacker::smp::Easy<EOT>(islandPop, islandData, alphaF); state_dim.storeFunctor(ptFeedbacker); dim::vectorupdater::Reward<EOT>* ptReward = NULL; if (rewardStrategy == "best") { ptReward = new dim::vectorupdater::Best<EOT>(alphaP, betaP); } else { ptReward = new dim::vectorupdater::Average<EOT>(alphaP, betaP); } state_dim.storeFunctor(ptReward); dim::vectorupdater::Base<EOT>* ptUpdater = new dim::vectorupdater::Easy<EOT>(*ptReward); state_dim.storeFunctor(ptUpdater); dim::memorizer::Base<EOT>* ptMemorizer = new dim::memorizer::Easy<EOT>(); state_dim.storeFunctor(ptMemorizer); dim::migrator::Base<EOT>* ptMigrator = new dim::migrator::smp::Easy<EOT>(islandPop, islandData, monitorPrefix); state_dim.storeFunctor(ptMigrator); dim::continuator::Base<EOT>& continuator = dim::do_make::continuator<EOT>(parser, state, eval); dim::utils::CheckPoint<EOT>& checkpoint = dim::do_make::checkpoint<EOT>(parser, state, continuator, *(islandData[i]), 1, stepTimer); dim::algo::Base<EOT>* ptIsland = new dim::algo::smp::Easy<EOT>( *ptEvolver, *ptFeedbacker, *ptUpdater, *ptMemorizer, *ptMigrator, checkpoint, islandPop, islandData, monitorPrefix ); state_dim.storeFunctor(ptIsland); ptEvolver->size(nislands); ptFeedbacker->size(nislands); ptReward->size(nislands); ptUpdater->size(nislands); ptMemorizer->size(nislands); ptMigrator->size(nislands); ptIsland->size(nislands); ptEvolver->rank(i); ptFeedbacker->rank(i); ptReward->rank(i); ptUpdater->rank(i); ptMemorizer->rank(i); ptMigrator->rank(i); ptIsland->rank(i); tr.add(*ptIsland); } dim::core::IslandData<EOT> data(nislands); tr(pop, data); for (size_t i = 0; i < nislands; ++i) { delete islandPop[i]; delete islandData[i]; } for ( std::map< std::string, eoMonOp<EOT>* >::iterator it = mapOperators.begin(); it != mapOperators.end(); ++it ) { delete it->second; } return 0; } <commit_msg>* ../../../application/TSP/tsp.cpp: fixed a missing param value for result location<commit_after>// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: * Caner Candan <caner.candan@univ-angers.fr> */ #include <boost/algorithm/string.hpp> #include <boost/mpi.hpp> #include <eo> #include <eoSwapMutation.h> #include <eoShiftMutation.h> #include <eoInversionMutation.h> #include <eoTwoOptMutation.h> #include <dim/dim> #include <dim/algo/Easy.h> #include <dim/evolver/Easy.h> #include <dim/feedbacker/Easy.h> #include <dim/migrator/Easy.h> #include <dim/vectorupdater/Easy.h> #include <dim/core/State.h> #if __cplusplus > 199711L namespace std_or_boost = std; #include <mutex> #include <condition_variable> #else #include <boost/thread/thread.hpp> #include <boost/chrono/chrono_io.hpp> #include <boost/thread/mutex.hpp> namespace std_or_boost = boost; #endif typedef dim::representation::Route<double> EOT; int main (int argc, char *argv[]) { /************************* * Initialisation de MPI * *************************/ // boost::mpi::environment env(argc, argv, MPI_THREAD_MULTIPLE, true); // boost::mpi::communicator world; /**************************** * Il faut au moins 4 nœuds * ****************************/ // const size_t ALL = world.size(); // const size_t RANK = world.rank(); /************************ * Initialisation de EO * ************************/ eoParser parser(argc, argv); eoState state; // keeps all things allocated dim::core::State state_dim; // keeps all things allocated /***************************** * Definition des paramètres * *****************************/ // N unsigned nislands = parser.createParam(unsigned(4), "nislands", "Number of islands (see --smp)", 'N', "Islands Model").value(); // a double alphaP = parser.createParam(double(0.2), "alpha", "Alpha Probability", 'a', "Islands Model").value(); // A double alphaF = parser.createParam(double(0.01), "alphaF", "Alpha Fitness", 'A', "Islands Model").value(); // b double betaP = parser.createParam(double(0.01), "beta", "Beta Probability", 'b', "Islands Model").value(); // d double probaSame = parser.createParam(double(100./nislands), "probaSame", "Probability for an individual to stay in the same island", 'd', "Islands Model").value(); // I bool initG = parser.createParam(bool(true), "initG", "initG", 'I', "Islands Model").value(); unsigned nmigrations = parser.createParam(unsigned(1), "nmigrations", "Number of migrations to do at each generation (0=all individuals are migrated)", 0, "Islands Model").value(); unsigned stepTimer = parser.createParam(unsigned(0), "stepTimer", "stepTimer", 0, "Islands Model").value(); bool deltaUpdate = parser.createParam(bool(true), "deltaUpdate", "deltaUpdate", 0, "Islands Model").value(); bool deltaFeedback = parser.createParam(bool(true), "deltaFeedback", "deltaFeedback", 0, "Islands Model").value(); double sensitivity = 1 / parser.createParam(double(1.), "sensitivity", "sensitivity of delta{t} (1/sensitivity)", 0, "Islands Model").value(); std::string rewardStrategy = parser.createParam(std::string("best"), "rewardStrategy", "Strategy of rewarding: best or avg", 0, "Islands Model").value(); /********************************* * Déclaration des composants EO * *********************************/ std::string tspInstance = parser.getORcreateParam(std::string("benchs/ali535.xml"), "tspInstance", "filename of the instance for TSP problem", 0, "Problem").value(); dim::evaluation::Route<double> mainEval; eoEvalFuncCounter<EOT> eval(mainEval); unsigned popSize = parser.getORcreateParam(unsigned(100), "popSize", "Population Size", 'P', "Evolution Engine").value(); double targetFitness = parser.getORcreateParam(double(0), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion").value(); unsigned maxGen = parser.getORcreateParam(unsigned(10000), "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion").value(); std::string monitorPrefix = parser.getORcreateParam(std::string("result"), "monitorPrefix", "Monitor prefix filenames", '\0', "Output").value(); std::map< std::string, eoMonOp<EOT>* > mapOperators; std::vector< std::string > operatorsOrder; mapOperators["swap"] = new eoSwapMutation<EOT>; operatorsOrder.push_back("swap"); mapOperators["shift"] = new eoShiftMutation<EOT>; operatorsOrder.push_back("shift"); mapOperators["inversion"] = new eoInversionMutation<EOT>; operatorsOrder.push_back("inversion"); mapOperators["first_improve_swap"] = new eoFirstImprovementSwapMutation<EOT>(eval); operatorsOrder.push_back("first_improve_swap"); mapOperators["first_improve_shift"] = new eoFirstImprovementShiftMutation<EOT>(eval); operatorsOrder.push_back("first_improve_shift"); mapOperators["first_improve_inversion"] = new eoFirstImprovementInversionMutation<EOT>(eval); operatorsOrder.push_back("first_improve_inversion"); mapOperators["relative_best_improve_swap"] = new eoRelativeBestImprovementSwapMutation<EOT>(eval); operatorsOrder.push_back("relative_best_improve_swap"); mapOperators["relative_best_improve_shift"] = new eoRelativeBestImprovementShiftMutation<EOT>(eval); operatorsOrder.push_back("relative_best_improve_shift"); mapOperators["relative_best_improve_inversion"] = new eoRelativeBestImprovementInversionMutation<EOT>(eval); operatorsOrder.push_back("relative_best_improve_inversion"); mapOperators["best_improve_swap"] = new eoBestImprovementSwapMutation<EOT>(eval); operatorsOrder.push_back("best_improve_swap"); mapOperators["best_improve_shift"] = new eoBestImprovementShiftMutation<EOT>(eval); operatorsOrder.push_back("best_improve_shift"); mapOperators["best_improve_inversion"] = new eoBestImprovementInversionMutation<EOT>(eval); operatorsOrder.push_back("best_improve_inversion"); mapOperators["2swap"] = new eoSwapMutation<EOT>(2); operatorsOrder.push_back("2swap"); mapOperators["2opt"] = new eoTwoOptMutation<EOT>; operatorsOrder.push_back("2opt"); std::ostringstream ssOrder, ssOrder2; ssOrder << "Set an operator between " << operatorsOrder[0]; ssOrder2 << "List of operators separeted by a comma. Select operators between " << operatorsOrder[0]; for ( size_t k = 1; k < operatorsOrder.size(); ++k ) { ssOrder << "," << operatorsOrder[k]; ssOrder2 << "," << operatorsOrder[k]; } std::vector<std::string> operatorsVec(nislands, ""); for (size_t i = 0; i < nislands; ++i) { std::ostringstream ss; ss << "operator" << i; operatorsVec[i] = parser.createParam(std::string(operatorsOrder[ i % operatorsOrder.size() ]), ss.str(), ssOrder.str(), 0, "Islands Model").value(); } // O std::string operators = parser.createParam(std::string(""), "operators", ssOrder2.str(), 'O', "Islands Model").value(); if (!operators.empty()) { boost::split(operatorsVec, operators, boost::is_any_of(",")); } /************** * EO routine * **************/ make_parallel(parser); make_verbose(parser); make_help(parser); dim::initialization::TSPLibGraph::load( tspInstance ); // Instance dim::initialization::Route<double> init ; // Sol. Random Init. dim::core::Pop<EOT>& pop = dim::do_make::detail::pop(parser, state, init); // smp /********************************** * Déclaration des composants DIM * **********************************/ dim::core::ThreadsRunner< EOT > tr; std::vector< dim::core::Pop<EOT>* > islandPop(nislands); std::vector< dim::core::IslandData<EOT>* > islandData(nislands); dim::core::MigrationMatrix probabilities( nislands ); dim::core::InitMatrix initmatrix( initG, probaSame ); initmatrix( probabilities ); std::cout << probabilities; std::cout << "size: " << dim::initialization::TSPLibGraph::size() << std::endl; for (size_t i = 0; i < nislands; ++i) { std::cout << "island " << i << std::endl; islandPop[i] = new dim::core::Pop<EOT>(popSize, init); islandData[i] = new dim::core::IslandData<EOT>(nislands, i); std::cout << islandData[i]->size() << " " << islandData[i]->rank() << " " << operatorsVec[ islandData[i]->rank() ] << std::endl; islandData[i]->proba = probabilities(i); apply<EOT>(eval, *(islandPop[i])); /**************************************** * Distribution des opérateurs aux iles * ****************************************/ eoMonOp<EOT>* ptMon = mapOperators[ operatorsVec[ islandData[i]->rank() ] ]; dim::evolver::Base<EOT>* ptEvolver = new dim::evolver::Easy<EOT>( /*eval*/mainEval, *ptMon ); state_dim.storeFunctor(ptEvolver); dim::feedbacker::Base<EOT>* ptFeedbacker = new dim::feedbacker::smp::Easy<EOT>(islandPop, islandData, alphaF, monitorPrefix); state_dim.storeFunctor(ptFeedbacker); dim::vectorupdater::Reward<EOT>* ptReward = NULL; if (rewardStrategy == "best") { ptReward = new dim::vectorupdater::Best<EOT>(alphaP, betaP); } else { ptReward = new dim::vectorupdater::Average<EOT>(alphaP, betaP); } state_dim.storeFunctor(ptReward); dim::vectorupdater::Base<EOT>* ptUpdater = new dim::vectorupdater::Easy<EOT>(*ptReward); state_dim.storeFunctor(ptUpdater); dim::memorizer::Base<EOT>* ptMemorizer = new dim::memorizer::Easy<EOT>(); state_dim.storeFunctor(ptMemorizer); dim::migrator::Base<EOT>* ptMigrator = new dim::migrator::smp::Easy<EOT>(islandPop, islandData, monitorPrefix); state_dim.storeFunctor(ptMigrator); dim::continuator::Base<EOT>& continuator = dim::do_make::continuator<EOT>(parser, state, eval); dim::utils::CheckPoint<EOT>& checkpoint = dim::do_make::checkpoint<EOT>(parser, state, continuator, *(islandData[i]), 1, stepTimer); dim::algo::Base<EOT>* ptIsland = new dim::algo::smp::Easy<EOT>( *ptEvolver, *ptFeedbacker, *ptUpdater, *ptMemorizer, *ptMigrator, checkpoint, islandPop, islandData, monitorPrefix ); state_dim.storeFunctor(ptIsland); ptEvolver->size(nislands); ptFeedbacker->size(nislands); ptReward->size(nislands); ptUpdater->size(nislands); ptMemorizer->size(nislands); ptMigrator->size(nislands); ptIsland->size(nislands); ptEvolver->rank(i); ptFeedbacker->rank(i); ptReward->rank(i); ptUpdater->rank(i); ptMemorizer->rank(i); ptMigrator->rank(i); ptIsland->rank(i); tr.add(*ptIsland); } dim::core::IslandData<EOT> data(nislands); tr(pop, data); for (size_t i = 0; i < nislands; ++i) { delete islandPop[i]; delete islandData[i]; } for ( std::map< std::string, eoMonOp<EOT>* >::iterator it = mapOperators.begin(); it != mapOperators.end(); ++it ) { delete it->second; } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: appinit.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: mav $ $Date: 2002-09-10 11:01:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "appinit.hxx" #include "cmdlineargs.hxx" #include "officeacceptthread.hxx" #ifndef _COM_SUN_STAR_REGISTRY_XSIMPLEREGISTRY_HPP_ #include <com/sun/star/registry/XSimpleRegistry.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _CPPUHELPER_SERVICEFACTORY_HXX_ #include <cppuhelper/servicefactory.hxx> #endif #ifndef _CPPUHELPER_BOOTSTRAP_HXX_ #include <cppuhelper/bootstrap.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _VOS_PROCESS_HXX_ #include <vos/process.hxx> #endif #ifndef _RTL_URI_HXX_ #include <rtl/uri.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _COMPHELPER_REGPATHHELPER_HXX_ #include <comphelper/regpathhelper.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _TOOLS_TEMPFILE_HXX #include <tools/tempfile.hxx> #endif #ifndef _UCBHELPER_CONFIGURATIONKEYS_HXX_ #include <ucbhelper/configurationkeys.hxx> #endif #include <cppuhelper/bootstrap.hxx> #include <tools/urlobj.hxx> #include <rtl/logfile.hxx> #include <comphelper/processfactory.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/ucbhelper.hxx> #include <unotools/tempfile.hxx> #include <ucbhelper/contentbroker.hxx> #include <vcl/svapp.hxx> #ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX #include <svtools/startoptions.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef INCLUDED_SVTOOLS_INTERNALOPTIONS_HXX #include <svtools/internaloptions.hxx> #endif #define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII)) #define DEFINE_CONST_OUSTRING(CONSTASCII) OUString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII)) #define DESKTOP_TEMPDIRNAME "soffice.tmp" using namespace rtl; using namespace vos; using namespace desktop; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::registry; extern desktop::CommandLineArgs* GetCommandLineArgs(); extern desktop::OOfficeAcceptorThread* pOfficeAcceptThread; static String aCurrentTempURL; // ----------------------------------------------------------------------------- static bool configureUcb(bool bServer, rtl::OUString const & rPortalConnect) { RTL_LOGFILE_CONTEXT( aLog, "desktop (sb93797) ::configureUcb" ); Reference< XMultiServiceFactory > xServiceFactory( comphelper::getProcessServiceFactory() ); if (!xServiceFactory.is()) { DBG_ERROR("configureUcb(): No XMultiServiceFactory"); return false; } rtl::OUString aPipe; vos::OSecurity().getUserIdent(aPipe); rtl::OUStringBuffer aPortal; if (rPortalConnect.getLength() != 0) { aPortal.append(sal_Unicode(',')); aPortal.append(rPortalConnect); } Sequence< Any > aArgs(6); aArgs[0] <<= rtl::OUString::createFromAscii(bServer ? UCB_CONFIGURATION_KEY1_SERVER : UCB_CONFIGURATION_KEY1_LOCAL); aArgs[1] <<= rtl::OUString::createFromAscii(UCB_CONFIGURATION_KEY2_OFFICE); aArgs[2] <<= rtl::OUString::createFromAscii("PIPE"); aArgs[3] <<= aPipe; aArgs[4] <<= rtl::OUString::createFromAscii("PORTAL"); aArgs[5] <<= aPortal.makeStringAndClear(); return ::ucb::ContentBroker::initialize( xServiceFactory, aArgs ) != false; } Reference< XMultiServiceFactory > createApplicationServiceManager() { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::createApplicationServiceManager" ); try { Reference<XComponentContext> xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext(); Reference<XMultiServiceFactory> xMS(xComponentContext->getServiceManager(), UNO_QUERY); return xMS; } catch( ::com::sun::star::uno::Exception& ) { } return Reference< XMultiServiceFactory >(); } void destroyApplicationServiceManager( Reference< XMultiServiceFactory >& xSMgr ) { Reference< XPropertySet > xProps( xSMgr, UNO_QUERY ); if ( xProps.is() ) { try { Reference< XComponent > xComp; if (xProps->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ))) >>= xComp ) { xComp->dispose(); } } catch ( UnknownPropertyException& ) { } } } void registerServices( Reference< XMultiServiceFactory >& xSMgr ) { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::registerServices" ); // read command line parameters ::rtl::OUString conDcp; ::rtl::OUString aClientDisplay; ::rtl::OUString aUserDir; ::rtl::OUString aTmpString; sal_Bool bHeadlessMode = sal_False; // interpret command line arguments CommandLineArgs* pCmdLine = GetCommandLineArgs(); // read accept string from configuration if ( !Application::IsRemoteServer() ) conDcp = SvtStartOptions().GetConnectionURL(); if ( pCmdLine->GetAcceptString( aTmpString )) conDcp = aTmpString; pCmdLine->GetUserDir( aUserDir ); if ( Application::IsRemoteServer() ) { bHeadlessMode = pCmdLine->IsHeadless(); pCmdLine->GetClientDisplay( aClientDisplay ); } if ( bHeadlessMode ) Application::EnableHeadlessMode(); if ( conDcp.getLength() > 0 ) { // accept incoming connections (scripting and one rvp) RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::OOfficeAcceptorThread::OOfficeAcceptorThread" ); pOfficeAcceptThread = new OOfficeAcceptorThread( xSMgr, conDcp, bHeadlessMode, aClientDisplay, aUserDir ); pOfficeAcceptThread->create(); } // improves parallel processing on Sun ONE Webtop // servicemanager up -> copy user installation if ( Application::IsRemoteServer() ) { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) createInstance com.sun.star.portal.InstallUser" ); Any aAny; Reference <XInterface> xRef = xSMgr->createInstanceWithArguments( OUString::createFromAscii( "com.sun.star.portal.InstallUser" ), Sequence<Any>( &aAny, 1 ) ); } ::rtl::OUString aPortalConnect; bool bServer = (bool) pCmdLine->IsServer(); pCmdLine->GetPortalConnectString( aPortalConnect ); if ( !configureUcb( bServer, aPortalConnect ) ) { DBG_ERROR( "Can't configure UCB" ); exit(-1); } // UCB_Helper::Initialize(); !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! createTemporaryDirectory(); } void createTemporaryDirectory() { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::createTemporaryDirectory" ); // remove possible old directory and base directory SvtPathOptions aOpt; SvtInternalOptions aInternalOpt; // set temp base directory ::rtl::OUString aTempBaseURL( aOpt.GetTempPath() ); sal_Int32 nLength = aTempBaseURL.getLength(); if ( aTempBaseURL.matchAsciiL( "/", 1, nLength-1 ) ) aTempBaseURL = aTempBaseURL.copy( 0, nLength - 1 ); String aOldTempURL = aInternalOpt.GetCurrentTempURL(); if ( aOldTempURL.Len() > 0 ) { // remove old temporary directory ::utl::UCBContentHelper::Kill( aOldTempURL ); } String aRet; ::rtl::OUString aTempPath( aTempBaseURL ); // create new current temporary directory ::utl::LocalFileHelper::ConvertURLToPhysicalName( aTempBaseURL, aRet ); ::osl::FileBase::getFileURLFromSystemPath( aRet, aTempPath ); aTempPath = ::utl::TempFile::SetTempNameBaseDirectory( aTempPath ); if ( !aTempPath.getLength() ) { ::osl::File::getTempDirURL( aTempBaseURL ); sal_Int32 nLength = aTempBaseURL.getLength(); if ( aTempBaseURL.matchAsciiL( "/", 1, nLength-1 ) ) aTempBaseURL = aTempBaseURL.copy( 0, nLength - 1 ); aTempPath = aTempBaseURL; ::osl::FileBase::getFileURLFromSystemPath( aRet, aTempPath ); aTempPath = ::utl::TempFile::SetTempNameBaseDirectory( aTempPath ); } // set new current temporary directory ::utl::LocalFileHelper::ConvertPhysicalNameToURL( aTempPath, aRet ); aInternalOpt.SetCurrentTempURL( aRet ); aCurrentTempURL = aRet; } void removeTemporaryDirectory() { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::removeTemporaryDirectory" ); // remove current temporary directory if ( aCurrentTempURL.Len() > 0 ) { if ( ::utl::UCBContentHelper::Kill( aCurrentTempURL ) ) SvtInternalOptions().SetCurrentTempURL( String() ); } } <commit_msg>#103426# Ignore -server cmdline parameter if not correcr env<commit_after>/************************************************************************* * * $RCSfile: appinit.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: cd $ $Date: 2002-09-23 11:05:07 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "appinit.hxx" #include "cmdlineargs.hxx" #include "officeacceptthread.hxx" #ifndef _COM_SUN_STAR_REGISTRY_XSIMPLEREGISTRY_HPP_ #include <com/sun/star/registry/XSimpleRegistry.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTENTENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XContentEnumerationAccess.hpp> #endif #ifndef _CPPUHELPER_SERVICEFACTORY_HXX_ #include <cppuhelper/servicefactory.hxx> #endif #ifndef _CPPUHELPER_BOOTSTRAP_HXX_ #include <cppuhelper/bootstrap.hxx> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _VOS_PROCESS_HXX_ #include <vos/process.hxx> #endif #ifndef _RTL_URI_HXX_ #include <rtl/uri.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _COMPHELPER_REGPATHHELPER_HXX_ #include <comphelper/regpathhelper.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _TOOLS_TEMPFILE_HXX #include <tools/tempfile.hxx> #endif #ifndef _UCBHELPER_CONFIGURATIONKEYS_HXX_ #include <ucbhelper/configurationkeys.hxx> #endif #include <cppuhelper/bootstrap.hxx> #include <tools/urlobj.hxx> #include <rtl/logfile.hxx> #include <comphelper/processfactory.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/ucbhelper.hxx> #include <unotools/tempfile.hxx> #include <ucbhelper/contentbroker.hxx> #include <vcl/svapp.hxx> #ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX #include <svtools/startoptions.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef INCLUDED_SVTOOLS_INTERNALOPTIONS_HXX #include <svtools/internaloptions.hxx> #endif #define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII)) #define DEFINE_CONST_OUSTRING(CONSTASCII) OUString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII)) #define DESKTOP_TEMPDIRNAME "soffice.tmp" using namespace rtl; using namespace vos; using namespace desktop; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::registry; extern desktop::CommandLineArgs* GetCommandLineArgs(); extern desktop::OOfficeAcceptorThread* pOfficeAcceptThread; static String aCurrentTempURL; // ----------------------------------------------------------------------------- static bool configureUcb(bool bServer, rtl::OUString const & rPortalConnect) { RTL_LOGFILE_CONTEXT( aLog, "desktop (sb93797) ::configureUcb" ); Reference< XMultiServiceFactory > xServiceFactory( comphelper::getProcessServiceFactory() ); if (!xServiceFactory.is()) { DBG_ERROR("configureUcb(): No XMultiServiceFactory"); return false; } rtl::OUString aPipe; vos::OSecurity().getUserIdent(aPipe); rtl::OUStringBuffer aPortal; if (rPortalConnect.getLength() != 0) { aPortal.append(sal_Unicode(',')); aPortal.append(rPortalConnect); } Sequence< Any > aArgs(6); aArgs[0] <<= rtl::OUString::createFromAscii(bServer ? UCB_CONFIGURATION_KEY1_SERVER : UCB_CONFIGURATION_KEY1_LOCAL); aArgs[1] <<= rtl::OUString::createFromAscii(UCB_CONFIGURATION_KEY2_OFFICE); aArgs[2] <<= rtl::OUString::createFromAscii("PIPE"); aArgs[3] <<= aPipe; aArgs[4] <<= rtl::OUString::createFromAscii("PORTAL"); aArgs[5] <<= aPortal.makeStringAndClear(); return ::ucb::ContentBroker::initialize( xServiceFactory, aArgs ) != false; } Reference< XMultiServiceFactory > createApplicationServiceManager() { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::createApplicationServiceManager" ); try { Reference<XComponentContext> xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext(); Reference<XMultiServiceFactory> xMS(xComponentContext->getServiceManager(), UNO_QUERY); return xMS; } catch( ::com::sun::star::uno::Exception& ) { } return Reference< XMultiServiceFactory >(); } void destroyApplicationServiceManager( Reference< XMultiServiceFactory >& xSMgr ) { Reference< XPropertySet > xProps( xSMgr, UNO_QUERY ); if ( xProps.is() ) { try { Reference< XComponent > xComp; if (xProps->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ))) >>= xComp ) { xComp->dispose(); } } catch ( UnknownPropertyException& ) { } } } void registerServices( Reference< XMultiServiceFactory >& xSMgr ) { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::registerServices" ); // read command line parameters ::rtl::OUString conDcp; ::rtl::OUString aClientDisplay; ::rtl::OUString aUserDir; ::rtl::OUString aTmpString; sal_Bool bHeadlessMode = sal_False; // interpret command line arguments CommandLineArgs* pCmdLine = GetCommandLineArgs(); // read accept string from configuration if ( !Application::IsRemoteServer() ) conDcp = SvtStartOptions().GetConnectionURL(); if ( pCmdLine->GetAcceptString( aTmpString )) conDcp = aTmpString; pCmdLine->GetUserDir( aUserDir ); if ( Application::IsRemoteServer() ) { bHeadlessMode = pCmdLine->IsHeadless(); pCmdLine->GetClientDisplay( aClientDisplay ); } if ( bHeadlessMode ) Application::EnableHeadlessMode(); if ( conDcp.getLength() > 0 ) { // accept incoming connections (scripting and one rvp) RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::OOfficeAcceptorThread::OOfficeAcceptorThread" ); pOfficeAcceptThread = new OOfficeAcceptorThread( xSMgr, conDcp, bHeadlessMode, aClientDisplay, aUserDir ); pOfficeAcceptThread->create(); } // improves parallel processing on Sun ONE Webtop // servicemanager up -> copy user installation if ( Application::IsRemoteServer() ) { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) createInstance com.sun.star.portal.InstallUser" ); Any aAny; Reference <XInterface> xRef = xSMgr->createInstanceWithArguments( OUString::createFromAscii( "com.sun.star.portal.InstallUser" ), Sequence<Any>( &aAny, 1 ) ); } else if ( pCmdLine->IsServer() ) { // Check some mandatory environment states if "-server" is possible. Otherwise ignore // this parameter. Reference< com::sun::star::container::XContentEnumerationAccess > rContent( xSMgr , UNO_QUERY ); if( rContent.is() ) { OUString sPortalService = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.portal.InstallUser" ) ); Reference < com::sun::star::container::XEnumeration > rEnum = rContent->createContentEnumeration( sPortalService ); if ( !rEnum.is() ) { // Reset server parameter so it is ignored in the furthermore startup process pCmdLine->SetBoolParam( CommandLineArgs::CMD_BOOLPARAM_SERVER, sal_False ); } } } ::rtl::OUString aPortalConnect; bool bServer = (bool) pCmdLine->IsServer(); pCmdLine->GetPortalConnectString( aPortalConnect ); if ( !configureUcb( bServer, aPortalConnect ) ) { DBG_ERROR( "Can't configure UCB" ); exit(-1); } // UCB_Helper::Initialize(); !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! createTemporaryDirectory(); } void createTemporaryDirectory() { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::createTemporaryDirectory" ); // remove possible old directory and base directory SvtPathOptions aOpt; SvtInternalOptions aInternalOpt; // set temp base directory ::rtl::OUString aTempBaseURL( aOpt.GetTempPath() ); sal_Int32 nLength = aTempBaseURL.getLength(); if ( aTempBaseURL.matchAsciiL( "/", 1, nLength-1 ) ) aTempBaseURL = aTempBaseURL.copy( 0, nLength - 1 ); String aOldTempURL = aInternalOpt.GetCurrentTempURL(); if ( aOldTempURL.Len() > 0 ) { // remove old temporary directory ::utl::UCBContentHelper::Kill( aOldTempURL ); } String aRet; ::rtl::OUString aTempPath( aTempBaseURL ); // create new current temporary directory ::utl::LocalFileHelper::ConvertURLToPhysicalName( aTempBaseURL, aRet ); ::osl::FileBase::getFileURLFromSystemPath( aRet, aTempPath ); aTempPath = ::utl::TempFile::SetTempNameBaseDirectory( aTempPath ); if ( !aTempPath.getLength() ) { ::osl::File::getTempDirURL( aTempBaseURL ); sal_Int32 nLength = aTempBaseURL.getLength(); if ( aTempBaseURL.matchAsciiL( "/", 1, nLength-1 ) ) aTempBaseURL = aTempBaseURL.copy( 0, nLength - 1 ); aTempPath = aTempBaseURL; ::osl::FileBase::getFileURLFromSystemPath( aRet, aTempPath ); aTempPath = ::utl::TempFile::SetTempNameBaseDirectory( aTempPath ); } // set new current temporary directory ::utl::LocalFileHelper::ConvertPhysicalNameToURL( aTempPath, aRet ); aInternalOpt.SetCurrentTempURL( aRet ); aCurrentTempURL = aRet; } void removeTemporaryDirectory() { RTL_LOGFILE_CONTEXT( aLog, "desktop (cd100003) ::removeTemporaryDirectory" ); // remove current temporary directory if ( aCurrentTempURL.Len() > 0 ) { if ( ::utl::UCBContentHelper::Kill( aCurrentTempURL ) ) SvtInternalOptions().SetCurrentTempURL( String() ); } } <|endoftext|>
<commit_before>// @(#)root/reflex:$Id$ // Author: Stefan Roiser 2006 // Copyright CERN, CH-1211 Geneva 23, 2004-2010, All rights reserved. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. #ifndef REFLEX_BUILD # define REFLEX_BUILD #endif #include "NameLookup.h" #include "Reflex/Base.h" #include "Reflex/Scope.h" #include "Reflex/Type.h" #include "Reflex/Tools.h" #include "Reflex/internal/OwnedMember.h" #include <sstream> #include <string.h> //______________________________________________________________________________ Reflex::NameLookup::NameLookup(const std::string& name, const Scope& current): fLookupName(name), fPosNamePart(0), fPosNamePartLen(std::string::npos), fCurrentScope(current), fPartialSuccess(false) { // Initialize a NameLookup object used internally to keep track of lookup // states. } //______________________________________________________________________________ Reflex::Type Reflex::NameLookup::LookupType(const std::string& nam, const Scope& current) { // Lookup up a (possibly scoped) type name appearing in the scope context // current. This is the public interface for type lookup. NameLookup lookup(nam, current); return lookup.Lookup<Type>(); } //______________________________________________________________________________ Reflex::Scope Reflex::NameLookup::LookupScope(const std::string& nam, const Scope& current) { // Lookup up a (possibly scoped) scope name appearing in the scope context // current. This is the public interface for scope lookup. NameLookup lookup(nam, current); return lookup.Lookup<Scope>(); } /* //______________________________________________________________________________ Reflex::Member LookupMember(const std::string& nam, const Scope& current ) { // Lookup up a (possibly scoped) member name appearing in the scope context // current. This is the public interface for member lookup. NameLookup lookup(nam, current); // this will not work, member lookup is too different from type lookup... return lookup.Lookup<Member>(); } */ //______________________________________________________________________________ template <class T> T Reflex::NameLookup::Lookup(bool isTemplateExpanded /* = false */) { // Lookup a type using fLookupName, fCurrentScope. Scope startScope = fCurrentScope; T result; fPartialSuccess = false; fPosNamePart = 0; fPosNamePartLen = std::string::npos; FindNextScopePos(); if (fPosNamePart == 2) { fLookedAtUsingDir.clear(); // ::A... fCurrentScope = Scope::GlobalScope(); result = LookupInScope<T>(); } else { // A... result = LookupInUnknownScope<T>(); } if (!isTemplateExpanded && !result && fLookupName.find('<') != std::string::npos) { // We need to replace the template argument both of this type // and any of it enclosing type: // myspace::mytop<A,B>::mytype<C> std::ostringstream tmp; for (size_t i = 0, level = 0, sofar = 0; i < fLookupName.size(); ++i) { if (level == 0) { tmp << fLookupName.substr(sofar, i + 1 - sofar); sofar = i + 1; } switch (fLookupName[i]) { case '<': ++level; break; case '>': --level; // intentional fall through to the ',' case case ',': if (level == (1 - (unsigned int) (fLookupName[i] == '>'))) { std::string arg(fLookupName.substr(sofar, i - sofar)); size_t p = arg.size(); while (p > 0 && (arg[p - 1] == '*' || arg[p - 1] == '&' || arg[p - 1] == ' ')) --p; std::string end(arg.substr(p)); arg.erase(p); const char* start = arg.c_str(); while (strncmp(start, "const ", 6) == 0) start += 6; tmp << arg.substr(0, start - arg.c_str()); while (strncmp(start, "std::", 5) == 0) start += 5; arg.erase(0, start - arg.c_str()); Reflex::Type type(LookupType(arg, startScope)); if (type) { if (type.Name() != "Double32_t" && type.Name() != "Float16_t") { // Use the real type rather than the typedef unless // this is Double32_t or Float16_t type = type.FinalType(); } tmp << type.Name(Reflex::SCOPED | Reflex::QUALIFIED); } else { tmp << arg; } tmp << end; tmp << fLookupName[i]; sofar = i + 1; } break; } // switch } NameLookup next(tmp.str(), startScope); return next.Lookup<T>(true); } return result; } // Lookup //______________________________________________________________________________ template <class T> T Reflex::NameLookup::LookupInScope() { // Lookup a type in fCurrentScope. // Checks sub-types, sub-scopes, using directives, and base classes for // the name given by fLookupName, fPosNamePart, and fPosNamePartLen. // If the name part is found, and another name part follows in fPosNamePart, // LookupTypeInScope requests the scope found to lookup the next name // part. fPartialMatch reflexts that the left part of the name was matched; // even if the trailing part of fLookupName cannot be found, the lookup // cannot continue on declaring scopes and has to fail. // A list of lookups performed in namespaces pulled in via using directives is // kept in fLookedAtUsingDir, to prevent infinite loops due to // namespace A{using namespace B;} namespace B{using namespace A;} // loops. // The lookup does not take the declaration order into account; the result of // parts of the lookup algorithm which depend on the order will be unpredictable. if (!fCurrentScope) { return Dummy::Get<T>(); } // prevent inf loop from // ns A { using ns B; } ns B {using ns A;} if (fLookedAtUsingDir.find(fCurrentScope) != fLookedAtUsingDir.end()) { return Dummy::Get<T>(); } // global scope can use hashed containers: if (fCurrentScope == Scope::GlobalScope()) { Type freeType(Type::ByName(fLookupName.c_str() + fPosNamePart)); if (freeType.Id()) { //fprintf(stderr, "Reflex::NameLookup::LookupInScope<T>: lookup up '%s', partial success with subscope '%s' ...\n", fLookupName.c_str(), name.c_str()); fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return freeType; } if (freeType.IsTypedef()) { fCurrentScope = freeType.FinalType(); } else { fCurrentScope = freeType; } return LookupInScope<T>(); } Scope freeScope(Scope::ByName(fLookupName.c_str() + fPosNamePart)); // only take namespaces into account - classes were checked as part of SubType if (freeScope.Id() && freeScope.IsNamespace()) { fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return (T) (freeScope); } fCurrentScope = freeScope; return LookupInScope<T>(); } } // end of: if global scope else { // if not global scope size_t len = fCurrentScope.SubTypeSize(); size_t i = 0; for (Type_Iterator it = fCurrentScope.SubType_Begin(); i < len; ++it, ++i) { const Type& type = *it; const TypeBase* base = type.ToTypeBase(); if (base) { size_t pos; const std::string& name(base->SimpleName(pos)); //fprintf(stderr, "Reflex::NameLookup::LookupInScope<T>: looking up '%s', considering subscope '%s' ...\n", fLookupName.c_str(), name.c_str()); if ( (fLookupName[fPosNamePart] == name[pos]) && !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length()) ) { //fprintf(stderr, "Reflex::NameLookup::LookupInScope<T>: lookup up '%s', partial success with subscope '%s' ...\n", fLookupName.c_str(), name.c_str()); fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return type; } if (it->IsTypedef()) { fCurrentScope = it->FinalType(); } else { fCurrentScope = type; } return LookupInScope<T>(); } } } Scope_Iterator subscope_end(fCurrentScope.SubScope_End()); for (Scope_Iterator in = fCurrentScope.SubScope_Begin(); in != subscope_end; ++in) { // only take namespaces into account - classes were checked as part of SubType if (in->IsNamespace()) { const Scope& scope = *in; const ScopeBase* base = scope.ToScopeBase(); if (base) { size_t pos; const std::string& name(base->SimpleName(pos)); if ( (fLookupName[fPosNamePart] == name[pos]) && !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length()) ) { fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return (T) (*in); } fCurrentScope = (Scope) (*in); return LookupInScope<T>(); } } } } } // end of: if not global scope if (fCurrentScope.UsingDirectiveSize()) { fLookedAtUsingDir.insert(fCurrentScope); Scope storeCurrentScope = fCurrentScope; Scope_Iterator usingscope_end(storeCurrentScope.UsingDirective_End()); for (Scope_Iterator si = storeCurrentScope.UsingDirective_Begin(); si != usingscope_end; ++si) { fCurrentScope = *si; T t = LookupInScope<T>(); if (fPartialSuccess) { return t; } } fCurrentScope = storeCurrentScope; } if (!fPosNamePart) { // only for "BaseClass...", not for "A::BaseClass..." Base_Iterator base_end(fCurrentScope.Base_End()); for (Base_Iterator bi = fCurrentScope.Base_Begin(); bi != base_end; ++bi) { if (!fLookupName.compare(fPosNamePart, fPosNamePartLen, bi->Name())) { fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return bi->ToType(); } fCurrentScope = bi->ToType().FinalType(); return LookupInScope<T>(); } } } if (fCurrentScope.BaseSize()) { Scope storeCurrentScope = fCurrentScope; Base_Iterator base_end(storeCurrentScope.Base_End()); for (Base_Iterator bi = storeCurrentScope.Base_Begin(); bi != base_end; ++bi) { fCurrentScope = bi->ToScope(); T t = LookupInScope<T>(); if (fPartialSuccess) { return t; } } fCurrentScope = storeCurrentScope; } return Dummy::Get<T>(); } // LookupInScope //______________________________________________________________________________ template <class T> T Reflex::NameLookup::LookupInUnknownScope() { // Lookup a type in fCurrentScope and its declaring scopes. for (fPartialSuccess = false; !fPartialSuccess && fCurrentScope; fCurrentScope = fCurrentScope.DeclaringScope()) { fLookedAtUsingDir.clear(); T t = LookupInScope<T>(); if (fPartialSuccess) { return t; } if (fCurrentScope.IsTopScope()) { break; } } return Dummy::Get<T>(); } //______________________________________________________________________________ Reflex::Member Reflex::NameLookup::LookupMember(const std::string& nam, const Scope& current) { // Lookup a member. if (Tools::GetBasePosition(nam)) { return LookupMemberQualified(nam); } return LookupMemberUnqualified(nam, current); } //______________________________________________________________________________ Reflex::Member Reflex::NameLookup::LookupMemberQualified(const std::string& nam) { // Lookup of a qualified member. Scope bscope = Scope::ByName(Tools::GetScopeName(nam)); if (bscope) { return LookupMemberUnqualified(Tools::GetBaseName(nam), bscope); } return Dummy::Member(); } //______________________________________________________________________________ Reflex::Member Reflex::NameLookup::LookupMemberUnqualified(const std::string& nam, const Scope& current) { // Lookup of an unqualified member. { Member m = current.MemberByName(nam); if (m) { return m; } } for (Scope_Iterator si = current.UsingDirective_Begin(); si != current.UsingDirective_End(); ++si) { Member m = LookupMember(nam, *si); if (m) { return m; } } for (Base_Iterator bi = current.Base_Begin(); bi != current.Base_End(); ++bi) { Member m = LookupMember(nam, bi->ToScope()); if (m) { return m; } } if (!current.IsTopScope()) { return LookupMember(nam, current.DeclaringScope()); } return Dummy::Member(); } // LookupMemberUnqualified //______________________________________________________________________________ Reflex::Type Reflex::NameLookup::AccessControl(const Type& typ, const Scope& /*current*/) { // Check access. // if (typ.IsPublic()) { // return true; // } // else if (typ.IsProtected() && current.HasBase(typ.DeclaringScope())) { // return true; // } return typ; } //______________________________________________________________________________ void Reflex::NameLookup::FindNextScopePos() { // Move fPosNamePart to point to the next scope in fLookupName, updating // fPosNamePartLen. If fPosNamePartLen == std::string::npos, initialize // fPosNamePart and fPosNamePartLen. If there is no next scope left, fPosNamePart // will be set to std::string::npos and fPosNamePartLen will be set to 0. if (fPosNamePartLen != std::string::npos) { // we know the length, so jump fPosNamePart += fPosNamePartLen + 2; if (fPosNamePart > fLookupName.length()) { // past the string's end? fPosNamePart = std::string::npos; fPosNamePartLen = 0; return; } } else { // uninitialized // set fPosNamePartLen and check that fLookupName doesn't start with '::' fPosNamePart = 0; if (!fLookupName.compare(0, 2, "::")) { fPosNamePart = 2; } } size_t start = 0; // yes, we should use it... Think of "int MyClass::*" where the scope is "MyClass", not "int MyClass" fPosNamePartLen = Tools::GetFirstScopePosition(fLookupName.substr(fPosNamePart), start); if (!fPosNamePartLen) { // no next "::" fPosNamePartLen = fLookupName.length(); } else { // no "::" fPosNamePartLen -= 2; } } // FindNextScopePos <commit_msg>fix illegal initialisation of a const string& from a const char*<commit_after>// @(#)root/reflex:$Id$ // Author: Stefan Roiser 2006 // Copyright CERN, CH-1211 Geneva 23, 2004-2010, All rights reserved. // // Permission to use, copy, modify, and distribute this software for any // purpose is hereby granted without fee, provided that this copyright and // permissions notice appear in all copies and derivatives. // // This software is provided "as is" without express or implied warranty. #ifndef REFLEX_BUILD # define REFLEX_BUILD #endif #include "NameLookup.h" #include "Reflex/Base.h" #include "Reflex/Scope.h" #include "Reflex/Type.h" #include "Reflex/Tools.h" #include "Reflex/internal/OwnedMember.h" #include <sstream> #include <cstring> //______________________________________________________________________________ Reflex::NameLookup::NameLookup(const std::string& name, const Scope& current): fLookupName(name), fPosNamePart(0), fPosNamePartLen(std::string::npos), fCurrentScope(current), fPartialSuccess(false) { // Initialize a NameLookup object used internally to keep track of lookup // states. } //______________________________________________________________________________ Reflex::Type Reflex::NameLookup::LookupType(const std::string& nam, const Scope& current) { // Lookup up a (possibly scoped) type name appearing in the scope context // current. This is the public interface for type lookup. NameLookup lookup(nam, current); return lookup.Lookup<Type>(); } //______________________________________________________________________________ Reflex::Scope Reflex::NameLookup::LookupScope(const std::string& nam, const Scope& current) { // Lookup up a (possibly scoped) scope name appearing in the scope context // current. This is the public interface for scope lookup. NameLookup lookup(nam, current); return lookup.Lookup<Scope>(); } /* //______________________________________________________________________________ Reflex::Member LookupMember(const std::string& nam, const Scope& current ) { // Lookup up a (possibly scoped) member name appearing in the scope context // current. This is the public interface for member lookup. NameLookup lookup(nam, current); // this will not work, member lookup is too different from type lookup... return lookup.Lookup<Member>(); } */ //______________________________________________________________________________ template <class T> T Reflex::NameLookup::Lookup(bool isTemplateExpanded /* = false */) { // Lookup a type using fLookupName, fCurrentScope. Scope startScope = fCurrentScope; T result; fPartialSuccess = false; fPosNamePart = 0; fPosNamePartLen = std::string::npos; FindNextScopePos(); if (fPosNamePart == 2) { fLookedAtUsingDir.clear(); // ::A... fCurrentScope = Scope::GlobalScope(); result = LookupInScope<T>(); } else { // A... result = LookupInUnknownScope<T>(); } if (!isTemplateExpanded && !result && fLookupName.find('<') != std::string::npos) { // We need to replace the template argument both of this type // and any of it enclosing type: // myspace::mytop<A,B>::mytype<C> std::ostringstream tmp; for (size_t i = 0, level = 0, sofar = 0; i < fLookupName.size(); ++i) { if (level == 0) { tmp << fLookupName.substr(sofar, i + 1 - sofar); sofar = i + 1; } switch (fLookupName[i]) { case '<': ++level; break; case '>': --level; // intentional fall through to the ',' case case ',': if (level == (1 - (unsigned int) (fLookupName[i] == '>'))) { std::string arg(fLookupName.substr(sofar, i - sofar)); size_t p = arg.size(); while (p > 0 && (arg[p - 1] == '*' || arg[p - 1] == '&' || arg[p - 1] == ' ')) --p; std::string end(arg.substr(p)); arg.erase(p); const char* start = arg.c_str(); while (strncmp(start, "const ", 6) == 0) start += 6; tmp << arg.substr(0, start - arg.c_str()); while (strncmp(start, "std::", 5) == 0) start += 5; arg.erase(0, start - arg.c_str()); Reflex::Type type(LookupType(arg, startScope)); if (type) { if (type.Name() != "Double32_t" && type.Name() != "Float16_t") { // Use the real type rather than the typedef unless // this is Double32_t or Float16_t type = type.FinalType(); } tmp << type.Name(Reflex::SCOPED | Reflex::QUALIFIED); } else { tmp << arg; } tmp << end; tmp << fLookupName[i]; sofar = i + 1; } break; } // switch } NameLookup next(tmp.str(), startScope); return next.Lookup<T>(true); } return result; } // Lookup //______________________________________________________________________________ template <class T> T Reflex::NameLookup::LookupInScope() { // Lookup a type in fCurrentScope. // Checks sub-types, sub-scopes, using directives, and base classes for // the name given by fLookupName, fPosNamePart, and fPosNamePartLen. // If the name part is found, and another name part follows in fPosNamePart, // LookupTypeInScope requests the scope found to lookup the next name // part. fPartialMatch reflexts that the left part of the name was matched; // even if the trailing part of fLookupName cannot be found, the lookup // cannot continue on declaring scopes and has to fail. // A list of lookups performed in namespaces pulled in via using directives is // kept in fLookedAtUsingDir, to prevent infinite loops due to // namespace A{using namespace B;} namespace B{using namespace A;} // loops. // The lookup does not take the declaration order into account; the result of // parts of the lookup algorithm which depend on the order will be unpredictable. if (!fCurrentScope) { return Dummy::Get<T>(); } // prevent inf loop from // ns A { using ns B; } ns B {using ns A;} if (fLookedAtUsingDir.find(fCurrentScope) != fLookedAtUsingDir.end()) { return Dummy::Get<T>(); } // global scope can use hashed containers: if (fCurrentScope == Scope::GlobalScope()) { Type freeType(Type::ByName(fLookupName.c_str() + fPosNamePart)); if (freeType.Id()) { //fprintf(stderr, "Reflex::NameLookup::LookupInScope<T>: lookup up '%s', partial success with subscope '%s' ...\n", fLookupName.c_str(), name.c_str()); fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return freeType; } if (freeType.IsTypedef()) { fCurrentScope = freeType.FinalType(); } else { fCurrentScope = freeType; } return LookupInScope<T>(); } Scope freeScope(Scope::ByName(fLookupName.c_str() + fPosNamePart)); // only take namespaces into account - classes were checked as part of SubType if (freeScope.Id() && freeScope.IsNamespace()) { fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return (T) (freeScope); } fCurrentScope = freeScope; return LookupInScope<T>(); } } // end of: if global scope else { // if not global scope size_t len = fCurrentScope.SubTypeSize(); size_t i = 0; for (Type_Iterator it = fCurrentScope.SubType_Begin(); i < len; ++it, ++i) { const Type& type = *it; const TypeBase* base = type.ToTypeBase(); if (base) { size_t pos; const std::string name(base->SimpleName(pos)); //fprintf(stderr, "Reflex::NameLookup::LookupInScope<T>: looking up '%s', considering subscope '%s' ...\n", fLookupName.c_str(), name.c_str()); if ( (fLookupName[fPosNamePart] == name[pos]) && !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length()) ) { //fprintf(stderr, "Reflex::NameLookup::LookupInScope<T>: lookup up '%s', partial success with subscope '%s' ...\n", fLookupName.c_str(), name.c_str()); fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return type; } if (it->IsTypedef()) { fCurrentScope = it->FinalType(); } else { fCurrentScope = type; } return LookupInScope<T>(); } } } Scope_Iterator subscope_end(fCurrentScope.SubScope_End()); for (Scope_Iterator in = fCurrentScope.SubScope_Begin(); in != subscope_end; ++in) { // only take namespaces into account - classes were checked as part of SubType if (in->IsNamespace()) { const Scope& scope = *in; const ScopeBase* base = scope.ToScopeBase(); if (base) { size_t pos; const std::string name(base->SimpleName(pos)); if ( (fLookupName[fPosNamePart] == name[pos]) && !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length()) ) { fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return (T) (*in); } fCurrentScope = (Scope) (*in); return LookupInScope<T>(); } } } } } // end of: if not global scope if (fCurrentScope.UsingDirectiveSize()) { fLookedAtUsingDir.insert(fCurrentScope); Scope storeCurrentScope = fCurrentScope; Scope_Iterator usingscope_end(storeCurrentScope.UsingDirective_End()); for (Scope_Iterator si = storeCurrentScope.UsingDirective_Begin(); si != usingscope_end; ++si) { fCurrentScope = *si; T t = LookupInScope<T>(); if (fPartialSuccess) { return t; } } fCurrentScope = storeCurrentScope; } if (!fPosNamePart) { // only for "BaseClass...", not for "A::BaseClass..." Base_Iterator base_end(fCurrentScope.Base_End()); for (Base_Iterator bi = fCurrentScope.Base_Begin(); bi != base_end; ++bi) { if (!fLookupName.compare(fPosNamePart, fPosNamePartLen, bi->Name())) { fPartialSuccess = true; fLookedAtUsingDir.clear(); FindNextScopePos(); if (fPosNamePart == std::string::npos) { return bi->ToType(); } fCurrentScope = bi->ToType().FinalType(); return LookupInScope<T>(); } } } if (fCurrentScope.BaseSize()) { Scope storeCurrentScope = fCurrentScope; Base_Iterator base_end(storeCurrentScope.Base_End()); for (Base_Iterator bi = storeCurrentScope.Base_Begin(); bi != base_end; ++bi) { fCurrentScope = bi->ToScope(); T t = LookupInScope<T>(); if (fPartialSuccess) { return t; } } fCurrentScope = storeCurrentScope; } return Dummy::Get<T>(); } // LookupInScope //______________________________________________________________________________ template <class T> T Reflex::NameLookup::LookupInUnknownScope() { // Lookup a type in fCurrentScope and its declaring scopes. for (fPartialSuccess = false; !fPartialSuccess && fCurrentScope; fCurrentScope = fCurrentScope.DeclaringScope()) { fLookedAtUsingDir.clear(); T t = LookupInScope<T>(); if (fPartialSuccess) { return t; } if (fCurrentScope.IsTopScope()) { break; } } return Dummy::Get<T>(); } //______________________________________________________________________________ Reflex::Member Reflex::NameLookup::LookupMember(const std::string& nam, const Scope& current) { // Lookup a member. if (Tools::GetBasePosition(nam)) { return LookupMemberQualified(nam); } return LookupMemberUnqualified(nam, current); } //______________________________________________________________________________ Reflex::Member Reflex::NameLookup::LookupMemberQualified(const std::string& nam) { // Lookup of a qualified member. Scope bscope = Scope::ByName(Tools::GetScopeName(nam)); if (bscope) { return LookupMemberUnqualified(Tools::GetBaseName(nam), bscope); } return Dummy::Member(); } //______________________________________________________________________________ Reflex::Member Reflex::NameLookup::LookupMemberUnqualified(const std::string& nam, const Scope& current) { // Lookup of an unqualified member. { Member m = current.MemberByName(nam); if (m) { return m; } } for (Scope_Iterator si = current.UsingDirective_Begin(); si != current.UsingDirective_End(); ++si) { Member m = LookupMember(nam, *si); if (m) { return m; } } for (Base_Iterator bi = current.Base_Begin(); bi != current.Base_End(); ++bi) { Member m = LookupMember(nam, bi->ToScope()); if (m) { return m; } } if (!current.IsTopScope()) { return LookupMember(nam, current.DeclaringScope()); } return Dummy::Member(); } // LookupMemberUnqualified //______________________________________________________________________________ Reflex::Type Reflex::NameLookup::AccessControl(const Type& typ, const Scope& /*current*/) { // Check access. // if (typ.IsPublic()) { // return true; // } // else if (typ.IsProtected() && current.HasBase(typ.DeclaringScope())) { // return true; // } return typ; } //______________________________________________________________________________ void Reflex::NameLookup::FindNextScopePos() { // Move fPosNamePart to point to the next scope in fLookupName, updating // fPosNamePartLen. If fPosNamePartLen == std::string::npos, initialize // fPosNamePart and fPosNamePartLen. If there is no next scope left, fPosNamePart // will be set to std::string::npos and fPosNamePartLen will be set to 0. if (fPosNamePartLen != std::string::npos) { // we know the length, so jump fPosNamePart += fPosNamePartLen + 2; if (fPosNamePart > fLookupName.length()) { // past the string's end? fPosNamePart = std::string::npos; fPosNamePartLen = 0; return; } } else { // uninitialized // set fPosNamePartLen and check that fLookupName doesn't start with '::' fPosNamePart = 0; if (!fLookupName.compare(0, 2, "::")) { fPosNamePart = 2; } } size_t start = 0; // yes, we should use it... Think of "int MyClass::*" where the scope is "MyClass", not "int MyClass" fPosNamePartLen = Tools::GetFirstScopePosition(fLookupName.substr(fPosNamePart), start); if (!fPosNamePartLen) { // no next "::" fPosNamePartLen = fLookupName.length(); } else { // no "::" fPosNamePartLen -= 2; } } // FindNextScopePos <|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 "remoting/base/encoder_vp8.h" #include "base/logging.h" #include "media/base/callback.h" #include "remoting/base/capture_data.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" #include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" #include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = vpx_codec_vp8_cx(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int clip_byte(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // And then do RGB->YUV conversion. // Currently we just produce the Y channel as the average of RGB. This will // giv ae gray scale image after conversion. // TODO(sergeyu): Move this code to a separate routine. // TODO(sergeyu): Optimize this code. DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32) << "Only RGB32 is supported"; uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int out_stride = image_->stride[0]; for (int i = 0; i < capture_data->height(); ++i) { for (int j = 0; j < capture_data->width(); ++j) { // Since the input pixel format is RGB32, there are 4 bytes per pixel. uint8* pixel = in + 4 * j; y_out[j] = clip_byte(((pixel[2] * 66 + pixel[1] * 129 + pixel[0] * 25 + 128) >> 8) + 16); if (i % 2 == 0 && j % 2 == 0) { u_out[j / 2] = clip_byte(((pixel[2] * -38 + pixel[1] * -74 + pixel[0] * 112 + 128) >> 8) + 128); v_out[j / 2] = clip_byte(((pixel[2] * 112 + pixel[1] * -94 + pixel[1] * -18 + 128) >> 8) + 128); } } in += in_stride; y_out += out_stride; if (i % 2 == 0) { u_out += out_stride / 2; v_out += out_stride / 2; } } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; // TODO(sergeyu): Split each frame into multiple partitions. message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET | VideoPacket::LAST_PARTITION); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <commit_msg>Chromoting host to convert only changed regions<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 "remoting/base/encoder_vp8.h" #include "base/logging.h" #include "media/base/callback.h" #include "media/base/yuv_convert.h" #include "remoting/base/capture_data.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/source/libvpx/vpx/vpx_codec.h" #include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h" #include "third_party/libvpx/source/libvpx/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = vpx_codec_vp8_cx(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int RoundToTwosMultiple(int x) { return x & (~1); } // Align the sides of the rectange to multiples of 2. static gfx::Rect AlignRect(const gfx::Rect& rect, int width, int height) { CHECK(rect.width() > 0 && rect.height() > 0); int x = RoundToTwosMultiple(rect.x()); int y = RoundToTwosMultiple(rect.y()); int right = std::min(RoundToTwosMultiple(rect.right() + 1), RoundToTwosMultiple(width)); int bottom = std::min(RoundToTwosMultiple(rect.bottom() + 1), RoundToTwosMultiple(height)); // Do the final check to make sure the width and height are not negative. gfx::Rect r(x, y, right - x, bottom - y); if (r.width() <= 0 || r.height() <= 0) { r.set_width(0); r.set_height(0); } return r; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // Perform RGB->YUV conversion. if (capture_data->pixel_format() != media::VideoFrame::RGB32) { LOG(ERROR) << "Only RGB32 is supported"; return false; } const InvalidRects& rects = capture_data->dirty_rects(); const uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int y_stride = image_->stride[0]; const int uv_stride = image_->stride[1]; for (InvalidRects::const_iterator r = rects.begin(); r != rects.end(); ++r) { gfx::Rect rect = AlignRect(*r, image_->w, image_->h); int in_offset = in_stride * rect.y() + 4 * rect.x(); int y_offset = y_stride * rect.y() + rect.x(); int uv_offset = (uv_stride * rect.y() + rect.x()) / 2; media::ConvertRGB32ToYUV(in + in_offset, y_out + y_offset, u_out + uv_offset, v_out + uv_offset, rect.width(), rect.height(), in_stride, y_stride, uv_stride); } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; // TODO(sergeyu): Split each frame into multiple partitions. message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET | VideoPacket::LAST_PARTITION); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "media/base/callback.h" #include "media/base/media.h" #include "remoting/base/capture_data.h" #include "remoting/base/encoder_vp8.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/include/vpx/vpx_codec.h" #include "third_party/libvpx/include/vpx/vpx_encoder.h" #include "third_party/libvpx/include/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int clip_byte(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // And then do RGB->YUV conversion. // Currently we just produce the Y channel as the average of RGB. This will // giv ae gray scale image after conversion. // TODO(sergeyu): Move this code to a separate routine. // TODO(sergeyu): Optimize this code. DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32) << "Only RGB32 is supported"; uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int out_stride = image_->stride[0]; for (int i = 0; i < capture_data->height(); ++i) { for (int j = 0; j < capture_data->width(); ++j) { // Since the input pixel format is RGB32, there are 4 bytes per pixel. uint8* pixel = in + 4 * j; y_out[j] = clip_byte(((pixel[0] * 66 + pixel[1] * 129 + pixel[2] * 25 + 128) >> 8) + 16); if (i % 2 == 0 && j % 2 == 0) { u_out[j / 2] = clip_byte(((pixel[0] * -38 + pixel[1] * -74 + pixel[2] * 112 + 128) >> 8) + 128); v_out[j / 2] = clip_byte(((pixel[0] * 112 + pixel[1] * -94 + pixel[2] * -18 + 128) >> 8) + 128); } } in += in_stride; y_out += out_stride; if (i % 2 == 0) { u_out += out_stride / 2; v_out += out_stride / 2; } } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <commit_msg>Refactor ZLib and Verbatim encoders.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "media/base/callback.h" #include "media/base/media.h" #include "remoting/base/capture_data.h" #include "remoting/base/encoder_vp8.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/include/vpx/vpx_codec.h" #include "third_party/libvpx/include/vpx/vpx_encoder.h" #include "third_party/libvpx/include/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int clip_byte(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // And then do RGB->YUV conversion. // Currently we just produce the Y channel as the average of RGB. This will // giv ae gray scale image after conversion. // TODO(sergeyu): Move this code to a separate routine. // TODO(sergeyu): Optimize this code. DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32) << "Only RGB32 is supported"; uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int out_stride = image_->stride[0]; for (int i = 0; i < capture_data->height(); ++i) { for (int j = 0; j < capture_data->width(); ++j) { // Since the input pixel format is RGB32, there are 4 bytes per pixel. uint8* pixel = in + 4 * j; y_out[j] = clip_byte(((pixel[2] * 66 + pixel[1] * 129 + pixel[0] * 25 + 128) >> 8) + 16); if (i % 2 == 0 && j % 2 == 0) { u_out[j / 2] = clip_byte(((pixel[2] * -38 + pixel[1] * -74 + pixel[0] * 112 + 128) >> 8) + 128); v_out[j / 2] = clip_byte(((pixel[2] * 112 + pixel[1] * -94 + pixel[1] * -18 + 128) >> 8) + 128); } } in += in_stride; y_out += out_stride; if (i % 2 == 0) { u_out += out_stride / 2; v_out += out_stride / 2; } } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <|endoftext|>
<commit_before>/* Copyright (c) 2013, Ford Motor Company All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Ford Motor Company nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string.h> #include "application_manager/commands/mobile/perform_audio_pass_thru_request.h" #include "application_manager/application_manager_impl.h" #include "application_manager/application_impl.h" #include "application_manager/message_helper.h" #include "config_profile/profile.h" #include "utils/helpers.h" namespace application_manager { namespace commands { namespace str = strings; PerformAudioPassThruRequest::PerformAudioPassThruRequest( const MessageSharedPtr& message) : CommandRequestImpl(message), is_active_tts_speak_(false), result_tts_speak_(mobile_apis::Result::SUCCESS) { subscribe_on_event(hmi_apis::FunctionID::TTS_OnResetTimeout); } PerformAudioPassThruRequest::~PerformAudioPassThruRequest() { } void PerformAudioPassThruRequest::onTimeOut() { LOG4CXX_AUTO_TRACE(logger_); FinishTTSSpeak(); CommandRequestImpl::onTimeOut(); } bool PerformAudioPassThruRequest::Init() { default_timeout_ += (((*message_)[str::msg_params][str::max_duration].asUInt())); return true; } void PerformAudioPassThruRequest::Run() { LOG4CXX_AUTO_TRACE(logger_); ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(connection_key()); if (!app) { LOG4CXX_ERROR(logger_, "APPLICATION_NOT_REGISTERED"); SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED); return; } if (mobile_api::HMILevel::HMI_NONE == app->hmi_level()) { LOG4CXX_ERROR(logger_, "application isn't activated"); SendResponse(false, mobile_apis::Result::REJECTED); return; } if (IsWhiteSpaceExist()) { LOG4CXX_ERROR(logger_, "Incoming perform audio pass thru has contains " "\\t\\n \\\\t \\\\n" " text contains only whitespace in initialPrompt"); SendResponse(false, mobile_apis::Result::INVALID_DATA); return; } if ((*message_)[str::msg_params].keyExists(str::initial_prompt) && (0 < (*message_)[str::msg_params][str::initial_prompt].length())) { // In case TTS Speak, subscribe on notification SendSpeakRequest(); SendPerformAudioPassThruRequest(); } else { SendPerformAudioPassThruRequest(); SendRecordStartNotification(); StartMicrophoneRecording(); } } void PerformAudioPassThruRequest::on_event(const event_engine::Event& event) { LOG4CXX_AUTO_TRACE(logger_); using namespace helpers; const smart_objects::SmartObject& message = event.smart_object(); switch (event.id()) { case hmi_apis::FunctionID::UI_PerformAudioPassThru: { LOG4CXX_INFO(logger_, "Received UI_PerformAudioPassThru"); if (!WaitTTSSpeak()) return; mobile_apis::Result::eType mobile_code = GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>( message[strings::params][hmi_response::code].asUInt())); // in case perform audio is started by other request skip stopping if (mobile_apis::Result::REJECTED == mobile_code) { LOG4CXX_ERROR(logger_, "Request was rejected"); SendResponse(false, mobile_code, NULL, &(message[strings::msg_params])); return; } FinishTTSSpeak(); std::string return_info; const bool result = Compare<mobile_api::Result::eType, EQ, ONE>( mobile_code, mobile_apis::Result::SUCCESS, mobile_apis::Result::RETRY, mobile_apis::Result::WARNINGS); const bool is_result_ok = Compare<mobile_api::Result::eType, EQ, ONE>( mobile_code, mobile_apis::Result::SUCCESS, mobile_apis::Result::WARNINGS); if (is_result_ok && mobile_apis::Result::UNSUPPORTED_RESOURCE == result_tts_speak_) { mobile_code = mobile_apis::Result::WARNINGS; return_info = "Unsupported phoneme type sent in a prompt"; } SendResponse(result, mobile_code, return_info.c_str(), &(message[strings::msg_params])); break; } case hmi_apis::FunctionID::TTS_Speak: { LOG4CXX_INFO(logger_, "Received TTS_Speak event"); result_tts_speak_ = GetMobileResultCode( static_cast<hmi_apis::Common_Result::eType>( message[strings::params][hmi_response::code].asUInt())); is_active_tts_speak_ = false; if (mobile_apis::Result::SUCCESS == result_tts_speak_) { SendRecordStartNotification(); StartMicrophoneRecording(); // update request timeout to get time for perform audio recording ApplicationManagerImpl::instance()-> updateRequestTimeout(connection_key(), correlation_id(), default_timeout()); } break; } case hmi_apis::FunctionID::TTS_OnResetTimeout: { LOG4CXX_INFO(logger_, "Received TTS_OnResetTimeout event"); ApplicationManagerImpl::instance()->updateRequestTimeout( connection_key(), correlation_id(), default_timeout()); break; } default: { LOG4CXX_ERROR(logger_, "Received unknown event" << event.id()); return; } } } void PerformAudioPassThruRequest::SendSpeakRequest() { LOG4CXX_AUTO_TRACE(logger_); using namespace hmi_apis; using namespace smart_objects; SmartObject msg_params = smart_objects::SmartObject(SmartType_Map); if ((*message_)[str::msg_params].keyExists(str::initial_prompt) && (0 < (*message_)[str::msg_params][str::initial_prompt].length())) { for (uint32_t i = 0; i < (*message_)[str::msg_params][str::initial_prompt].length(); ++i) { msg_params[hmi_request::tts_chunks][i][str::text] = (*message_)[str::msg_params][str::initial_prompt][i][str::text]; msg_params[hmi_request::tts_chunks][i][str::type] = (*message_)[str::msg_params][str::initial_prompt][i][str::type]; } // app_id msg_params[strings::app_id] = connection_key(); msg_params[hmi_request::speak_type] = Common_MethodName::AUDIO_PASS_THRU; is_active_tts_speak_ = true; SendHMIRequest(FunctionID::TTS_Speak, &msg_params, true); } } void PerformAudioPassThruRequest::SendPerformAudioPassThruRequest() { LOG4CXX_AUTO_TRACE(logger_); smart_objects::SmartObject msg_params = smart_objects::SmartObject( smart_objects::SmartType_Map); msg_params[str::app_id] = connection_key(); msg_params[hmi_request::max_duration] = (*message_)[str::msg_params][str::max_duration]; msg_params[hmi_request::audio_pass_display_texts] = smart_objects::SmartObject(smart_objects::SmartType_Array); if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text1)) { msg_params[hmi_request::audio_pass_display_texts] [0][hmi_request::field_name] = static_cast<int32_t> (hmi_apis::Common_TextFieldName::audioPassThruDisplayText1); msg_params[hmi_request::audio_pass_display_texts] [0][hmi_request::field_text] = (*message_)[str::msg_params][str::audio_pass_display_text1]; } if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text2)) { msg_params[hmi_request::audio_pass_display_texts] [1][hmi_request::field_name] = static_cast<int32_t> (hmi_apis::Common_TextFieldName::audioPassThruDisplayText2); msg_params[hmi_request::audio_pass_display_texts] [1][hmi_request::field_text] = (*message_)[str::msg_params][str::audio_pass_display_text2]; } if ((*message_)[str::msg_params].keyExists(str::mute_audio)) { msg_params[str::mute_audio] = (*message_)[str::msg_params][str::mute_audio].asBool(); } else { // If omitted, the value is set to true msg_params[str::mute_audio] = true; } SendHMIRequest(hmi_apis::FunctionID::UI_PerformAudioPassThru, &msg_params, true); } void PerformAudioPassThruRequest::SendRecordStartNotification() { LOG4CXX_AUTO_TRACE(logger_); smart_objects::SmartObject msg_params = smart_objects::SmartObject( smart_objects::SmartType_Map); msg_params[strings::app_id] = connection_key(); CreateHMINotification(hmi_apis::FunctionID::UI_OnRecordStart, msg_params); } void PerformAudioPassThruRequest::StartMicrophoneRecording() { LOG4CXX_AUTO_TRACE(logger_); ApplicationManagerImpl::instance()->begin_audio_pass_thru(); ApplicationManagerImpl::instance()->StartAudioPassThruThread( connection_key(), correlation_id(), (*message_)[str::msg_params][str::max_duration].asInt(), (*message_)[str::msg_params][str::sampling_rate].asInt(), (*message_)[str::msg_params][str::bits_per_sample].asInt(), (*message_)[str::msg_params][str::audio_type].asInt()); } bool PerformAudioPassThruRequest::IsWhiteSpaceExist() { LOG4CXX_AUTO_TRACE(logger_); const char* str = NULL; if ((*message_)[strings::msg_params].keyExists(strings::initial_prompt)) { const smart_objects::SmartArray* ip_array = (*message_)[strings::msg_params][strings::initial_prompt].asArray(); smart_objects::SmartArray::const_iterator it_ip = ip_array->begin(); smart_objects::SmartArray::const_iterator it_ip_end = ip_array->end(); for (; it_ip != it_ip_end; ++it_ip) { str = (*it_ip)[strings::text].asCharArray(); if (strlen(str) && !CheckSyntax(str)) { LOG4CXX_ERROR(logger_, "Invalid initial_prompt syntax check failed"); return true; } } } if ((*message_)[strings::msg_params]. keyExists(strings::audio_pass_display_text1)) { str = (*message_)[strings::msg_params] [strings::audio_pass_display_text1].asCharArray(); if (!CheckSyntax(str)) { LOG4CXX_ERROR(logger_, "Invalid audio_pass_display_text1 value syntax check failed"); return true; } } if ((*message_)[strings::msg_params]. keyExists(strings::audio_pass_display_text2)) { str = (*message_)[strings::msg_params] [strings::audio_pass_display_text2].asCharArray(); if (!CheckSyntax(str)) { LOG4CXX_ERROR(logger_, "Invalid audio_pass_display_text2 value syntax check failed"); return true; } } return false; } void PerformAudioPassThruRequest::FinishTTSSpeak(){ LOG4CXX_AUTO_TRACE(logger_); if (ApplicationManagerImpl::instance()->end_audio_pass_thru()) { ApplicationManagerImpl::instance()-> StopAudioPassThru(connection_key()); } if (!is_active_tts_speak_) { LOG4CXX_DEBUG(logger_, "TTS Speak is inactive."); return; } is_active_tts_speak_ = false; SendHMIRequest(hmi_apis::FunctionID::TTS_StopSpeaking, NULL); } bool PerformAudioPassThruRequest::WaitTTSSpeak() { LOG4CXX_AUTO_TRACE(logger_); uint32_t default_timeout_msec = profile::Profile::instance()->default_timeout(); TimevalStruct start_time = date_time::DateTime::getCurrentTime(); // Waiting for TTS_Speak while (is_active_tts_speak_) { int64_t difference_between_start_current_time = date_time::DateTime::calculateTimeSpan(start_time); // Send GENERIC_ERROR after default timeout if (difference_between_start_current_time > default_timeout_msec) { LOG4CXX_ERROR(logger_, "Expired timeout for TTS.Speak response"); // Don't using onTimeOut(), becouse there default time is bigger than // Default time in *.ini file FinishTTSSpeak(); SendResponse(false, mobile_apis::Result::eType::GENERIC_ERROR, "Expired timeout for TTS.Speak response"); return false; } } return true; } } // namespace commands } // namespace application_manager <commit_msg>Add logs to WaitTTSSpeak method.<commit_after>/* Copyright (c) 2013, Ford Motor Company All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Ford Motor Company nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "application_manager/commands/mobile/perform_audio_pass_thru_request.h" #include "application_manager/application_manager_impl.h" #include "application_manager/application_impl.h" #include "application_manager/message_helper.h" #include "config_profile/profile.h" #include "utils/helpers.h" namespace application_manager { namespace commands { namespace str = strings; PerformAudioPassThruRequest::PerformAudioPassThruRequest( const MessageSharedPtr& message) : CommandRequestImpl(message), is_active_tts_speak_(false), result_tts_speak_(mobile_apis::Result::SUCCESS) { subscribe_on_event(hmi_apis::FunctionID::TTS_OnResetTimeout); } PerformAudioPassThruRequest::~PerformAudioPassThruRequest() { } void PerformAudioPassThruRequest::onTimeOut() { LOG4CXX_AUTO_TRACE(logger_); FinishTTSSpeak(); CommandRequestImpl::onTimeOut(); } bool PerformAudioPassThruRequest::Init() { default_timeout_ += (((*message_)[str::msg_params][str::max_duration].asUInt())); return true; } void PerformAudioPassThruRequest::Run() { LOG4CXX_AUTO_TRACE(logger_); ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(connection_key()); if (!app) { LOG4CXX_ERROR(logger_, "APPLICATION_NOT_REGISTERED"); SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED); return; } if (mobile_api::HMILevel::HMI_NONE == app->hmi_level()) { LOG4CXX_ERROR(logger_, "application isn't activated"); SendResponse(false, mobile_apis::Result::REJECTED); return; } if (IsWhiteSpaceExist()) { LOG4CXX_ERROR(logger_, "Incoming perform audio pass thru has contains " "\\t\\n \\\\t \\\\n" " text contains only whitespace in initialPrompt"); SendResponse(false, mobile_apis::Result::INVALID_DATA); return; } if ((*message_)[str::msg_params].keyExists(str::initial_prompt) && (0 < (*message_)[str::msg_params][str::initial_prompt].length())) { // In case TTS Speak, subscribe on notification SendSpeakRequest(); SendPerformAudioPassThruRequest(); } else { SendPerformAudioPassThruRequest(); SendRecordStartNotification(); StartMicrophoneRecording(); } } void PerformAudioPassThruRequest::on_event(const event_engine::Event& event) { LOG4CXX_AUTO_TRACE(logger_); using namespace helpers; const smart_objects::SmartObject& message = event.smart_object(); switch (event.id()) { case hmi_apis::FunctionID::UI_PerformAudioPassThru: { LOG4CXX_INFO(logger_, "Received UI_PerformAudioPassThru"); if (!WaitTTSSpeak()) { LOG4CXX_AUTO_TRACE(logger_); return; } mobile_apis::Result::eType mobile_code = GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>( message[strings::params][hmi_response::code].asUInt())); // in case perform audio is started by other request skip stopping if (mobile_apis::Result::REJECTED == mobile_code) { LOG4CXX_ERROR(logger_, "Request was rejected"); SendResponse(false, mobile_code, NULL, &(message[strings::msg_params])); return; } FinishTTSSpeak(); std::string return_info; const bool result = Compare<mobile_api::Result::eType, EQ, ONE>( mobile_code, mobile_apis::Result::SUCCESS, mobile_apis::Result::RETRY, mobile_apis::Result::WARNINGS); const bool is_result_ok = Compare<mobile_api::Result::eType, EQ, ONE>( mobile_code, mobile_apis::Result::SUCCESS, mobile_apis::Result::WARNINGS); if (is_result_ok && mobile_apis::Result::UNSUPPORTED_RESOURCE == result_tts_speak_) { mobile_code = mobile_apis::Result::WARNINGS; return_info = "Unsupported phoneme type sent in a prompt"; } SendResponse(result, mobile_code, return_info.c_str(), &(message[strings::msg_params])); break; } case hmi_apis::FunctionID::TTS_Speak: { LOG4CXX_INFO(logger_, "Received TTS_Speak event"); result_tts_speak_ = GetMobileResultCode( static_cast<hmi_apis::Common_Result::eType>( message[strings::params][hmi_response::code].asUInt())); is_active_tts_speak_ = false; if (mobile_apis::Result::SUCCESS == result_tts_speak_) { SendRecordStartNotification(); StartMicrophoneRecording(); // update request timeout to get time for perform audio recording ApplicationManagerImpl::instance()-> updateRequestTimeout(connection_key(), correlation_id(), default_timeout()); } break; } case hmi_apis::FunctionID::TTS_OnResetTimeout: { LOG4CXX_INFO(logger_, "Received TTS_OnResetTimeout event"); ApplicationManagerImpl::instance()->updateRequestTimeout( connection_key(), correlation_id(), default_timeout()); break; } default: { LOG4CXX_ERROR(logger_, "Received unknown event" << event.id()); return; } } } void PerformAudioPassThruRequest::SendSpeakRequest() { LOG4CXX_AUTO_TRACE(logger_); using namespace hmi_apis; using namespace smart_objects; SmartObject msg_params = smart_objects::SmartObject(SmartType_Map); if ((*message_)[str::msg_params].keyExists(str::initial_prompt) && (0 < (*message_)[str::msg_params][str::initial_prompt].length())) { for (uint32_t i = 0; i < (*message_)[str::msg_params][str::initial_prompt].length(); ++i) { msg_params[hmi_request::tts_chunks][i][str::text] = (*message_)[str::msg_params][str::initial_prompt][i][str::text]; msg_params[hmi_request::tts_chunks][i][str::type] = (*message_)[str::msg_params][str::initial_prompt][i][str::type]; } // app_id msg_params[strings::app_id] = connection_key(); msg_params[hmi_request::speak_type] = Common_MethodName::AUDIO_PASS_THRU; is_active_tts_speak_ = true; SendHMIRequest(FunctionID::TTS_Speak, &msg_params, true); } } void PerformAudioPassThruRequest::SendPerformAudioPassThruRequest() { LOG4CXX_AUTO_TRACE(logger_); smart_objects::SmartObject msg_params = smart_objects::SmartObject( smart_objects::SmartType_Map); msg_params[str::app_id] = connection_key(); msg_params[hmi_request::max_duration] = (*message_)[str::msg_params][str::max_duration]; msg_params[hmi_request::audio_pass_display_texts] = smart_objects::SmartObject(smart_objects::SmartType_Array); if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text1)) { msg_params[hmi_request::audio_pass_display_texts] [0][hmi_request::field_name] = static_cast<int32_t> (hmi_apis::Common_TextFieldName::audioPassThruDisplayText1); msg_params[hmi_request::audio_pass_display_texts] [0][hmi_request::field_text] = (*message_)[str::msg_params][str::audio_pass_display_text1]; } if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text2)) { msg_params[hmi_request::audio_pass_display_texts] [1][hmi_request::field_name] = static_cast<int32_t> (hmi_apis::Common_TextFieldName::audioPassThruDisplayText2); msg_params[hmi_request::audio_pass_display_texts] [1][hmi_request::field_text] = (*message_)[str::msg_params][str::audio_pass_display_text2]; } if ((*message_)[str::msg_params].keyExists(str::mute_audio)) { msg_params[str::mute_audio] = (*message_)[str::msg_params][str::mute_audio].asBool(); } else { // If omitted, the value is set to true msg_params[str::mute_audio] = true; } SendHMIRequest(hmi_apis::FunctionID::UI_PerformAudioPassThru, &msg_params, true); } void PerformAudioPassThruRequest::SendRecordStartNotification() { LOG4CXX_AUTO_TRACE(logger_); smart_objects::SmartObject msg_params = smart_objects::SmartObject( smart_objects::SmartType_Map); msg_params[strings::app_id] = connection_key(); CreateHMINotification(hmi_apis::FunctionID::UI_OnRecordStart, msg_params); } void PerformAudioPassThruRequest::StartMicrophoneRecording() { LOG4CXX_AUTO_TRACE(logger_); ApplicationManagerImpl::instance()->begin_audio_pass_thru(); ApplicationManagerImpl::instance()->StartAudioPassThruThread( connection_key(), correlation_id(), (*message_)[str::msg_params][str::max_duration].asInt(), (*message_)[str::msg_params][str::sampling_rate].asInt(), (*message_)[str::msg_params][str::bits_per_sample].asInt(), (*message_)[str::msg_params][str::audio_type].asInt()); } bool PerformAudioPassThruRequest::IsWhiteSpaceExist() { LOG4CXX_AUTO_TRACE(logger_); const char* str = NULL; if ((*message_)[strings::msg_params].keyExists(strings::initial_prompt)) { const smart_objects::SmartArray* ip_array = (*message_)[strings::msg_params][strings::initial_prompt].asArray(); smart_objects::SmartArray::const_iterator it_ip = ip_array->begin(); smart_objects::SmartArray::const_iterator it_ip_end = ip_array->end(); for (; it_ip != it_ip_end; ++it_ip) { str = (*it_ip)[strings::text].asCharArray(); if (strlen(str) && !CheckSyntax(str)) { LOG4CXX_ERROR(logger_, "Invalid initial_prompt syntax check failed"); return true; } } } if ((*message_)[strings::msg_params]. keyExists(strings::audio_pass_display_text1)) { str = (*message_)[strings::msg_params] [strings::audio_pass_display_text1].asCharArray(); if (!CheckSyntax(str)) { LOG4CXX_ERROR(logger_, "Invalid audio_pass_display_text1 value syntax check failed"); return true; } } if ((*message_)[strings::msg_params]. keyExists(strings::audio_pass_display_text2)) { str = (*message_)[strings::msg_params] [strings::audio_pass_display_text2].asCharArray(); if (!CheckSyntax(str)) { LOG4CXX_ERROR(logger_, "Invalid audio_pass_display_text2 value syntax check failed"); return true; } } return false; } void PerformAudioPassThruRequest::FinishTTSSpeak() { LOG4CXX_AUTO_TRACE(logger_); if (ApplicationManagerImpl::instance()->end_audio_pass_thru()) { LOG4CXX_DEBUG(logger_, "Stop AudioPassThru."); ApplicationManagerImpl::instance()-> StopAudioPassThru(connection_key()); } if (!is_active_tts_speak_) { LOG4CXX_DEBUG(logger_, "TTS Speak is inactive."); return; } is_active_tts_speak_ = false; SendHMIRequest(hmi_apis::FunctionID::TTS_StopSpeaking, NULL); } bool PerformAudioPassThruRequest::WaitTTSSpeak() { LOG4CXX_AUTO_TRACE(logger_); uint64_t default_timeout_msec = profile::Profile::instance()->default_timeout(); const TimevalStruct start_time = date_time::DateTime::getCurrentTime(); // Waiting for TTS_Speak while (is_active_tts_speak_) { uint64_t difference_between_start_current_time = date_time::DateTime::calculateTimeSpan(start_time); // Send GENERIC_ERROR after default timeout if (difference_between_start_current_time > default_timeout_msec) { LOG4CXX_WARN(logger_, "Expired timeout for TTS.Speak response"); // Don't use onTimeOut(), becouse default_timeout_ is bigger than // Default time in *.ini file FinishTTSSpeak(); SendResponse(false, mobile_apis::Result::eType::GENERIC_ERROR, "Expired timeout for TTS.Speak response"); return false; } } return true; } } // namespace commands } // namespace application_manager <|endoftext|>
<commit_before>/*================================================== Flexbar - flexible barcode and adapter removal Version 3.0.2 uses SeqAn library release 2.2.0 and TBB library 4.0 or later Developer: Johannes Roehr Former contributors: Matthias Dodt Benjamin Menkuec Sebastian Roskosch https://github.com/seqan/flexbar ===================================================*/ #include "Flexbar.h" int main(int argc, const char* argv[]){ using namespace std; using namespace seqan; const string version = "3.0.2"; const string date = "May 2017"; ArgumentParser parser("flexbar"); defineOptions(parser, version, date); parseCmdLine(parser, version, argc, argv); Options o; initOptions(o, parser); loadOptions(o, parser); startComputation(o); return 0; } <commit_msg>Flexbar 3.0.3 release<commit_after>/*================================================== Flexbar - flexible barcode and adapter removal Version 3.0.3 uses SeqAn library release 2.2.0 and TBB library 4.0 or later Developer: Johannes Roehr Former contributors: Matthias Dodt Benjamin Menkuec Sebastian Roskosch https://github.com/seqan/flexbar ===================================================*/ #include "Flexbar.h" int main(int argc, const char* argv[]){ using namespace std; using namespace seqan; const string version = "3.0.3"; const string date = "May 2017"; ArgumentParser parser("flexbar"); defineOptions(parser, version, date); parseCmdLine(parser, version, argc, argv); Options o; initOptions(o, parser); loadOptions(o, parser); startComputation(o); return 0; } <|endoftext|>
<commit_before>/** * \file * * \brief Implements a way to build and deal with a backend * * \copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #include <merging/threewaymerge.hpp> using namespace std; namespace kdb { namespace tools { namespace merging { /** * @brief Determines if two keys are equal based on their GetString() values. * Returns true if they are equal. False if they are not. */ bool ThreeWayMerge::keyDataEqual(const Key& k1, const Key& k2) { if (!k1 && k2) return false; if (k1 && !k2) return false; if (k1.getString () != k2.getString ()) { return false; } return true; } bool ThreeWayMerge::keyMetaEqual(Key& k1, Key& k2) { k1.rewindMeta (); Key currentMeta; while ((currentMeta = k1.nextMeta ())) { string metaName = currentMeta.getName (); if (!k2.hasMeta (metaName)) return false; if (currentMeta.getString () != k2.getMeta<std::string> (metaName)) return false; } k2.rewindMeta (); while ((currentMeta = k2.nextMeta ())) { string metaName = currentMeta.getName (); if (!k1.hasMeta (metaName)) return false; if (currentMeta.getString () != k1.getMeta<std::string> (metaName)) return false; } return true; } string ThreeWayMerge::rebasePath(const Key& key, const Key& oldParent, const Key& newParent) { string oldPath = key.getFullName (); string relativePath = oldPath.substr (oldParent.getFullName ().length (), oldPath.length ()); string newPath = newParent.getFullName () + relativePath; return newPath; } Key ThreeWayMerge::rebaseKey(const Key& key, const Key& oldParent, const Key& newParent) { Key result = key.dup (); result.setName (rebasePath (key, oldParent, newParent)); return result; } // TODO: compare metakeys void ThreeWayMerge::automaticMerge(const MergeTask& task, MergeResult& mergeResult, bool reverseConflictMeta = false) { Key our; cursor_t savedCursor = task.ours.getCursor (); task.ours.rewind (); while ((our = task.ours.next ())) { string theirLookup = rebasePath (our, task.ourParent, task.theirParent); Key theirLookupResult = task.theirs.lookup (theirLookup); Key mergeKey = rebaseKey (our, task.ourParent, task.mergeRoot); if (keyDataEqual (our, theirLookupResult)) { // keydata matches, see if metakeys match if (keyMetaEqual (our, theirLookupResult)) { mergeResult.addMergeKey (mergeKey); } else { // metakeys are different mergeResult.addConflict (mergeKey, META, META); } } else { string baseLookup = rebasePath (our, task.ourParent, task.baseParent); Key baseLookupResult = task.base.lookup (baseLookup); // check if the keys was newly added in ours if (baseLookupResult) { // the key exists in base, check if the key still exists in theirs if (theirLookupResult) { // check if only they modified it if (!keyDataEqual (our, baseLookupResult) && keyDataEqual (theirLookupResult, baseLookupResult)) { // the key was only modified in theirs, take their version mergeResult.addMergeKey (mergeKey); } else { // check if both modified it if (!keyDataEqual (our, baseLookupResult) && !keyDataEqual (theirLookupResult, baseLookupResult)) { // the key was modified on both sides mergeResult.addConflict (mergeKey, MODIFY, MODIFY); } } } else { // the key does not exist in theirs anymore, check if ours has modified it if (keyDataEqual (our, baseLookupResult)) { // the key was deleted in theirs, and not modified in ours mergeResult.removeMergeKey (mergeKey); } else { // the key was deleted in theirs, but modified in ours if (!reverseConflictMeta) mergeResult.addConflict (mergeKey, MODIFY, DELETE); else mergeResult.addConflict (mergeKey, DELETE, MODIFY); } } } else { // the key does not exist in base, check if the key was added in theirs if (theirLookupResult) { // check if the key was added with the same value in theirs if (keyDataEqual (mergeKey, theirLookupResult)) { // the key was added on both sides with the same value mergeResult.addMergeKey (mergeKey); } else { // the key was added on both sides with different values mergeResult.addConflict (mergeKey, ADD, ADD); } } else { // the key was only added to ours mergeResult.addMergeKey (mergeKey); } } } } task.ours.setCursor (savedCursor); } /** * Returns a keyset that is the result of a merge on two keysets (ours and theirs) using a base keyset as a refernece (a three-way merge). * If the merge function is unscuessful an empty KeySet will be returned. * This function is inteded as a full version for the kdb merge command or for the C++ API. * It works by taking in three keysets, their parent keys and a parent key for where to store the merged KeySet. **/ MergeResult ThreeWayMerge::mergeKeySet(const MergeTask& task) { MergeResult result; automaticMerge (task, result); automaticMerge (task.reverse (), result, true); return result; } /** * * Returns a keyset that is the result of a merge on two keysets (ours and theirs) using a base keyset as a refernece (a three-way merge). * If the merge function is unscuessful an empty KeySet will be returned. * This function is inteded as a basic version for the C++ API. It takes in three keysets and a parent key for where to store the merged keys. * It works by finidng the parent key for each keyset and then calling the more complex function above. **/ MergeResult ThreeWayMerge::mergeKeySet(const KeySet& base, const KeySet& ours, const KeySet& theirs, Key& mergeRoot) { Key ourkey = ours.head ().dup (); Key theirkey = theirs.head ().dup (); Key basekey = base.head ().dup (); MergeResult merged = mergeKeySet ( MergeTask (BaseMergeKeys (base, basekey), OurMergeKeys (ours, ourkey), TheirMergeKeys (theirs, theirkey), mergeRoot)); return merged; } } } } <commit_msg>Wrote comments for the ThreeWayMerge functions<commit_after>/** * \file * * \brief Implements a way to build and deal with a backend * * \copyright BSD License (see doc/COPYING or http://www.libelektra.org) * */ #include <merging/threewaymerge.hpp> using namespace std; namespace kdb { namespace tools { namespace merging { /** * Determines if two keys are equal based on their string value * If one of the two keys is null, false is returned * * @param k1 the first key to be compared * @param k2 the second key to be compared * @return true if both keys are not null and have an * equal string value, false otherwise */ bool ThreeWayMerge::keyDataEqual(const Key& k1, const Key& k2) { if (!k1 && k2) return false; if (k1 && !k2) return false; if (k1.getString () != k2.getString ()) { return false; } return true; } /** * Determines if two keys have equal metadata * * * @param k1 the first key whose metadata should be compared * @param k2 the second key whose metadata should be compared * @return true if the keys have equal metadata, false otherwise */ bool ThreeWayMerge::keyMetaEqual(Key& k1, Key& k2) { k1.rewindMeta (); Key currentMeta; while ((currentMeta = k1.nextMeta ())) { string metaName = currentMeta.getName (); if (!k2.hasMeta (metaName)) return false; if (currentMeta.getString () != k2.getMeta<std::string> (metaName)) return false; } k2.rewindMeta (); while ((currentMeta = k2.nextMeta ())) { string metaName = currentMeta.getName (); if (!k1.hasMeta (metaName)) return false; if (currentMeta.getString () != k1.getMeta<std::string> (metaName)) return false; } return true; } /** * Rebases the relative path of the passed key from the old parent * to the new parent and returns the new path. * * For example a key /user/example/config/key1 with the oldparent * /user/example and the new parent /user/newexample/newpath would * result in /user/newexample/newpath/config/key1 * * @param key the key whose path should be rebased * @param oldParent the old parent of the key * @param newParent the new parent of the key * @return the rebased path */ string ThreeWayMerge::rebasePath(const Key& key, const Key& oldParent, const Key& newParent) { string oldPath = key.getFullName (); string relativePath = oldPath.substr (oldParent.getFullName ().length (), oldPath.length ()); string newPath = newParent.getFullName () + relativePath; return newPath; } /** * Rebases the supplied key from the old parent to the new parent. * * @see ThreeWayMerge::rebasePath * @param key the key to be rebased * @param oldParent the old parent of the key * @param newParent the new parent of the key * @return a rebased copy of the supplied key */ Key ThreeWayMerge::rebaseKey(const Key& key, const Key& oldParent, const Key& newParent) { Key result = key.dup (); result.setName (rebasePath (key, oldParent, newParent)); return result; } // TODO: compare metakeys void ThreeWayMerge::automaticMerge(const MergeTask& task, MergeResult& mergeResult, bool reverseConflictMeta = false) { Key our; cursor_t savedCursor = task.ours.getCursor (); task.ours.rewind (); while ((our = task.ours.next ())) { string theirLookup = rebasePath (our, task.ourParent, task.theirParent); Key theirLookupResult = task.theirs.lookup (theirLookup); Key mergeKey = rebaseKey (our, task.ourParent, task.mergeRoot); if (keyDataEqual (our, theirLookupResult)) { // keydata matches, see if metakeys match if (keyMetaEqual (our, theirLookupResult)) { mergeResult.addMergeKey (mergeKey); } else { // metakeys are different mergeResult.addConflict (mergeKey, META, META); } } else { string baseLookup = rebasePath (our, task.ourParent, task.baseParent); Key baseLookupResult = task.base.lookup (baseLookup); // check if the keys was newly added in ours if (baseLookupResult) { // the key exists in base, check if the key still exists in theirs if (theirLookupResult) { // check if only they modified it if (!keyDataEqual (our, baseLookupResult) && keyDataEqual (theirLookupResult, baseLookupResult)) { // the key was only modified in theirs, take their version mergeResult.addMergeKey (mergeKey); } else { // check if both modified it if (!keyDataEqual (our, baseLookupResult) && !keyDataEqual (theirLookupResult, baseLookupResult)) { // the key was modified on both sides mergeResult.addConflict (mergeKey, MODIFY, MODIFY); } } } else { // the key does not exist in theirs anymore, check if ours has modified it if (keyDataEqual (our, baseLookupResult)) { // the key was deleted in theirs, and not modified in ours mergeResult.removeMergeKey (mergeKey); } else { // the key was deleted in theirs, but modified in ours if (!reverseConflictMeta) mergeResult.addConflict (mergeKey, MODIFY, DELETE); else mergeResult.addConflict (mergeKey, DELETE, MODIFY); } } } else { // the key does not exist in base, check if the key was added in theirs if (theirLookupResult) { // check if the key was added with the same value in theirs if (keyDataEqual (mergeKey, theirLookupResult)) { // the key was added on both sides with the same value mergeResult.addMergeKey (mergeKey); } else { // the key was added on both sides with different values mergeResult.addConflict (mergeKey, ADD, ADD); } } else { // the key was only added to ours mergeResult.addMergeKey (mergeKey); } } } } task.ours.setCursor (savedCursor); } /** * Performs a threeway merge according to the supplied MergeTask. All merged keys will * be below the given mergeParent in the MergeTask. Found conflicts will be * reported in the MergeResult. Conflicts are below the mergeParent as well and * are not part of the mergedKeys. * * @see MergeTask * @see MergeResult * * @param task a MergeTask describing the intended merge oparation * @return a MergeResult that contains the merged keys as well as all found conflicts. * **/ MergeResult ThreeWayMerge::mergeKeySet(const MergeTask& task) { MergeResult result; automaticMerge (task, result); automaticMerge (task.reverse (), result, true); return result; } /** * Performs a threeway merge based on the supplied KeySets. The result is the same * as for ThreeWayMerge::mergeKeySet(const MergeTask&). The first key (i.e. the shortest) * in each of the supplied KeySets is considered to be the corresponding parentKey. * This means that the parent key of each KeySet MUST be part of the KeySet. * * @see ThreeWayMerge::mergeKeySet(const MergeTask&) * * @param base the KeySet containing the base keys and the base parentKey * @param ours the KeySet containing our keys and our parentKey * @param theirs the KeySet containing their keys and their parentKey * @param meregRoot the parentKey for the merged keys * @return a MergeResult that contains the merged keys as well as all found conflicts. */ MergeResult ThreeWayMerge::mergeKeySet(const KeySet& base, const KeySet& ours, const KeySet& theirs, Key& mergeRoot) { Key ourkey = ours.head ().dup (); Key theirkey = theirs.head ().dup (); Key basekey = base.head ().dup (); MergeResult merged = mergeKeySet ( MergeTask (BaseMergeKeys (base, basekey), OurMergeKeys (ours, ourkey), TheirMergeKeys (theirs, theirkey), mergeRoot)); return merged; } } } } <|endoftext|>
<commit_before>#ifndef ITER_ACCUMULATE_H_ #define ITER_ACCUMULATE_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> #include <functional> #include <type_traits> namespace iter { //Forward declarations of Accumulator and accumulate template <typename Container, typename AccumulateFunc> class Accumulator; template <typename Container, typename AccumulateFunc> Accumulator<Container, AccumulateFunc> accumulate( Container&&, AccumulateFunc); template <typename T, typename AccumulateFunc> Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate( std::initializer_list<T>, AccumulateFunc); template <typename Container, typename AccumulateFunc> class Accumulator { private: Container container; AccumulateFunc accumulate_func; friend Accumulator accumulate<Container, AccumulateFunc>( Container&&, AccumulateFunc); template <typename T, typename AF> friend Accumulator<std::initializer_list<T>, AF> accumulate( std::initializer_list<T>, AF); // AccumVal must be default constructible using AccumVal = typename std::remove_reference< typename std::result_of<AccumulateFunc( iterator_deref<Container>, iterator_deref<Container>)>::type>::type; static_assert( std::is_default_constructible<AccumVal>::value, "Cannot accumulate a non-default constructible type"); Accumulator(Container&& container, AccumulateFunc accumulate_func) : container(std::forward<Container>(container)), accumulate_func(accumulate_func) { } public: class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> { private: iterator_type<Container> sub_iter; iterator_type<Container> sub_end; AccumulateFunc accumulate_func; AccumVal acc_val; public: Iterator (iterator_type<Container> iter, iterator_type<Container> end, AccumulateFunc accumulate_func) : sub_iter{iter}, sub_end{end}, accumulate_func(accumulate_func), // only get first value if not an end iterator acc_val(!(iter != end) ? AccumVal{} : *iter) { } const AccumVal& operator*() const { return this->acc_val; } Iterator& operator++() { ++this->sub_iter; if (this->sub_iter != this->sub_end) { this->acc_val = accumulate_func( this->acc_val, *this->sub_iter); } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), this->accumulate_func}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->accumulate_func}; } }; // Helper function to instantiate an Accumulator template <typename Container, typename AccumulateFunc> Accumulator<Container, AccumulateFunc> accumulate( Container&& container, AccumulateFunc accumulate_func) { return {std::forward<Container>(container), accumulate_func}; } template <typename Container> auto accumulate(Container&& container) -> decltype(accumulate(std::forward<Container>(container), std::plus<typename std::remove_reference< iterator_deref<Container>>::type>{})) { return accumulate(std::forward<Container>(container), std::plus<typename std::remove_reference< iterator_deref<Container>>::type>{}); } template <typename T, typename AccumulateFunc> Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate( std::initializer_list<T> il, AccumulateFunc accumulate_func) { return {std::move(il), accumulate_func}; } template <typename T> auto accumulate(std::initializer_list<T> il) -> decltype(accumulate(std::move(il), std::plus<T>{})) { return accumulate(std::move(il), std::plus<T>{}); } } #endif <commit_msg>uses c++14 type aliases<commit_after>#ifndef ITER_ACCUMULATE_H_ #define ITER_ACCUMULATE_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> #include <functional> #include <type_traits> namespace iter { //Forward declarations of Accumulator and accumulate template <typename Container, typename AccumulateFunc> class Accumulator; template <typename Container, typename AccumulateFunc> Accumulator<Container, AccumulateFunc> accumulate( Container&&, AccumulateFunc); template <typename T, typename AccumulateFunc> Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate( std::initializer_list<T>, AccumulateFunc); template <typename Container, typename AccumulateFunc> class Accumulator { private: Container container; AccumulateFunc accumulate_func; friend Accumulator accumulate<Container, AccumulateFunc>( Container&&, AccumulateFunc); template <typename T, typename AF> friend Accumulator<std::initializer_list<T>, AF> accumulate( std::initializer_list<T>, AF); // AccumVal must be default constructible using AccumVal = std::remove_reference_t< std::result_of_t<AccumulateFunc( iterator_deref<Container>, iterator_deref<Container>)>>; static_assert( std::is_default_constructible<AccumVal>::value, "Cannot accumulate a non-default constructible type"); Accumulator(Container&& container, AccumulateFunc accumulate_func) : container(std::forward<Container>(container)), accumulate_func(accumulate_func) { } public: class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> { private: iterator_type<Container> sub_iter; iterator_type<Container> sub_end; AccumulateFunc accumulate_func; AccumVal acc_val; public: Iterator (iterator_type<Container> iter, iterator_type<Container> end, AccumulateFunc accumulate_func) : sub_iter{iter}, sub_end{end}, accumulate_func(accumulate_func), // only get first value if not an end iterator acc_val(!(iter != end) ? AccumVal{} : *iter) { } const AccumVal& operator*() const { return this->acc_val; } Iterator& operator++() { ++this->sub_iter; if (this->sub_iter != this->sub_end) { this->acc_val = accumulate_func( this->acc_val, *this->sub_iter); } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), this->accumulate_func}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->accumulate_func}; } }; // Helper function to instantiate an Accumulator template <typename Container, typename AccumulateFunc> Accumulator<Container, AccumulateFunc> accumulate( Container&& container, AccumulateFunc accumulate_func) { return {std::forward<Container>(container), accumulate_func}; } template <typename Container> auto accumulate(Container&& container) -> decltype(accumulate(std::forward<Container>(container), std::plus<std::remove_reference_t< iterator_deref<Container>>>{})) { return accumulate(std::forward<Container>(container), std::plus<std::remove_reference_t< iterator_deref<Container>>>{}); } template <typename T, typename AccumulateFunc> Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate( std::initializer_list<T> il, AccumulateFunc accumulate_func) { return {std::move(il), accumulate_func}; } template <typename T> auto accumulate(std::initializer_list<T> il) -> decltype(accumulate(std::move(il), std::plus<T>{})) { return accumulate(std::move(il), std::plus<T>{}); } } #endif <|endoftext|>
<commit_before>#include "writer/CoutWriter.hpp" #include "fmi/ValueInfo.hpp" namespace Writer { CoutWriter::CoutWriter(const Initialization::WriterPlan & in) : IWriter(in), _lineEndingSign('\n'), _separator(',') { LOGGER_WRITE("Using CoutWriter", Util::LC_LOADER, Util::LL_INFO); } CoutWriter::~CoutWriter() { deinitialize(); } void CoutWriter::initialize() { IWriter::initialize(); if (std::cout.fail()) throw runtime_error("Cannot create and open result file."); } void CoutWriter::deinitialize() { IWriter::deinitialize(); } void CoutWriter::appendTimeHeader() { assert(isInitialized()); std::cout << "time"; } void CoutWriter::appendTime(double time) { assert(isInitialized()); std::cout << _lineEndingSign << std::endl << time; } void CoutWriter::appendHeader(const string_type& fmuName, const FMI::ValueInfo& variables) { assert(isInitialized()); for(string_type value : variables.getAllValueNames()) { Util::StringHelper::replaceAll(value, ",", "_"); std::cout << _separator << fmuName << "." << value; } } void CoutWriter::appendResults(const string_type& fmuName, const FMI::ValueCollection& values) { assert(isInitialized()); for(real_type value : values.getValues<real_type>()) std::cout << _separator << to_string(value); for(int_type value : values.getValues<int_type>()) std::cout << _separator << to_string(value); for(bool_type value : values.getValues<bool_type>()) std::cout << _separator << to_string(value); for(string_type value : values.getValues<string_type>()) std::cout << _separator << "\"" << value << "\""; } void CoutWriter::flushResults() { assert(isInitialized()); std::cout.flush(); } } /* namespace DataAccess */ <commit_msg>Cosmetic changes<commit_after>#include "writer/CoutWriter.hpp" #include "fmi/ValueInfo.hpp" namespace Writer { CoutWriter::CoutWriter(const Initialization::WriterPlan & in) : IWriter(in), _lineEndingSign('\n'), _separator(',') { LOGGER_WRITE("Using CoutWriter", Util::LC_LOADER, Util::LL_INFO); } CoutWriter::~CoutWriter() { deinitialize(); } void CoutWriter::initialize() { IWriter::initialize(); if (std::cout.fail()) throw runtime_error("Cannot create and open result file."); } void CoutWriter::deinitialize() { IWriter::deinitialize(); } void CoutWriter::appendTimeHeader() { assert(isInitialized()); std::cout << "time"; } void CoutWriter::appendTime(double time) { assert(isInitialized()); std::cout << _lineEndingSign << std::endl << time; } void CoutWriter::appendHeader(const string_type& fmuName, const FMI::ValueInfo& variables) { assert(isInitialized()); for (string_type value : variables.getAllValueNames()) { Util::StringHelper::replaceAll(value, ",", "_"); std::cout << _separator << fmuName << "." << value; } } void CoutWriter::appendResults(const string_type& fmuName, const FMI::ValueCollection& values) { assert(isInitialized()); for (real_type value : values.getValues<real_type>()) std::cout << _separator << to_string(value); for (int_type value : values.getValues<int_type>()) std::cout << _separator << to_string(value); for (bool_type value : values.getValues<bool_type>()) std::cout << _separator << to_string(value); for (string_type value : values.getValues<string_type>()) std::cout << _separator << "\"" << value << "\""; } void CoutWriter::flushResults() { assert(isInitialized()); std::cout.flush(); } } /* namespace DataAccess */ <|endoftext|>
<commit_before>/* Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "analyzer.h" #include "ir/ir.h" #include "frontends/p4/fromv1.0/v1model.h" #include "frontends/p4/typeMap.h" #include "frontends/common/resolveReferences/referenceMap.h" #include "frontends/p4/methodInstance.h" #include "frontends/p4/tableApply.h" namespace FPGA { cstring nameFromAnnotation(const IR::Annotations* annotations, cstring defaultValue) { CHECK_NULL(annotations); CHECK_NULL(defaultValue); auto anno = annotations->getSingle(IR::Annotation::nameAnnotation); if (anno != nullptr) { CHECK_NULL(anno->expr); auto str = anno->expr->to<IR::StringLiteral>(); CHECK_NULL(str); return str->value; } return defaultValue; } unsigned CFG::Node::crtId = 0; void CFG::EdgeSet::dbprint(std::ostream& out) const { for (auto s : edges) out << " " << s; } void CFG::Edge::dbprint(std::ostream& out) const { out << endpoint->name; switch (type) { case EdgeType::True: out << "(true)"; break; case EdgeType::False: out << "(false)"; break; case EdgeType::Label: out << "(" << label << ")"; break; default: break; } } void CFG::Node::dbprint(std::ostream& out) const { out << name << " =>" << successors; } void CFG::dbprint(std::ostream& out, CFG::Node* node, std::set<CFG::Node*> &done) const { if (done.find(node) != done.end()) return; for (auto p : node->predecessors.edges) dbprint(out, p->endpoint, done); out << std::endl << node; done.emplace(node); } void CFG::dbprint(std::ostream& out) const { out << "CFG for " << container; std::set<CFG::Node*> done; for (auto n : allNodes) dbprint(out, n, done); } void CFG::Node::computeSuccessors() { for (auto e : predecessors.edges) e->getNode()->successors.emplace(e->clone(this)); } namespace { // This visitor "converts" IR::Node* into EdgeSets // Since we cannot return EdgeSets, we place them in the 'after' map. class CFGBuilder : public Inspector { CFG* cfg; const CFG::EdgeSet* current; // predecessors of current node std::map<const IR::Statement*, const CFG::EdgeSet*> after; // successors of each statement const P4::ReferenceMap* refMap; const P4::TypeMap* typeMap; void setAfter(const IR::Statement* statement, const CFG::EdgeSet* value) { LOG1("After " << statement << " " << value); CHECK_NULL(statement); if (value == nullptr) { // This can happen when an error is signaled // one cause is assignmentStatement return; } after.emplace(statement, value); current = value; } const CFG::EdgeSet* get(const IR::Statement* statement) { return ::get(after, statement); } bool preorder(const IR::Statement* statement) override { //::error("%1%: not supported in control block on this architecture", statement); return false; } bool preorder(const IR::ReturnStatement* statement) override { if (current != nullptr) { cfg->exitPoint->addPredecessors(current); } setAfter(statement, new CFG::EdgeSet()); // empty successor set return false; } bool preorder(const IR::ExitStatement* statement) override { if (current != nullptr) { cfg->exitPoint->addPredecessors(current); } setAfter(statement, new CFG::EdgeSet()); // empty successor set return false; } bool preorder(const IR::EmptyStatement* statement) override { // unchanged 'current' setAfter(statement, current); return false; } bool preorder(const IR::MethodCallStatement* statement) override { auto instance = P4::MethodInstance::resolve(statement->methodCall, refMap, typeMap); if (!instance->is<P4::ApplyMethod>()) return false; auto am = instance->to<P4::ApplyMethod>(); if (!am->object->is<IR::P4Table>()) { ::error("%1%: apply method must be on a table", statement); return false; } auto tc = am->object->to<IR::P4Table>(); LOG1("table << " << tc); auto node = cfg->makeNode(tc, statement->methodCall); if (current != nullptr) { node->addPredecessors(current); } setAfter(statement, new CFG::EdgeSet(new CFG::Edge(node))); return false; } bool preorder(const IR::IfStatement* statement) override { // We only allow expressions of the form t.apply().hit currently. // If the expression is more complex it should have been // simplified by prior passes. auto tc = P4::TableApplySolver::isHit(statement->condition, refMap, typeMap); CFG::Node* node; if (tc != nullptr) { // hit-miss case. LOG1("if << " << tc); node = cfg->makeNode(tc, statement->condition); } else { node = cfg->makeNode(statement); } if (current != nullptr) { node->addPredecessors(current); } // If branch current = new CFG::EdgeSet(new CFG::Edge(node, true)); visit(statement->ifTrue); auto ifTrue = get(statement->ifTrue); if (ifTrue == nullptr) return false; auto result = new CFG::EdgeSet(ifTrue); // Else branch if (statement->ifFalse != nullptr) { current = new CFG::EdgeSet(new CFG::Edge(node, false)); visit(statement->ifFalse); auto ifFalse = get(statement->ifFalse); if (ifFalse != nullptr) { result->mergeWith(ifFalse); } } else { // no else branch result->mergeWith(new CFG::EdgeSet(new CFG::Edge(node, false))); } setAfter(statement, result); return false; } bool preorder(const IR::BlockStatement* statement) override { for (auto s : *statement->components) { // NOTE: ignore AssignmentStatement, insert it to 'after' map will // break cfg. if (s->is<IR::AssignmentStatement>()) continue; auto stat = s->to<IR::Statement>(); if (stat == nullptr) continue; visit(stat); current = get(stat); } setAfter(statement, current); return false; } bool preorder(const IR::SwitchStatement* statement) override { auto tc = P4::TableApplySolver::isActionRun(statement->expression, refMap, typeMap); BUG_CHECK(tc != nullptr, "%1%: unexpected switch statement expression", statement->expression); LOG1("switch << " << tc); auto node = cfg->makeNode(tc, statement->expression); if (current != nullptr) { node->addPredecessors(current); } auto result = new CFG::EdgeSet(new CFG::Edge(node)); // In case no label matches auto labels = new CFG::EdgeSet(); for (auto sw : statement->cases) { cstring label; if (sw->label->is<IR::DefaultExpression>()) { label = "default"; } else { auto pe = sw->label->to<IR::PathExpression>(); CHECK_NULL(pe); label = pe->path->name.name; } labels->mergeWith(new CFG::EdgeSet(new CFG::Edge(node, label))); if (sw->statement != nullptr) { current = labels; visit(sw->statement); labels = new CFG::EdgeSet(); } // else we accumulate edges if (current != nullptr) { result->mergeWith(current); } } setAfter(statement, result); return false; } public: CFGBuilder(CFG* cfg, const P4::ReferenceMap* refMap, const P4::TypeMap* typeMap) : cfg(cfg), current(nullptr), refMap(refMap), typeMap(typeMap) {} const CFG::EdgeSet* run(const IR::Statement* startNode, const CFG::EdgeSet* predecessors) { CHECK_NULL(startNode); CHECK_NULL(predecessors); current = predecessors; LOG1("start " << startNode->node_type_name()); LOG1("pred " << predecessors); startNode->apply(*this); return current; } }; } // end anonymous namespace void CFG::build(const IR::P4Control* cc, const P4::ReferenceMap* refMap, const P4::TypeMap* typeMap) { container = cc; entryPoint = makeNode("entry"); exitPoint = makeNode("exit"); CFGBuilder builder(this, refMap, typeMap); auto startValue = new CFG::EdgeSet(new CFG::Edge(entryPoint)); auto last = builder.run(cc->body, startValue); LOG1("Before exit " << last); if (last != nullptr) { // nullptr can happen when there is an error exitPoint->addPredecessors(last); computeSuccessors(); } } namespace { class DiscoverStructure : public Inspector { ProgramParts* structure; public: explicit DiscoverStructure(ProgramParts* structure) : structure(structure) {} void postorder(const IR::ParameterList* paramList) override { bool inAction = findContext<IR::P4Action>() != nullptr; unsigned index = 0; for (auto p : *paramList->getEnumerator()) { structure->index.emplace(p, index); if (!inAction) structure->nonActionParameters.emplace(p); index++; } } void postorder(const IR::P4Action* action) override { auto control = findContext<IR::P4Control>(); structure->actions.emplace(action, control); } void postorder(const IR::Declaration_Variable* decl) override { structure->variables.push_back(decl); } }; } // namespace void ProgramParts::analyze(IR::ToplevelBlock* toplevel) { DiscoverStructure disc(this); toplevel->getProgram()->apply(disc); } } // namespace FPGA <commit_msg>make sure annotated name does not have '.'<commit_after>/* Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string> #include <algorithm> #include "analyzer.h" #include "ir/ir.h" #include "frontends/p4/fromv1.0/v1model.h" #include "frontends/p4/typeMap.h" #include "frontends/common/resolveReferences/referenceMap.h" #include "frontends/p4/methodInstance.h" #include "frontends/p4/tableApply.h" namespace FPGA { cstring nameFromAnnotation(const IR::Annotations* annotations, cstring defaultValue) { CHECK_NULL(annotations); CHECK_NULL(defaultValue); auto anno = annotations->getSingle(IR::Annotation::nameAnnotation); if (anno != nullptr) { CHECK_NULL(anno->expr); auto str = anno->expr->to<IR::StringLiteral>(); CHECK_NULL(str); // NOTE: replace '.' with '_' to make bsc happy std::string name(str->value); std::replace(name.begin(), name.end(), '.', '_'); return name.c_str(); } return defaultValue; } unsigned CFG::Node::crtId = 0; void CFG::EdgeSet::dbprint(std::ostream& out) const { for (auto s : edges) out << " " << s; } void CFG::Edge::dbprint(std::ostream& out) const { out << endpoint->name; switch (type) { case EdgeType::True: out << "(true)"; break; case EdgeType::False: out << "(false)"; break; case EdgeType::Label: out << "(" << label << ")"; break; default: break; } } void CFG::Node::dbprint(std::ostream& out) const { out << name << " =>" << successors; } void CFG::dbprint(std::ostream& out, CFG::Node* node, std::set<CFG::Node*> &done) const { if (done.find(node) != done.end()) return; for (auto p : node->predecessors.edges) dbprint(out, p->endpoint, done); out << std::endl << node; done.emplace(node); } void CFG::dbprint(std::ostream& out) const { out << "CFG for " << container; std::set<CFG::Node*> done; for (auto n : allNodes) dbprint(out, n, done); } void CFG::Node::computeSuccessors() { for (auto e : predecessors.edges) e->getNode()->successors.emplace(e->clone(this)); } namespace { // This visitor "converts" IR::Node* into EdgeSets // Since we cannot return EdgeSets, we place them in the 'after' map. class CFGBuilder : public Inspector { CFG* cfg; const CFG::EdgeSet* current; // predecessors of current node std::map<const IR::Statement*, const CFG::EdgeSet*> after; // successors of each statement const P4::ReferenceMap* refMap; const P4::TypeMap* typeMap; void setAfter(const IR::Statement* statement, const CFG::EdgeSet* value) { LOG1("After " << statement << " " << value); CHECK_NULL(statement); if (value == nullptr) { // This can happen when an error is signaled // one cause is assignmentStatement return; } after.emplace(statement, value); current = value; } const CFG::EdgeSet* get(const IR::Statement* statement) { return ::get(after, statement); } bool preorder(const IR::Statement* statement) override { //::error("%1%: not supported in control block on this architecture", statement); return false; } bool preorder(const IR::ReturnStatement* statement) override { if (current != nullptr) { cfg->exitPoint->addPredecessors(current); } setAfter(statement, new CFG::EdgeSet()); // empty successor set return false; } bool preorder(const IR::ExitStatement* statement) override { if (current != nullptr) { cfg->exitPoint->addPredecessors(current); } setAfter(statement, new CFG::EdgeSet()); // empty successor set return false; } bool preorder(const IR::EmptyStatement* statement) override { // unchanged 'current' setAfter(statement, current); return false; } bool preorder(const IR::MethodCallStatement* statement) override { auto instance = P4::MethodInstance::resolve(statement->methodCall, refMap, typeMap); if (!instance->is<P4::ApplyMethod>()) return false; auto am = instance->to<P4::ApplyMethod>(); if (!am->object->is<IR::P4Table>()) { ::error("%1%: apply method must be on a table", statement); return false; } auto tc = am->object->to<IR::P4Table>(); LOG1("table << " << tc); auto node = cfg->makeNode(tc, statement->methodCall); if (current != nullptr) { node->addPredecessors(current); } setAfter(statement, new CFG::EdgeSet(new CFG::Edge(node))); return false; } bool preorder(const IR::IfStatement* statement) override { // We only allow expressions of the form t.apply().hit currently. // If the expression is more complex it should have been // simplified by prior passes. auto tc = P4::TableApplySolver::isHit(statement->condition, refMap, typeMap); CFG::Node* node; if (tc != nullptr) { // hit-miss case. LOG1("if << " << tc); node = cfg->makeNode(tc, statement->condition); } else { node = cfg->makeNode(statement); } if (current != nullptr) { node->addPredecessors(current); } // If branch current = new CFG::EdgeSet(new CFG::Edge(node, true)); visit(statement->ifTrue); auto ifTrue = get(statement->ifTrue); if (ifTrue == nullptr) return false; auto result = new CFG::EdgeSet(ifTrue); // Else branch if (statement->ifFalse != nullptr) { current = new CFG::EdgeSet(new CFG::Edge(node, false)); visit(statement->ifFalse); auto ifFalse = get(statement->ifFalse); if (ifFalse != nullptr) { result->mergeWith(ifFalse); } } else { // no else branch result->mergeWith(new CFG::EdgeSet(new CFG::Edge(node, false))); } setAfter(statement, result); return false; } bool preorder(const IR::BlockStatement* statement) override { for (auto s : *statement->components) { // NOTE: ignore AssignmentStatement, insert it to 'after' map will // break cfg. if (s->is<IR::AssignmentStatement>()) continue; auto stat = s->to<IR::Statement>(); if (stat == nullptr) continue; visit(stat); current = get(stat); } setAfter(statement, current); return false; } bool preorder(const IR::SwitchStatement* statement) override { auto tc = P4::TableApplySolver::isActionRun(statement->expression, refMap, typeMap); BUG_CHECK(tc != nullptr, "%1%: unexpected switch statement expression", statement->expression); LOG1("switch << " << tc); auto node = cfg->makeNode(tc, statement->expression); if (current != nullptr) { node->addPredecessors(current); } auto result = new CFG::EdgeSet(new CFG::Edge(node)); // In case no label matches auto labels = new CFG::EdgeSet(); for (auto sw : statement->cases) { cstring label; if (sw->label->is<IR::DefaultExpression>()) { label = "default"; } else { auto pe = sw->label->to<IR::PathExpression>(); CHECK_NULL(pe); label = pe->path->name.name; } labels->mergeWith(new CFG::EdgeSet(new CFG::Edge(node, label))); if (sw->statement != nullptr) { current = labels; visit(sw->statement); labels = new CFG::EdgeSet(); } // else we accumulate edges if (current != nullptr) { result->mergeWith(current); } } setAfter(statement, result); return false; } public: CFGBuilder(CFG* cfg, const P4::ReferenceMap* refMap, const P4::TypeMap* typeMap) : cfg(cfg), current(nullptr), refMap(refMap), typeMap(typeMap) {} const CFG::EdgeSet* run(const IR::Statement* startNode, const CFG::EdgeSet* predecessors) { CHECK_NULL(startNode); CHECK_NULL(predecessors); current = predecessors; LOG1("start " << startNode->node_type_name()); LOG1("pred " << predecessors); startNode->apply(*this); return current; } }; } // end anonymous namespace void CFG::build(const IR::P4Control* cc, const P4::ReferenceMap* refMap, const P4::TypeMap* typeMap) { container = cc; entryPoint = makeNode("entry"); exitPoint = makeNode("exit"); CFGBuilder builder(this, refMap, typeMap); auto startValue = new CFG::EdgeSet(new CFG::Edge(entryPoint)); auto last = builder.run(cc->body, startValue); LOG1("Before exit " << last); if (last != nullptr) { // nullptr can happen when there is an error exitPoint->addPredecessors(last); computeSuccessors(); } } namespace { class DiscoverStructure : public Inspector { ProgramParts* structure; public: explicit DiscoverStructure(ProgramParts* structure) : structure(structure) {} void postorder(const IR::ParameterList* paramList) override { bool inAction = findContext<IR::P4Action>() != nullptr; unsigned index = 0; for (auto p : *paramList->getEnumerator()) { structure->index.emplace(p, index); if (!inAction) structure->nonActionParameters.emplace(p); index++; } } void postorder(const IR::P4Action* action) override { auto control = findContext<IR::P4Control>(); structure->actions.emplace(action, control); } void postorder(const IR::Declaration_Variable* decl) override { structure->variables.push_back(decl); } }; } // namespace void ProgramParts::analyze(IR::ToplevelBlock* toplevel) { DiscoverStructure disc(this); toplevel->getProgram()->apply(disc); } } // namespace FPGA <|endoftext|>
<commit_before>//===-------- IncludeInserter.cpp - clang-tidy ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IncludeInserter.h" namespace clang { namespace tidy { class IncludeInserterCallback : public PPCallbacks { public: explicit IncludeInserterCallback(IncludeInserter *IncludeInserter) : IncludeInserter(IncludeInserter) {} // Implements PPCallbacks::InclusionDerective(). Records the names and source // locations of the inclusions in the main source file being processed. void InclusionDirective(SourceLocation HashLocation, const Token & /*include_token*/, StringRef FileNameRef, bool IsAngled, CharSourceRange FileNameRange, const FileEntry * /*IncludedFile*/, StringRef /*SearchPath*/, StringRef /*RelativePath*/, const Module * /*ImportedModule*/) override { IncludeInserter->AddInclude(FileNameRef, IsAngled, HashLocation, FileNameRange.getEnd()); } private: IncludeInserter *IncludeInserter; }; IncludeInserter::IncludeInserter(const SourceManager &SourceMgr, const LangOptions &LangOpts, IncludeSorter::IncludeStyle Style) : SourceMgr(SourceMgr), LangOpts(LangOpts), Style(Style) {} IncludeInserter::~IncludeInserter() {} std::unique_ptr<PPCallbacks> IncludeInserter::CreatePPCallbacks() { return llvm::make_unique<IncludeInserterCallback>(this); } llvm::Optional<FixItHint> IncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header, bool IsAngled) { // We assume the same Header will never be included both angled and not // angled. if (!InsertedHeaders.insert(std::make_pair(FileID, std::set<std::string>())) .second) { return llvm::None; } if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) { return llvm::None; } return IncludeSorterByFile[FileID]->CreateIncludeInsertion(Header, IsAngled); } void IncludeInserter::AddInclude(StringRef file_name, bool IsAngled, SourceLocation HashLocation, SourceLocation end_location) { FileID FileID = SourceMgr.getFileID(HashLocation); if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) { IncludeSorterByFile.insert(std::make_pair( FileID, llvm::make_unique<IncludeSorter>( &SourceMgr, &LangOpts, FileID, SourceMgr.getFilename(HashLocation), Style))); } IncludeSorterByFile[FileID]->AddInclude(file_name, IsAngled, HashLocation, end_location); } } // namespace tidy } // namespace clang <commit_msg>Fix shadowing of type with variable.<commit_after>//===-------- IncludeInserter.cpp - clang-tidy ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IncludeInserter.h" namespace clang { namespace tidy { class IncludeInserterCallback : public PPCallbacks { public: explicit IncludeInserterCallback(IncludeInserter *Inserter) : Inserter(Inserter) {} // Implements PPCallbacks::InclusionDerective(). Records the names and source // locations of the inclusions in the main source file being processed. void InclusionDirective(SourceLocation HashLocation, const Token & /*include_token*/, StringRef FileNameRef, bool IsAngled, CharSourceRange FileNameRange, const FileEntry * /*IncludedFile*/, StringRef /*SearchPath*/, StringRef /*RelativePath*/, const Module * /*ImportedModule*/) override { Inserter->AddInclude(FileNameRef, IsAngled, HashLocation, FileNameRange.getEnd()); } private: IncludeInserter *Inserter; }; IncludeInserter::IncludeInserter(const SourceManager &SourceMgr, const LangOptions &LangOpts, IncludeSorter::IncludeStyle Style) : SourceMgr(SourceMgr), LangOpts(LangOpts), Style(Style) {} IncludeInserter::~IncludeInserter() {} std::unique_ptr<PPCallbacks> IncludeInserter::CreatePPCallbacks() { return llvm::make_unique<IncludeInserterCallback>(this); } llvm::Optional<FixItHint> IncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header, bool IsAngled) { // We assume the same Header will never be included both angled and not // angled. if (!InsertedHeaders.insert(std::make_pair(FileID, std::set<std::string>())) .second) { return llvm::None; } if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) { return llvm::None; } return IncludeSorterByFile[FileID]->CreateIncludeInsertion(Header, IsAngled); } void IncludeInserter::AddInclude(StringRef file_name, bool IsAngled, SourceLocation HashLocation, SourceLocation end_location) { FileID FileID = SourceMgr.getFileID(HashLocation); if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) { IncludeSorterByFile.insert(std::make_pair( FileID, llvm::make_unique<IncludeSorter>( &SourceMgr, &LangOpts, FileID, SourceMgr.getFilename(HashLocation), Style))); } IncludeSorterByFile[FileID]->AddInclude(file_name, IsAngled, HashLocation, end_location); } } // namespace tidy } // namespace clang <|endoftext|>
<commit_before>/** * @author Ryan Huang <ryanhuang@cs.ucsd.edu> * @organization University of California, San Diego * * Sample test of Tachyon C/C++ APIs * */ #include "Tachyon.h" #include "Util.h" #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace tachyon; const char * program_name; const char *masterUri; const char *filePath; const char *writef = "/hello.txt"; void usage() { fprintf(stderr, "\n\tUsage: %s masterUri testFilePath\n\n", program_name); } void testGetFile(jTachyonClient client, const char *fpath) { jTachyonFile file = client->getFile(fpath); if (file == NULL) { die("fail to get tachyon file: %s", fpath); } int fid = client->getFileId(fpath); if (fid < 0) { die("fail to get file id for %s", fpath); } long size = file->length(); if (size < 0) { die("fail to get tachyon file size"); } printf("got tachyon file, size: %ld, id: %d\n", size, fid); if (file->isFile() == true) { printf("Is a regular file\n"); } else { printf("Not a regular file\n"); } char * rpath = file->getPath(); if (rpath == NULL) { die("fail to get tachyon file path"); } printf("===================================\n"); printf(" content for : %s \n", rpath); printf("===================================\n"); free(rpath); jInStream istream = file->getInStream(NO_CACHE); if (istream == NULL) { die("fail to get tachyon file instream"); } char buf[512]; int rdSz = istream->read(buf, 511); while (rdSz > 0) { if (rdSz >= 512) { printf("impossible read size\n"); break; } buf[rdSz] = '\0'; printf("%s", buf); rdSz = istream->read(buf, 511); } istream->close(); // close istream printf("\n"); printf("===================================\n"); } void testMkdir(jTachyonClient client, const char *path) { bool ok = client->mkdir(path); if (!ok) { die("fail to create tachyon dir %s", path); } printf("created tachyon dir %s\n", path); } void testCreateFile(jTachyonClient client, const char *path) { char *rpath; int fid = client->createFile(path); if (fid < 0) { die("fail to create tachyon file %s", path); } printf("created tachyon file fid:%d\n", fid); jTachyonFile nfile = client->getFile(fid); if (nfile == NULL) { die("fail to get the created file"); } rpath = nfile->getPath(); if (rpath == NULL) { die("fail to get tachyon file path"); } printf("the created tachyon file has path: %s\n", rpath); free(rpath); } void testWriteFile(jTachyonClient client, const char *path) { jTachyonFile nfile = client->getFile(path); char content[] = "hello, tachyon!!\n"; jOutStream ostream = nfile->getOutStream(MUST_CACHE); if (ostream == NULL) { die("fail to get outstream"); } ostream->write(content, strlen(content)); ostream->close(); jInStream istream = nfile->getInStream(CACHE); char buf[32]; int rdSz = istream->read(buf, 31); buf[rdSz] = '\0'; printf("Content of the created file:\n"); printf("%s\n", buf); istream->close(); // close istream } void testDeleteFile(jTachyonClient client, const char *path, bool recursive) { bool ok = client->deletePath(path, recursive); if (!ok) { die("fail to delete path %s", path); } printf("successfully deleted path %s\n", path); } int main(int argc, char*argv[]) { program_name = argv[0]; if (argc != 3) { usage(); exit(1); } masterUri = argv[1]; filePath = argv[2]; jTachyonClient client = TachyonClient::createClient(masterUri); if (client == NULL) { die("fail to create tachyon client"); } char * fullFilePath = fullTachyonPath(masterUri, filePath); testGetFile(client, fullFilePath); testCreateFile(client, writef); testWriteFile(client, writef); testDeleteFile(client, writef, false); testMkdir(client, "/kvstore"); testDeleteFile(client, "/kvstore", true); return 0; } /* vim: set ts=4 sw=4 : */ <commit_msg>release tachyon objects in test<commit_after>/** * @author Ryan Huang <ryanhuang@cs.ucsd.edu> * @organization University of California, San Diego * * Sample test of Tachyon C/C++ APIs * */ #include "Tachyon.h" #include "Util.h" #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace tachyon; const char * program_name; const char *masterUri; const char *filePath; const char *writef = "/hello.txt"; void usage() { fprintf(stderr, "\n\tUsage: %s masterUri testFilePath\n\n", program_name); } void testGetFile(jTachyonClient client, const char *fpath) { jTachyonFile nfile = client->getFile(fpath); if (nfile == NULL) { die("fail to get tachyon file: %s", fpath); } int fid = client->getFileId(fpath); if (fid < 0) { die("fail to get file id for %s", fpath); } long size = nfile->length(); if (size < 0) { die("fail to get tachyon file size"); } printf("got tachyon file, size: %ld, id: %d\n", size, fid); if (nfile->isFile() == true) { printf("Is a regular file\n"); } else { printf("Not a regular file\n"); } char * rpath = nfile->getPath(); if (rpath == NULL) { die("fail to get tachyon file path"); } printf("===================================\n"); printf(" content for : %s \n", rpath); printf("===================================\n"); free(rpath); jInStream istream = nfile->getInStream(NO_CACHE); if (istream == NULL) { die("fail to get tachyon file instream"); } char buf[512]; int rdSz = istream->read(buf, 511); while (rdSz > 0) { if (rdSz >= 512) { printf("impossible read size\n"); break; } buf[rdSz] = '\0'; printf("%s", buf); rdSz = istream->read(buf, 511); } istream->close(); // close istream printf("\n"); printf("===================================\n"); delete istream; delete nfile; } void testMkdir(jTachyonClient client, const char *path) { bool ok = client->mkdir(path); if (!ok) { die("fail to create tachyon dir %s", path); } printf("created tachyon dir %s\n", path); } void testCreateFile(jTachyonClient client, const char *path) { char *rpath; int fid = client->createFile(path); if (fid < 0) { die("fail to create tachyon file %s", path); } printf("created tachyon file fid:%d\n", fid); jTachyonFile nfile = client->getFile(fid); if (nfile == NULL) { die("fail to get the created file"); } rpath = nfile->getPath(); if (rpath == NULL) { die("fail to get tachyon file path"); } printf("the created tachyon file has path: %s\n", rpath); free(rpath); delete nfile; } void testWriteFile(jTachyonClient client, const char *path) { jTachyonFile nfile = client->getFile(path); char content[] = "hello, tachyon!!\n"; jOutStream ostream = nfile->getOutStream(MUST_CACHE); if (ostream == NULL) { die("fail to get outstream"); } ostream->write(content, strlen(content)); ostream->close(); delete ostream; // release the jobject jInStream istream = nfile->getInStream(CACHE); char buf[32]; int rdSz = istream->read(buf, 31); buf[rdSz] = '\0'; printf("Content of the created file:\n"); printf("%s\n", buf); istream->close(); // close istream delete istream; // release the jobject delete nfile; } void testDeleteFile(jTachyonClient client, const char *path, bool recursive) { bool ok = client->deletePath(path, recursive); if (!ok) { die("fail to delete path %s", path); } printf("successfully deleted path %s\n", path); } int main(int argc, char*argv[]) { program_name = argv[0]; if (argc != 3) { usage(); exit(1); } masterUri = argv[1]; filePath = argv[2]; jTachyonClient client = TachyonClient::createClient(masterUri); if (client == NULL) { die("fail to create tachyon client"); } char * fullFilePath = fullTachyonPath(masterUri, filePath); testGetFile(client, fullFilePath); testCreateFile(client, writef); testWriteFile(client, writef); testDeleteFile(client, writef, false); testMkdir(client, "/kvstore"); testDeleteFile(client, "/kvstore", true); delete client; return 0; } /* vim: set ts=4 sw=4 : */ <|endoftext|>
<commit_before>#include "Common.h" #include "Install.h" #include "PathUtil.h" // Maybe: not ideal, decouple this via SetAppDirName() instead of APP_DIR_NAME #include "ve8.h" // http://msdn.microsoft.com/en-us/library/windows/desktop/bb773569(v=vs.85).aspx // TODO: on win8 use PathCchCanonicalize or PathCchCanonicalizeEx void NormalizePathInPlace(WCHAR *src, size_t srcCchSize) { // TODO: make it work even if srcCchSize is < MAX_PATH CrashIf(srcCchSize < MAX_PATH); WCHAR buf[MAX_PATH]; BOOL ok = PathCanonicalizeW(buf, src); if (!ok) { return; } memcpy(src, buf, sizeof(buf)); } // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683197(v=vs.85).aspx static std::string GetExePath() { WCHAR buf[1024*4]; // it's full path, not name DWORD bufCchSize = dimof(buf); DWORD ret = GetModuleFileNameW(NULL, buf, bufCchSize); CrashIf(ret == 0); // on XP it returns bufCchSize if buffer too small CrashIf(ret == bufCchSize); // post XP error is indicated by GetLastError() CrashIfLastError(); NormalizePathInPlace(buf, dimof(buf)); return WstrToUtf8Str(buf); } // http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181(v=vs.85).aspx static std::string GetKnownFolderPathXp(int nFolder) { WCHAR buf[MAX_PATH]; // TODO: on Vista+ use SHGetSpecialFolderPath, SHGetFolderPath is deprecated HRESULT hr = SHGetFolderPath(NULL, nFolder, NULL, SHGFP_TYPE_DEFAULT, buf); CrashIf(hr != S_OK); return WstrToUtf8Str(buf); } // TODO: make it GetLocalAppDir(const char *add1 = NULL, const char *add2 = NULL, const char *add3 = NULL) // so that GetInstallationBaseDir() is just return GetLocalAppDir("velociraptor8") std::string GetLocalAppDir() { return GetKnownFolderPathXp(CSIDL_LOCAL_APPDATA); } std::string GetInstallationBaseDir() { auto path = GetLocalAppDir(); path::Join(path, APP_DIR_NAME); return path; } std::string GetInstallationBinDir() { auto path = GetInstallationBaseDir(); path::Join(path, "bin"); return path; } // we consider the program installed if the exe is in the installation // directory bool IsRunningInstalled() { auto exePath = GetExePath(); auto binDir = GetInstallationBinDir(); // Maybe: compare for equality? auto pos = exePath.find(binDir); return pos == 0; } bool IsRunnignPortable() { return !IsRunningInstalled(); } <commit_msg>newlines<commit_after>#include "Common.h" #include "Install.h" #include "PathUtil.h" // Maybe: not ideal, decouple this via SetAppDirName() instead of APP_DIR_NAME #include "ve8.h" // http://msdn.microsoft.com/en-us/library/windows/desktop/bb773569(v=vs.85).aspx // TODO: on win8 use PathCchCanonicalize or PathCchCanonicalizeEx void NormalizePathInPlace(WCHAR *src, size_t srcCchSize) { // TODO: make it work even if srcCchSize is < MAX_PATH CrashIf(srcCchSize < MAX_PATH); WCHAR buf[MAX_PATH]; BOOL ok = PathCanonicalizeW(buf, src); if (!ok) { return; } memcpy(src, buf, sizeof(buf)); } // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683197(v=vs.85).aspx static std::string GetExePath() { WCHAR buf[1024*4]; // it's full path, not name DWORD bufCchSize = dimof(buf); DWORD ret = GetModuleFileNameW(NULL, buf, bufCchSize); CrashIf(ret == 0); // on XP it returns bufCchSize if buffer too small CrashIf(ret == bufCchSize); // post XP error is indicated by GetLastError() CrashIfLastError(); NormalizePathInPlace(buf, dimof(buf)); return WstrToUtf8Str(buf); } // http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181(v=vs.85).aspx static std::string GetKnownFolderPathXp(int nFolder) { WCHAR buf[MAX_PATH]; // TODO: on Vista+ use SHGetSpecialFolderPath, SHGetFolderPath is deprecated HRESULT hr = SHGetFolderPath(NULL, nFolder, NULL, SHGFP_TYPE_DEFAULT, buf); CrashIf(hr != S_OK); return WstrToUtf8Str(buf); } // TODO: make it GetLocalAppDir(const char *add1 = NULL, const char *add2 = NULL, const char *add3 = NULL) // so that GetInstallationBaseDir() is just return GetLocalAppDir("velociraptor8") std::string GetLocalAppDir() { return GetKnownFolderPathXp(CSIDL_LOCAL_APPDATA); } std::string GetInstallationBaseDir() { auto path = GetLocalAppDir(); path::Join(path, APP_DIR_NAME); return path; } std::string GetInstallationBinDir() { auto path = GetInstallationBaseDir(); path::Join(path, "bin"); return path; } // we consider the program installed if the exe is in the installation // directory bool IsRunningInstalled() { auto exePath = GetExePath(); auto binDir = GetInstallationBinDir(); // Maybe: compare for equality? auto pos = exePath.find(binDir); return pos == 0; } bool IsRunnignPortable() { return !IsRunningInstalled(); } <|endoftext|>
<commit_before><commit_msg>remove unused const<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unomodel.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2001-09-13 08:24:44 $ * * 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 UNOMODEL_HXX #define UNOMODEL_HXX #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_ #include <com/sun/star/beans/XMultiPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_ #include <com/sun/star/beans/XPropertyState.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_ #include <com/sun/star/lang/XUnoTunnel.hpp> #endif #ifndef _SFX_SFXBASEMODEL_HXX_ #include <sfx2/sfxbasemodel.hxx> #endif #ifndef _COMPHELPER_PROPERTYSETHELPER_HXX_ #include <comphelper/propertysethelper.hxx> #endif class SmFormat; //----------------------------------------------------------------------------- class SmModel : public SfxBaseModel, public comphelper::PropertySetHelper, public com::sun::star::lang::XServiceInfo, public com::sun::star::lang::XUnoTunnel { protected: virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const ::com::sun::star::uno::Any* pValues ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException ); virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::uno::Any* pValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException ); public: SmModel( SfxObjectShell *pObjSh = 0 ); virtual ~SmModel() throw (); //XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL release( ) throw(::com::sun::star::uno::RuntimeException); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId(); //XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); //XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException ); virtual BOOL SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException ); inline ::rtl::OUString SmModel::getImplementationName_Static() throw( ); }; inline ::rtl::OUString SmModel::getImplementationName_Static() throw( ) { return rtl::OUString::createFromAscii("math.SmModel"); } #endif <commit_msg>#92924#: exception specifications<commit_after>/************************************************************************* * * $RCSfile: unomodel.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2001-10-18 12:10:19 $ * * 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 UNOMODEL_HXX #define UNOMODEL_HXX #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_ #include <com/sun/star/beans/XMultiPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_ #include <com/sun/star/beans/XPropertyState.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_ #include <com/sun/star/lang/XUnoTunnel.hpp> #endif #ifndef _SFX_SFXBASEMODEL_HXX_ #include <sfx2/sfxbasemodel.hxx> #endif #ifndef _COMPHELPER_PROPERTYSETHELPER_HXX_ #include <comphelper/propertysethelper.hxx> #endif class SmFormat; //----------------------------------------------------------------------------- class SmModel : public SfxBaseModel, public comphelper::PropertySetHelper, public com::sun::star::lang::XServiceInfo, public com::sun::star::lang::XUnoTunnel { protected: virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const ::com::sun::star::uno::Any* pValues ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException ); virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::uno::Any* pValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException ); public: SmModel( SfxObjectShell *pObjSh = 0 ); virtual ~SmModel() throw (); //XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( ) throw(); virtual void SAL_CALL release( ) throw(); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId(); //XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); //XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException ); virtual BOOL SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException ); inline ::rtl::OUString SmModel::getImplementationName_Static() throw( ); }; inline ::rtl::OUString SmModel::getImplementationName_Static() throw( ) { return rtl::OUString::createFromAscii("math.SmModel"); } #endif <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexBaan.cxx ** Lexer for Baan. ** Based heavily on LexCPP.cxx **/ // Copyright 2001- by Vamsi Potluru <vamsi@who.net> & Praveen Ambekar <ambekarpraveen@yahoo.com> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '$' || ch == ':'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } static void ColouriseBaanDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor"); if (initStyle == SCE_BAAN_STRINGEOL) // Does not leak onto next line initStyle = SCE_BAAN_DEFAULT; int visibleChars = 0; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.state == SCE_BAAN_OPERATOR) { sc.SetState(SCE_BAAN_DEFAULT); } else if (sc.state == SCE_BAAN_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_BAAN_DEFAULT); } } else if (sc.state == SCE_BAAN_IDENTIFIER) { if (!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_BAAN_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_BAAN_WORD2); } sc.SetState(SCE_BAAN_DEFAULT); } } else if (sc.state == SCE_BAAN_PREPROCESSOR) { if (stylingWithinPreprocessor) { if (IsASpace(sc.ch)) { sc.SetState(SCE_BAAN_DEFAULT); } } else { if (sc.atLineEnd && (sc.chNext != '^')) { sc.SetState(SCE_BAAN_DEFAULT); } } } else if (sc.state == SCE_BAAN_COMMENT) { if (sc.atLineEnd) { sc.SetState(SCE_BAAN_DEFAULT); } } else if (sc.state == SCE_BAAN_COMMENTDOC) { if (sc.MatchIgnoreCase("enddllusage")) { for (unsigned int i = 0; i < 10; i++){ sc.Forward(); } sc.ForwardSetState(SCE_BAAN_DEFAULT); } } else if (sc.state == SCE_BAAN_STRING) { if (sc.ch == '\"') { sc.ForwardSetState(SCE_BAAN_DEFAULT); } else if ((sc.atLineEnd) && (sc.chNext != '^')) { sc.ChangeState(SCE_BAAN_STRINGEOL); sc.ForwardSetState(SCE_C_DEFAULT); visibleChars = 0; } } if (sc.state == SCE_BAAN_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_BAAN_NUMBER); } else if (sc.MatchIgnoreCase("dllusage")){ sc.SetState(SCE_BAAN_COMMENTDOC); do { sc.Forward(); } while ((!sc.atLineEnd) && sc.More()); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_BAAN_IDENTIFIER); } else if (sc.Match('|')){ sc.SetState(SCE_BAAN_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_BAAN_STRING); } else if (sc.ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line sc.SetState(SCE_BAAN_PREPROCESSOR); // Skip whitespace between # and preprocessor word do { sc.Forward(); } while (IsASpace(sc.ch) && sc.More()); } else if (isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_BAAN_OPERATOR); } } if (sc.atLineEnd) { // Reset states to begining of colourise so no surprises // if different sets of lines lexed. visibleChars = 0; } if (!IsASpace(sc.ch)) { visibleChars++; } } sc.Complete(); } static void FoldBaanDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { bool foldComment = styler.GetPropertyInt("fold.comment"); bool foldCompact = styler.GetPropertyInt("fold.compact", 1); unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && (style == SCE_BAAN_COMMENT || style == SCE_BAAN_COMMENTDOC)) { if (style != stylePrev) { levelCurrent++; } else if ((style != styleNext) && !atEOL) { // Comments don't end at end of line and the next character may be unstyled. levelCurrent--; } } if (style == SCE_BAAN_OPERATOR) { if (ch == '{') { levelCurrent++; } else if (ch == '}') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmBAAN(SCLEX_BAAN, ColouriseBaanDoc, "baan", FoldBaanDoc); <commit_msg>Changed lexer name to mathc KeyWords.cxx.<commit_after>// Scintilla source code edit control /** @file LexBaan.cxx ** Lexer for Baan. ** Based heavily on LexCPP.cxx **/ // Copyright 2001- by Vamsi Potluru <vamsi@who.net> & Praveen Ambekar <ambekarpraveen@yahoo.com> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '$' || ch == ':'); } inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } static void ColouriseBaanDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor"); if (initStyle == SCE_BAAN_STRINGEOL) // Does not leak onto next line initStyle = SCE_BAAN_DEFAULT; int visibleChars = 0; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.state == SCE_BAAN_OPERATOR) { sc.SetState(SCE_BAAN_DEFAULT); } else if (sc.state == SCE_BAAN_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_BAAN_DEFAULT); } } else if (sc.state == SCE_BAAN_IDENTIFIER) { if (!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_BAAN_WORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_BAAN_WORD2); } sc.SetState(SCE_BAAN_DEFAULT); } } else if (sc.state == SCE_BAAN_PREPROCESSOR) { if (stylingWithinPreprocessor) { if (IsASpace(sc.ch)) { sc.SetState(SCE_BAAN_DEFAULT); } } else { if (sc.atLineEnd && (sc.chNext != '^')) { sc.SetState(SCE_BAAN_DEFAULT); } } } else if (sc.state == SCE_BAAN_COMMENT) { if (sc.atLineEnd) { sc.SetState(SCE_BAAN_DEFAULT); } } else if (sc.state == SCE_BAAN_COMMENTDOC) { if (sc.MatchIgnoreCase("enddllusage")) { for (unsigned int i = 0; i < 10; i++){ sc.Forward(); } sc.ForwardSetState(SCE_BAAN_DEFAULT); } } else if (sc.state == SCE_BAAN_STRING) { if (sc.ch == '\"') { sc.ForwardSetState(SCE_BAAN_DEFAULT); } else if ((sc.atLineEnd) && (sc.chNext != '^')) { sc.ChangeState(SCE_BAAN_STRINGEOL); sc.ForwardSetState(SCE_C_DEFAULT); visibleChars = 0; } } if (sc.state == SCE_BAAN_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_BAAN_NUMBER); } else if (sc.MatchIgnoreCase("dllusage")){ sc.SetState(SCE_BAAN_COMMENTDOC); do { sc.Forward(); } while ((!sc.atLineEnd) && sc.More()); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_BAAN_IDENTIFIER); } else if (sc.Match('|')){ sc.SetState(SCE_BAAN_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_BAAN_STRING); } else if (sc.ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line sc.SetState(SCE_BAAN_PREPROCESSOR); // Skip whitespace between # and preprocessor word do { sc.Forward(); } while (IsASpace(sc.ch) && sc.More()); } else if (isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_BAAN_OPERATOR); } } if (sc.atLineEnd) { // Reset states to begining of colourise so no surprises // if different sets of lines lexed. visibleChars = 0; } if (!IsASpace(sc.ch)) { visibleChars++; } } sc.Complete(); } static void FoldBaanDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { bool foldComment = styler.GetPropertyInt("fold.comment"); bool foldCompact = styler.GetPropertyInt("fold.compact", 1); unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && (style == SCE_BAAN_COMMENT || style == SCE_BAAN_COMMENTDOC)) { if (style != stylePrev) { levelCurrent++; } else if ((style != styleNext) && !atEOL) { // Comments don't end at end of line and the next character may be unstyled. levelCurrent--; } } if (style == SCE_BAAN_OPERATOR) { if (ch == '{') { levelCurrent++; } else if (ch == '}') { levelCurrent--; } } if (atEOL) { int lev = levelPrev; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmBaan(SCLEX_BAAN, ColouriseBaanDoc, "baan", FoldBaanDoc); <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexYAML.cxx ** Lexer for YAML. **/ // Copyright 2003- by Sean O'Dell <sean@celsoft.com> // Release under the same license as Scintilla/SciTE. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static const char * const yamlWordListDesc[] = { "Keywords", 0 }; static inline bool AtEOL(Accessor &styler, unsigned int i) { return (styler[i] == '\n') || ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n')); } static unsigned int SpaceCount(char* lineBuffer) { if (lineBuffer == NULL) return 0; char* headBuffer = lineBuffer; while (*headBuffer == ' ') headBuffer++; return headBuffer - lineBuffer; } #define YAML_STATE_BITSIZE 16 #define YAML_STATE_MASK (0xFFFF0000) #define YAML_STATE_DOCUMENT (1 << YAML_STATE_BITSIZE) #define YAML_STATE_VALUE (2 << YAML_STATE_BITSIZE) #define YAML_STATE_COMMENT (3 << YAML_STATE_BITSIZE) #define YAML_STATE_TEXT_PARENT (4 << YAML_STATE_BITSIZE) #define YAML_STATE_TEXT (5 << YAML_STATE_BITSIZE) static void ColouriseYAMLLine( char *lineBuffer, unsigned int currentLine, unsigned int lengthLine, unsigned int startLine, unsigned int endPos, WordList &keywords, Accessor &styler) { unsigned int i = 0; bool bInQuotes = false; unsigned int indentAmount = SpaceCount(lineBuffer); if (currentLine > 0) { int parentLineState = styler.GetLineState(currentLine - 1); if ((parentLineState&YAML_STATE_MASK) == YAML_STATE_TEXT || (parentLineState&YAML_STATE_MASK) == YAML_STATE_TEXT_PARENT) { unsigned int parentIndentAmount = parentLineState&(~YAML_STATE_MASK); if (indentAmount > parentIndentAmount) { styler.SetLineState(currentLine, YAML_STATE_TEXT | parentIndentAmount); styler.ColourTo(endPos, SCE_YAML_TEXT); return; } } } styler.SetLineState(currentLine, 0); if (strncmp(lineBuffer, "---", 3) == 0) { // Document marker styler.SetLineState(currentLine, YAML_STATE_DOCUMENT); styler.ColourTo(endPos, SCE_YAML_DOCUMENT); return; } // Skip initial spaces while ((i < lengthLine) && lineBuffer[i] == ' ') { // YAML always uses space, never TABS or anything else i++; } if (lineBuffer[i] == '\t') { // if we skipped all spaces, and we are NOT inside a text block, this is wrong styler.ColourTo(endPos, SCE_YAML_ERROR); return; } if (lineBuffer[i] == '#') { // Comment styler.SetLineState(currentLine, YAML_STATE_COMMENT); styler.ColourTo(endPos, SCE_YAML_COMMENT); return; } while (i < lengthLine) { if (lineBuffer[i] == '\'' || lineBuffer[i] == '\"') { bInQuotes = !bInQuotes; } else if (lineBuffer[i] == ':' && !bInQuotes) { styler.ColourTo(startLine + i - 1, SCE_YAML_IDENTIFIER); styler.ColourTo(startLine + i, SCE_YAML_OPERATOR); // Non-folding scalar i++; while ((i < lengthLine) && isspacechar(lineBuffer[i])) i++; unsigned int endValue = lengthLine - 1; while ((endValue >= i) && isspacechar(lineBuffer[endValue])) endValue--; lineBuffer[endValue + 1] = '\0'; if (lineBuffer[i] == '|' || lineBuffer[i] == '>') { i++; if (lineBuffer[i] == '+' || lineBuffer[i] == '-') i++; while ((i < lengthLine) && isspacechar(lineBuffer[i])) i++; if (lineBuffer[i] == '\0') { styler.SetLineState(currentLine, YAML_STATE_TEXT_PARENT | indentAmount); styler.ColourTo(endPos, SCE_YAML_DEFAULT); return; } else if (lineBuffer[i] == '#') { styler.SetLineState(currentLine, YAML_STATE_TEXT_PARENT | indentAmount); styler.ColourTo(startLine + i - 1, SCE_YAML_DEFAULT); styler.ColourTo(endPos, SCE_YAML_COMMENT); return; } else { styler.ColourTo(endPos, SCE_YAML_ERROR); return; } } else if (lineBuffer[i] == '#') { styler.ColourTo(startLine + i - 1, SCE_YAML_DEFAULT); styler.ColourTo(endPos, SCE_YAML_COMMENT); return; } styler.SetLineState(currentLine, YAML_STATE_VALUE); if (lineBuffer[i] == '&' || lineBuffer[i] == '*') { styler.ColourTo(endPos, SCE_YAML_REFERENCE); return; } if (keywords.InList(&lineBuffer[i])) { // Convertible value (true/false, etc.) styler.ColourTo(endPos, SCE_YAML_KEYWORD); return; } else { unsigned int i2 = i; while ((i < lengthLine) && lineBuffer[i]) { if (!(isascii(lineBuffer[i]) && isdigit(lineBuffer[i])) && lineBuffer[i] != '-' && lineBuffer[i] != '.' && lineBuffer[i] != ',') { styler.ColourTo(endPos, SCE_YAML_DEFAULT); return; } i++; } if (i > i2) { styler.ColourTo(endPos, SCE_YAML_NUMBER); return; } } break; // shouldn't get here, but just in case, the rest of the line is coloured the default } i++; } styler.ColourTo(endPos, SCE_YAML_DEFAULT); } static void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) { char lineBuffer[1024]; styler.StartAt(startPos); styler.StartSegment(startPos); unsigned int linePos = 0; unsigned int startLine = startPos; unsigned int endPos = startPos + length; unsigned int maxPos = styler.Length(); unsigned int lineCurrent = styler.GetLine(startPos); for (unsigned int i = startPos; i < maxPos && i < endPos; i++) { lineBuffer[linePos++] = styler[i]; if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) { // End of line (or of line buffer) met, colourise it lineBuffer[linePos] = '\0'; ColouriseYAMLLine(lineBuffer, lineCurrent, linePos, startLine, i, *keywordLists[0], styler); linePos = 0; startLine = i + 1; lineCurrent++; } } if (linePos > 0) { // Last line does not have ending characters ColouriseYAMLLine(lineBuffer, lineCurrent, linePos, startLine, startPos + length - 1, *keywordLists[0], styler); } } static bool IsCommentLine(int line, Accessor &styler) { int pos = styler.LineStart(line); if (styler[pos] == '#') return true; return false; } static void FoldYAMLDoc(unsigned int startPos, int length, int /*initStyle - unused*/, WordList *[], Accessor &styler) { const int maxPos = startPos + length; const int maxLines = styler.GetLine(maxPos - 1); // Requested last line const int docLines = styler.GetLine(styler.Length() - 1); // Available last line const bool foldComment = styler.GetPropertyInt("fold.comment.yaml") != 0; // Backtrack to previous non-blank line so we can determine indent level // for any white space lines // and so we can fix any preceding fold level (which is why we go back // at least one line in all cases) int spaceFlags = 0; int lineCurrent = styler.GetLine(startPos); int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL); while (lineCurrent > 0) { lineCurrent--; indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) && (!IsCommentLine(lineCurrent, styler))) break; } int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK; // Set up initial loop state int prevComment = 0; if (lineCurrent >= 1) prevComment = foldComment && IsCommentLine(lineCurrent - 1, styler); // Process all characters to end of requested range // or comment that hangs over the end of the range. Cap processing in all cases // to end of document (in case of unclosed comment at end). while ((lineCurrent <= docLines) && ((lineCurrent <= maxLines) || prevComment)) { // Gather info int lev = indentCurrent; int lineNext = lineCurrent + 1; int indentNext = indentCurrent; if (lineNext <= docLines) { // Information about next line is only available if not at end of document indentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL); } const int comment = foldComment && IsCommentLine(lineCurrent, styler); const int comment_start = (comment && !prevComment && (lineNext <= docLines) && IsCommentLine(lineNext, styler) && (lev > SC_FOLDLEVELBASE)); const int comment_continue = (comment && prevComment); if (!comment) indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK; if (indentNext & SC_FOLDLEVELWHITEFLAG) indentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel; if (comment_start) { // Place fold point at start of a block of comments lev |= SC_FOLDLEVELHEADERFLAG; } else if (comment_continue) { // Add level to rest of lines in the block lev = lev + 1; } // Skip past any blank lines for next indent level info; we skip also // comments (all comments, not just those starting in column 0) // which effectively folds them into surrounding code rather // than screwing up folding. while ((lineNext < docLines) && ((indentNext & SC_FOLDLEVELWHITEFLAG) || (lineNext <= docLines && IsCommentLine(lineNext, styler)))) { lineNext++; indentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL); } const int levelAfterComments = indentNext & SC_FOLDLEVELNUMBERMASK; const int levelBeforeComments = Platform::Maximum(indentCurrentLevel,levelAfterComments); // Now set all the indent levels on the lines we skipped // Do this from end to start. Once we encounter one line // which is indented more than the line after the end of // the comment-block, use the level of the block before int skipLine = lineNext; int skipLevel = levelAfterComments; while (--skipLine > lineCurrent) { int skipLineIndent = styler.IndentAmount(skipLine, &spaceFlags, NULL); if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments) skipLevel = levelBeforeComments; int whiteFlag = skipLineIndent & SC_FOLDLEVELWHITEFLAG; styler.SetLevel(skipLine, skipLevel | whiteFlag); } // Set fold header on non-comment line if (!comment && !(indentCurrent & SC_FOLDLEVELWHITEFLAG) ) { if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) lev |= SC_FOLDLEVELHEADERFLAG; } // Keep track of block comment state of previous line prevComment = comment_start || comment_continue; // Set fold level for this line and move to next line styler.SetLevel(lineCurrent, lev); indentCurrent = indentNext; lineCurrent = lineNext; } // NOTE: Cannot set level of last line here because indentCurrent doesn't have // header flag set; the loop above is crafted to take care of this case! //styler.SetLevel(lineCurrent, indentCurrent); } LexerModule lmYAML(SCLEX_YAML, ColouriseYAMLDoc, "yaml", FoldYAMLDoc, yamlWordListDesc); <commit_msg>Update from Sean O'Dell changes the license text to be the same as other code.<commit_after>// Scintilla source code edit control /** @file LexYAML.cxx ** Lexer for YAML. **/ // Copyright 2003- by Sean O'Dell <sean@celsoft.com> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static const char * const yamlWordListDesc[] = { "Keywords", 0 }; static inline bool AtEOL(Accessor &styler, unsigned int i) { return (styler[i] == '\n') || ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n')); } static unsigned int SpaceCount(char* lineBuffer) { if (lineBuffer == NULL) return 0; char* headBuffer = lineBuffer; while (*headBuffer == ' ') headBuffer++; return headBuffer - lineBuffer; } #define YAML_STATE_BITSIZE 16 #define YAML_STATE_MASK (0xFFFF0000) #define YAML_STATE_DOCUMENT (1 << YAML_STATE_BITSIZE) #define YAML_STATE_VALUE (2 << YAML_STATE_BITSIZE) #define YAML_STATE_COMMENT (3 << YAML_STATE_BITSIZE) #define YAML_STATE_TEXT_PARENT (4 << YAML_STATE_BITSIZE) #define YAML_STATE_TEXT (5 << YAML_STATE_BITSIZE) static void ColouriseYAMLLine( char *lineBuffer, unsigned int currentLine, unsigned int lengthLine, unsigned int startLine, unsigned int endPos, WordList &keywords, Accessor &styler) { unsigned int i = 0; bool bInQuotes = false; unsigned int indentAmount = SpaceCount(lineBuffer); if (currentLine > 0) { int parentLineState = styler.GetLineState(currentLine - 1); if ((parentLineState&YAML_STATE_MASK) == YAML_STATE_TEXT || (parentLineState&YAML_STATE_MASK) == YAML_STATE_TEXT_PARENT) { unsigned int parentIndentAmount = parentLineState&(~YAML_STATE_MASK); if (indentAmount > parentIndentAmount) { styler.SetLineState(currentLine, YAML_STATE_TEXT | parentIndentAmount); styler.ColourTo(endPos, SCE_YAML_TEXT); return; } } } styler.SetLineState(currentLine, 0); if (strncmp(lineBuffer, "---", 3) == 0) { // Document marker styler.SetLineState(currentLine, YAML_STATE_DOCUMENT); styler.ColourTo(endPos, SCE_YAML_DOCUMENT); return; } // Skip initial spaces while ((i < lengthLine) && lineBuffer[i] == ' ') { // YAML always uses space, never TABS or anything else i++; } if (lineBuffer[i] == '\t') { // if we skipped all spaces, and we are NOT inside a text block, this is wrong styler.ColourTo(endPos, SCE_YAML_ERROR); return; } if (lineBuffer[i] == '#') { // Comment styler.SetLineState(currentLine, YAML_STATE_COMMENT); styler.ColourTo(endPos, SCE_YAML_COMMENT); return; } while (i < lengthLine) { if (lineBuffer[i] == '\'' || lineBuffer[i] == '\"') { bInQuotes = !bInQuotes; } else if (lineBuffer[i] == ':' && !bInQuotes) { styler.ColourTo(startLine + i - 1, SCE_YAML_IDENTIFIER); styler.ColourTo(startLine + i, SCE_YAML_OPERATOR); // Non-folding scalar i++; while ((i < lengthLine) && isspacechar(lineBuffer[i])) i++; unsigned int endValue = lengthLine - 1; while ((endValue >= i) && isspacechar(lineBuffer[endValue])) endValue--; lineBuffer[endValue + 1] = '\0'; if (lineBuffer[i] == '|' || lineBuffer[i] == '>') { i++; if (lineBuffer[i] == '+' || lineBuffer[i] == '-') i++; while ((i < lengthLine) && isspacechar(lineBuffer[i])) i++; if (lineBuffer[i] == '\0') { styler.SetLineState(currentLine, YAML_STATE_TEXT_PARENT | indentAmount); styler.ColourTo(endPos, SCE_YAML_DEFAULT); return; } else if (lineBuffer[i] == '#') { styler.SetLineState(currentLine, YAML_STATE_TEXT_PARENT | indentAmount); styler.ColourTo(startLine + i - 1, SCE_YAML_DEFAULT); styler.ColourTo(endPos, SCE_YAML_COMMENT); return; } else { styler.ColourTo(endPos, SCE_YAML_ERROR); return; } } else if (lineBuffer[i] == '#') { styler.ColourTo(startLine + i - 1, SCE_YAML_DEFAULT); styler.ColourTo(endPos, SCE_YAML_COMMENT); return; } styler.SetLineState(currentLine, YAML_STATE_VALUE); if (lineBuffer[i] == '&' || lineBuffer[i] == '*') { styler.ColourTo(endPos, SCE_YAML_REFERENCE); return; } if (keywords.InList(&lineBuffer[i])) { // Convertible value (true/false, etc.) styler.ColourTo(endPos, SCE_YAML_KEYWORD); return; } else { unsigned int i2 = i; while ((i < lengthLine) && lineBuffer[i]) { if (!(isascii(lineBuffer[i]) && isdigit(lineBuffer[i])) && lineBuffer[i] != '-' && lineBuffer[i] != '.' && lineBuffer[i] != ',') { styler.ColourTo(endPos, SCE_YAML_DEFAULT); return; } i++; } if (i > i2) { styler.ColourTo(endPos, SCE_YAML_NUMBER); return; } } break; // shouldn't get here, but just in case, the rest of the line is coloured the default } i++; } styler.ColourTo(endPos, SCE_YAML_DEFAULT); } static void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) { char lineBuffer[1024]; styler.StartAt(startPos); styler.StartSegment(startPos); unsigned int linePos = 0; unsigned int startLine = startPos; unsigned int endPos = startPos + length; unsigned int maxPos = styler.Length(); unsigned int lineCurrent = styler.GetLine(startPos); for (unsigned int i = startPos; i < maxPos && i < endPos; i++) { lineBuffer[linePos++] = styler[i]; if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) { // End of line (or of line buffer) met, colourise it lineBuffer[linePos] = '\0'; ColouriseYAMLLine(lineBuffer, lineCurrent, linePos, startLine, i, *keywordLists[0], styler); linePos = 0; startLine = i + 1; lineCurrent++; } } if (linePos > 0) { // Last line does not have ending characters ColouriseYAMLLine(lineBuffer, lineCurrent, linePos, startLine, startPos + length - 1, *keywordLists[0], styler); } } static bool IsCommentLine(int line, Accessor &styler) { int pos = styler.LineStart(line); if (styler[pos] == '#') return true; return false; } static void FoldYAMLDoc(unsigned int startPos, int length, int /*initStyle - unused*/, WordList *[], Accessor &styler) { const int maxPos = startPos + length; const int maxLines = styler.GetLine(maxPos - 1); // Requested last line const int docLines = styler.GetLine(styler.Length() - 1); // Available last line const bool foldComment = styler.GetPropertyInt("fold.comment.yaml") != 0; // Backtrack to previous non-blank line so we can determine indent level // for any white space lines // and so we can fix any preceding fold level (which is why we go back // at least one line in all cases) int spaceFlags = 0; int lineCurrent = styler.GetLine(startPos); int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL); while (lineCurrent > 0) { lineCurrent--; indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) && (!IsCommentLine(lineCurrent, styler))) break; } int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK; // Set up initial loop state int prevComment = 0; if (lineCurrent >= 1) prevComment = foldComment && IsCommentLine(lineCurrent - 1, styler); // Process all characters to end of requested range // or comment that hangs over the end of the range. Cap processing in all cases // to end of document (in case of unclosed comment at end). while ((lineCurrent <= docLines) && ((lineCurrent <= maxLines) || prevComment)) { // Gather info int lev = indentCurrent; int lineNext = lineCurrent + 1; int indentNext = indentCurrent; if (lineNext <= docLines) { // Information about next line is only available if not at end of document indentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL); } const int comment = foldComment && IsCommentLine(lineCurrent, styler); const int comment_start = (comment && !prevComment && (lineNext <= docLines) && IsCommentLine(lineNext, styler) && (lev > SC_FOLDLEVELBASE)); const int comment_continue = (comment && prevComment); if (!comment) indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK; if (indentNext & SC_FOLDLEVELWHITEFLAG) indentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel; if (comment_start) { // Place fold point at start of a block of comments lev |= SC_FOLDLEVELHEADERFLAG; } else if (comment_continue) { // Add level to rest of lines in the block lev = lev + 1; } // Skip past any blank lines for next indent level info; we skip also // comments (all comments, not just those starting in column 0) // which effectively folds them into surrounding code rather // than screwing up folding. while ((lineNext < docLines) && ((indentNext & SC_FOLDLEVELWHITEFLAG) || (lineNext <= docLines && IsCommentLine(lineNext, styler)))) { lineNext++; indentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL); } const int levelAfterComments = indentNext & SC_FOLDLEVELNUMBERMASK; const int levelBeforeComments = Platform::Maximum(indentCurrentLevel,levelAfterComments); // Now set all the indent levels on the lines we skipped // Do this from end to start. Once we encounter one line // which is indented more than the line after the end of // the comment-block, use the level of the block before int skipLine = lineNext; int skipLevel = levelAfterComments; while (--skipLine > lineCurrent) { int skipLineIndent = styler.IndentAmount(skipLine, &spaceFlags, NULL); if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments) skipLevel = levelBeforeComments; int whiteFlag = skipLineIndent & SC_FOLDLEVELWHITEFLAG; styler.SetLevel(skipLine, skipLevel | whiteFlag); } // Set fold header on non-comment line if (!comment && !(indentCurrent & SC_FOLDLEVELWHITEFLAG) ) { if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) lev |= SC_FOLDLEVELHEADERFLAG; } // Keep track of block comment state of previous line prevComment = comment_start || comment_continue; // Set fold level for this line and move to next line styler.SetLevel(lineCurrent, lev); indentCurrent = indentNext; lineCurrent = lineNext; } // NOTE: Cannot set level of last line here because indentCurrent doesn't have // header flag set; the loop above is crafted to take care of this case! //styler.SetLevel(lineCurrent, indentCurrent); } LexerModule lmYAML(SCLEX_YAML, ColouriseYAMLDoc, "yaml", FoldYAMLDoc, yamlWordListDesc); <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexYAML.cxx ** Lexer for YAML. **/ // Copyright 2003- by Sean O'Dell <sean@celsoft.com> // Release under the same license as Scintilla/SciTE. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static const char * const yamlWordListDesc[] = { "Keywords", 0 }; static inline bool AtEOL(Accessor &styler, unsigned int i) { return (styler[i] == '\n') || ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n')); } static void ColouriseYAMLLine( char *lineBuffer, unsigned int lengthLine, unsigned int startLine, unsigned int endPos, WordList &keywords, Accessor &styler) { unsigned int i = 0; bool bInQuotes = false; unsigned int startValue, endValue, valueLen; char scalar[256]; if (lineBuffer[0] == '#') { // Comment styler.ColourTo(endPos, SCE_YAML_COMMENT); return; } if (strncmp(lineBuffer, "---", 3) == 0) { // Document marker styler.ColourTo(endPos, SCE_YAML_DOCUMENT); return; } // Skip initial spaces while ((i < lengthLine) && isspacechar(lineBuffer[i])) { i++; } while (i < lengthLine) { if (lineBuffer[i] == '\'' || lineBuffer[i] == '\"') { bInQuotes = !bInQuotes; } else if (lineBuffer[i] == ':' && !bInQuotes) { styler.ColourTo(startLine + i, SCE_YAML_IDENTIFIER); // Non-folding scalar startValue = i + 1; while ((startValue < lengthLine) && isspacechar(lineBuffer[startValue])) { startValue++; } endValue = lengthLine - 1; while ((endValue >= startValue) && isspacechar(lineBuffer[endValue])) { endValue--; } valueLen = endValue - startValue + 1; if (endValue < startValue || valueLen > sizeof(scalar)) { break; } strncpy(scalar, &lineBuffer[startValue], valueLen); scalar[valueLen] = '\0'; if (scalar[0] == '&' || scalar[0] == '*') { styler.ColourTo(startLine + endValue, SCE_YAML_REFERENCE); } else if (keywords.InList(scalar)) { // Convertible value (true/false, etc.) styler.ColourTo(startLine + endValue, SCE_YAML_KEYWORD); } else { startValue = 0; while (startValue < valueLen) { if (!isdigit(scalar[startValue]) && scalar[startValue] != '-' && scalar[startValue] != '.' && scalar[startValue] != ',') { break; } startValue++; } if (startValue >= valueLen) { styler.ColourTo(startLine + endValue, SCE_YAML_NUMBER); } } break; // the rest of the line is coloured the default } i++; } styler.ColourTo(endPos, SCE_YAML_DEFAULT); } static void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) { char lineBuffer[1024]; styler.StartAt(startPos); styler.StartSegment(startPos); unsigned int linePos = 0; unsigned int startLine = startPos; for (unsigned int i = startPos; i < startPos + length; i++) { lineBuffer[linePos++] = styler[i]; if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) { // End of line (or of line buffer) met, colourise it lineBuffer[linePos] = '\0'; ColouriseYAMLLine(lineBuffer, linePos, startLine, i, *keywordLists[0], styler); linePos = 0; startLine = i + 1; } } if (linePos > 0) { // Last line does not have ending characters ColouriseYAMLLine(lineBuffer, linePos, startLine, startPos + length - 1, *keywordLists[0], styler); } } static int IdentifierLevelYAMLLine( char *lineBuffer, unsigned int lengthLine) { unsigned int i = 0; bool bInQuotes = false; int level; if (lineBuffer[0] == '#') { // Comment return 0xFFFFFFFF; } if (strncmp(lineBuffer, "---", 3) == 0) { // Document marker return 0; } // Count initial spaces and '-' character while ((i < lengthLine) && (isspacechar(lineBuffer[i]) || lineBuffer[i] == '-')) { i++; } level = i; while (i < lengthLine) { if (lineBuffer[i] == '\'' || lineBuffer[i] == '\"') { bInQuotes = !bInQuotes; } else if (lineBuffer[i] == ':' && !bInQuotes) { return level; } i++; } return -level; // Scalar } static void FoldYAMLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { char lineBuffer[1024]; styler.StartAt(startPos); styler.StartSegment(startPos); unsigned int linePos = 0; int currentLevel; int lastLevel = 0xFFFFFFFF; unsigned int lineCurrent = 0; for (unsigned int i = startPos; i < startPos + length; i++) { lineBuffer[linePos++] = styler[i]; if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) { // End of line (or of line buffer) met, colourise it lineBuffer[linePos] = '\0'; currentLevel = IdentifierLevelYAMLLine(lineBuffer, linePos); if (currentLevel != static_cast<int>(0xFFFFFFFF)) { if (abs(currentLevel) > abs(lastLevel) && lastLevel >= 0) { // indented higher than last, and last was an identifier line styler.SetLevel(lineCurrent - 1, SC_FOLDLEVELHEADERFLAG); } lastLevel = currentLevel; } linePos = 0; lineCurrent++; } } if (linePos > 0) { // Last line does not have ending characters currentLevel = IdentifierLevelYAMLLine(lineBuffer, linePos); if (currentLevel != static_cast<int>(0xFFFFFFFF)) { if (abs(currentLevel) > abs(lastLevel) && lastLevel >= 0) { styler.SetLevel(lineCurrent - 1, SC_FOLDLEVELHEADERFLAG); } } } } LexerModule lmYAML(SCLEX_YAML, ColouriseYAMLDoc, "yaml", FoldYAMLDoc, yamlWordListDesc); <commit_msg>Added Platform.h as it includes compile pragmas to avoid unwanted warnings.<commit_after>// Scintilla source code edit control /** @file LexYAML.cxx ** Lexer for YAML. **/ // Copyright 2003- by Sean O'Dell <sean@celsoft.com> // Release under the same license as Scintilla/SciTE. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static const char * const yamlWordListDesc[] = { "Keywords", 0 }; static inline bool AtEOL(Accessor &styler, unsigned int i) { return (styler[i] == '\n') || ((styler[i] == '\r') && (styler.SafeGetCharAt(i + 1) != '\n')); } static void ColouriseYAMLLine( char *lineBuffer, unsigned int lengthLine, unsigned int startLine, unsigned int endPos, WordList &keywords, Accessor &styler) { unsigned int i = 0; bool bInQuotes = false; unsigned int startValue, endValue, valueLen; char scalar[256]; if (lineBuffer[0] == '#') { // Comment styler.ColourTo(endPos, SCE_YAML_COMMENT); return; } if (strncmp(lineBuffer, "---", 3) == 0) { // Document marker styler.ColourTo(endPos, SCE_YAML_DOCUMENT); return; } // Skip initial spaces while ((i < lengthLine) && isspacechar(lineBuffer[i])) { i++; } while (i < lengthLine) { if (lineBuffer[i] == '\'' || lineBuffer[i] == '\"') { bInQuotes = !bInQuotes; } else if (lineBuffer[i] == ':' && !bInQuotes) { styler.ColourTo(startLine + i, SCE_YAML_IDENTIFIER); // Non-folding scalar startValue = i + 1; while ((startValue < lengthLine) && isspacechar(lineBuffer[startValue])) { startValue++; } endValue = lengthLine - 1; while ((endValue >= startValue) && isspacechar(lineBuffer[endValue])) { endValue--; } valueLen = endValue - startValue + 1; if (endValue < startValue || valueLen > sizeof(scalar)) { break; } strncpy(scalar, &lineBuffer[startValue], valueLen); scalar[valueLen] = '\0'; if (scalar[0] == '&' || scalar[0] == '*') { styler.ColourTo(startLine + endValue, SCE_YAML_REFERENCE); } else if (keywords.InList(scalar)) { // Convertible value (true/false, etc.) styler.ColourTo(startLine + endValue, SCE_YAML_KEYWORD); } else { startValue = 0; while (startValue < valueLen) { if (!isdigit(scalar[startValue]) && scalar[startValue] != '-' && scalar[startValue] != '.' && scalar[startValue] != ',') { break; } startValue++; } if (startValue >= valueLen) { styler.ColourTo(startLine + endValue, SCE_YAML_NUMBER); } } break; // the rest of the line is coloured the default } i++; } styler.ColourTo(endPos, SCE_YAML_DEFAULT); } static void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) { char lineBuffer[1024]; styler.StartAt(startPos); styler.StartSegment(startPos); unsigned int linePos = 0; unsigned int startLine = startPos; for (unsigned int i = startPos; i < startPos + length; i++) { lineBuffer[linePos++] = styler[i]; if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) { // End of line (or of line buffer) met, colourise it lineBuffer[linePos] = '\0'; ColouriseYAMLLine(lineBuffer, linePos, startLine, i, *keywordLists[0], styler); linePos = 0; startLine = i + 1; } } if (linePos > 0) { // Last line does not have ending characters ColouriseYAMLLine(lineBuffer, linePos, startLine, startPos + length - 1, *keywordLists[0], styler); } } static int IdentifierLevelYAMLLine( char *lineBuffer, unsigned int lengthLine) { unsigned int i = 0; bool bInQuotes = false; int level; if (lineBuffer[0] == '#') { // Comment return 0xFFFFFFFF; } if (strncmp(lineBuffer, "---", 3) == 0) { // Document marker return 0; } // Count initial spaces and '-' character while ((i < lengthLine) && (isspacechar(lineBuffer[i]) || lineBuffer[i] == '-')) { i++; } level = i; while (i < lengthLine) { if (lineBuffer[i] == '\'' || lineBuffer[i] == '\"') { bInQuotes = !bInQuotes; } else if (lineBuffer[i] == ':' && !bInQuotes) { return level; } i++; } return -level; // Scalar } static void FoldYAMLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { char lineBuffer[1024]; styler.StartAt(startPos); styler.StartSegment(startPos); unsigned int linePos = 0; int currentLevel; int lastLevel = 0xFFFFFFFF; unsigned int lineCurrent = 0; for (unsigned int i = startPos; i < startPos + length; i++) { lineBuffer[linePos++] = styler[i]; if (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) { // End of line (or of line buffer) met, colourise it lineBuffer[linePos] = '\0'; currentLevel = IdentifierLevelYAMLLine(lineBuffer, linePos); if (currentLevel != static_cast<int>(0xFFFFFFFF)) { if (abs(currentLevel) > abs(lastLevel) && lastLevel >= 0) { // indented higher than last, and last was an identifier line styler.SetLevel(lineCurrent - 1, SC_FOLDLEVELHEADERFLAG); } lastLevel = currentLevel; } linePos = 0; lineCurrent++; } } if (linePos > 0) { // Last line does not have ending characters currentLevel = IdentifierLevelYAMLLine(lineBuffer, linePos); if (currentLevel != static_cast<int>(0xFFFFFFFF)) { if (abs(currentLevel) > abs(lastLevel) && lastLevel >= 0) { styler.SetLevel(lineCurrent - 1, SC_FOLDLEVELHEADERFLAG); } } } } LexerModule lmYAML(SCLEX_YAML, ColouriseYAMLDoc, "yaml", FoldYAMLDoc, yamlWordListDesc); <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * Copyright (C) 2020 The Symbiflow Authors * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "kernel/register.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN void register_in_tcl_interpreter(const std::string& command) { Tcl_Interp* interp = yosys_get_tcl_interp(); std::string tcl_script = stringf("proc %s args { return [yosys %s {*}$args] }", command.c_str(), command.c_str()); Tcl_Eval(interp, tcl_script.c_str()); } struct GetParam : public Pass { GetParam() : Pass("getparam", "get parameter on object") { register_in_tcl_interpreter(pass_name); } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" getparam name selection\n"); log("\n"); log("Get the given parameter on the selected object. \n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design* design) override { if (args.size() == 1) { log_error("Incorrect number of arguments"); } std::string param(args.at(1)); std::string value; extra_args(args, 2, design); for (auto module : design->selected_modules()) { for (auto cell : module->selected_cells()) { auto params = cell->parameters; auto it = params.find(RTLIL::IdString(RTLIL::escape_id(param))); if (it != params.end()) { auto param_obj = it->second; if (param_obj.flags & RTLIL::CONST_FLAG_STRING) { value = param_obj.decode_string(); } else { value = std::to_string(param_obj.as_int()); } } } } char* tcl_param = Tcl_Alloc(value.size() + 1); strcpy(tcl_param, value.c_str()); Tcl_Interp *interp = yosys_get_tcl_interp(); Tcl_SetResult(interp, tcl_param, TCL_DYNAMIC); } } GetParam; PRIVATE_NAMESPACE_END <commit_msg>Params plugin: Move IdString outside of loop<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * Copyright (C) 2020 The Symbiflow Authors * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "kernel/register.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN void register_in_tcl_interpreter(const std::string& command) { Tcl_Interp* interp = yosys_get_tcl_interp(); std::string tcl_script = stringf("proc %s args { return [yosys %s {*}$args] }", command.c_str(), command.c_str()); Tcl_Eval(interp, tcl_script.c_str()); } struct GetParam : public Pass { GetParam() : Pass("getparam", "get parameter on object") { register_in_tcl_interpreter(pass_name); } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" getparam name selection\n"); log("\n"); log("Get the given parameter on the selected object. \n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design* design) override { if (args.size() == 1) { log_error("Incorrect number of arguments"); } auto param = RTLIL::IdString(RTLIL::escape_id(args.at(1))); std::string value; extra_args(args, 2, design); for (auto module : design->selected_modules()) { for (auto cell : module->selected_cells()) { auto params = cell->parameters; auto it = params.find(param); if (it != params.end()) { auto param_obj = it->second; if (param_obj.flags & RTLIL::CONST_FLAG_STRING) { value = param_obj.decode_string(); } else { value = std::to_string(param_obj.as_int()); } } } } char* tcl_param = Tcl_Alloc(value.size() + 1); strcpy(tcl_param, value.c_str()); Tcl_Interp *interp = yosys_get_tcl_interp(); Tcl_SetResult(interp, tcl_param, TCL_DYNAMIC); } } GetParam; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>#include <pybind11/pybind11.h> namespace MetaOpt { namespace Python { namespace py = pybind11; void init_swarm(py::module &m); void init_functions(py::module &m); PYBIND11_PLUGIN(pymetaopt) { py::module m("pymetaopt", "Meta optimization library"); init_swarm(m); init_functions(m); return m.ptr(); } } } <commit_msg>Update python lib name<commit_after>#include <pybind11/pybind11.h> namespace MetaOpt { namespace Python { namespace py = pybind11; void init_swarm(py::module &m); void init_functions(py::module &m); PYBIND11_PLUGIN(pyoptima) { py::module m("pyoptima", "Meta heuristic optimization library"); init_swarm(m); init_functions(m); return m.ptr(); } } } <|endoftext|>
<commit_before>#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("Bitcoin will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your bitcoins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); } <commit_msg>qt: Improve capslock detection on non-us keyboards (issue #1855)<commit_after>#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("Bitcoin will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your bitcoins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); } <|endoftext|>
<commit_before> // Copyright (c) 2008-2009, Regents of the University of Colorado. // This work was supported by NASA contracts NNJ05HE10G, NNC06CB40C, and // NNC07CB47C. #include "node.h" Node::Node(QString name, QWidget* parent) : QWidget(parent) { this->name = name; QRegExp streamRX(".*\\..*\\..*\\:.*"); // matches *.*.*:* QRegExp nodeRX(".*\\..*\\..*"); // matches *.*.* QRegExp habRX(".*\\..*"); // matches *.* if ( streamRX.exactMatch(name) ) { id = name.section('.', 2, 2).section(':', 1, 1); bionetType = STREAM; bionet_stream_t* stream = bionet_cache_lookup_stream( qPrintable(name.section('.', 0, 0)), qPrintable(name.section('.', 1, 1)), qPrintable(name.section('.', 2, 2).section(':', 0, 0)), qPrintable(id)); if (bionet_stream_get_direction(stream) == BIONET_STREAM_DIRECTION_CONSUMER) endpointType = CONSUMER; else if (bionet_stream_get_direction(stream) == BIONET_STREAM_DIRECTION_PRODUCER) endpointType = PRODUCER; else endpointType = NEITHER; bionetPtr = (void*)stream; } else if ( nodeRX.exactMatch(name) ) { bionet_node_t* node = bionet_cache_lookup_node( qPrintable(name.section('.', 0, 0)), qPrintable(name.section('.', 1, 1)), qPrintable(name.section('.', 2, 2))); bionetPtr = (void*)node; id = name.section('.',2,2); bionetType = NODE; endpointType = NEITHER; } else if ( habRX.exactMatch(name) ) { bionet_hab_t* hab = bionet_cache_lookup_hab( qPrintable(name.section('.', 0, 0)), qPrintable(name.section('.', 1, 1))); bionetPtr = (void*)hab; id = name; bionetType = HAB; endpointType = NEITHER; } else if ( name.isEmpty() ) { id = QString(); bionetType = ROOT; endpointType = NEITHER; } children = new QList<Node*>; /* path = new QPainterPath(QPoint(0,0)); path->addEllipse(area); path->addText(area, Qt::AlignHCenter, Qt::AlignVCenter, id); */ } Node::~Node() { while ( !children->isEmpty() ) { Node* child = children->takeFirst(); delete child; } delete children; } void Node::addChild(Node* child) { children->append(child); } void Node::addChildWithoutArea(Node* child) { children->append(child); } bool Node::removeChild(QString id) { int size = children->size(); for (int i = 0; i < size; i++ ) { Node* child = children->at(i); if (child->getId() == id) { Node* child = children->takeAt(i); delete child; return true; } } return false; } Node* Node::find(QString fullname) { if (this->name == fullname) return this; foreach (Node* node, *children) { Node* leaf = node->find(fullname); if (leaf != NULL) return leaf; } return NULL; } Node* Node::find(QPoint point) { if (area.contains(point)) return this; foreach (Node* node, *children) { Node *leaf = node->find(point); if (leaf != NULL) return leaf; } return NULL; } Node* Node::find(QRect rect) { if (area.intersects(rect)) return this; foreach (Node* node, *children) { Node *leaf = node->find(rect); if (leaf != NULL) return leaf; } return NULL; } void Node::setArea(QRect newArea) { this->area = newArea; //cout << "this->area = " << area.x() << ", " << area.y() << endl; } <commit_msg>fixing 3 possible uninitialized variables<commit_after> // Copyright (c) 2008-2009, Regents of the University of Colorado. // This work was supported by NASA contracts NNJ05HE10G, NNC06CB40C, and // NNC07CB47C. #include "node.h" Node::Node(QString name, QWidget* parent) : QWidget(parent) { this->name = name; QRegExp streamRX(".*\\..*\\..*\\:.*"); // matches *.*.*:* QRegExp nodeRX(".*\\..*\\..*"); // matches *.*.* QRegExp habRX(".*\\..*"); // matches *.* bionetPtr = NULL; bionetType = ROOT; endpointType = NEITHER; if ( streamRX.exactMatch(name) ) { id = name.section('.', 2, 2).section(':', 1, 1); bionetType = STREAM; bionet_stream_t* stream = bionet_cache_lookup_stream( qPrintable(name.section('.', 0, 0)), qPrintable(name.section('.', 1, 1)), qPrintable(name.section('.', 2, 2).section(':', 0, 0)), qPrintable(id)); if (bionet_stream_get_direction(stream) == BIONET_STREAM_DIRECTION_CONSUMER) endpointType = CONSUMER; else if (bionet_stream_get_direction(stream) == BIONET_STREAM_DIRECTION_PRODUCER) endpointType = PRODUCER; else endpointType = NEITHER; bionetPtr = (void*)stream; } else if ( nodeRX.exactMatch(name) ) { bionet_node_t* node = bionet_cache_lookup_node( qPrintable(name.section('.', 0, 0)), qPrintable(name.section('.', 1, 1)), qPrintable(name.section('.', 2, 2))); bionetPtr = (void*)node; id = name.section('.',2,2); bionetType = NODE; endpointType = NEITHER; } else if ( habRX.exactMatch(name) ) { bionet_hab_t* hab = bionet_cache_lookup_hab( qPrintable(name.section('.', 0, 0)), qPrintable(name.section('.', 1, 1))); bionetPtr = (void*)hab; id = name; bionetType = HAB; endpointType = NEITHER; } else if ( name.isEmpty() ) { id = QString(); bionetType = ROOT; endpointType = NEITHER; } children = new QList<Node*>; /* path = new QPainterPath(QPoint(0,0)); path->addEllipse(area); path->addText(area, Qt::AlignHCenter, Qt::AlignVCenter, id); */ } Node::~Node() { while ( !children->isEmpty() ) { Node* child = children->takeFirst(); delete child; } delete children; } void Node::addChild(Node* child) { children->append(child); } void Node::addChildWithoutArea(Node* child) { children->append(child); } bool Node::removeChild(QString id) { int size = children->size(); for (int i = 0; i < size; i++ ) { Node* child = children->at(i); if (child->getId() == id) { Node* child = children->takeAt(i); delete child; return true; } } return false; } Node* Node::find(QString fullname) { if (this->name == fullname) return this; foreach (Node* node, *children) { Node* leaf = node->find(fullname); if (leaf != NULL) return leaf; } return NULL; } Node* Node::find(QPoint point) { if (area.contains(point)) return this; foreach (Node* node, *children) { Node *leaf = node->find(point); if (leaf != NULL) return leaf; } return NULL; } Node* Node::find(QRect rect) { if (area.intersects(rect)) return this; foreach (Node* node, *children) { Node *leaf = node->find(rect); if (leaf != NULL) return leaf; } return NULL; } void Node::setArea(QRect newArea) { this->area = newArea; //cout << "this->area = " << area.x() << ", " << area.y() << endl; } <|endoftext|>
<commit_before>#include "recvfileprogressdialog.h" #include <QStringList> #include <QMessageBox> #include <QFileDialog> #include <QTimer> #include "constants.h" /** * Returns a list of requested files */ QList<RecvFileInfo> RecvFileProgressDialog::parsePayloadFileList(QByteArray payload) { QList<RecvFileInfo> recvFiles; QList<QByteArray> headers = payload.split(QOM_FILELIST_SEPARATOR); foreach(QByteArray header, headers) { RecvFileInfo info; QList<QByteArray> tokens = header.split(':'); qDebug() << "Tokens:" << tokens; if(tokens.size() < 5) continue; info.fileID = tokens[0].toInt(); info.fileName = tokens[1]; info.size = tokens[2].toInt(0, 16); info.mtime = tokens[3].toInt(0, 16); info.type = tokens[4].toInt(0, 16); qDebug() << "Parsed ID:"<<info.fileID<<"name:"<<info.fileName<<"size:"<<info.size<<"mtime"<<info.mtime<<"type:"<<info.type; //NOTE: additional tokens can be parsed here if required recvFiles << info ; } return recvFiles; } void RecvFileProgressDialog::error(QAbstractSocket::SocketError e) { qDebug() << "Socket error:" << e << m_socket->errorString(); reject(); } void RecvFileProgressDialog::accept() { qDebug() << "$$$$$ Socket disconnected"; QProgressDialog::accept(); } void RecvFileProgressDialog::startReceiving() { m_socket = new QTcpSocket(this); m_socket->abort(); m_socket->connectToHost(m_msg.sender()->addressString(), UDP_PORT); connect(m_socket, SIGNAL(readyRead()), this, SLOT(readRequest())); connect(m_socket, SIGNAL(connected()), this, SLOT(requestFiles())); connect(m_socket, SIGNAL(disconnected()), this, SLOT(accept())); connect(m_socket, SIGNAL(disconnected()), m_socket, SLOT(deleteLater())); connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError))); } void RecvFileProgressDialog::requestFiles() { while(!m_fileHeaders.isEmpty()) { if(m_waitingForData > 0) { qDebug() << "Waiting for"<< m_waitingForData; QTimer::singleShot(1000, this, SLOT(requestFiles())); break; } startReceiving(); RecvFileInfo info = m_fileHeaders.takeFirst(); m_requestType = info.type; QByteArray payload = QByteArray::number(m_msg.packetNo(), 16); payload += ":"; payload += QByteArray::number(info.fileID, 16); qDebug() << "Writing request for file data"<<info.fileName << "id" << info.fileID; QString path = m_saveDir + QDir::separator() + info.fileName; //TODO: fix offset call if(m_requestType == QOM_FILE_REGULAR) { m_currentSize = info.size; m_waitingForData = info.size; if(!openFile(path)) continue; payload += ":0"; writeBlock(messenger()->makeMessage(QOM_GETFILEDATA, payload).toAscii()); } else if(m_requestType == QOM_FILE_DIR) { writeBlock(messenger()->makeMessage(QOM_GETDIRFILES, payload).toAscii()); } } } void RecvFileProgressDialog::informUser() { QString message(m_msg.sender()->name()); message.append(tr(" has sent the following files\n\n")); qint64 totalSize = 0; foreach(RecvFileInfo info, m_fileHeaders) { message.append(info.fileName); message.append(" ("); if(info.type == QOM_FILE_REGULAR) { message.append(QString::number(info.size)); totalSize += info.size; message.append(" bytes)\n"); } else if(info.type == QOM_FILE_DIR) { message.append("Directory, unknown size)\n"); } } message.append(tr("\nTotal Size: ")); if(totalSize > 1024*1024) { message.append(QString::number(totalSize / (1024*1024) )); message.append("Mb"); } else if( totalSize > 1024 ) { message.append(QString::number(totalSize / 1024)); message.append("Kb"); } else { message.append(QString::number(totalSize)); message.append("bytes"); } QString msg = m_msg.payload().left(m_msg.payload().indexOf("\a")); if(!msg.isEmpty()) message.append("\n\nMessage: " + msg); message.append(tr("\n\nDo you want to accept the files?")); if(QMessageBox::No == QMessageBox::question(NULL, tr("Receiving files"), message, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)) // last is default button reject(); else m_saveDir = QFileDialog::getExistingDirectory(this, tr("Save To")); if(!m_saveDir.isEmpty()) { qDebug() << m_saveDir; } } // TODO: share with sending dialog? bool RecvFileProgressDialog::writeBlock(QByteArray b) { int bytesToWrite = b.size(); int bytesWritten = 0; do { qDebug() << "Writing" << b << "to socket"; bytesWritten = m_socket->write(b); if(bytesWritten == -1) return false; b.remove(0, bytesWritten); bytesToWrite -= bytesWritten; } while(bytesToWrite > 0); return true; } /** * Instead of actually reading the data * it notifies seperate functions depending * on what we are reading, which read as required */ void RecvFileProgressDialog::readRequest() { // QByteArray data; // while(m_socket->bytesAvailable()) // { // data += m_socket->read(1024); // //qDebug() << "Reading"; // } // qDebug() << ":: readRequest data size" << data.size(); // qDebug() << data << "\n\n"; if(m_requestType == QOM_FILE_REGULAR) requestWriteToFile(); else if(m_requestType == QOM_FILE_DIR) requestWriteToDirectory(); } void RecvFileProgressDialog::requestWriteToFile() { QByteArray data = m_socket->readAll(); writeToFile(data); } /** * Attempts to read headers individually * and then read the file as required */ void RecvFileProgressDialog::requestWriteToDirectory() { while(m_socket->bytesAvailable()) { if(m_inHeader) { m_header += m_socket->read(1); //qDebug() << m_header; QByteArray drop; // TODO: ideally not required RecvFileInfo info = parseDirectoryHeader(m_header, &drop); if(info.fileID >= 0) { qDebug() << "# Header parsed successfully"; qDebug() << info.fileName << info.size << info.type; // we got a valid header, process it m_inHeader = false; m_header.clear(); if(info.type == QOM_FILE_REGULAR) { qDebug() << "Now writing new file" << info.fileName; if(!openFile(m_dir->absoluteFilePath(info.fileName))) return ; m_waitingForData = info.size; m_currentSize = info.size; } else if(info.type == QOM_FILE_DIR) { qDebug() << "Creating directory" << info.fileName; bool made = false; if(m_dir == NULL) made = makeDirectory(m_saveDir + QDir::separator() + info.fileName); else made = makeDirectory(m_dir->absoluteFilePath(info.fileName)); if(!made) return; m_inHeader = true; continue; } else if(info.type == QOM_FILE_RETPARENT) { qDebug() << "Going up"; m_dir->cdUp(); if(m_dir->absolutePath() == m_saveDir) accept(); m_inHeader = true; continue; } else { QMessageBox::critical(this, tr("Receive failed"), tr("Bad header! Could not understand file type %1").arg(info.type)); reject(); } } } // write to file whatever we get if(!m_inHeader) { QByteArray fileData = m_socket->read(m_waitingForData); writeToFile(fileData); if(m_waitingForData == 0) { m_inHeader = true; } } } } bool RecvFileProgressDialog::openFile(const QString& fileName) { m_currentFile = new QFile(fileName); if(m_currentFile->exists()) { if(QMessageBox::No == QMessageBox::question(this, tr("Replace file"), tr("File %1 exists, overwrite?").arg(fileName), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)) { m_waitingForData = 0; return false; } } if(!m_currentFile->open(QIODevice::Truncate | QIODevice::WriteOnly)) { qWarning() << "Cannot open" << fileName << "for writing"; m_currentFile->close(); m_waitingForData = 0; return false; } qDebug() << fileName << "Opened with truncate"; return true; } /* * TODO: i know, the remainder thing is a bad hack. */ bool RecvFileProgressDialog::writeToFile(QByteArray& b, QByteArray* remainder) { if(m_currentFile == NULL) return false; while(b.size() > 0) { if(m_waitingForData < b.size()) { qDebug() << "Excess data, setting remainder"; if(remainder != NULL) { *remainder = b.right(b.size() - m_waitingForData); } b = b.left(m_waitingForData); } int written = m_currentFile->write(b); //qDebug() << "Wrote" << written << "bytes to" << m_currentFile->fileName(); if(written == -1) { qWarning() << "Write error" << m_currentFile->errorString(); m_currentFile->close(); return false; } m_waitingForData -= written; qDebug() << "Wrote" << written << "bytes" << "Left" << m_waitingForData; b.remove(0, written); } setLabelText(tr("Receiving %1").arg(m_currentFile->fileName())); setValue((float)(m_currentSize-m_waitingForData)/m_currentSize * 100.0); if(m_waitingForData <= 0) { qDebug() << "Finished writing" << m_currentFile->fileName(); m_currentFile->close(); } return true; } bool RecvFileProgressDialog::makeDirectory(const QString& path) { qDebug() << "makeDirectory" << path; if(m_dir != NULL) { delete m_dir; m_dir = NULL; } m_dir = new QDir(path); if(!m_dir->exists() && !m_dir->mkdir(path)) { // TODO: convert to QMessageBox qWarning() << "Could not create directory" << m_dir->absolutePath() ; return false; } return true; } bool RecvFileProgressDialog::writeToDirectory(QByteArray& b) { m_header += b; //qDebug() << "At the beginning of writeToDirectory" << m_header; QByteArray leftover; RecvFileInfo info = parseDirectoryHeader(m_header, &leftover); if(m_waitingForData != 0 && m_header.isEmpty()) { qDebug() << "Need to flush"; exit(5); } //info is filled, only leftover is valuable if(info.fileID >= 0) { m_inHeader = false; m_header = leftover; //qDebug() << "! Leftover" << leftover; if(info.type == QOM_FILE_REGULAR) { qDebug() << "Now writing new file" << info.fileName; if(!openFile(m_dir->absoluteFilePath(info.fileName))) return false; m_waitingForData = info.size; m_currentSize = info.size; QByteArray moreLeftover; // leftover can't immediately have another header // any headers it has now are in moreLeftover if(!writeToFile(leftover, &moreLeftover)) return false; //qDebug() << "!moreLeftover" << moreLeftover; qDebug() << "line 306:" << m_waitingForData; if(m_waitingForData == 0) { m_inHeader = true; m_header = moreLeftover; } else { m_inHeader = false; m_header.clear(); } } else if(info.type == QOM_FILE_DIR) { qDebug() << "Creating new directory" << info.fileName; bool made = false; if(m_dir == NULL) made = makeDirectory(m_saveDir + QDir::separator() + info.fileName); else made = makeDirectory(m_dir->absoluteFilePath(info.fileName)); if(!made) return false; m_inHeader = true; //m_header.clear(); } else if(info.type == QOM_FILE_RETPARENT) { qDebug() << "Going up"; m_dir->cdUp(); m_inHeader = true; } //qDebug() << "After all processing of header, in header?" << m_inHeader<<"\n"; } if(!m_inHeader) { qDebug() << "> In file"; QByteArray leftover; writeToFile(m_header, &leftover); qDebug() << "line 337:" << m_waitingForData ; if(m_waitingForData == 0) { m_header = leftover; m_inHeader = true; } else { m_header.clear(); m_inHeader = false; } } qDebug() << " << Returning from writeToDirectory"; return true; } /** * Tries to parse a header if it can * if it can, fills in RecvFileInfo correctly * Otherwise sets RecvFileInfo.fileID to -1, other fields are kept default * If any data is left over after parsing header, it is stored in remainder. */ RecvFileInfo RecvFileProgressDialog::parseDirectoryHeader(const QByteArray& a, QByteArray* remainder) { bool bad = false; RecvFileInfo ret; if(a.contains(":")) { QList<QByteArray> tokens = a.split(':'); int headerSize = tokens[0].toInt(0, 16); //qDebug() << "Header size:"<<headerSize; if( headerSize == 0 ) //bad data, perhaps binary bad = true; else if(a.size() < headerSize || tokens.size() < 4) { //qDebug() << "not enough data" << tokens << "expected" << tokens[0].size(); bad = true; } else { //qDebug() << "Header list" << tokens; ret.fileID = 0; ret.fileName = tokens[1]; ret.size = tokens[2].toLongLong(0, 16); ret.type = tokens[3].toInt(0, 16); *remainder = a.right(a.size() - headerSize); } } else bad = true; if(bad) { ret.fileID = -1; } return ret; }<commit_msg>toLongLong to accomodate large files<commit_after>#include "recvfileprogressdialog.h" #include <QStringList> #include <QMessageBox> #include <QFileDialog> #include <QTimer> #include "constants.h" /** * Returns a list of requested files */ QList<RecvFileInfo> RecvFileProgressDialog::parsePayloadFileList(QByteArray payload) { QList<RecvFileInfo> recvFiles; QList<QByteArray> headers = payload.split(QOM_FILELIST_SEPARATOR); foreach(QByteArray header, headers) { RecvFileInfo info; QList<QByteArray> tokens = header.split(':'); qDebug() << "Tokens:" << tokens; if(tokens.size() < 5) continue; info.fileID = tokens[0].toInt(); info.fileName = tokens[1]; info.size = tokens[2].toLongLong(0, 16); info.mtime = tokens[3].toInt(0, 16); info.type = tokens[4].toInt(0, 16); qDebug() << "Parsed ID:"<<info.fileID<<"name:"<<info.fileName<<"size:"<<info.size<<"mtime"<<info.mtime<<"type:"<<info.type; //NOTE: additional tokens can be parsed here if required recvFiles << info ; } return recvFiles; } void RecvFileProgressDialog::error(QAbstractSocket::SocketError e) { qDebug() << "Socket error:" << e << m_socket->errorString(); reject(); } void RecvFileProgressDialog::accept() { qDebug() << "$$$$$ Socket disconnected"; QProgressDialog::accept(); } void RecvFileProgressDialog::startReceiving() { m_socket = new QTcpSocket(this); m_socket->abort(); m_socket->connectToHost(m_msg.sender()->addressString(), UDP_PORT); connect(m_socket, SIGNAL(readyRead()), this, SLOT(readRequest())); connect(m_socket, SIGNAL(connected()), this, SLOT(requestFiles())); connect(m_socket, SIGNAL(disconnected()), this, SLOT(accept())); connect(m_socket, SIGNAL(disconnected()), m_socket, SLOT(deleteLater())); connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError))); } void RecvFileProgressDialog::requestFiles() { while(!m_fileHeaders.isEmpty()) { if(m_waitingForData > 0) { qDebug() << "Waiting for"<< m_waitingForData; QTimer::singleShot(1000, this, SLOT(requestFiles())); break; } startReceiving(); RecvFileInfo info = m_fileHeaders.takeFirst(); m_requestType = info.type; QByteArray payload = QByteArray::number(m_msg.packetNo(), 16); payload += ":"; payload += QByteArray::number(info.fileID, 16); qDebug() << "Writing request for file data"<<info.fileName << "id" << info.fileID; QString path = m_saveDir + QDir::separator() + info.fileName; //TODO: fix offset call if(m_requestType == QOM_FILE_REGULAR) { m_currentSize = info.size; m_waitingForData = info.size; if(!openFile(path)) continue; payload += ":0"; writeBlock(messenger()->makeMessage(QOM_GETFILEDATA, payload).toAscii()); } else if(m_requestType == QOM_FILE_DIR) { writeBlock(messenger()->makeMessage(QOM_GETDIRFILES, payload).toAscii()); } } } void RecvFileProgressDialog::informUser() { QString message(m_msg.sender()->name()); message.append(tr(" has sent the following files\n\n")); qint64 totalSize = 0; foreach(RecvFileInfo info, m_fileHeaders) { message.append(info.fileName); message.append(" ("); if(info.type == QOM_FILE_REGULAR) { message.append(QString::number(info.size)); totalSize += info.size; message.append(" bytes)\n"); } else if(info.type == QOM_FILE_DIR) { message.append("Directory, unknown size)\n"); } } message.append(tr("\nTotal Size: ")); if(totalSize > 1024*1024) { message.append(QString::number(totalSize / (1024*1024) )); message.append("Mb"); } else if( totalSize > 1024 ) { message.append(QString::number(totalSize / 1024)); message.append("Kb"); } else { message.append(QString::number(totalSize)); message.append("bytes"); } QString msg = m_msg.payload().left(m_msg.payload().indexOf("\a")); if(!msg.isEmpty()) message.append("\n\nMessage: " + msg); message.append(tr("\n\nDo you want to accept the files?")); if(QMessageBox::No == QMessageBox::question(NULL, tr("Receiving files"), message, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)) // last is default button reject(); else m_saveDir = QFileDialog::getExistingDirectory(this, tr("Save To")); if(!m_saveDir.isEmpty()) { qDebug() << m_saveDir; } } // TODO: share with sending dialog? bool RecvFileProgressDialog::writeBlock(QByteArray b) { int bytesToWrite = b.size(); int bytesWritten = 0; do { qDebug() << "Writing" << b << "to socket"; bytesWritten = m_socket->write(b); if(bytesWritten == -1) return false; b.remove(0, bytesWritten); bytesToWrite -= bytesWritten; } while(bytesToWrite > 0); return true; } /** * Instead of actually reading the data * it notifies seperate functions depending * on what we are reading, which read as required */ void RecvFileProgressDialog::readRequest() { // QByteArray data; // while(m_socket->bytesAvailable()) // { // data += m_socket->read(1024); // //qDebug() << "Reading"; // } // qDebug() << ":: readRequest data size" << data.size(); // qDebug() << data << "\n\n"; if(m_requestType == QOM_FILE_REGULAR) requestWriteToFile(); else if(m_requestType == QOM_FILE_DIR) requestWriteToDirectory(); } void RecvFileProgressDialog::requestWriteToFile() { QByteArray data = m_socket->readAll(); writeToFile(data); } /** * Attempts to read headers individually * and then read the file as required */ void RecvFileProgressDialog::requestWriteToDirectory() { while(m_socket->bytesAvailable()) { if(m_inHeader) { m_header += m_socket->read(1); //qDebug() << m_header; QByteArray drop; // TODO: ideally not required RecvFileInfo info = parseDirectoryHeader(m_header, &drop); if(info.fileID >= 0) { qDebug() << "# Header parsed successfully"; qDebug() << info.fileName << info.size << info.type; // we got a valid header, process it m_inHeader = false; m_header.clear(); if(info.type == QOM_FILE_REGULAR) { qDebug() << "Now writing new file" << info.fileName; if(!openFile(m_dir->absoluteFilePath(info.fileName))) return ; m_waitingForData = info.size; m_currentSize = info.size; } else if(info.type == QOM_FILE_DIR) { qDebug() << "Creating directory" << info.fileName; bool made = false; if(m_dir == NULL) made = makeDirectory(m_saveDir + QDir::separator() + info.fileName); else made = makeDirectory(m_dir->absoluteFilePath(info.fileName)); if(!made) return; m_inHeader = true; continue; } else if(info.type == QOM_FILE_RETPARENT) { qDebug() << "Going up"; m_dir->cdUp(); if(m_dir->absolutePath() == m_saveDir) accept(); m_inHeader = true; continue; } else { QMessageBox::critical(this, tr("Receive failed"), tr("Bad header! Could not understand file type %1").arg(info.type)); reject(); } } } // write to file whatever we get if(!m_inHeader) { QByteArray fileData = m_socket->read(m_waitingForData); writeToFile(fileData); if(m_waitingForData == 0) { m_inHeader = true; } } } } bool RecvFileProgressDialog::openFile(const QString& fileName) { m_currentFile = new QFile(fileName); if(m_currentFile->exists()) { if(QMessageBox::No == QMessageBox::question(this, tr("Replace file"), tr("File %1 exists, overwrite?").arg(fileName), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)) { m_waitingForData = 0; return false; } } if(!m_currentFile->open(QIODevice::Truncate | QIODevice::WriteOnly)) { qWarning() << "Cannot open" << fileName << "for writing"; m_currentFile->close(); m_waitingForData = 0; return false; } qDebug() << fileName << "Opened with truncate"; return true; } /* * TODO: i know, the remainder thing is a bad hack. */ bool RecvFileProgressDialog::writeToFile(QByteArray& b, QByteArray* remainder) { if(m_currentFile == NULL) return false; while(b.size() > 0) { if(m_waitingForData < b.size()) { qDebug() << "Excess data, setting remainder"; if(remainder != NULL) { *remainder = b.right(b.size() - m_waitingForData); } b = b.left(m_waitingForData); } int written = m_currentFile->write(b); //qDebug() << "Wrote" << written << "bytes to" << m_currentFile->fileName(); if(written == -1) { qWarning() << "Write error" << m_currentFile->errorString(); m_currentFile->close(); return false; } m_waitingForData -= written; qDebug() << "Wrote" << written << "bytes" << "Left" << m_waitingForData; b.remove(0, written); } setLabelText(tr("Receiving %1").arg(m_currentFile->fileName())); setValue((float)(m_currentSize-m_waitingForData)/m_currentSize * 100.0); if(m_waitingForData <= 0) { qDebug() << "Finished writing" << m_currentFile->fileName(); m_currentFile->close(); } return true; } bool RecvFileProgressDialog::makeDirectory(const QString& path) { qDebug() << "makeDirectory" << path; if(m_dir != NULL) { delete m_dir; m_dir = NULL; } m_dir = new QDir(path); if(!m_dir->exists() && !m_dir->mkdir(path)) { // TODO: convert to QMessageBox qWarning() << "Could not create directory" << m_dir->absolutePath() ; return false; } return true; } bool RecvFileProgressDialog::writeToDirectory(QByteArray& b) { m_header += b; //qDebug() << "At the beginning of writeToDirectory" << m_header; QByteArray leftover; RecvFileInfo info = parseDirectoryHeader(m_header, &leftover); if(m_waitingForData != 0 && m_header.isEmpty()) { qDebug() << "Need to flush"; exit(5); } //info is filled, only leftover is valuable if(info.fileID >= 0) { m_inHeader = false; m_header = leftover; //qDebug() << "! Leftover" << leftover; if(info.type == QOM_FILE_REGULAR) { qDebug() << "Now writing new file" << info.fileName; if(!openFile(m_dir->absoluteFilePath(info.fileName))) return false; m_waitingForData = info.size; m_currentSize = info.size; QByteArray moreLeftover; // leftover can't immediately have another header // any headers it has now are in moreLeftover if(!writeToFile(leftover, &moreLeftover)) return false; //qDebug() << "!moreLeftover" << moreLeftover; qDebug() << "line 306:" << m_waitingForData; if(m_waitingForData == 0) { m_inHeader = true; m_header = moreLeftover; } else { m_inHeader = false; m_header.clear(); } } else if(info.type == QOM_FILE_DIR) { qDebug() << "Creating new directory" << info.fileName; bool made = false; if(m_dir == NULL) made = makeDirectory(m_saveDir + QDir::separator() + info.fileName); else made = makeDirectory(m_dir->absoluteFilePath(info.fileName)); if(!made) return false; m_inHeader = true; //m_header.clear(); } else if(info.type == QOM_FILE_RETPARENT) { qDebug() << "Going up"; m_dir->cdUp(); m_inHeader = true; } //qDebug() << "After all processing of header, in header?" << m_inHeader<<"\n"; } if(!m_inHeader) { qDebug() << "> In file"; QByteArray leftover; writeToFile(m_header, &leftover); qDebug() << "line 337:" << m_waitingForData ; if(m_waitingForData == 0) { m_header = leftover; m_inHeader = true; } else { m_header.clear(); m_inHeader = false; } } qDebug() << " << Returning from writeToDirectory"; return true; } /** * Tries to parse a header if it can * if it can, fills in RecvFileInfo correctly * Otherwise sets RecvFileInfo.fileID to -1, other fields are kept default * If any data is left over after parsing header, it is stored in remainder. */ RecvFileInfo RecvFileProgressDialog::parseDirectoryHeader(const QByteArray& a, QByteArray* remainder) { bool bad = false; RecvFileInfo ret; if(a.contains(":")) { QList<QByteArray> tokens = a.split(':'); int headerSize = tokens[0].toInt(0, 16); //qDebug() << "Header size:"<<headerSize; if( headerSize == 0 ) //bad data, perhaps binary bad = true; else if(a.size() < headerSize || tokens.size() < 4) { //qDebug() << "not enough data" << tokens << "expected" << tokens[0].size(); bad = true; } else { //qDebug() << "Header list" << tokens; ret.fileID = 0; ret.fileName = tokens[1]; ret.size = tokens[2].toLongLong(0, 16); ret.type = tokens[3].toInt(0, 16); *remainder = a.right(a.size() - headerSize); } } else bad = true; if(bad) { ret.fileID = -1; } return ret; }<|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Nokia Corporation (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "effectwidget.h" #include "effectwidget_p.h" #include <QtCore/QtAlgorithms> #include <QtCore/QList> #include "effect.h" #include "effectparameter.h" #include "phonondefs_p.h" #include <QtGui/QBoxLayout> #include <QtGui/QLabel> #include <QtGui/QSpinBox> #include <QtGui/QCheckBox> #include <QtGui/QComboBox> #include <QtGui/QSlider> #include <limits> #ifdef min #undef min #endif #ifdef max #undef max #endif static const qreal DEFAULT_MIN = std::numeric_limits<qreal>::min(); static const qreal DEFAULT_MAX = std::numeric_limits<qreal>::max(); static const int DEFAULT_MIN_INT = std::numeric_limits<int>::min(); static const int DEFAULT_MAX_INT = std::numeric_limits<int>::max(); static const int SLIDER_RANGE = 8; static const int TICKINTERVAL = 4; QT_BEGIN_NAMESPACE #ifndef QT_NO_PHONON_EFFECTWIDGET namespace Phonon { EffectWidget::EffectWidget(Effect *effect, QWidget *parent) : QWidget(parent), k_ptr(new EffectWidgetPrivate(effect)) { K_D(EffectWidget); d->q_ptr = this; d->autogenerateUi(); } EffectWidget::~EffectWidget() { delete k_ptr; } /* EffectWidget::EffectWidget(EffectWidgetPrivate &dd, QWidget *parent) : QWidget(parent) , k_ptr(&dd) { K_D(EffectWidget); d->q_ptr = this; d->autogenerateUi(); } */ EffectWidgetPrivate::EffectWidgetPrivate(Effect *e) : effect(e) { //TODO: look up whether there is a specialized widget for this effect. This //could be a DSO or a Designer ui file found via KTrader. // //if no specialized widget is available: } void EffectWidgetPrivate::autogenerateUi() { Q_Q(EffectWidget); QVBoxLayout *mainLayout = new QVBoxLayout(q); mainLayout->setMargin(0); foreach (const EffectParameter &para, effect->parameters()) { QVariant value = effect->parameterValue(para); QHBoxLayout *pLayout = new QHBoxLayout; mainLayout->addLayout(pLayout); QLabel *label = new QLabel(q); pLayout->addWidget(label); label->setText(para.name()); #ifndef QT_NO_TOOLTIP label->setToolTip(para.description()); #endif QWidget *control = 0; switch (para.type()) { case QVariant::String: { QComboBox *cb = new QComboBox(q); control = cb; if (value.type() == QVariant::Int) { //value just defines the item index foreach (const QVariant &item, para.possibleValues()) { cb->addItem(item.toString()); } cb->setCurrentIndex(value.toInt()); QObject::connect(cb, SIGNAL(currentIndexChanged(int)), q, SLOT(_k_setIntParameter(int))); } else { foreach (const QVariant &item, para.possibleValues()) { cb->addItem(item.toString()); if (item == value) { cb->setCurrentIndex(cb->count() - 1); } } QObject::connect(cb, SIGNAL(currentIndexChanged(QString)), q, SLOT(_k_setStringParameter(QString))); } } break; case QVariant::Bool: { QCheckBox *cb = new QCheckBox(q); control = cb; cb->setChecked(value.toBool()); QObject::connect(cb, SIGNAL(toggled(bool)), q, SLOT(_k_setToggleParameter(bool))); } break; case QVariant::Int: { QSpinBox *sb = new QSpinBox(q); control = sb; bool minValueOk = false; bool maxValueOk = false; const int minValue = para.minimumValue().toInt(&minValueOk); const int maxValue = para.minimumValue().toInt(&maxValueOk); sb->setRange(minValueOk ? minValue : DEFAULT_MIN_INT, maxValueOk ? maxValue : DEFAULT_MAX_INT); sb->setValue(value.toInt()); QObject::connect(sb, SIGNAL(valueChanged(int)), q, SLOT(_k_setIntParameter(int))); } break; case QVariant::Double: { const double minValue = (para.minimumValue().type() == QVariant::Double ? para.minimumValue().toDouble() : DEFAULT_MIN); const double maxValue = (para.maximumValue().type() == QVariant::Double ? para.maximumValue().toDouble() : DEFAULT_MAX); if (minValue == -1. && maxValue == 1.) { //Special case values between -1 and 1.0 to use a slider for improved usability QSlider *slider = new QSlider(Qt::Horizontal, q); slider->setRange(-SLIDER_RANGE, +SLIDER_RANGE); slider->setValue(int(SLIDER_RANGE * value.toDouble())); slider->setTickPosition(QSlider::TicksBelow); slider->setTickInterval(TICKINTERVAL); QObject::connect(slider, SIGNAL(valueChanged(int)), q, SLOT(_k_setSliderParameter(int))); } else { double step = 0.1; if (qAbs(maxValue - minValue) > 50) step = 1.0; QDoubleSpinBox *sb = new QDoubleSpinBox(q); control = sb; sb->setRange(minValue, maxValue); sb->setValue(value.toDouble()); sb->setSingleStep(step); QObject::connect(sb, SIGNAL(valueChanged(double)), q, SLOT(_k_setDoubleParameter(double))); } } break; default: break; } #ifndef QT_NO_TOOLTIP control->setToolTip(para.description()); #endif if (control) { #ifndef QT_NO_SHORTCUT label->setBuddy(control); #endif pLayout->addWidget(control); parameterForObject.insert(control, para); } } } void EffectWidgetPrivate::_k_setToggleParameter(bool checked) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], checked); } } void EffectWidgetPrivate::_k_setIntParameter(int value) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], value); } } void EffectWidgetPrivate::_k_setDoubleParameter(double value) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], value); } } void EffectWidgetPrivate::_k_setStringParameter(const QString &value) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], value); } } void EffectWidgetPrivate::_k_setSliderParameter(int value) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], double(value) / double(SLIDER_RANGE)); } } } // namespace Phonon #endif // QT_NO_PHONON_EFFECTWIDGET QT_END_NAMESPACE #include "moc_effectwidget.cpp" // vim: sw=4 ts=4 <commit_msg>Fix a crash in Phonon::EffectWidget<commit_after>/* This file is part of the KDE project Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Nokia Corporation (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "effectwidget.h" #include "effectwidget_p.h" #include <QtCore/QtAlgorithms> #include <QtCore/QList> #include "effect.h" #include "effectparameter.h" #include "phonondefs_p.h" #include <QtGui/QBoxLayout> #include <QtGui/QLabel> #include <QtGui/QSpinBox> #include <QtGui/QCheckBox> #include <QtGui/QComboBox> #include <QtGui/QSlider> #include <limits> #ifdef min #undef min #endif #ifdef max #undef max #endif static const qreal DEFAULT_MIN = std::numeric_limits<qreal>::min(); static const qreal DEFAULT_MAX = std::numeric_limits<qreal>::max(); static const int DEFAULT_MIN_INT = std::numeric_limits<int>::min(); static const int DEFAULT_MAX_INT = std::numeric_limits<int>::max(); static const int SLIDER_RANGE = 8; static const int TICKINTERVAL = 4; QT_BEGIN_NAMESPACE #ifndef QT_NO_PHONON_EFFECTWIDGET namespace Phonon { EffectWidget::EffectWidget(Effect *effect, QWidget *parent) : QWidget(parent), k_ptr(new EffectWidgetPrivate(effect)) { K_D(EffectWidget); d->q_ptr = this; d->autogenerateUi(); } EffectWidget::~EffectWidget() { delete k_ptr; } /* EffectWidget::EffectWidget(EffectWidgetPrivate &dd, QWidget *parent) : QWidget(parent) , k_ptr(&dd) { K_D(EffectWidget); d->q_ptr = this; d->autogenerateUi(); } */ EffectWidgetPrivate::EffectWidgetPrivate(Effect *e) : effect(e) { //TODO: look up whether there is a specialized widget for this effect. This //could be a DSO or a Designer ui file found via KTrader. // //if no specialized widget is available: } void EffectWidgetPrivate::autogenerateUi() { Q_Q(EffectWidget); QVBoxLayout *mainLayout = new QVBoxLayout(q); mainLayout->setMargin(0); foreach (const EffectParameter &para, effect->parameters()) { QVariant value = effect->parameterValue(para); QHBoxLayout *pLayout = new QHBoxLayout; mainLayout->addLayout(pLayout); QLabel *label = new QLabel(q); pLayout->addWidget(label); label->setText(para.name()); #ifndef QT_NO_TOOLTIP label->setToolTip(para.description()); #endif QWidget *control = 0; switch (para.type()) { case QVariant::String: { QComboBox *cb = new QComboBox(q); control = cb; if (value.type() == QVariant::Int) { //value just defines the item index foreach (const QVariant &item, para.possibleValues()) { cb->addItem(item.toString()); } cb->setCurrentIndex(value.toInt()); QObject::connect(cb, SIGNAL(currentIndexChanged(int)), q, SLOT(_k_setIntParameter(int))); } else { foreach (const QVariant &item, para.possibleValues()) { cb->addItem(item.toString()); if (item == value) { cb->setCurrentIndex(cb->count() - 1); } } QObject::connect(cb, SIGNAL(currentIndexChanged(QString)), q, SLOT(_k_setStringParameter(QString))); } } break; case QVariant::Bool: { QCheckBox *cb = new QCheckBox(q); control = cb; cb->setChecked(value.toBool()); QObject::connect(cb, SIGNAL(toggled(bool)), q, SLOT(_k_setToggleParameter(bool))); } break; case QVariant::Int: { QSpinBox *sb = new QSpinBox(q); control = sb; bool minValueOk = false; bool maxValueOk = false; const int minValue = para.minimumValue().toInt(&minValueOk); const int maxValue = para.minimumValue().toInt(&maxValueOk); sb->setRange(minValueOk ? minValue : DEFAULT_MIN_INT, maxValueOk ? maxValue : DEFAULT_MAX_INT); sb->setValue(value.toInt()); QObject::connect(sb, SIGNAL(valueChanged(int)), q, SLOT(_k_setIntParameter(int))); } break; case QVariant::Double: { const double minValue = (para.minimumValue().type() == QVariant::Double ? para.minimumValue().toDouble() : DEFAULT_MIN); const double maxValue = (para.maximumValue().type() == QVariant::Double ? para.maximumValue().toDouble() : DEFAULT_MAX); if (minValue == -1. && maxValue == 1.) { //Special case values between -1 and 1.0 to use a slider for improved usability QSlider *slider = new QSlider(Qt::Horizontal, q); control = slider; slider->setRange(-SLIDER_RANGE, +SLIDER_RANGE); slider->setValue(int(SLIDER_RANGE * value.toDouble())); slider->setTickPosition(QSlider::TicksBelow); slider->setTickInterval(TICKINTERVAL); QObject::connect(slider, SIGNAL(valueChanged(int)), q, SLOT(_k_setSliderParameter(int))); } else { double step = 0.1; if (qAbs(maxValue - minValue) > 50) step = 1.0; QDoubleSpinBox *sb = new QDoubleSpinBox(q); control = sb; sb->setRange(minValue, maxValue); sb->setValue(value.toDouble()); sb->setSingleStep(step); QObject::connect(sb, SIGNAL(valueChanged(double)), q, SLOT(_k_setDoubleParameter(double))); } } break; default: break; } if (control) { #ifndef QT_NO_TOOLTIP control->setToolTip(para.description()); #endif #ifndef QT_NO_SHORTCUT label->setBuddy(control); #endif pLayout->addWidget(control); parameterForObject.insert(control, para); } } } void EffectWidgetPrivate::_k_setToggleParameter(bool checked) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], checked); } } void EffectWidgetPrivate::_k_setIntParameter(int value) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], value); } } void EffectWidgetPrivate::_k_setDoubleParameter(double value) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], value); } } void EffectWidgetPrivate::_k_setStringParameter(const QString &value) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], value); } } void EffectWidgetPrivate::_k_setSliderParameter(int value) { Q_Q(EffectWidget); if (parameterForObject.contains(q->sender())) { effect->setParameterValue(parameterForObject[q->sender()], double(value) / double(SLIDER_RANGE)); } } } // namespace Phonon #endif // QT_NO_PHONON_EFFECTWIDGET QT_END_NAMESPACE #include "moc_effectwidget.cpp" // vim: sw=4 ts=4 <|endoftext|>
<commit_before>#pragma once #include "SuperComponent.hpp" #include <glm\glm.hpp> namespace Component { /// %Component handling a camera lens. class Lens : public SuperComponent { public: /// Create new lens. /** * @param entity Pointer to which entity this component corresponds. */ Lens(Entity* entity); /// Save the component. /** * @return JSON value to be stored on disk. */ Json::Value Save() const override; /// Load component from JSON node. /** * @param node JSON node to load from. */ void Load(const Json::Value& node) override; /// Get the projection matrix. /** * @param screenSize Screen size in pixels. * @return The projection matrix. */ glm::mat4 GetProjection(const glm::vec2& screenSize) const; /// Field of view, in degrees. /** * Default: 45.0 */ float fieldOfView = 45.f; /// Near plane. /** * Default: 0.5 */ float zNear = 0.5f; /// Far plane. /** * Default: 100.0 */ float zFar = 100.f; }; } <commit_msg>Fix GLM include<commit_after>#pragma once #include "SuperComponent.hpp" #include <glm/glm.hpp> namespace Component { /// %Component handling a camera lens. class Lens : public SuperComponent { public: /// Create new lens. /** * @param entity Pointer to which entity this component corresponds. */ Lens(Entity* entity); /// Save the component. /** * @return JSON value to be stored on disk. */ Json::Value Save() const override; /// Load component from JSON node. /** * @param node JSON node to load from. */ void Load(const Json::Value& node) override; /// Get the projection matrix. /** * @param screenSize Screen size in pixels. * @return The projection matrix. */ glm::mat4 GetProjection(const glm::vec2& screenSize) const; /// Field of view, in degrees. /** * Default: 45.0 */ float fieldOfView = 45.f; /// Near plane. /** * Default: 0.5 */ float zNear = 0.5f; /// Far plane. /** * Default: 100.0 */ float zFar = 100.f; }; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2014, Intel Corporation * 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. */ #pragma once #include <limits> #include <sstream> #include <string> #include <stdint.h> #include <cmath> /* details namespace is here to hide implementation details to header end user. It * is NOT intended to be used outside. */ namespace details { /** Helper class to limit instantiation of templates */ template<typename T> struct ConvertionAllowed; /* List of allowed types for conversion */ template<> struct ConvertionAllowed<bool> {}; template<> struct ConvertionAllowed<uint64_t> {}; template<> struct ConvertionAllowed<int64_t> {}; template<> struct ConvertionAllowed<uint32_t> {}; template<> struct ConvertionAllowed<int32_t> {}; template<> struct ConvertionAllowed<uint16_t> {}; template<> struct ConvertionAllowed<int16_t> {}; template<> struct ConvertionAllowed<float> {}; template<> struct ConvertionAllowed<double> {}; template<typename T> static inline bool convertTo(const std::string &str, T &result) { /* Check that conversion to that type is allowed. * If this fails, this means that this template was not intended to be used * with this type, thus that the result is undefined. */ ConvertionAllowed<T>(); if (str.find_first_of(std::string("\r\n\t\v ")) != std::string::npos) { return false; } /* Check for a '-' in string. If type is unsigned and a - is found, the * parsing fails. This is made necessary because "-1" is read as 65535 for * uint16_t, for example */ if (str.find("-") != std::string::npos && !std::numeric_limits<T>::is_signed) { return false; } std::stringstream ss(str); /* Sadly, the stream conversion does not handle hexadecimal format, thus * check is done manually */ if (str.substr(0, 2) == "0x") { if (std::numeric_limits<T>::is_integer) { ss >> std::hex >> result; } else { /* Conversion undefined for non integers */ return false; } } else { ss >> result; } return ss.eof() && !ss.fail() && !ss.bad(); } } // namespace details /** * Convert a string to a given type. * * This template function read the value of the type T in the given string. * The function does not allow to have white spaces around the value to parse * and tries to parse the whole string, which means that if some bytes were not * read in the string, the function fails. * Hexadecimal representation (ie numbers starting with 0x) is supported only * for integral types conversions. * Result may be modified, even in case of failure. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<typename T> static inline bool convertTo(const std::string &str, T &result) { return details::convertTo<T>(str, result); } /** * Specialization for float of convertTo template function. * * This function follows the same paradigm than it's generic version and is * based on it but makes furthers checks on the returned value. * * The specific implementation is made necessary because the stlport conversion * from string to float behaves differently than GNU STL: overflow produce * +/-Infinity rather than an error. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<float>(const std::string &str, float &result) { if (!details::convertTo(str, result)) { return false; } if (!std::isfinite(result)) { return false; } return true; } /** * Specialization for double of convertTo template function. * * This function follows the same paradigm than it's generic version and is * based on it but makes furthers checks on the returned value. * * The specific implementation is made necessary because the stlport conversion * from string to double behaves differently than GNU STL: overflow produce * +/-Infinity rather than an error. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<double>(const std::string &str, double &result) { if (!details::convertTo(str, result)) { return false; } if (!std::isfinite(result)) { return false; } return true; } /** * Specialization for boolean of convertTo template function. * * This function follows the same paradigm than it's generic version. * This function accepts to parse boolean as "0/1" or "false/true" or * "FALSE/TRUE". * The specific implementation is made necessary because the behaviour of * string streams when parsing boolean values is not sufficient to fit our * requirements. Indeed, parsing "true" will correctly parse the value, but the * end of stream is not reached which makes the ss.eof() fails in the generic * implementation. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<bool>(const std::string &str, bool &result) { if (str == "0" || str == "FALSE" || str == "false") { result = false; return true; } if (str == "1" || str == "TRUE" || str == "true") { result = true; return true; } return false; } <commit_msg>Define special case for convertTo<uint8_t>() and convertTo<int8_t>()<commit_after>/* * Copyright (c) 2011-2014, Intel Corporation * 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. */ #pragma once #include <limits> #include <sstream> #include <string> #include <stdint.h> #include <cmath> /* details namespace is here to hide implementation details to header end user. It * is NOT intended to be used outside. */ namespace details { /** Helper class to limit instantiation of templates */ template<typename T> struct ConvertionAllowed; template<typename T, typename Via> struct ConvertionAllowedVia; /* List of allowed types for conversion */ template<> struct ConvertionAllowed<bool> {}; template<> struct ConvertionAllowed<uint64_t> {}; template<> struct ConvertionAllowed<int64_t> {}; template<> struct ConvertionAllowed<uint32_t> {}; template<> struct ConvertionAllowed<int32_t> {}; template<> struct ConvertionAllowed<uint16_t> {}; template<> struct ConvertionAllowed<int16_t> {}; template<> struct ConvertionAllowed<int8_t> {}; template<> struct ConvertionAllowed<uint8_t> {}; template<> struct ConvertionAllowed<float> {}; template<> struct ConvertionAllowed<double> {}; /* Allow chars and unsigned chars to be converted via integers */ template<> struct ConvertionAllowedVia<uint8_t, uint32_t> {}; template<> struct ConvertionAllowedVia<int8_t, int32_t> {}; template<typename T> static inline bool convertTo(const std::string &str, T &result) { /* Check that conversion to that type is allowed. * If this fails, this means that this template was not intended to be used * with this type, thus that the result is undefined. */ ConvertionAllowed<T>(); if (str.find_first_of(std::string("\r\n\t\v ")) != std::string::npos) { return false; } /* Check for a '-' in string. If type is unsigned and a - is found, the * parsing fails. This is made necessary because "-1" is read as 65535 for * uint16_t, for example */ if (str.find("-") != std::string::npos && !std::numeric_limits<T>::is_signed) { return false; } std::stringstream ss(str); /* Sadly, the stream conversion does not handle hexadecimal format, thus * check is done manually */ if (str.substr(0, 2) == "0x") { if (std::numeric_limits<T>::is_integer) { ss >> std::hex >> result; } else { /* Conversion undefined for non integers */ return false; } } else { ss >> result; } return ss.eof() && !ss.fail() && !ss.bad(); } template<typename T, typename Via> static inline bool convertToVia(const std::string &str, T &result) { /* Check that conversion to that type is allowed. * If this fails, this means that this template was not intended to be used * with this type, thus that the result is undefined. */ ConvertionAllowedVia<T, Via>(); /* We want to override the behaviour of convertTo<T> with that of * convertTo<Via> and then safely cast the result into a T. */ Via res; if (!convertTo<Via>(str, res)) { return false; } if ((res > std::numeric_limits<T>::max()) or (res < std::numeric_limits<T>::min())) { return false; } result = static_cast<T>(res); return true; } } // namespace details /** * Convert a string to a given type. * * This template function read the value of the type T in the given string. * The function does not allow to have white spaces around the value to parse * and tries to parse the whole string, which means that if some bytes were not * read in the string, the function fails. * Hexadecimal representation (ie numbers starting with 0x) is supported only * for integral types conversions. * Result may be modified, even in case of failure. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<typename T> static inline bool convertTo(const std::string &str, T &result) { return details::convertTo<T>(str, result); } /** Specialization for uint8_t of convertTo template function. * * This function follows the same paradigm than it's generic version. * * The generic version was converting int8 as it was a character * (uint8_t is an alias to unsigned char on most compiler). * Thus converting "1" would return 49 ie '1'. * As convertTo is thought as an _numerical_ convertion tool * (contrary to boost::lexical_cast for example), * forbid considering the input as a character and consider uint8_t * (aka unsigned char) as a number exclusively. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<uint8_t>(const std::string &str, uint8_t &result) { return details::convertToVia<uint8_t, uint32_t>(str, result); } /** Specialization for int8_t of convertTo template function. * * @see convertTo<uint8_t> */ template<> inline bool convertTo<int8_t>(const std::string &str, int8_t &result) { return details::convertToVia<int8_t, int32_t>(str, result); } /** * Specialization for float of convertTo template function. * * This function follows the same paradigm than it's generic version and is * based on it but makes furthers checks on the returned value. * * The specific implementation is made necessary because the stlport conversion * from string to float behaves differently than GNU STL: overflow produce * +/-Infinity rather than an error. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<float>(const std::string &str, float &result) { if (!details::convertTo(str, result)) { return false; } if (!std::isfinite(result)) { return false; } return true; } /** * Specialization for double of convertTo template function. * * This function follows the same paradigm than it's generic version and is * based on it but makes furthers checks on the returned value. * * The specific implementation is made necessary because the stlport conversion * from string to double behaves differently than GNU STL: overflow produce * +/-Infinity rather than an error. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<double>(const std::string &str, double &result) { if (!details::convertTo(str, result)) { return false; } if (!std::isfinite(result)) { return false; } return true; } /** * Specialization for boolean of convertTo template function. * * This function follows the same paradigm than it's generic version. * This function accepts to parse boolean as "0/1" or "false/true" or * "FALSE/TRUE". * The specific implementation is made necessary because the behaviour of * string streams when parsing boolean values is not sufficient to fit our * requirements. Indeed, parsing "true" will correctly parse the value, but the * end of stream is not reached which makes the ss.eof() fails in the generic * implementation. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<bool>(const std::string &str, bool &result) { if (str == "0" || str == "FALSE" || str == "false") { result = false; return true; } if (str == "1" || str == "TRUE" || str == "true") { result = true; return true; } return false; } <|endoftext|>