text
stringlengths
54
60.6k
<commit_before>#include "stdafx.h" #include "AdvCalc.h" #include <intrin.h> AdvCalc::AdvCalc() { // ڴ m_pV = (float*)_aligned_malloc(sizeof(float) * c_len, 64); // for (int i = 0;i < c_len;i++) { m_pV[i] = 1.0f * rand() / RAND_MAX; } } AdvCalc::~AdvCalc() { _aligned_free(m_pV); m_pV = NULL; } // SIMD֧ BOOL AdvCalc::IsSupport(SIMD level) { // https://en.wikipedia.org/wiki/CPUID int cpuinfo[4], cpuinfo7[4]; __cpuid(cpuinfo, 0x01); __cpuid(cpuinfo7, 0x07); int ebx = cpuinfo7[1]; int ecx = cpuinfo[2]; int edx = cpuinfo[3]; BOOL bSupport = FALSE; switch (level) { case NA: bSupport = TRUE; break; case MMX: bSupport = edx & 0x00800000; break; case SSE: bSupport = edx & 0x02000000; break; case AVX: bSupport = ecx & 0x10000000; break; case FMA: bSupport = ecx & 0x00001000; break; case AVX512: bSupport = ebx & 0x04000000; break; default: break; } return bSupport; } // float AdvCalc::calcBasic() { float fSum; for (int j = 0;j < c_loop;j++) { fSum = 0.0f; for (int i = 0;i < c_len;i++) { float fX = m_fA * m_pV[i] + m_fB; fSum += fX; } } return fSum; } // SSE float AdvCalc::calcSSE() { float fSum; for (int j = 0;j < c_loop;j++) { __m128 a = _mm_set_ps1(m_fA); __m128 b = _mm_set_ps1(m_fB); __m128* pV = (__m128*)m_pV; __m128 sum = _mm_set_ps1(0.0f); for (int i = 0;i < c_len / 4;i++) { __m128 x = _mm_mul_ps(a, pV[i]); x = _mm_add_ps(x, b); sum = _mm_add_ps(sum, x); } float* pSum = (float*)_aligned_malloc(sizeof(float) * 4, 64); _mm_store_ps(pSum, sum); fSum = 0.0f; for (int i = 0;i < 4;i++) { fSum += pSum[i]; } _aligned_free(pSum); } return fSum; } // AVX float AdvCalc::calcAVX() { float fSum; for (int j = 0;j < c_loop;j++) { __m256 a = _mm256_set1_ps(m_fA); __m256 b = _mm256_set1_ps(m_fB); __m256* pV = (__m256*)m_pV; __m256 sum = _mm256_set1_ps(0.0f); for (int i = 0;i < c_len / 8;i++) { __m256 x = _mm256_mul_ps(a, pV[i]); x = _mm256_add_ps(x, b); sum = _mm256_add_ps(sum, x); } sum = _mm256_hadd_ps(sum, sum); sum = _mm256_hadd_ps(sum, sum); sum = _mm256_hadd_ps(sum, sum); float* pSum = (float*)_aligned_malloc(sizeof(float) * 8, 64); _mm256_store_ps(pSum, sum); fSum = *pSum; _aligned_free(pSum); } return fSum; } // FMA float AdvCalc::calcFMA() { float fSum; for (int j = 0;j < c_loop;j++) { __m256 a = _mm256_set1_ps(m_fA); __m256 b = _mm256_set1_ps(m_fB); __m256* pV = (__m256*)m_pV; __m256 sum = _mm256_set1_ps(0.0f); for (int i = 0;i < c_len / 8;i++) { __m256 x = _mm256_fmadd_ps(pV[i], a, b); sum = _mm256_add_ps(sum, x); } sum = _mm256_hadd_ps(sum, sum); sum = _mm256_hadd_ps(sum, sum); sum = _mm256_hadd_ps(sum, sum); float* pSum = (float*)_aligned_malloc(sizeof(float) * 8, 64); _mm256_store_ps(pSum, sum); fSum = *pSum; _aligned_free(pSum); } return fSum; } // AVX512 float AdvCalc::calcAVX512() { float fSum; for (int j = 0;j < c_loop;j++) { __m512 a = _mm512_set1_ps(m_fA); __m512 b = _mm512_set1_ps(m_fB); __m512* pV = (__m512*)m_pV; __m512 sum = _mm512_set1_ps(0.0f); for (int i = 0;i < c_len / 16;i++) { __m512 x = _mm512_fmadd_ps(pV[i], a, b); sum = _mm512_add_ps(sum, x); } float* pSum = (float*)_aligned_malloc(sizeof(float) * 16, 64); _mm512_store_ps(pSum, sum); fSum = 0.0f; for (int i = 0;i < 16;i++) { fSum += pSum[i]; } _aligned_free(pSum); } return fSum; }<commit_msg>reduce add<commit_after>#include "stdafx.h" #include "AdvCalc.h" #include <intrin.h> AdvCalc::AdvCalc() { // ڴ m_pV = (float*)_aligned_malloc(sizeof(float) * c_len, 64); // for (int i = 0;i < c_len;i++) { m_pV[i] = 1.0f * rand() / RAND_MAX; } } AdvCalc::~AdvCalc() { _aligned_free(m_pV); m_pV = NULL; } // SIMD֧ BOOL AdvCalc::IsSupport(SIMD level) { // https://en.wikipedia.org/wiki/CPUID int cpuinfo[4], cpuinfo7[4]; __cpuid(cpuinfo, 0x01); __cpuid(cpuinfo7, 0x07); int ebx = cpuinfo7[1]; int ecx = cpuinfo[2]; int edx = cpuinfo[3]; BOOL bSupport = FALSE; switch (level) { case NA: bSupport = TRUE; break; case MMX: bSupport = edx & 0x00800000; break; case SSE: bSupport = edx & 0x02000000; break; case AVX: bSupport = ecx & 0x10000000; break; case FMA: bSupport = ecx & 0x00001000; break; case AVX512: bSupport = ebx & 0x04000000; break; default: break; } return bSupport; } // float AdvCalc::calcBasic() { float fSum; for (int j = 0;j < c_loop;j++) { fSum = 0.0f; for (int i = 0;i < c_len;i++) { float fX = m_fA * m_pV[i] + m_fB; fSum += fX; } } return fSum; } // SSE float AdvCalc::calcSSE() { float fSum; for (int j = 0;j < c_loop;j++) { __m128 a = _mm_set_ps1(m_fA); __m128 b = _mm_set_ps1(m_fB); __m128* pV = (__m128*)m_pV; __m128 sum = _mm_set_ps1(0.0f); for (int i = 0;i < c_len / 4;i++) { __m128 x = _mm_mul_ps(a, pV[i]); x = _mm_add_ps(x, b); sum = _mm_add_ps(sum, x); } float* pSum = (float*)_aligned_malloc(sizeof(float) * 4, 64); _mm_store_ps(pSum, sum); fSum = 0.0f; for (int i = 0;i < 4;i++) { fSum += pSum[i]; } _aligned_free(pSum); } return fSum; } // AVX float AdvCalc::calcAVX() { float fSum; for (int j = 0;j < c_loop;j++) { __m256 a = _mm256_set1_ps(m_fA); __m256 b = _mm256_set1_ps(m_fB); __m256* pV = (__m256*)m_pV; __m256 sum = _mm256_set1_ps(0.0f); for (int i = 0;i < c_len / 8;i++) { __m256 x = _mm256_mul_ps(a, pV[i]); x = _mm256_add_ps(x, b); sum = _mm256_add_ps(sum, x); } sum = _mm256_hadd_ps(sum, sum); sum = _mm256_hadd_ps(sum, sum); sum = _mm256_hadd_ps(sum, sum); float* pSum = (float*)_aligned_malloc(sizeof(float) * 8, 64); _mm256_store_ps(pSum, sum); fSum = *pSum; _aligned_free(pSum); } return fSum; } // FMA float AdvCalc::calcFMA() { float fSum; for (int j = 0;j < c_loop;j++) { __m256 a = _mm256_set1_ps(m_fA); __m256 b = _mm256_set1_ps(m_fB); __m256* pV = (__m256*)m_pV; __m256 sum = _mm256_set1_ps(0.0f); for (int i = 0;i < c_len / 8;i++) { __m256 x = _mm256_fmadd_ps(pV[i], a, b); sum = _mm256_add_ps(sum, x); } sum = _mm256_hadd_ps(sum, sum); sum = _mm256_hadd_ps(sum, sum); sum = _mm256_hadd_ps(sum, sum); float* pSum = (float*)_aligned_malloc(sizeof(float) * 8, 64); _mm256_store_ps(pSum, sum); fSum = *pSum; _aligned_free(pSum); } return fSum; } // AVX512 float AdvCalc::calcAVX512() { float fSum; for (int j = 0;j < c_loop;j++) { __m512 a = _mm512_set1_ps(m_fA); __m512 b = _mm512_set1_ps(m_fB); __m512* pV = (__m512*)m_pV; __m512 sum = _mm512_set1_ps(0.0f); for (int i = 0;i < c_len / 16;i++) { __m512 x = _mm512_fmadd_ps(pV[i], a, b); sum = _mm512_add_ps(sum, x); } fSum = _mm512_reduce_add_ps(sum); } return fSum; }<|endoftext|>
<commit_before>#define png_infopp_NULL (png_infopp)NULL #define int_p_NULL (int*)NULL #include <boost/gil/extension/io/png_io.hpp> #include <cctag/fileDebug.hpp> #include <cctag/visualDebug.hpp> #include <cctag/progBase/exceptions.hpp> #include <cctag/progBase/MemoryPool.hpp> #include <cctag/detection.hpp> #include <cctag/view.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/gil/gil_all.hpp> #include <boost/gil/image.hpp> #include <boost/gil/extension/io/jpeg_io.hpp> #include <boost/exception/all.hpp> #include <boost/ptr_container/ptr_list.hpp> #include <boost/archive/xml_oarchive.hpp> #include <boost/archive/xml_iarchive.hpp> #include <terry/sampler/all.hpp> #include <terry/sampler/resample_subimage.hpp> #include <sstream> #include <iostream> #include <string> #include <fstream> #include <exception> using namespace cctag::vision; using boost::timer; using namespace boost::gil; namespace bfs = boost::filesystem; static const std::string kUsageString = "Usage: detection image_file.png\n"; void detection(std::size_t frame, cctag::View& view, const std::string & paramsFilename = "") { POP_ENTER; // Process markers detection boost::timer t; boost::ptr_list<marker::CCTag> markers; cctag::vision::marker::Parameters params; if (paramsFilename != "") { std::ifstream ifs(paramsFilename.c_str()); boost::archive::xml_iarchive ia(ifs); // write class instance to archive ia >> boost::serialization::make_nvp("CCTagsParams", params); } else { std::ofstream ofs("detectionCCTagParams.xml"); boost::archive::xml_oarchive oa(ofs); // write class instance to archive oa << boost::serialization::make_nvp("CCTagsParams", params); } view.setNumLayers( params._numberOfMultiresLayers ); ROM_COUT("beforecctagDetection"); cctagDetection( markers, frame, view._grayView, params, true ); ROM_COUT("aftercctagDetection"); std::cout << "Id : "; int i = 0; BOOST_FOREACH(const cctag::vision::marker::CCTag & marker, markers) { cctag::vision::marker::drawMarkerOnGilImage(view._view, marker, false); cctag::vision::marker::drawMarkerInfos(view._view, marker, false); if (i == 0) { std::cout << marker.id() + 1; } else { std::cout << ", " << marker.id() + 1; } ++i; } std::cout << std::endl; ROM_TCOUT( markers.size() << " markers."); ROM_TCOUT("Total time: " << t.elapsed()); POP_LEAVE; } /*************************************************************/ /* Main entry */ /*************************************************************/ int main(int argc, char** argv) { try { if (argc <= 1) { BOOST_THROW_EXCEPTION(cctag::exception::Bug() << cctag::exception::user() + kUsageString); } cctag::MemoryPool::instance().updateMemoryAuthorizedWithRAM(); const std::string filename(argv[1]); std::string paramsFilename; if (argc >= 3) { paramsFilename = argv[2]; } bfs::path myPath(filename); const bfs::path extPath(myPath.extension()); const bfs::path subFilenamePath(myPath.filename()); const bfs::path parentPath(myPath.parent_path()); std::string ext(extPath.string()); bfs::path folder(argv[1]); if ((ext == ".png") || (ext == ".jpg")) { cctag::View my_view( filename ); rgb8_image_t& image = my_view._image; rgb8_view_t& svw = my_view._view; // Increase image size. /*{ rgb8_image_t simage; simage.recreate( 2 * image.width(), 2 * image.height() ); rgb8_view_t osvw( view( simage ) ); terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() ); }*/ // Create inputImagePath/result if it does not exist std::stringstream resultFolderName, localizationFolderName, identificationFolderName; resultFolderName << parentPath.string() << "/result"; localizationFolderName << resultFolderName.str() << "/localization"; identificationFolderName << resultFolderName.str() << "/identification"; if (!bfs::exists(resultFolderName.str())) { bfs::create_directory(resultFolderName.str()); } if (!bfs::exists(localizationFolderName.str())) { bfs::create_directory(localizationFolderName.str()); } if (!bfs::exists(identificationFolderName.str())) { bfs::create_directory(identificationFolderName.str()); } // Set the output image name, holding the same name as the original image // so that the result will be placed in the inputImagePath/result/ folder std::stringstream strstreamResult; strstreamResult << resultFolderName.str() << "/" << myPath.stem().string() << ".png"; ROM_TCOUT(strstreamResult.str()); resultFolderName << "/" << myPath.stem().string(); if (!bfs::exists(resultFolderName.str())) { bfs::create_directory(resultFolderName.str()); } POP_INFO << "using result folder " << resultFolderName.str() << std::endl; POP_INFO << "looking at image " << myPath.stem().string() << std::endl; CCTagVisualDebug::instance().initBackgroundImage(svw); CCTagVisualDebug::instance().initPath(resultFolderName.str()); CCTagVisualDebug::instance().setImageFileName(myPath.stem().string()); CCTagFileDebug::instance().setPath(resultFolderName.str()); detection(0, my_view, paramsFilename); CCTagFileDebug::instance().outPutAllSessions(); CCTagFileDebug::instance().clearSessions(); // write visual file output CCTagVisualDebug::instance().outPutAllSessions(); } else if (bfs::is_directory(folder)) { // todo@Lilian: does not work std::cout << folder << " is a directory containing:\n"; std::vector<bfs::path> filesInFolder; copy(bfs::directory_iterator(folder), bfs::directory_iterator(), back_inserter(filesInFolder)); // is directory_entry, which is // converted to a path by the // path stream inserter sort(filesInFolder.begin(), filesInFolder.end()); std::size_t frame = 0; BOOST_FOREACH(const bfs::path & fileInFolder, filesInFolder) { ROM_TCOUT(fileInFolder); const std::string ext(bfs::extension(fileInFolder)); std::stringstream outFilename, inFilename; if (ext == ".png") { inFilename << argv[3] << "/orig/" << std::setfill('0') << std::setw(5) << frame << ".png"; outFilename << argv[3] << "/" << std::setfill('0') << std::setw(5) << frame << ".png"; cctag::View my_view( inFilename.str() ); rgb8_image_t& image = my_view._image; rgb8_view_t& sourceView = my_view._view; // rgb8_image_t image(png_read_dimensions(fileInFolder.c_str())); // rgb8_view_t sourceView(view(image)); // png_read_and_convert_view(fileInFolder.c_str(), sourceView); POP_INFO << "writing input image to " << inFilename.str() << std::endl; png_write_view(inFilename.str(), sourceView); CCTagVisualDebug::instance().initBackgroundImage(sourceView); detection(frame, my_view, paramsFilename); POP_INFO << "writing ouput image to " << outFilename.str() << std::endl; png_write_view(outFilename.str(), sourceView); ++frame; } } } else { throw std::logic_error("Unrecognized input."); } } catch (...) { std::cerr << boost::current_exception_diagnostic_information() << std::endl; return 1; } return 0; } <commit_msg>Add video mode: - read - process<commit_after>#define png_infopp_NULL (png_infopp)NULL #define int_p_NULL (int*)NULL #include <boost/gil/extension/io/png_io.hpp> #include <cctag/fileDebug.hpp> #include <cctag/visualDebug.hpp> #include <cctag/progBase/exceptions.hpp> #include <cctag/progBase/MemoryPool.hpp> #include <cctag/detection.hpp> #include <cctag/view.hpp> #include <cctag/image.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/gil/gil_all.hpp> #include <boost/gil/image.hpp> #include <boost/gil/extension/io/jpeg_io.hpp> #include <boost/exception/all.hpp> #include <boost/ptr_container/ptr_list.hpp> #include <boost/archive/xml_oarchive.hpp> #include <boost/archive/xml_iarchive.hpp> #include <terry/sampler/all.hpp> #include <terry/sampler/resample_subimage.hpp> #include <opencv/cv.h> #include <opencv/highgui.h> #include <opencv2/core/core.hpp> #include <sstream> #include <iostream> #include <string> #include <fstream> #include <exception> using namespace cctag::vision; using boost::timer; using namespace boost::gil; namespace bfs = boost::filesystem; static const std::string kUsageString = "Usage: detection image_file.png\n"; void detection(std::size_t frame, cctag::View& view, const std::string & paramsFilename = "") { POP_ENTER; // Process markers detection boost::timer t; boost::ptr_list<marker::CCTag> markers; cctag::vision::marker::Parameters params; if (paramsFilename != "") { std::ifstream ifs(paramsFilename.c_str()); boost::archive::xml_iarchive ia(ifs); // write class instance to archive ia >> boost::serialization::make_nvp("CCTagsParams", params); } else { std::ofstream ofs("detectionCCTagParams.xml"); boost::archive::xml_oarchive oa(ofs); // write class instance to archive oa << boost::serialization::make_nvp("CCTagsParams", params); } view.setNumLayers( params._numberOfMultiresLayers ); ROM_COUT("beforecctagDetection"); cctagDetection( markers, frame, view._grayView, params, true ); ROM_COUT("aftercctagDetection"); std::cout << "Id : "; int i = 0; BOOST_FOREACH(const cctag::vision::marker::CCTag & marker, markers) { cctag::vision::marker::drawMarkerOnGilImage(view._view, marker, false); cctag::vision::marker::drawMarkerInfos(view._view, marker, false); if (i == 0) { std::cout << marker.id() + 1; } else { std::cout << ", " << marker.id() + 1; } ++i; } std::cout << std::endl; ROM_TCOUT( markers.size() << " markers."); ROM_TCOUT("Total time: " << t.elapsed()); POP_LEAVE; } /*************************************************************/ /* Main entry */ /*************************************************************/ int main(int argc, char** argv) { try { if (argc <= 1) { BOOST_THROW_EXCEPTION(cctag::exception::Bug() << cctag::exception::user() + kUsageString); } cctag::MemoryPool::instance().updateMemoryAuthorizedWithRAM(); const std::string filename(argv[1]); std::string paramsFilename; if (argc >= 3) { paramsFilename = argv[2]; } bfs::path myPath(filename); const bfs::path extPath(myPath.extension()); const bfs::path subFilenamePath(myPath.filename()); const bfs::path parentPath(myPath.parent_path()); std::string ext(extPath.string()); bfs::path folder(argv[1]); if ((ext == ".png") || (ext == ".jpg")) { cctag::View my_view( filename ); rgb8_image_t& image = my_view._image; rgb8_view_t& svw = my_view._view; // Increase image size. /*{ rgb8_image_t simage; simage.recreate( 2 * image.width(), 2 * image.height() ); rgb8_view_t osvw( view( simage ) ); terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() ); }*/ // Create inputImagePath/result if it does not exist std::stringstream resultFolderName, localizationFolderName, identificationFolderName; resultFolderName << parentPath.string() << "/result"; localizationFolderName << resultFolderName.str() << "/localization"; identificationFolderName << resultFolderName.str() << "/identification"; if (!bfs::exists(resultFolderName.str())) { bfs::create_directory(resultFolderName.str()); } if (!bfs::exists(localizationFolderName.str())) { bfs::create_directory(localizationFolderName.str()); } if (!bfs::exists(identificationFolderName.str())) { bfs::create_directory(identificationFolderName.str()); } // Set the output image name, holding the same name as the original image // so that the result will be placed in the inputImagePath/result/ folder std::stringstream strstreamResult; strstreamResult << resultFolderName.str() << "/" << myPath.stem().string() << ".png"; ROM_TCOUT(strstreamResult.str()); resultFolderName << "/" << myPath.stem().string(); if (!bfs::exists(resultFolderName.str())) { bfs::create_directory(resultFolderName.str()); } POP_INFO << "using result folder " << resultFolderName.str() << std::endl; POP_INFO << "looking at image " << myPath.stem().string() << std::endl; CCTagVisualDebug::instance().initBackgroundImage(svw); CCTagVisualDebug::instance().initPath(resultFolderName.str()); CCTagVisualDebug::instance().setImageFileName(myPath.stem().string()); CCTagFileDebug::instance().setPath(resultFolderName.str()); detection(0, my_view, paramsFilename); CCTagFileDebug::instance().outPutAllSessions(); CCTagFileDebug::instance().clearSessions(); // write visual file output CCTagVisualDebug::instance().outPutAllSessions(); } else if (bfs::is_directory(folder)) { // todo@Lilian: does not work std::cout << folder << " is a directory containing:\n"; std::vector<bfs::path> filesInFolder; copy(bfs::directory_iterator(folder), bfs::directory_iterator(), back_inserter(filesInFolder)); // is directory_entry, which is // converted to a path by the // path stream inserter sort(filesInFolder.begin(), filesInFolder.end()); std::size_t frame = 0; BOOST_FOREACH(const bfs::path & fileInFolder, filesInFolder) { ROM_TCOUT(fileInFolder); const std::string ext(bfs::extension(fileInFolder)); std::stringstream outFilename, inFilename; if (ext == ".png") { inFilename << argv[3] << "/orig/" << std::setfill('0') << std::setw(5) << frame << ".png"; outFilename << argv[3] << "/" << std::setfill('0') << std::setw(5) << frame << ".png"; cctag::View my_view( inFilename.str() ); rgb8_image_t& image = my_view._image; rgb8_view_t& sourceView = my_view._view; // rgb8_image_t image(png_read_dimensions(fileInFolder.c_str())); // rgb8_view_t sourceView(view(image)); // png_read_and_convert_view(fileInFolder.c_str(), sourceView); POP_INFO << "writing input image to " << inFilename.str() << std::endl; png_write_view(inFilename.str(), sourceView); CCTagVisualDebug::instance().initBackgroundImage(sourceView); detection(frame, my_view, paramsFilename); POP_INFO << "writing ouput image to " << outFilename.str() << std::endl; png_write_view(outFilename.str(), sourceView); ++frame; } } } else if (ext == ".avi" ){// || ext == ".mts" || ext == ".mov") { std::cout << "*** Video mode ***" << std::endl; // open video and check cv::VideoCapture video(filename.c_str()); if(!video.isOpened()) {std::cout << "Unable to open the video : " << filename; return -1;} // play loop int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT); int frameId = 0; while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame ) { cv::Mat frame; video >> frame; cv::Mat imgGray; cv::cvtColor( frame, imgGray, CV_BGR2GRAY ); cctag::View cctagView((const unsigned char *) imgGray.data, imgGray.cols, imgGray.rows , imgGray.step ); cctag::vision::marker::Parameters params; boost::ptr_list<marker::CCTag> cctags; cctagDetection(cctags, frameId ,cctagView._grayView ,params, true); ++frameId; } } else { throw std::logic_error("Unrecognized input."); } } catch (...) { std::cerr << boost::current_exception_diagnostic_information() << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before><commit_msg>Fix warning<commit_after><|endoftext|>
<commit_before>#include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgDB/WriteFile> #include <osg/ref_ptr> #include <iostream> #include "TXPNode.h" using namespace osg; bool TXPNode_readLocalData(osg::Object &obj, osgDB::Input &fr); bool TXPNode_writeLocalData(const osg::Object &obj, osgDB::Output &fw); osgDB::RegisterDotOsgWrapperProxy TXPNode_Proxy ( new txp::TXPNode, "TXPNode", "Object Node TXPNode", TXPNode_readLocalData, TXPNode_writeLocalData ); bool TXPNode_readLocalData(osg::Object &obj, osgDB::Input &fr) { txp::TXPNode &txpNode = static_cast<txp::TXPNode &>(obj); bool itrAdvanced = false; if (fr.matchSequence("databaseOptions %s")) { txpNode.setOptions(fr[1].getStr()); fr += 2; itrAdvanced = true; } if (fr.matchSequence("databaseName %s")) { txpNode.setArchiveName(fr[1].getStr()); txpNode.loadArchive(); fr += 2; itrAdvanced = true; } return itrAdvanced; } class Dump2Osg : public osg::NodeVisitor { public: Dump2Osg(osgDB::Output &fw) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _fw(fw) {}; virtual void apply(osg::Node& node) { _fw.writeObject(node); NodeVisitor::apply(node); } osgDB::Output &_fw; }; bool TXPNode_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { const txp::TXPNode &txpNode = static_cast<const txp::TXPNode&>(obj); if (!txpNode.getOptions().empty()) fw.indent() << "databaseOptions \"" << txpNode.getOptions() << "\""<<std::endl; if (!txpNode.getArchiveName().empty()) fw.indent() << "archive name\"" << txpNode.getArchiveName() << "\"" << std::endl; osg::Group* grp = const_cast<osg::Group*>(txpNode.asGroup()); Dump2Osg wrt(fw); grp->accept(wrt); return true; } <commit_msg>Fixed keyword used for setting the database name.<commit_after>#include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include <osgDB/WriteFile> #include <osg/ref_ptr> #include <iostream> #include "TXPNode.h" using namespace osg; bool TXPNode_readLocalData(osg::Object &obj, osgDB::Input &fr); bool TXPNode_writeLocalData(const osg::Object &obj, osgDB::Output &fw); osgDB::RegisterDotOsgWrapperProxy TXPNode_Proxy ( new txp::TXPNode, "TXPNode", "Object Node TXPNode", TXPNode_readLocalData, TXPNode_writeLocalData ); bool TXPNode_readLocalData(osg::Object &obj, osgDB::Input &fr) { txp::TXPNode &txpNode = static_cast<txp::TXPNode &>(obj); bool itrAdvanced = false; if (fr.matchSequence("databaseOptions %s")) { txpNode.setOptions(fr[1].getStr()); fr += 2; itrAdvanced = true; } if (fr.matchSequence("databaseName %s")) { txpNode.setArchiveName(fr[1].getStr()); txpNode.loadArchive(); fr += 2; itrAdvanced = true; } return itrAdvanced; } class Dump2Osg : public osg::NodeVisitor { public: Dump2Osg(osgDB::Output &fw) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _fw(fw) {}; virtual void apply(osg::Node& node) { _fw.writeObject(node); NodeVisitor::apply(node); } osgDB::Output &_fw; }; bool TXPNode_writeLocalData(const osg::Object &obj, osgDB::Output &fw) { const txp::TXPNode &txpNode = static_cast<const txp::TXPNode&>(obj); if (!txpNode.getOptions().empty()) fw.indent() << "databaseOptions \"" << txpNode.getOptions() << "\""<<std::endl; if (!txpNode.getArchiveName().empty()) fw.indent() << "databaseName \"" << txpNode.getArchiveName() << "\"" << std::endl; osg::Group* grp = const_cast<osg::Group*>(txpNode.asGroup()); Dump2Osg wrt(fw); grp->accept(wrt); return true; } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., 51 * * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #define MY_PARAM_TYPE(name, DType, MType) \ struct name { \ typedef DType DataType; \ typedef MType MassType; \ }; \ #include "Sofa_test.h" #include <SofaComponentMain/init.h> //Including Simulation #include <sofa/simulation/common/Simulation.h> #include <sofa/simulation/graph/DAGSimulation.h> #include <sofa/simulation/common/Node.h> #include <SceneCreator/SceneCreator.h> #include <SofaBaseMechanics/DiagonalMass.h> #include <SofaBaseTopology/HexahedronSetTopologyContainer.h> #include <SofaBaseTopology/HexahedronSetGeometryAlgorithms.h> #include <SofaBaseMechanics/MechanicalObject.h> //TODO : Perform smart tests :) Infrastructure for multi templated tests is ok. namespace sofa { template <class T> class DiagonalMass_test : public ::testing::Test { public : typedef typename T::DataType dt; typedef typename T::MassType mt; typedef typename dt::Coord Coord; typedef typename dt::VecCoord VecCoord; typedef sofa::component::mass::DiagonalMass<dt,mt> DiagonalMassType; typename DiagonalMassType::SPtr m; /// Root of the scene graph sofa::simulation::Node::SPtr root; /// Simulation sofa::simulation::Simulation* simulation; /** * Constructor call for each test */ virtual void SetUp() { // Init simulation sofa::component::init(); sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); root = simulation::getSimulation()->createNewGraph("root"); } void createSceneHexa() { simulation::Node::SPtr oneHexa = root->createChild("oneHexa"); sofa::component::topology::HexahedronSetTopologyContainer::SPtr container = sofa::modeling::addNew<sofa::component::topology::HexahedronSetTopologyContainer>(oneHexa, "container"); container->addHexa(0,1,2,3,4,5,6,7); typename sofa::component::topology::HexahedronSetGeometryAlgorithms<dt>::SPtr algo = sofa::modeling::addNew<sofa::component::topology::HexahedronSetGeometryAlgorithms<dt> >(oneHexa); typename sofa::component::container::MechanicalObject<dt>::SPtr meca= sofa::modeling::addNew<sofa::component::container::MechanicalObject<dt> >(oneHexa); VecCoord pos; pos.push_back(Coord(0.0, 0.0, 0.0)); pos.push_back(Coord(1.0, 0.0, 0.0)); pos.push_back(Coord(1.0, 1.0, 0.0)); pos.push_back(Coord(0.0, 1.0, 0.0)); pos.push_back(Coord(0.0, 0.0, 1.0)); pos.push_back(Coord(1.0, 0.0, 1.0)); pos.push_back(Coord(1.0, 1.0, 1.0)); pos.push_back(Coord(0.0, 1.0, 1.0)); meca->x = pos; typename sofa::component::mass::DiagonalMass<dt,mt>::SPtr mass = sofa::modeling::addNew<sofa::component::mass::DiagonalMass<dt,mt> >(oneHexa); } bool testHexaMass() { //initialize the simulation sofa::simulation::getSimulation()->init(root.get()); //get the node called "oneHexa" simulation::Node *node = root->getChild("oneHexa"); //the node is supposed to be found if (!node) { ADD_FAILURE() << "Cannot find first node" << std::endl; return false; } //get the mass sofa::component::mass::DiagonalMass<dt,mt> *mass = node->get<sofa::component::mass::DiagonalMass<dt,mt> >(node->SearchDown); if (!mass) { ADD_FAILURE() << "Cannot find mass" << std::endl; return false; } //get the mechanical object typename sofa::component::container::MechanicalObject<dt> *meca = node->get<sofa::component::container::MechanicalObject<dt> >(node->SearchDown); if (!meca) { ADD_FAILURE() << "Cannot find mechanical object" << std::endl; return false; } //test the number of mass points if (meca->x.getValue().size() != mass->f_mass.getValue().size()) { ADD_FAILURE() << "Mass vector has not the same size as the number of points (" << mass->f_mass.getValue().size() << "!="<< meca->x.getValue().size() << ")" << std::endl; return false; } //check if the total mass is correct if ( fabs(1.0 - mass->m_totalMass.getValue()) > 1e-6) { ADD_FAILURE() << "Not the expected total mass: " << mass->m_totalMass << " and should be 1" << std::endl; return false; } return true; } void TearDown() { if (root!=NULL) sofa::simulation::getSimulation()->unload(root); } }; TYPED_TEST_CASE_P(DiagonalMass_test); TYPED_TEST_P(DiagonalMass_test, testHexahedra) { this->createSceneHexa(); ASSERT_TRUE(this->testHexaMass()); } REGISTER_TYPED_TEST_CASE_P(DiagonalMass_test, testHexahedra); #ifndef SOFA_FLOAT MY_PARAM_TYPE(Vec3dd, sofa::defaulttype::Vec3dTypes, double) MY_PARAM_TYPE(Vec2dd, sofa::defaulttype::Vec2dTypes, double) MY_PARAM_TYPE(Vec1dd, sofa::defaulttype::Vec1dTypes, double) INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_hexa_test_case3d, DiagonalMass_test, Vec3dd); //INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case1d, DiagonalMass_test, Vec3dd); //INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case2d, DiagonalMass_test, Vec2dd); //INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case3d, DiagonalMass_test, Vec1dd); #endif #ifndef SOFA_DOUBLE MY_PARAM_TYPE(Vec3ff, sofa::defaulttype::Vec3fTypes, float) MY_PARAM_TYPE(Vec2ff, sofa::defaulttype::Vec2fTypes, float) MY_PARAM_TYPE(Vec1ff, sofa::defaulttype::Vec1fTypes, float) INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_hexa_test_case3f, DiagonalMass_test, Vec3ff); //INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case1f, DiagonalMass_test, Vec3ff); //INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case2f, DiagonalMass_test, Vec2ff); //INSTANTIATE_TYPED_TEST_CASE_P(DiagonalMass_test_case3f, DiagonalMass_test, Vec1ff); #endif } // namespace sofa <commit_msg>SofaBaseMechanics: clean up tests for DiagonalMass<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., 51 * * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include "Sofa_test.h" #include <SofaComponentMain/init.h> #include <sofa/simulation/common/Simulation.h> #include <sofa/simulation/graph/DAGSimulation.h> #include <sofa/simulation/common/Node.h> #include <SofaBaseMechanics/DiagonalMass.h> #include <SofaBaseMechanics/MechanicalObject.h> #include <SofaBaseTopology/HexahedronSetTopologyContainer.h> #include <SofaBaseTopology/HexahedronSetGeometryAlgorithms.h> using namespace sofa::defaulttype; using namespace sofa::component::topology; using sofa::core::objectmodel::New; using sofa::component::mass::DiagonalMass; using sofa::component::container::MechanicalObject; namespace sofa { template <class T> class DiagonalMass_test : public ::testing::Test { public: simulation::Node::SPtr root; simulation::Simulation* simulation; virtual void SetUp() { component::init(); simulation::setSimulation(simulation = new simulation::graph::DAGSimulation()); root = simulation::getSimulation()->createNewGraph("root"); } void TearDown() { if (root!=NULL) simulation::getSimulation()->unload(root); } }; // Define the list of DataTypes to instanciate the tests with. using testing::Types; typedef Types< #if defined(SOFA_FLOAT) Vec3fTypes #elif defined(SOFA_DOUBLE) Vec3dTypes #else Vec3fTypes, Vec3dTypes #endif > DataTypes; // Instanciate the test suite for each type in 'DataTypes'. TYPED_TEST_CASE(DiagonalMass_test, DataTypes); TYPED_TEST(DiagonalMass_test, singleHexahedron) { typedef TypeParam DataTypes; typedef typename DataTypes::Coord Coord; typedef typename DataTypes::VecCoord VecCoord; typedef MechanicalObject<DataTypes> MechanicalObject; typedef DiagonalMass<DataTypes, typename DataTypes::Real> DiagonalMass; // Create the scene graph. simulation::Node::SPtr node = this->root->createChild("oneHexa"); HexahedronSetTopologyContainer::SPtr container = New<HexahedronSetTopologyContainer>(); node->addObject(container); typename MechanicalObject::SPtr mstate = New<MechanicalObject>(); node->addObject(mstate); node->addObject(New<HexahedronSetGeometryAlgorithms<DataTypes> >()); typename DiagonalMass::SPtr mass = New<DiagonalMass>(); node->addObject(mass); // Handcraft a cubic hexahedron. VecCoord pos; pos.push_back(Coord(0.0, 0.0, 0.0)); pos.push_back(Coord(1.0, 0.0, 0.0)); pos.push_back(Coord(1.0, 1.0, 0.0)); pos.push_back(Coord(0.0, 1.0, 0.0)); pos.push_back(Coord(0.0, 0.0, 1.0)); pos.push_back(Coord(1.0, 0.0, 1.0)); pos.push_back(Coord(1.0, 1.0, 1.0)); pos.push_back(Coord(0.0, 1.0, 1.0)); mstate->x = pos; container->addHexa(0,1,2,3,4,5,6,7); // DiagonalMass computes the mass in reinit(), so init() the graph. simulation::getSimulation()->init(this->root.get()); // Check that the mass vector has the right size. ASSERT_EQ(mstate->x.getValue().size(), mass->f_mass.getValue().size()); // Check the mass at each index. EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[0]); EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[1]); EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[2]); EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[3]); EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[4]); EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[5]); EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[6]); EXPECT_FLOAT_EQ(0.125, mass->f_mass.getValue()[7]); // Check the total mass. EXPECT_FLOAT_EQ(mass->m_totalMass.getValue(), 1.0); } } // namespace sofa <|endoftext|>
<commit_before>#include <sstream> #include <algorithm> #include <set> #include <memory> #include <dlfcn.h> #include "plugin-loader.hpp" #include "wayfire/output-layout.hpp" #include "wayfire/output.hpp" #include "../core/wm.hpp" #include "wayfire/core.hpp" #include <wayfire/util/log.hpp> namespace { template<class A, class B> B union_cast(A object) { union { A x; B y; } helper; helper.x = object; return helper.y; } } plugin_manager::plugin_manager(wf::output_t *o) { this->output = o; this->plugins_opt.load_option("core/plugins"); reload_dynamic_plugins(); load_static_plugins(); this->plugins_opt.set_callback([=] () { /* reload when config reload has finished */ idle_reaload_plugins.run_once([&] () {reload_dynamic_plugins(); }); }); } void plugin_manager::deinit_plugins(bool unloadable) { for (auto& p : loaded_plugins) { if (!p.second) // already destroyed on the previous iteration continue; if (p.second->is_unloadable() == unloadable) destroy_plugin(p.second); } } plugin_manager::~plugin_manager() { /* First remove unloadable plugins, then others */ deinit_plugins(true); deinit_plugins(false); loaded_plugins.clear(); } void plugin_manager::init_plugin(wayfire_plugin& p) { p->grab_interface = std::make_unique<wf::plugin_grab_interface_t> (output); p->output = output; p->init(); } void plugin_manager::destroy_plugin(wayfire_plugin& p) { p->grab_interface->ungrab(); output->deactivate_plugin(p->grab_interface); p->fini(); auto handle = p->handle; p.reset(); /* dlopen()/dlclose() do reference counting, so we should close the plugin * as many times as we opened it. * * We also need to close the handle after deallocating the plugin, otherwise * we unload its destructor before calling it. */ if (handle) dlclose(handle); } wayfire_plugin plugin_manager::load_plugin_from_file(std::string path) { // RTLD_GLOBAL is required for RTTI/dynamic_cast across plugins void *handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL); if(handle == NULL) { LOGE("error loading plugin: ", dlerror()); return nullptr; } /* Check plugin version */ auto version_func_ptr = dlsym(handle, "getWayfireVersion"); if (version_func_ptr == NULL) { LOGE(path, ": missing getWayfireVersion()", path.c_str()); dlclose(handle); return nullptr; } auto version_func = union_cast<void*, wayfire_plugin_version_func> (version_func_ptr); int32_t plugin_abi_version = version_func(); if (version_func() != WAYFIRE_API_ABI_VERSION) { LOGE(path, ": API/ABI version mismatch: Wayfire is ", WAYFIRE_API_ABI_VERSION, ", plugin built with ", plugin_abi_version); dlclose(handle); return nullptr; } auto new_instance_func_ptr = dlsym(handle, "newInstance"); if(new_instance_func_ptr == NULL) { LOGE(path, ": missing newInstance(). ", dlerror()); return nullptr; } LOGD("Loading plugin ", path.c_str()); auto new_instance_func = union_cast<void*, wayfire_plugin_load_func> (new_instance_func_ptr); auto ptr = wayfire_plugin(new_instance_func()); ptr->handle = handle; return ptr; } void plugin_manager::reload_dynamic_plugins() { std::string plugin_list = plugins_opt; if (plugin_list == "none") { LOGE("No plugins specified in the config file, or config file is " "missing. In this state the compositor is nearly unusable, please " "ensure your configuration file is set up properly."); } std::stringstream stream(plugin_list); std::vector<std::string> next_plugins; auto plugin_prefix = std::string(PLUGIN_PATH "/"); std::string plugin_name; while(stream >> plugin_name) { if (plugin_name.size()) { if (plugin_name.at(0) == '/') next_plugins.push_back(plugin_name); else next_plugins.push_back(plugin_prefix + "lib" + plugin_name + ".so"); } } /* erase plugins that have been removed from the config */ auto it = loaded_plugins.begin(); while(it != loaded_plugins.end()) { /* skip built-in(static) plugins */ if (it->first.size() && it->first[0] == '_') { ++it; continue; } if (std::find(next_plugins.begin(), next_plugins.end(), it->first) == next_plugins.end() && it->second->is_unloadable()) { LOGD("unload plugin ", it->first.c_str()); destroy_plugin(it->second); it = loaded_plugins.erase(it); } else { ++it; } } /* load new plugins */ for (auto plugin : next_plugins) { if (loaded_plugins.count(plugin)) continue; auto ptr = load_plugin_from_file(plugin); if (ptr) { init_plugin(ptr); loaded_plugins[plugin] = std::move(ptr); } } } template<class T> static wayfire_plugin create_plugin() { return std::unique_ptr<wf::plugin_interface_t>(new T); } void plugin_manager::load_static_plugins() { loaded_plugins["_exit"] = create_plugin<wayfire_exit>(); loaded_plugins["_focus"] = create_plugin<wayfire_focus>(); loaded_plugins["_close"] = create_plugin<wayfire_close>(); init_plugin(loaded_plugins["_exit"]); init_plugin(loaded_plugins["_focus"]); init_plugin(loaded_plugins["_close"]); } <commit_msg>plugin-loader: Call fini before ungrabbing<commit_after>#include <sstream> #include <algorithm> #include <set> #include <memory> #include <dlfcn.h> #include "plugin-loader.hpp" #include "wayfire/output-layout.hpp" #include "wayfire/output.hpp" #include "../core/wm.hpp" #include "wayfire/core.hpp" #include <wayfire/util/log.hpp> namespace { template<class A, class B> B union_cast(A object) { union { A x; B y; } helper; helper.x = object; return helper.y; } } plugin_manager::plugin_manager(wf::output_t *o) { this->output = o; this->plugins_opt.load_option("core/plugins"); reload_dynamic_plugins(); load_static_plugins(); this->plugins_opt.set_callback([=] () { /* reload when config reload has finished */ idle_reaload_plugins.run_once([&] () {reload_dynamic_plugins(); }); }); } void plugin_manager::deinit_plugins(bool unloadable) { for (auto& p : loaded_plugins) { if (!p.second) // already destroyed on the previous iteration continue; if (p.second->is_unloadable() == unloadable) destroy_plugin(p.second); } } plugin_manager::~plugin_manager() { /* First remove unloadable plugins, then others */ deinit_plugins(true); deinit_plugins(false); loaded_plugins.clear(); } void plugin_manager::init_plugin(wayfire_plugin& p) { p->grab_interface = std::make_unique<wf::plugin_grab_interface_t> (output); p->output = output; p->init(); } void plugin_manager::destroy_plugin(wayfire_plugin& p) { p->fini(); p->grab_interface->ungrab(); output->deactivate_plugin(p->grab_interface); auto handle = p->handle; p.reset(); /* dlopen()/dlclose() do reference counting, so we should close the plugin * as many times as we opened it. * * We also need to close the handle after deallocating the plugin, otherwise * we unload its destructor before calling it. */ if (handle) dlclose(handle); } wayfire_plugin plugin_manager::load_plugin_from_file(std::string path) { // RTLD_GLOBAL is required for RTTI/dynamic_cast across plugins void *handle = dlopen(path.c_str(), RTLD_NOW | RTLD_GLOBAL); if(handle == NULL) { LOGE("error loading plugin: ", dlerror()); return nullptr; } /* Check plugin version */ auto version_func_ptr = dlsym(handle, "getWayfireVersion"); if (version_func_ptr == NULL) { LOGE(path, ": missing getWayfireVersion()", path.c_str()); dlclose(handle); return nullptr; } auto version_func = union_cast<void*, wayfire_plugin_version_func> (version_func_ptr); int32_t plugin_abi_version = version_func(); if (version_func() != WAYFIRE_API_ABI_VERSION) { LOGE(path, ": API/ABI version mismatch: Wayfire is ", WAYFIRE_API_ABI_VERSION, ", plugin built with ", plugin_abi_version); dlclose(handle); return nullptr; } auto new_instance_func_ptr = dlsym(handle, "newInstance"); if(new_instance_func_ptr == NULL) { LOGE(path, ": missing newInstance(). ", dlerror()); return nullptr; } LOGD("Loading plugin ", path.c_str()); auto new_instance_func = union_cast<void*, wayfire_plugin_load_func> (new_instance_func_ptr); auto ptr = wayfire_plugin(new_instance_func()); ptr->handle = handle; return ptr; } void plugin_manager::reload_dynamic_plugins() { std::string plugin_list = plugins_opt; if (plugin_list == "none") { LOGE("No plugins specified in the config file, or config file is " "missing. In this state the compositor is nearly unusable, please " "ensure your configuration file is set up properly."); } std::stringstream stream(plugin_list); std::vector<std::string> next_plugins; auto plugin_prefix = std::string(PLUGIN_PATH "/"); std::string plugin_name; while(stream >> plugin_name) { if (plugin_name.size()) { if (plugin_name.at(0) == '/') next_plugins.push_back(plugin_name); else next_plugins.push_back(plugin_prefix + "lib" + plugin_name + ".so"); } } /* erase plugins that have been removed from the config */ auto it = loaded_plugins.begin(); while(it != loaded_plugins.end()) { /* skip built-in(static) plugins */ if (it->first.size() && it->first[0] == '_') { ++it; continue; } if (std::find(next_plugins.begin(), next_plugins.end(), it->first) == next_plugins.end() && it->second->is_unloadable()) { LOGD("unload plugin ", it->first.c_str()); destroy_plugin(it->second); it = loaded_plugins.erase(it); } else { ++it; } } /* load new plugins */ for (auto plugin : next_plugins) { if (loaded_plugins.count(plugin)) continue; auto ptr = load_plugin_from_file(plugin); if (ptr) { init_plugin(ptr); loaded_plugins[plugin] = std::move(ptr); } } } template<class T> static wayfire_plugin create_plugin() { return std::unique_ptr<wf::plugin_interface_t>(new T); } void plugin_manager::load_static_plugins() { loaded_plugins["_exit"] = create_plugin<wayfire_exit>(); loaded_plugins["_focus"] = create_plugin<wayfire_focus>(); loaded_plugins["_close"] = create_plugin<wayfire_close>(); init_plugin(loaded_plugins["_exit"]); init_plugin(loaded_plugins["_focus"]); init_plugin(loaded_plugins["_close"]); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AResultSetMetaData.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2006-09-17 02:15:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #ifndef _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_ #include "ado/AResultSetMetaData.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_ #include <com/sun/star/sdbc/DataType.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_ #include "ado/Awrapado.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include "connectivity/dbexception.hxx" #endif using namespace connectivity; using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; // ------------------------------------------------------------------------- OResultSetMetaData::~OResultSetMetaData() { m_pRecordSet->Release(); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid() && aField.GetActualSize() != -1) return aField.GetActualSize(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); return ADOS::MapADOType2Jdbc(aField.GetADOType()); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount( ) throw(SQLException, RuntimeException) { if(m_nColCount != -1) return m_nColCount; ADOFields* pFields = NULL; m_pRecordSet->get_Fields(&pFields); WpOLEAppendCollection<ADOFields, ADOField, WpADOField> aFields(pFields); m_nColCount = aFields.GetItemCount(); return m_nColCount; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Bool bRet = sal_False; WpADOField aField = ADOS::getField(m_pRecordSet,column); if ( aField.IsValid() ) { WpADOProperties aProps( aField.get_Properties() ); if ( aProps.IsValid() ) bRet = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ISCASESENSITIVE")) ); } return bRet; } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) return aField.GetName(); return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) throw(SQLException, RuntimeException) { ::rtl::OUString sTableName; WpADOField aField = ADOS::getField(m_pRecordSet,column); if ( aField.IsValid() ) { WpADOProperties aProps( aField.get_Properties() ); if ( aProps.IsValid() ) sTableName = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BASETABLENAME")) ); } return sTableName; } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(SQLException, RuntimeException) { return getColumnName(column); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return ::rtl::OUString(); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { return ((aField.GetAttributes() & adFldFixed) == adFldFixed) && (aField.GetADOType() == adCurrency); } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Bool bRet = sal_False; WpADOField aField = ADOS::getField(m_pRecordSet,column); if ( aField.IsValid() ) { WpADOProperties aProps( aField.get_Properties() ); if ( aProps.IsValid() ) { bRet = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ISAUTOINCREMENT")) ); #if OSL_DEBUG_LEVEL > 0 sal_Int32 nCount = aProps.GetItemCount(); for (sal_Int32 i = 0; i<nCount; ++i) { WpADOProperty aProp = aProps.GetItem(i); ::rtl::OUString sName = aProp.GetName(); ::rtl::OUString sVal = aProp.GetValue(); } #endif } } return bRet; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { DataTypeEnum eType = aField.GetADOType(); return !(eType == adUnsignedBigInt || eType == adUnsignedInt || eType == adUnsignedSmallInt || eType == adUnsignedTinyInt); } return sal_False; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) return aField.GetPrecision(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) return aField.GetNumericScale(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { return (aField.GetAttributes() & adFldIsNullable) == adFldIsNullable; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return sal_True; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { // return (aField.GetStatus() & adFieldReadOnly) == adFieldReadOnly; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { return (aField.GetAttributes() & adFldUpdatable) == adFldUpdatable; } return sal_False; ; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) throw(SQLException, RuntimeException) { return isDefinitelyWritable(column); } // ------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS dba21fini (1.11.26); FILE MERGED 2006/10/27 08:14:33 oj 1.11.26.1: #142400# check recordset<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: AResultSetMetaData.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2006-11-06 14:34:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #ifndef _CONNECTIVITY_ADO_ARESULTSETMETADATA_HXX_ #include "ado/AResultSetMetaData.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_ #include <com/sun/star/sdbc/DataType.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_ #include <com/sun/star/sdbc/ColumnValue.hpp> #endif #ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_ #include "ado/Awrapado.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include "connectivity/dbexception.hxx" #endif using namespace connectivity; using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; OResultSetMetaData::OResultSetMetaData( ADORecordset* _pRecordSet) : m_pRecordSet(_pRecordSet), m_nColCount(-1) { if ( m_pRecordSet ) m_pRecordSet->AddRef(); } // ------------------------------------------------------------------------- OResultSetMetaData::~OResultSetMetaData() { if ( m_pRecordSet ) m_pRecordSet->Release(); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid() && aField.GetActualSize() != -1) return aField.GetActualSize(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); return ADOS::MapADOType2Jdbc(aField.GetADOType()); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount( ) throw(SQLException, RuntimeException) { if(m_nColCount != -1 ) return m_nColCount; if ( !m_pRecordSet ) return 0; ADOFields* pFields = NULL; m_pRecordSet->get_Fields(&pFields); WpOLEAppendCollection<ADOFields, ADOField, WpADOField> aFields(pFields); m_nColCount = aFields.GetItemCount(); return m_nColCount; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Bool bRet = sal_False; WpADOField aField = ADOS::getField(m_pRecordSet,column); if ( aField.IsValid() ) { WpADOProperties aProps( aField.get_Properties() ); if ( aProps.IsValid() ) bRet = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ISCASESENSITIVE")) ); } return bRet; } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) return aField.GetName(); return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) throw(SQLException, RuntimeException) { ::rtl::OUString sTableName; WpADOField aField = ADOS::getField(m_pRecordSet,column); if ( aField.IsValid() ) { WpADOProperties aProps( aField.get_Properties() ); if ( aProps.IsValid() ) sTableName = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BASETABLENAME")) ); } return sTableName; } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(SQLException, RuntimeException) { return getColumnName(column); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return ::rtl::OUString(); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { return ((aField.GetAttributes() & adFldFixed) == adFldFixed) && (aField.GetADOType() == adCurrency); } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Bool bRet = sal_False; WpADOField aField = ADOS::getField(m_pRecordSet,column); if ( aField.IsValid() ) { WpADOProperties aProps( aField.get_Properties() ); if ( aProps.IsValid() ) { bRet = OTools::getValue( aProps, ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ISAUTOINCREMENT")) ); #if OSL_DEBUG_LEVEL > 0 sal_Int32 nCount = aProps.GetItemCount(); for (sal_Int32 i = 0; i<nCount; ++i) { WpADOProperty aProp = aProps.GetItem(i); ::rtl::OUString sName = aProp.GetName(); ::rtl::OUString sVal = aProp.GetValue(); } #endif } } return bRet; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { DataTypeEnum eType = aField.GetADOType(); return !(eType == adUnsignedBigInt || eType == adUnsignedInt || eType == adUnsignedSmallInt || eType == adUnsignedTinyInt); } return sal_False; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) return aField.GetPrecision(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) return aField.GetNumericScale(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { return (aField.GetAttributes() & adFldIsNullable) == adFldIsNullable; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 /*column*/ ) throw(SQLException, RuntimeException) { return sal_True; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { // return (aField.GetStatus() & adFieldReadOnly) == adFieldReadOnly; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(SQLException, RuntimeException) { WpADOField aField = ADOS::getField(m_pRecordSet,column); if(aField.IsValid()) { return (aField.GetAttributes() & adFldUpdatable) == adFldUpdatable; } return sal_False; ; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) throw(SQLException, RuntimeException) { return isDefinitelyWritable(column); } // ------------------------------------------------------------------------- <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/lattice/trajectory_generation/trajectory_evaluator.h" #include <algorithm> #include <cmath> #include <functional> #include <limits> #include <utility> #include "modules/common/log.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/constraint_checker1d.h" #include "modules/planning/lattice/trajectory1d/piecewise_acceleration_trajectory1d.h" namespace apollo { namespace planning { using Trajectory1d = Curve1d; TrajectoryEvaluator::TrajectoryEvaluator( const std::array<double, 3>& init_s, const PlanningTarget& planning_target, const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories, const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories, std::shared_ptr<PathTimeGraph> path_time_graph) : path_time_graph_(path_time_graph), init_s_(init_s) { const double start_time = 0.0; const double end_time = FLAGS_trajectory_time_length; path_time_intervals_ = path_time_graph_->GetPathBlockingIntervals( start_time, end_time, FLAGS_trajectory_time_resolution); // if we have a stop point along the reference line, // filter out the lon. trajectories that pass the stop point. double stop_point = std::numeric_limits<double>::max(); if (planning_target.has_stop_point()) { stop_point = planning_target.stop_point().s(); } for (const auto lon_trajectory : lon_trajectories) { double lon_end_s = lon_trajectory->Evaluate(0, end_time); if (lon_end_s > stop_point) { continue; } if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) { continue; } for (const auto lat_trajectory : lat_trajectories) { /** if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory, *lon_trajectory)) { continue; } */ if (!FLAGS_enable_auto_tuning) { double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory); cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost)); } else { std::vector<double> cost_components; double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory, &cost_components); cost_queue_with_components_.push(PairCostWithComponents( {lon_trajectory, lat_trajectory}, {cost_components, cost})); } } } if (!FLAGS_enable_auto_tuning) { ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size(); } else { ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_with_components_.size(); } } bool TrajectoryEvaluator::has_more_trajectory_pairs() const { if (!FLAGS_enable_auto_tuning) { return !cost_queue_.empty(); } else { return !cost_queue_with_components_.empty(); } } std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const { if (!FLAGS_enable_auto_tuning) { return cost_queue_.size(); } else { return cost_queue_with_components_.size(); } } std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>> TrajectoryEvaluator::next_top_trajectory_pair() { CHECK(has_more_trajectory_pairs() == true); if (!FLAGS_enable_auto_tuning) { auto top = cost_queue_.top(); cost_queue_.pop(); return top.first; } else { auto top = cost_queue_with_components_.top(); cost_queue_with_components_.pop(); return top.first; } } double TrajectoryEvaluator::top_trajectory_pair_cost() const { if (!FLAGS_enable_auto_tuning) { return cost_queue_.top().second; } else { return cost_queue_with_components_.top().second.second; } } std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost() const { CHECK(FLAGS_enable_auto_tuning); return cost_queue_with_components_.top().second.first; } double TrajectoryEvaluator::Evaluate( const PlanningTarget& planning_target, const std::shared_ptr<Trajectory1d>& lon_trajectory, const std::shared_ptr<Trajectory1d>& lat_trajectory, std::vector<double>* cost_components) const { // Costs: // 1. Cost of missing the objective, e.g., cruise, stop, etc. // 2. Cost of logitudinal jerk // 3. Cost of logitudinal collision // 4. Cost of lateral offsets // 5. Cost of lateral comfort // Longitudinal costs auto reference_s_dot = ComputeLongitudinalGuideVelocity(planning_target); double lon_objective_cost = LonObjectiveCost(lon_trajectory, planning_target, reference_s_dot); double lon_jerk_cost = LonComfortCost(lon_trajectory); double lon_collision_cost = LonCollisionCost(lon_trajectory); // decides the longitudinal evaluation horizon for lateral trajectories. double evaluation_horizon = std::min(FLAGS_decision_horizon, lon_trajectory->Evaluate(0, lon_trajectory->ParamLength())); std::vector<double> s_values; for (double s = 0.0; s < evaluation_horizon; s += FLAGS_trajectory_space_resolution) { s_values.push_back(s); } // Lateral costs double lat_offset_cost = LatOffsetCost(lat_trajectory, s_values); double lat_comfort_cost = LatComfortCost(lon_trajectory, lat_trajectory); if (cost_components != nullptr) { cost_components->push_back(lon_objective_cost); cost_components->push_back(lon_jerk_cost); cost_components->push_back(lon_collision_cost); cost_components->push_back(lat_offset_cost); } return lon_objective_cost * FLAGS_weight_lon_travel + lon_jerk_cost * FLAGS_weight_lon_jerk + lon_collision_cost * FLAGS_weight_lon_collision + lat_offset_cost * FLAGS_weight_lat_offset + lat_comfort_cost * FLAGS_weight_lat_comfort; } double TrajectoryEvaluator::LatOffsetCost( const std::shared_ptr<Trajectory1d>& lat_trajectory, const std::vector<double>& s_values) const { double lat_offset_start = lat_trajectory->Evaluate(0, 0.0); double cost_sqr_sum = 0.0; double cost_abs_sum = 0.0; for (const auto& s : s_values) { double lat_offset = lat_trajectory->Evaluate(0, s); double cost = lat_offset / FLAGS_lat_offset_bound; if (lat_offset * lat_offset_start < 0.0) { cost_sqr_sum += cost * cost * FLAGS_weight_opposite_side_offset; cost_abs_sum += std::abs(cost) * FLAGS_weight_opposite_side_offset; } else { cost_sqr_sum += cost * cost * FLAGS_weight_same_side_offset; cost_abs_sum += std::abs(cost) * FLAGS_weight_same_side_offset; } } return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon); } double TrajectoryEvaluator::LatComfortCost( const std::shared_ptr<Trajectory1d>& lon_trajectory, const std::shared_ptr<Trajectory1d>& lat_trajectory) const { double max_cost = 0.0; for (double t = 0.0; t < FLAGS_trajectory_time_length; t += FLAGS_trajectory_time_resolution) { double s = lon_trajectory->Evaluate(0, t); double s_dot = lon_trajectory->Evaluate(1, t); double s_dotdot = lon_trajectory->Evaluate(2, t); double l_prime = lat_trajectory->Evaluate(1, s); double l_primeprime = lat_trajectory->Evaluate(2, s); double cost = l_primeprime * s_dot * s_dot + l_prime * s_dotdot; max_cost = std::max(max_cost, std::abs(cost)); } return max_cost; } double TrajectoryEvaluator::LonComfortCost( const std::shared_ptr<Trajectory1d>& lon_trajectory) const { double cost_sqr_sum = 0.0; double cost_abs_sum = 0.0; for (double t = 0.0; t < FLAGS_trajectory_time_length; t += FLAGS_trajectory_time_resolution) { double jerk = lon_trajectory->Evaluate(3, t); double cost = jerk / FLAGS_longitudinal_jerk_upper_bound; cost_sqr_sum += cost * cost; cost_abs_sum += std::abs(cost); } return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon); } double TrajectoryEvaluator::LonObjectiveCost( const std::shared_ptr<Trajectory1d>& lon_trajectory, const PlanningTarget& planning_target, const std::vector<double>& ref_s_dots) const { double t_max = lon_trajectory->ParamLength(); double dist_s = lon_trajectory->Evaluate(0, t_max) - lon_trajectory->Evaluate(0, 0.0); double speed_cost_sqr_sum = 0.0; double speed_cost_abs_sum = 0.0; for (std::size_t i = 0; i < ref_s_dots.size(); ++i) { double t = i * FLAGS_trajectory_time_resolution; double cost = ref_s_dots[i] - lon_trajectory->Evaluate(1, t); speed_cost_sqr_sum += cost * cost; speed_cost_abs_sum += std::abs(cost); } double speed_cost = speed_cost_sqr_sum / (speed_cost_abs_sum + FLAGS_lattice_epsilon); double dist_travelled_cost = 1.0 / (1.0 + dist_s); return (speed_cost * FLAGS_weight_target_speed + dist_travelled_cost * FLAGS_weight_dist_travelled) / (FLAGS_weight_target_speed + FLAGS_weight_dist_travelled); } // TODO(all): consider putting pointer of reference_line_info and frame // while constructing trajectory evaluator double TrajectoryEvaluator::LonCollisionCost( const std::shared_ptr<Trajectory1d>& lon_trajectory) const { double cost_sqr_sum = 0.0; double cost_abs_sum = 0.0; for (std::size_t i = 0; i < path_time_intervals_.size(); ++i) { const auto& pt_interval = path_time_intervals_[i]; if (pt_interval.empty()) { continue; } double t = i * FLAGS_trajectory_time_resolution; double traj_s = lon_trajectory->Evaluate(0, t); double sigma = FLAGS_lon_collision_cost_std; for (const auto& m : pt_interval) { double dist = 0.0; if (traj_s < m.first - FLAGS_lon_collision_yield_buffer) { dist = m.first - FLAGS_lon_collision_yield_buffer - traj_s; } else if (traj_s > m.second + FLAGS_lon_collision_overtake_buffer) { dist = traj_s - m.second - FLAGS_lon_collision_overtake_buffer; } double cost = std::exp(-dist * dist / (2.0 * sigma * sigma)); cost_sqr_sum += cost * cost; cost_abs_sum += cost; } } return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon); } std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory( const PlanningTarget& planning_target, const std::vector<apollo::common::SpeedPoint> st_points, const std::vector<apollo::common::FrenetFramePoint> sl_points) { std::vector<double> ret; return ret; } std::vector<double> TrajectoryEvaluator::ComputeLongitudinalGuideVelocity( const PlanningTarget& planning_target) const { double comfort_a = FLAGS_longitudinal_acceleration_lower_bound * FLAGS_comfort_acceleration_factor; double cruise_s_dot = planning_target.cruise_speed(); ConstantAccelerationTrajectory1d lon_traj(init_s_[0], cruise_s_dot); if (!planning_target.has_stop_point()) { lon_traj.AppendSgment(0.0, FLAGS_trajectory_time_length); } else { double stop_s = planning_target.stop_point().s(); double dist = stop_s - init_s_[0]; double stop_a = -cruise_s_dot * cruise_s_dot * 0.5 / dist; if (stop_a > comfort_a) { double stop_t = cruise_s_dot / (-comfort_a); double stop_dist = cruise_s_dot * stop_t * 0.5; double cruise_t = (dist - stop_dist) / cruise_s_dot; lon_traj.AppendSgment(0.0, cruise_t); lon_traj.AppendSgment(comfort_a, stop_t); } else { double stop_t = cruise_s_dot / (-stop_a); lon_traj.AppendSgment(stop_a, stop_t); } if (lon_traj.ParamLength() < FLAGS_trajectory_time_length) { lon_traj.AppendSgment( 0.0, FLAGS_trajectory_time_length - lon_traj.ParamLength()); } } std::vector<double> reference_s_dot; for (double t = 0.0; t < FLAGS_trajectory_time_length; t += FLAGS_trajectory_time_resolution) { reference_s_dot.push_back(lon_traj.Evaluate(1, t)); } return reference_s_dot; } } // namespace planning } // namespace apollo <commit_msg>Planning: adjust lon objective cost in lattice planner<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/lattice/trajectory_generation/trajectory_evaluator.h" #include <algorithm> #include <cmath> #include <functional> #include <limits> #include <utility> #include "modules/common/log.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/constraint_checker1d.h" #include "modules/planning/lattice/trajectory1d/piecewise_acceleration_trajectory1d.h" namespace apollo { namespace planning { using Trajectory1d = Curve1d; TrajectoryEvaluator::TrajectoryEvaluator( const std::array<double, 3>& init_s, const PlanningTarget& planning_target, const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories, const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories, std::shared_ptr<PathTimeGraph> path_time_graph) : path_time_graph_(path_time_graph), init_s_(init_s) { const double start_time = 0.0; const double end_time = FLAGS_trajectory_time_length; path_time_intervals_ = path_time_graph_->GetPathBlockingIntervals( start_time, end_time, FLAGS_trajectory_time_resolution); // if we have a stop point along the reference line, // filter out the lon. trajectories that pass the stop point. double stop_point = std::numeric_limits<double>::max(); if (planning_target.has_stop_point()) { stop_point = planning_target.stop_point().s(); } for (const auto lon_trajectory : lon_trajectories) { double lon_end_s = lon_trajectory->Evaluate(0, end_time); if (lon_end_s > stop_point) { continue; } if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) { continue; } for (const auto lat_trajectory : lat_trajectories) { /** if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory, *lon_trajectory)) { continue; } */ if (!FLAGS_enable_auto_tuning) { double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory); cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost)); } else { std::vector<double> cost_components; double cost = Evaluate(planning_target, lon_trajectory, lat_trajectory, &cost_components); cost_queue_with_components_.push(PairCostWithComponents( {lon_trajectory, lat_trajectory}, {cost_components, cost})); } } } if (!FLAGS_enable_auto_tuning) { ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size(); } else { ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_with_components_.size(); } } bool TrajectoryEvaluator::has_more_trajectory_pairs() const { if (!FLAGS_enable_auto_tuning) { return !cost_queue_.empty(); } else { return !cost_queue_with_components_.empty(); } } std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const { if (!FLAGS_enable_auto_tuning) { return cost_queue_.size(); } else { return cost_queue_with_components_.size(); } } std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>> TrajectoryEvaluator::next_top_trajectory_pair() { CHECK(has_more_trajectory_pairs() == true); if (!FLAGS_enable_auto_tuning) { auto top = cost_queue_.top(); cost_queue_.pop(); return top.first; } else { auto top = cost_queue_with_components_.top(); cost_queue_with_components_.pop(); return top.first; } } double TrajectoryEvaluator::top_trajectory_pair_cost() const { if (!FLAGS_enable_auto_tuning) { return cost_queue_.top().second; } else { return cost_queue_with_components_.top().second.second; } } std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost() const { CHECK(FLAGS_enable_auto_tuning); return cost_queue_with_components_.top().second.first; } double TrajectoryEvaluator::Evaluate( const PlanningTarget& planning_target, const std::shared_ptr<Trajectory1d>& lon_trajectory, const std::shared_ptr<Trajectory1d>& lat_trajectory, std::vector<double>* cost_components) const { // Costs: // 1. Cost of missing the objective, e.g., cruise, stop, etc. // 2. Cost of logitudinal jerk // 3. Cost of logitudinal collision // 4. Cost of lateral offsets // 5. Cost of lateral comfort // Longitudinal costs auto reference_s_dot = ComputeLongitudinalGuideVelocity(planning_target); double lon_objective_cost = LonObjectiveCost(lon_trajectory, planning_target, reference_s_dot); double lon_jerk_cost = LonComfortCost(lon_trajectory); double lon_collision_cost = LonCollisionCost(lon_trajectory); // decides the longitudinal evaluation horizon for lateral trajectories. double evaluation_horizon = std::min(FLAGS_decision_horizon, lon_trajectory->Evaluate(0, lon_trajectory->ParamLength())); std::vector<double> s_values; for (double s = 0.0; s < evaluation_horizon; s += FLAGS_trajectory_space_resolution) { s_values.push_back(s); } // Lateral costs double lat_offset_cost = LatOffsetCost(lat_trajectory, s_values); double lat_comfort_cost = LatComfortCost(lon_trajectory, lat_trajectory); if (cost_components != nullptr) { cost_components->push_back(lon_objective_cost); cost_components->push_back(lon_jerk_cost); cost_components->push_back(lon_collision_cost); cost_components->push_back(lat_offset_cost); } return lon_objective_cost * FLAGS_weight_lon_travel + lon_jerk_cost * FLAGS_weight_lon_jerk + lon_collision_cost * FLAGS_weight_lon_collision + lat_offset_cost * FLAGS_weight_lat_offset + lat_comfort_cost * FLAGS_weight_lat_comfort; } double TrajectoryEvaluator::LatOffsetCost( const std::shared_ptr<Trajectory1d>& lat_trajectory, const std::vector<double>& s_values) const { double lat_offset_start = lat_trajectory->Evaluate(0, 0.0); double cost_sqr_sum = 0.0; double cost_abs_sum = 0.0; for (const auto& s : s_values) { double lat_offset = lat_trajectory->Evaluate(0, s); double cost = lat_offset / FLAGS_lat_offset_bound; if (lat_offset * lat_offset_start < 0.0) { cost_sqr_sum += cost * cost * FLAGS_weight_opposite_side_offset; cost_abs_sum += std::abs(cost) * FLAGS_weight_opposite_side_offset; } else { cost_sqr_sum += cost * cost * FLAGS_weight_same_side_offset; cost_abs_sum += std::abs(cost) * FLAGS_weight_same_side_offset; } } return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon); } double TrajectoryEvaluator::LatComfortCost( const std::shared_ptr<Trajectory1d>& lon_trajectory, const std::shared_ptr<Trajectory1d>& lat_trajectory) const { double max_cost = 0.0; for (double t = 0.0; t < FLAGS_trajectory_time_length; t += FLAGS_trajectory_time_resolution) { double s = lon_trajectory->Evaluate(0, t); double s_dot = lon_trajectory->Evaluate(1, t); double s_dotdot = lon_trajectory->Evaluate(2, t); double l_prime = lat_trajectory->Evaluate(1, s); double l_primeprime = lat_trajectory->Evaluate(2, s); double cost = l_primeprime * s_dot * s_dot + l_prime * s_dotdot; max_cost = std::max(max_cost, std::abs(cost)); } return max_cost; } double TrajectoryEvaluator::LonComfortCost( const std::shared_ptr<Trajectory1d>& lon_trajectory) const { double cost_sqr_sum = 0.0; double cost_abs_sum = 0.0; for (double t = 0.0; t < FLAGS_trajectory_time_length; t += FLAGS_trajectory_time_resolution) { double jerk = lon_trajectory->Evaluate(3, t); double cost = jerk / FLAGS_longitudinal_jerk_upper_bound; cost_sqr_sum += cost * cost; cost_abs_sum += std::abs(cost); } return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon); } double TrajectoryEvaluator::LonObjectiveCost( const std::shared_ptr<Trajectory1d>& lon_trajectory, const PlanningTarget& planning_target, const std::vector<double>& ref_s_dots) const { double t_max = lon_trajectory->ParamLength(); double dist_s = lon_trajectory->Evaluate(0, t_max) - lon_trajectory->Evaluate(0, 0.0); double speed_cost_sqr_sum = 0.0; double speed_cost_weight_sum = 0.0; for (std::size_t i = 0; i < ref_s_dots.size(); ++i) { double t = i * FLAGS_trajectory_time_resolution; double cost = ref_s_dots[i] - lon_trajectory->Evaluate(1, t); speed_cost_sqr_sum += t * t * std::abs(cost); speed_cost_weight_sum += t * t; } double speed_cost = speed_cost_sqr_sum / (speed_cost_weight_sum + FLAGS_lattice_epsilon); double dist_travelled_cost = 1.0 / (1.0 + dist_s); return (speed_cost * FLAGS_weight_target_speed + dist_travelled_cost * FLAGS_weight_dist_travelled) / (FLAGS_weight_target_speed + FLAGS_weight_dist_travelled); } // TODO(all): consider putting pointer of reference_line_info and frame // while constructing trajectory evaluator double TrajectoryEvaluator::LonCollisionCost( const std::shared_ptr<Trajectory1d>& lon_trajectory) const { double cost_sqr_sum = 0.0; double cost_abs_sum = 0.0; for (std::size_t i = 0; i < path_time_intervals_.size(); ++i) { const auto& pt_interval = path_time_intervals_[i]; if (pt_interval.empty()) { continue; } double t = i * FLAGS_trajectory_time_resolution; double traj_s = lon_trajectory->Evaluate(0, t); double sigma = FLAGS_lon_collision_cost_std; for (const auto& m : pt_interval) { double dist = 0.0; if (traj_s < m.first - FLAGS_lon_collision_yield_buffer) { dist = m.first - FLAGS_lon_collision_yield_buffer - traj_s; } else if (traj_s > m.second + FLAGS_lon_collision_overtake_buffer) { dist = traj_s - m.second - FLAGS_lon_collision_overtake_buffer; } double cost = std::exp(-dist * dist / (2.0 * sigma * sigma)); cost_sqr_sum += cost * cost; cost_abs_sum += cost; } } return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon); } std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory( const PlanningTarget& planning_target, const std::vector<apollo::common::SpeedPoint> st_points, const std::vector<apollo::common::FrenetFramePoint> sl_points) { std::vector<double> ret; return ret; } std::vector<double> TrajectoryEvaluator::ComputeLongitudinalGuideVelocity( const PlanningTarget& planning_target) const { double comfort_a = FLAGS_longitudinal_acceleration_lower_bound * FLAGS_comfort_acceleration_factor; double cruise_s_dot = planning_target.cruise_speed(); ConstantAccelerationTrajectory1d lon_traj(init_s_[0], cruise_s_dot); if (!planning_target.has_stop_point()) { lon_traj.AppendSgment(0.0, FLAGS_trajectory_time_length); } else { double stop_s = planning_target.stop_point().s(); double dist = stop_s - init_s_[0]; double stop_a = -cruise_s_dot * cruise_s_dot * 0.5 / dist; if (stop_a > comfort_a) { double stop_t = cruise_s_dot / (-comfort_a); double stop_dist = cruise_s_dot * stop_t * 0.5; double cruise_t = (dist - stop_dist) / cruise_s_dot; lon_traj.AppendSgment(0.0, cruise_t); lon_traj.AppendSgment(comfort_a, stop_t); } else { double stop_t = cruise_s_dot / (-stop_a); lon_traj.AppendSgment(stop_a, stop_t); } if (lon_traj.ParamLength() < FLAGS_trajectory_time_length) { lon_traj.AppendSgment( 0.0, FLAGS_trajectory_time_length - lon_traj.ParamLength()); } } std::vector<double> reference_s_dot; for (double t = 0.0; t < FLAGS_trajectory_time_length; t += FLAGS_trajectory_time_resolution) { reference_s_dot.push_back(lon_traj.Evaluate(1, t)); } return reference_s_dot; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/**************************************************************************** * * USBSerial core library for Arduino STM32 + HAL + CubeMX (HALMX). * * Copyright (c) 2016 by Vassilis Serasidis <[email protected]> * Home: http://www.serasidis.gr * email: [email protected] * * Arduino_STM32 forum: http://www.stm32duino.com * * 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. * * Some functions follow the sam and samd arduino core libray files. * * 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 * ****************************************************************************/ /* * Modified on: 2016. 7.12. * Author: Baram, PBHP */ #include <chip.h> #include <USBSerial.h> #include "variant.h" extern uint32_t usb_cdc_bitrate; extern uint32_t usb_cdc_debug_cnt[]; USBSerial::USBSerial(){ baudrate = 0; rx_cnt = 0; tx_cnt = 0; rx_err_cnt = 0; tx_err_cnt = 0; } void USBSerial::begin(uint32_t baud_count){ UNUSED(baud_count); } void USBSerial::begin(uint32_t baud_count, uint8_t config){ UNUSED(baud_count); UNUSED(config); } void USBSerial::end(void){ } int USBSerial::available(void){ return vcp_is_available(); } int USBSerial::peek(void) { return vcp_peek(); } int USBSerial::read(void) { if ( vcp_is_available() == 0 ) return -1; rx_cnt++; return vcp_getch(); } void USBSerial::flush(void){ while(vcp_is_transmitted() == FALSE); } size_t USBSerial::write(const uint8_t *buffer, size_t size) { uint32_t length; length = vcp_write((uint8_t *)buffer, (uint32_t)size); tx_cnt += length; return (size_t)length; } size_t USBSerial::write(uint8_t c) { return write(&c, 1); } uint32_t USBSerial::getBaudRate(void) { return usb_cdc_bitrate; } uint32_t USBSerial::getRxCnt(void) { return rx_cnt; } uint32_t USBSerial::getTxCnt(void) { return tx_cnt; } uint32_t USBSerial::getRxErrCnt(void) { return usb_cdc_debug_cnt[0]; } uint32_t USBSerial::getTxErrCnt(void) { return usb_cdc_debug_cnt[1]; } // This operator is a convenient way for a sketch to check whether the // port has actually been configured and opened by the host (as opposed // to just being connected to the host). It can be used, for example, in // setup() before printing to ensure that an application on the host is // actually ready to receive and display the data. // We add a short delay before returning to fix a bug observed by Federico // where the port is configured (lineState != 0) but not quite opened. USBSerial::operator bool() { if( vcp_is_connected() == TRUE ) return true; else return false; } <commit_msg>Fixed #92<commit_after>/**************************************************************************** * * USBSerial core library for Arduino STM32 + HAL + CubeMX (HALMX). * * Copyright (c) 2016 by Vassilis Serasidis <[email protected]> * Home: http://www.serasidis.gr * email: [email protected] * * Arduino_STM32 forum: http://www.stm32duino.com * * 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. * * Some functions follow the sam and samd arduino core libray files. * * 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 * ****************************************************************************/ /* * Modified on: 2016. 7.12. * Author: Baram, PBHP */ #include <chip.h> #include <USBSerial.h> #include "variant.h" extern uint32_t usb_cdc_bitrate; extern uint32_t usb_cdc_debug_cnt[]; USBSerial::USBSerial(){ baudrate = 0; rx_cnt = 0; tx_cnt = 0; rx_err_cnt = 0; tx_err_cnt = 0; } void USBSerial::begin(uint32_t baud_count){ UNUSED(baud_count); } void USBSerial::begin(uint32_t baud_count, uint8_t config){ UNUSED(baud_count); UNUSED(config); } void USBSerial::end(void){ } int USBSerial::available(void){ return vcp_is_available(); } int USBSerial::peek(void) { return vcp_peek(); } int USBSerial::read(void) { if ( vcp_is_available() == 0 ) return -1; rx_cnt++; return vcp_getch(); } void USBSerial::flush(void){ while( vcp_is_transmitted() == FALSE ); } size_t USBSerial::write(const uint8_t *buffer, size_t size) { uint32_t length; length = vcp_write((uint8_t *)buffer, (uint32_t)size); tx_cnt += length; return (size_t)length; } size_t USBSerial::write(uint8_t c) { return write(&c, 1); } uint32_t USBSerial::getBaudRate(void) { return usb_cdc_bitrate; } uint32_t USBSerial::getRxCnt(void) { return rx_cnt; } uint32_t USBSerial::getTxCnt(void) { return tx_cnt; } uint32_t USBSerial::getRxErrCnt(void) { return usb_cdc_debug_cnt[0]; } uint32_t USBSerial::getTxErrCnt(void) { return usb_cdc_debug_cnt[1]; } // This operator is a convenient way for a sketch to check whether the // port has actually been configured and opened by the host (as opposed // to just being connected to the host). It can be used, for example, in // setup() before printing to ensure that an application on the host is // actually ready to receive and display the data. // We add a short delay before returning to fix a bug observed by Federico // where the port is configured (lineState != 0) but not quite opened. USBSerial::operator bool() { if( vcp_is_connected() == TRUE ) return true; else return false; } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/composite_qoi.h" namespace GRINS { CompositeQoI::CompositeQoI() : libMesh::DifferentiableQoI() { return; } CompositeQoI::~CompositeQoI() { for( std::vector<QoIBase*>::iterator qoi = _qois.begin(); qoi != _qois.end(); ++qoi ) { delete (*qoi); } return; } void CompositeQoI::add_qoi( QoIBase& qoi ) { _qois.push_back( qoi.clone() ); return; } void CompositeQoI::init_qoi( std::vector<Number>& sys_qoi ) { sys_qoi.resize(qois.size(), 0.0); return; } void CompositeQoI::init( const GetPot& input, const MultiphysicsSystem& system ) { for( std::vector<QoIBase*>::iterator qoi = _qois.begin(); qoi != _qois.end(); ++qoi ) { qoi->init(input,system); } return; } void CompositeQoI::init_context( libMesh::DiffContext& context ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( std::vector<QoIBase*>::iterator qoi = _qois.begin(); qoi != _qois.end(); ++qoi ) { qoi->init_context(c); } return; } void CompositeQoI::element_qoi( libMesh::DiffContext& context, const libMesh::QoISet& /*qoi_indices*/ ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).element_qoi(c,q); } return; } void CompositeQoI::element_qoi_derivative( libMesh::DiffContext& context, const libMesh::QoISet& /*qoi_indices*/ ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).element_qoi_derivative(c,q); } return; } void CompositeQoI::side_qoi( libMesh::DiffContext& context, const libMesh::QoISet& /*qoi_indices*/ ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).side_qoi(c,q); } return; } void CompositeQoI::side_qoi_derivative( libMesh::DiffContext& context, const libMesh::QoISet& /*qoi_indices*/ ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).side_qoi_derivative(c,q); } return; } void CompositeQoI::parallel_op( const libMesh::Parallel::Communicator& communicator, std::vector<Number>& sys_qoi, std::vector<Number>& local_qoi, const QoISet& /*qoi_indices*/ ) { for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).parallel_op( communicator, sys_qoi[q], local_qoi[q] ); } return; } void CompositeQoI::thread_join( std::vector<libMesh::Number>& qoi, const std::vector<libMesh::Number>& other_qoi, const QoISet& /*qoi_indices*/ ) { for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).thread_join( qoi[q], other_qoi[q] ); } return; } void CompositeQoI::output_qoi( std::ostream& out ) const { for( std::vector<QoIBase*>::iterator qoi = _qois.begin(); qoi != _qois.end(); ++qoi ) { qoi->output_qoi(out); } return; } libMesh::Number CompositeQoI::get_qoi( unsigned int qoi_index ) const { return (*_qois[qoi_index]).value(); } } // end namespace GRINS <commit_msg>Need correct headers.<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // GRINS - General Reacting Incompressible Navier-Stokes // // Copyright (C) 2010-2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- // This class #include "grins/composite_qoi.h" // GRINS #include "grins/assembly_context.h" // libMesh #include "libmesh/diff_context.h" namespace GRINS { CompositeQoI::CompositeQoI() : libMesh::DifferentiableQoI() { return; } CompositeQoI::~CompositeQoI() { for( std::vector<QoIBase*>::iterator qoi = _qois.begin(); qoi != _qois.end(); ++qoi ) { delete (*qoi); } return; } void CompositeQoI::add_qoi( QoIBase& qoi ) { _qois.push_back( qoi.clone() ); return; } void CompositeQoI::init_qoi( std::vector<Number>& sys_qoi ) { sys_qoi.resize(qois.size(), 0.0); return; } void CompositeQoI::init( const GetPot& input, const MultiphysicsSystem& system ) { for( std::vector<QoIBase*>::iterator qoi = _qois.begin(); qoi != _qois.end(); ++qoi ) { qoi->init(input,system); } return; } void CompositeQoI::init_context( libMesh::DiffContext& context ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( std::vector<QoIBase*>::iterator qoi = _qois.begin(); qoi != _qois.end(); ++qoi ) { qoi->init_context(c); } return; } void CompositeQoI::element_qoi( libMesh::DiffContext& context, const libMesh::QoISet& /*qoi_indices*/ ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).element_qoi(c,q); } return; } void CompositeQoI::element_qoi_derivative( libMesh::DiffContext& context, const libMesh::QoISet& /*qoi_indices*/ ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).element_qoi_derivative(c,q); } return; } void CompositeQoI::side_qoi( libMesh::DiffContext& context, const libMesh::QoISet& /*qoi_indices*/ ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).side_qoi(c,q); } return; } void CompositeQoI::side_qoi_derivative( libMesh::DiffContext& context, const libMesh::QoISet& /*qoi_indices*/ ) { AssemblyContext& c = libmesh_cast_ref<AssemblyContext&>(context); for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).side_qoi_derivative(c,q); } return; } void CompositeQoI::parallel_op( const libMesh::Parallel::Communicator& communicator, std::vector<Number>& sys_qoi, std::vector<Number>& local_qoi, const QoISet& /*qoi_indices*/ ) { for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).parallel_op( communicator, sys_qoi[q], local_qoi[q] ); } return; } void CompositeQoI::thread_join( std::vector<libMesh::Number>& qoi, const std::vector<libMesh::Number>& other_qoi, const QoISet& /*qoi_indices*/ ) { for( unsigned int q = 0; q < _qois.size(); q++ ) { (*_qois[q]).thread_join( qoi[q], other_qoi[q] ); } return; } void CompositeQoI::output_qoi( std::ostream& out ) const { for( std::vector<QoIBase*>::iterator qoi = _qois.begin(); qoi != _qois.end(); ++qoi ) { qoi->output_qoi(out); } return; } libMesh::Number CompositeQoI::get_qoi( unsigned int qoi_index ) const { return (*_qois[qoi_index]).value(); } } // end namespace GRINS <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/chromeos/keyboard_handler.h" #include "base/command_line.h" #include "base/values.h" #include "chrome/browser/chromeos/input_method/xkeyboard.h" #include "chrome/common/chrome_switches.h" #include "content/public/browser/web_ui.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { const struct ModifierKeysSelectItem { int message_id; chromeos::input_method::ModifierKey value; } kModifierKeysSelectItems[] = { { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH, chromeos::input_method::kSearchKey }, { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL, chromeos::input_method::kControlKey }, { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT, chromeos::input_method::kAltKey }, { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_VOID, chromeos::input_method::kVoidKey }, { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK, chromeos::input_method::kCapsLockKey }, }; const char* kDataValuesNames[] = { "remapSearchKeyToValue", "remapControlKeyToValue", "remapAltKeyToValue", "remapCapsLockKeyToValue", "remapDiamondKeyToValue", }; } // namespace namespace chromeos { namespace options { KeyboardHandler::KeyboardHandler() { } KeyboardHandler::~KeyboardHandler() { } void KeyboardHandler::GetLocalizedValues(DictionaryValue* localized_strings) { DCHECK(localized_strings); localized_strings->SetString("keyboardOverlayTitle", l10n_util::GetStringUTF16(IDS_OPTIONS_KEYBOARD_OVERLAY_TITLE)); localized_strings->SetString("remapSearchKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH_LABEL)); localized_strings->SetString("remapControlKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL_LABEL)); localized_strings->SetString("remapAltKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT_LABEL)); localized_strings->SetString("remapCapsLockKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK_LABEL)); localized_strings->SetString("remapDiamondKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_DIAMOND_KEY_LABEL)); localized_strings->SetString("changeLanguageAndInputSettings", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_CHANGE_LANGUAGE_AND_INPUT_SETTINGS)); for (size_t i = 0; i < arraysize(kDataValuesNames); ++i) { ListValue* list_value = new ListValue(); for (size_t j = 0; j < arraysize(kModifierKeysSelectItems); ++j) { const input_method::ModifierKey value = kModifierKeysSelectItems[j].value; const int message_id = kModifierKeysSelectItems[j].message_id; // Only the seach key can be remapped to the caps lock key. if (kDataValuesNames[i] != std::string("remapSearchKeyToValue") && kDataValuesNames[i] != std::string("remapCapsLockKeyToValue") && value == input_method::kCapsLockKey) { continue; } ListValue* option = new ListValue(); option->Append(new base::FundamentalValue(value)); option->Append(new base::StringValue(l10n_util::GetStringUTF16( message_id))); list_value->Append(option); } localized_strings->Set(kDataValuesNames[i], list_value); } } void KeyboardHandler::InitializePage() { bool chromeos_keyboard = CommandLine::ForCurrentProcess()->HasSwitch( switches::kHasChromeOSKeyboard); const base::FundamentalValue show_caps_lock_options(chromeos_keyboard); bool has_diamond_key = CommandLine::ForCurrentProcess()->HasSwitch( switches::kHasChromeOSDiamondKey); const base::FundamentalValue show_diamond_key_options(has_diamond_key); web_ui()->CallJavascriptFunction( "options.KeyboardOverlay.showCapsLockOptions", show_caps_lock_options); web_ui()->CallJavascriptFunction( "options.KeyboardOverlay.showDiamondKeyOptions", show_diamond_key_options); } } // namespace options } // namespace chromeos <commit_msg>Fix the badly inverted flag to show caps lock settings.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/options/chromeos/keyboard_handler.h" #include "base/command_line.h" #include "base/values.h" #include "chrome/browser/chromeos/input_method/xkeyboard.h" #include "chrome/common/chrome_switches.h" #include "content/public/browser/web_ui.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { const struct ModifierKeysSelectItem { int message_id; chromeos::input_method::ModifierKey value; } kModifierKeysSelectItems[] = { { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH, chromeos::input_method::kSearchKey }, { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL, chromeos::input_method::kControlKey }, { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT, chromeos::input_method::kAltKey }, { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_VOID, chromeos::input_method::kVoidKey }, { IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK, chromeos::input_method::kCapsLockKey }, }; const char* kDataValuesNames[] = { "remapSearchKeyToValue", "remapControlKeyToValue", "remapAltKeyToValue", "remapCapsLockKeyToValue", "remapDiamondKeyToValue", }; } // namespace namespace chromeos { namespace options { KeyboardHandler::KeyboardHandler() { } KeyboardHandler::~KeyboardHandler() { } void KeyboardHandler::GetLocalizedValues(DictionaryValue* localized_strings) { DCHECK(localized_strings); localized_strings->SetString("keyboardOverlayTitle", l10n_util::GetStringUTF16(IDS_OPTIONS_KEYBOARD_OVERLAY_TITLE)); localized_strings->SetString("remapSearchKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_SEARCH_LABEL)); localized_strings->SetString("remapControlKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_CTRL_LABEL)); localized_strings->SetString("remapAltKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_LEFT_ALT_LABEL)); localized_strings->SetString("remapCapsLockKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_CAPS_LOCK_LABEL)); localized_strings->SetString("remapDiamondKeyToContent", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_LANGUAGES_KEY_DIAMOND_KEY_LABEL)); localized_strings->SetString("changeLanguageAndInputSettings", l10n_util::GetStringUTF16( IDS_OPTIONS_SETTINGS_CHANGE_LANGUAGE_AND_INPUT_SETTINGS)); for (size_t i = 0; i < arraysize(kDataValuesNames); ++i) { ListValue* list_value = new ListValue(); for (size_t j = 0; j < arraysize(kModifierKeysSelectItems); ++j) { const input_method::ModifierKey value = kModifierKeysSelectItems[j].value; const int message_id = kModifierKeysSelectItems[j].message_id; // Only the seach key can be remapped to the caps lock key. if (kDataValuesNames[i] != std::string("remapSearchKeyToValue") && kDataValuesNames[i] != std::string("remapCapsLockKeyToValue") && value == input_method::kCapsLockKey) { continue; } ListValue* option = new ListValue(); option->Append(new base::FundamentalValue(value)); option->Append(new base::StringValue(l10n_util::GetStringUTF16( message_id))); list_value->Append(option); } localized_strings->Set(kDataValuesNames[i], list_value); } } void KeyboardHandler::InitializePage() { bool chromeos_keyboard = CommandLine::ForCurrentProcess()->HasSwitch( switches::kHasChromeOSKeyboard); const base::FundamentalValue show_caps_lock_options(!chromeos_keyboard); bool has_diamond_key = CommandLine::ForCurrentProcess()->HasSwitch( switches::kHasChromeOSDiamondKey); const base::FundamentalValue show_diamond_key_options(has_diamond_key); web_ui()->CallJavascriptFunction( "options.KeyboardOverlay.showCapsLockOptions", show_caps_lock_options); web_ui()->CallJavascriptFunction( "options.KeyboardOverlay.showDiamondKeyOptions", show_diamond_key_options); } } // namespace options } // namespace chromeos <|endoftext|>
<commit_before>#include <qt/test/wallettests.h> #include <qt/test/util.h> #include <interfaces/chain.h> #include <interfaces/node.h> #include <qt/bitcoinamountfield.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/qvalidatedlineedit.h> #include <qt/sendcoinsdialog.h> #include <qt/sendcoinsentry.h> #include <qt/transactiontablemodel.h> #include <qt/transactionview.h> #include <qt/walletmodel.h> #include <key_io.h> #include <test/util/setup_common.h> #include <validation.h> #include <wallet/wallet.h> #include <qt/overviewpage.h> #include <qt/receivecoinsdialog.h> #include <qt/recentrequeststablemodel.h> #include <qt/receiverequestdialog.h> #include <memory> #include <QAbstractButton> #include <QAction> #include <QApplication> #include <QCheckBox> #include <QPushButton> #include <QTimer> #include <QVBoxLayout> #include <QTextEdit> #include <QListView> #include <QDialogButtonBox> namespace { //! Press "Yes" or "Cancel" buttons in modal send confirmation dialog. void ConfirmSend(QString* text = nullptr, bool cancel = false) { QTimer::singleShot(0, [text, cancel]() { for (QWidget* widget : QApplication::topLevelWidgets()) { if (widget->inherits("SendConfirmationDialog")) { SendConfirmationDialog* dialog = qobject_cast<SendConfirmationDialog*>(widget); if (text) *text = dialog->text(); QAbstractButton* button = dialog->button(cancel ? QMessageBox::Cancel : QMessageBox::Yes); button->setEnabled(true); button->click(); } } }); } //! Send coins to address and return txid. uint256 SendCoins(CWallet& wallet, SendCoinsDialog& sendCoinsDialog, const CTxDestination& address, CAmount amount, bool rbf) { QVBoxLayout* entries = sendCoinsDialog.findChild<QVBoxLayout*>("entries"); SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(entries->itemAt(0)->widget()); entry->findChild<QValidatedLineEdit*>("payTo")->setText(QString::fromStdString(EncodeDestination(address))); entry->findChild<BitcoinAmountField*>("payAmount")->setValue(amount); sendCoinsDialog.findChild<QFrame*>("frameFee") ->findChild<QFrame*>("frameFeeSelection") ->findChild<QCheckBox*>("optInRBF") ->setCheckState(rbf ? Qt::Checked : Qt::Unchecked); uint256 txid; boost::signals2::scoped_connection c(wallet.NotifyTransactionChanged.connect([&txid](CWallet*, const uint256& hash, ChangeType status) { if (status == CT_NEW) txid = hash; })); ConfirmSend(); bool invoked = QMetaObject::invokeMethod(&sendCoinsDialog, "on_sendButton_clicked"); assert(invoked); return txid; } //! Find index of txid in transaction list. QModelIndex FindTx(const QAbstractItemModel& model, const uint256& txid) { QString hash = QString::fromStdString(txid.ToString()); int rows = model.rowCount({}); for (int row = 0; row < rows; ++row) { QModelIndex index = model.index(row, 0, {}); if (model.data(index, TransactionTableModel::TxHashRole) == hash) { return index; } } return {}; } //! Invoke bumpfee on txid and check results. void BumpFee(TransactionView& view, const uint256& txid, bool expectDisabled, std::string expectError, bool cancel) { QTableView* table = view.findChild<QTableView*>("transactionView"); QModelIndex index = FindTx(*table->selectionModel()->model(), txid); QVERIFY2(index.isValid(), "Could not find BumpFee txid"); // Select row in table, invoke context menu, and make sure bumpfee action is // enabled or disabled as expected. QAction* action = view.findChild<QAction*>("bumpFeeAction"); table->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); action->setEnabled(expectDisabled); table->customContextMenuRequested({}); QCOMPARE(action->isEnabled(), !expectDisabled); action->setEnabled(true); QString text; if (expectError.empty()) { ConfirmSend(&text, cancel); } else { ConfirmMessage(&text); } action->trigger(); QVERIFY(text.indexOf(QString::fromStdString(expectError)) != -1); } //! Simple qt wallet tests. // // Test widgets can be debugged interactively calling show() on them and // manually running the event loop, e.g.: // // sendCoinsDialog.show(); // QEventLoop().exec(); // // This also requires overriding the default minimal Qt platform: // // QT_QPA_PLATFORM=xcb src/qt/test/test_bitcoin-qt # Linux // QT_QPA_PLATFORM=windows src/qt/test/test_bitcoin-qt # Windows // QT_QPA_PLATFORM=cocoa src/qt/test/test_bitcoin-qt # macOS void TestGUI(interfaces::Node& node) { // Set up wallet and chain with 105 blocks (5 mature blocks for spending). TestChain100Setup test; for (int i = 0; i < 5; ++i) { test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey())); } node.context()->connman = std::move(test.m_node.connman); std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(node.context()->chain.get(), WalletLocation(), WalletDatabase::CreateMock()); bool firstRun; wallet->LoadWallet(firstRun); { auto spk_man = wallet->GetLegacyScriptPubKeyMan(); auto locked_chain = wallet->chain().lock(); LOCK(wallet->cs_wallet); AssertLockHeld(spk_man->cs_wallet); wallet->SetAddressBook(GetDestinationForKey(test.coinbaseKey.GetPubKey(), wallet->m_default_address_type), "", "receive"); spk_man->AddKeyPubKey(test.coinbaseKey, test.coinbaseKey.GetPubKey()); wallet->SetLastBlockProcessed(105, ::ChainActive().Tip()->GetBlockHash()); } { auto locked_chain = wallet->chain().lock(); LockAssertion lock(::cs_main); WalletRescanReserver reserver(wallet.get()); reserver.reserve(); CWallet::ScanResult result = wallet->ScanForWalletTransactions(locked_chain->getBlockHash(0), {} /* stop_block */, reserver, true /* fUpdate */); QCOMPARE(result.status, CWallet::ScanResult::SUCCESS); QCOMPARE(result.last_scanned_block, ::ChainActive().Tip()->GetBlockHash()); QVERIFY(result.last_failed_block.IsNull()); } wallet->SetBroadcastTransactions(true); // Create widgets for sending coins and listing transactions. std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other")); SendCoinsDialog sendCoinsDialog(platformStyle.get()); TransactionView transactionView(platformStyle.get()); OptionsModel optionsModel(node); AddWallet(wallet); WalletModel walletModel(interfaces::MakeWallet(wallet), node, platformStyle.get(), &optionsModel); RemoveWallet(wallet); sendCoinsDialog.setModel(&walletModel); transactionView.setModel(&walletModel); // Send two transactions, and verify they are added to transaction list. TransactionTableModel* transactionTableModel = walletModel.getTransactionTableModel(); QCOMPARE(transactionTableModel->rowCount({}), 105); uint256 txid1 = SendCoins(*wallet.get(), sendCoinsDialog, PKHash(), 5 * COIN, false /* rbf */); uint256 txid2 = SendCoins(*wallet.get(), sendCoinsDialog, PKHash(), 10 * COIN, true /* rbf */); QCOMPARE(transactionTableModel->rowCount({}), 107); QVERIFY(FindTx(*transactionTableModel, txid1).isValid()); QVERIFY(FindTx(*transactionTableModel, txid2).isValid()); // Call bumpfee. Test disabled, canceled, enabled, then failing cases. BumpFee(transactionView, txid1, true /* expect disabled */, "not BIP 125 replaceable" /* expected error */, false /* cancel */); BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, true /* cancel */); BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, false /* cancel */); BumpFee(transactionView, txid2, true /* expect disabled */, "already bumped" /* expected error */, false /* cancel */); // Check current balance on OverviewPage OverviewPage overviewPage(platformStyle.get()); overviewPage.setWalletModel(&walletModel); QLabel* balanceLabel = overviewPage.findChild<QLabel*>("labelBalance"); QString balanceText = balanceLabel->text(); int unit = walletModel.getOptionsModel()->getDisplayUnit(); CAmount balance = walletModel.wallet().getBalance(); QString balanceComparison = BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways); QCOMPARE(balanceText, balanceComparison); // Check Request Payment button ReceiveCoinsDialog receiveCoinsDialog(platformStyle.get()); receiveCoinsDialog.setModel(&walletModel); RecentRequestsTableModel* requestTableModel = walletModel.getRecentRequestsTableModel(); // Label input QLineEdit* labelInput = receiveCoinsDialog.findChild<QLineEdit*>("reqLabel"); labelInput->setText("TEST_LABEL_1"); // Amount input BitcoinAmountField* amountInput = receiveCoinsDialog.findChild<BitcoinAmountField*>("reqAmount"); amountInput->setValue(1); // Message input QLineEdit* messageInput = receiveCoinsDialog.findChild<QLineEdit*>("reqMessage"); messageInput->setText("TEST_MESSAGE_1"); int initialRowCount = requestTableModel->rowCount({}); QPushButton* requestPaymentButton = receiveCoinsDialog.findChild<QPushButton*>("receiveButton"); requestPaymentButton->click(); for (QWidget* widget : QApplication::topLevelWidgets()) { if (widget->inherits("ReceiveRequestDialog")) { ReceiveRequestDialog* receiveRequestDialog = qobject_cast<ReceiveRequestDialog*>(widget); QTextEdit* rlist = receiveRequestDialog->QObject::findChild<QTextEdit*>("outUri"); QString paymentText = rlist->toPlainText(); QStringList paymentTextList = paymentText.split('\n'); QCOMPARE(paymentTextList.at(0), QString("Payment information")); QVERIFY(paymentTextList.at(1).indexOf(QString("URI: bitcoin:")) != -1); QVERIFY(paymentTextList.at(2).indexOf(QString("Address:")) != -1); QCOMPARE(paymentTextList.at(3), QString("Amount: 0.00000001 ") + QString::fromStdString(CURRENCY_UNIT)); QCOMPARE(paymentTextList.at(4), QString("Label: TEST_LABEL_1")); QCOMPARE(paymentTextList.at(5), QString("Message: TEST_MESSAGE_1")); } } // Clear button QPushButton* clearButton = receiveCoinsDialog.findChild<QPushButton*>("clearButton"); clearButton->click(); QCOMPARE(labelInput->text(), QString("")); QCOMPARE(amountInput->value(), CAmount(0)); QCOMPARE(messageInput->text(), QString("")); // Check addition to history int currentRowCount = requestTableModel->rowCount({}); QCOMPARE(currentRowCount, initialRowCount+1); // Check Remove button QTableView* table = receiveCoinsDialog.findChild<QTableView*>("recentRequestsView"); table->selectRow(currentRowCount-1); QPushButton* removeRequestButton = receiveCoinsDialog.findChild<QPushButton*>("removeRequestButton"); removeRequestButton->click(); QCOMPARE(requestTableModel->rowCount({}), currentRowCount-1); } } // namespace void WalletTests::walletTests() { #ifdef Q_OS_MAC if (QApplication::platformName() == "minimal") { // Disable for mac on "minimal" platform to avoid crashes inside the Qt // framework when it tries to look up unimplemented cocoa functions, // and fails to handle returned nulls // (https://bugreports.qt.io/browse/QTBUG-49686). QWARN("Skipping WalletTests on mac build with 'minimal' platform set due to Qt bugs. To run AppTests, invoke " "with 'QT_QPA_PLATFORM=cocoa test_bitcoin-qt' on mac, or else use a linux or windows build."); return; } #endif TestGUI(m_node); } <commit_msg>[test] qt: add send screen balance test<commit_after>#include <qt/test/wallettests.h> #include <qt/test/util.h> #include <interfaces/chain.h> #include <interfaces/node.h> #include <qt/bitcoinamountfield.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/qvalidatedlineedit.h> #include <qt/sendcoinsdialog.h> #include <qt/sendcoinsentry.h> #include <qt/transactiontablemodel.h> #include <qt/transactionview.h> #include <qt/walletmodel.h> #include <key_io.h> #include <test/util/setup_common.h> #include <validation.h> #include <wallet/wallet.h> #include <qt/overviewpage.h> #include <qt/receivecoinsdialog.h> #include <qt/recentrequeststablemodel.h> #include <qt/receiverequestdialog.h> #include <memory> #include <QAbstractButton> #include <QAction> #include <QApplication> #include <QCheckBox> #include <QPushButton> #include <QTimer> #include <QVBoxLayout> #include <QTextEdit> #include <QListView> #include <QDialogButtonBox> namespace { //! Press "Yes" or "Cancel" buttons in modal send confirmation dialog. void ConfirmSend(QString* text = nullptr, bool cancel = false) { QTimer::singleShot(0, [text, cancel]() { for (QWidget* widget : QApplication::topLevelWidgets()) { if (widget->inherits("SendConfirmationDialog")) { SendConfirmationDialog* dialog = qobject_cast<SendConfirmationDialog*>(widget); if (text) *text = dialog->text(); QAbstractButton* button = dialog->button(cancel ? QMessageBox::Cancel : QMessageBox::Yes); button->setEnabled(true); button->click(); } } }); } //! Send coins to address and return txid. uint256 SendCoins(CWallet& wallet, SendCoinsDialog& sendCoinsDialog, const CTxDestination& address, CAmount amount, bool rbf) { QVBoxLayout* entries = sendCoinsDialog.findChild<QVBoxLayout*>("entries"); SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(entries->itemAt(0)->widget()); entry->findChild<QValidatedLineEdit*>("payTo")->setText(QString::fromStdString(EncodeDestination(address))); entry->findChild<BitcoinAmountField*>("payAmount")->setValue(amount); sendCoinsDialog.findChild<QFrame*>("frameFee") ->findChild<QFrame*>("frameFeeSelection") ->findChild<QCheckBox*>("optInRBF") ->setCheckState(rbf ? Qt::Checked : Qt::Unchecked); uint256 txid; boost::signals2::scoped_connection c(wallet.NotifyTransactionChanged.connect([&txid](CWallet*, const uint256& hash, ChangeType status) { if (status == CT_NEW) txid = hash; })); ConfirmSend(); bool invoked = QMetaObject::invokeMethod(&sendCoinsDialog, "on_sendButton_clicked"); assert(invoked); return txid; } //! Find index of txid in transaction list. QModelIndex FindTx(const QAbstractItemModel& model, const uint256& txid) { QString hash = QString::fromStdString(txid.ToString()); int rows = model.rowCount({}); for (int row = 0; row < rows; ++row) { QModelIndex index = model.index(row, 0, {}); if (model.data(index, TransactionTableModel::TxHashRole) == hash) { return index; } } return {}; } //! Invoke bumpfee on txid and check results. void BumpFee(TransactionView& view, const uint256& txid, bool expectDisabled, std::string expectError, bool cancel) { QTableView* table = view.findChild<QTableView*>("transactionView"); QModelIndex index = FindTx(*table->selectionModel()->model(), txid); QVERIFY2(index.isValid(), "Could not find BumpFee txid"); // Select row in table, invoke context menu, and make sure bumpfee action is // enabled or disabled as expected. QAction* action = view.findChild<QAction*>("bumpFeeAction"); table->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); action->setEnabled(expectDisabled); table->customContextMenuRequested({}); QCOMPARE(action->isEnabled(), !expectDisabled); action->setEnabled(true); QString text; if (expectError.empty()) { ConfirmSend(&text, cancel); } else { ConfirmMessage(&text); } action->trigger(); QVERIFY(text.indexOf(QString::fromStdString(expectError)) != -1); } //! Simple qt wallet tests. // // Test widgets can be debugged interactively calling show() on them and // manually running the event loop, e.g.: // // sendCoinsDialog.show(); // QEventLoop().exec(); // // This also requires overriding the default minimal Qt platform: // // QT_QPA_PLATFORM=xcb src/qt/test/test_bitcoin-qt # Linux // QT_QPA_PLATFORM=windows src/qt/test/test_bitcoin-qt # Windows // QT_QPA_PLATFORM=cocoa src/qt/test/test_bitcoin-qt # macOS void TestGUI(interfaces::Node& node) { // Set up wallet and chain with 105 blocks (5 mature blocks for spending). TestChain100Setup test; for (int i = 0; i < 5; ++i) { test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey())); } node.context()->connman = std::move(test.m_node.connman); std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(node.context()->chain.get(), WalletLocation(), WalletDatabase::CreateMock()); bool firstRun; wallet->LoadWallet(firstRun); { auto spk_man = wallet->GetLegacyScriptPubKeyMan(); auto locked_chain = wallet->chain().lock(); LOCK(wallet->cs_wallet); AssertLockHeld(spk_man->cs_wallet); wallet->SetAddressBook(GetDestinationForKey(test.coinbaseKey.GetPubKey(), wallet->m_default_address_type), "", "receive"); spk_man->AddKeyPubKey(test.coinbaseKey, test.coinbaseKey.GetPubKey()); wallet->SetLastBlockProcessed(105, ::ChainActive().Tip()->GetBlockHash()); } { auto locked_chain = wallet->chain().lock(); LockAssertion lock(::cs_main); WalletRescanReserver reserver(wallet.get()); reserver.reserve(); CWallet::ScanResult result = wallet->ScanForWalletTransactions(locked_chain->getBlockHash(0), {} /* stop_block */, reserver, true /* fUpdate */); QCOMPARE(result.status, CWallet::ScanResult::SUCCESS); QCOMPARE(result.last_scanned_block, ::ChainActive().Tip()->GetBlockHash()); QVERIFY(result.last_failed_block.IsNull()); } wallet->SetBroadcastTransactions(true); // Create widgets for sending coins and listing transactions. std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other")); SendCoinsDialog sendCoinsDialog(platformStyle.get()); TransactionView transactionView(platformStyle.get()); OptionsModel optionsModel(node); AddWallet(wallet); WalletModel walletModel(interfaces::MakeWallet(wallet), node, platformStyle.get(), &optionsModel); RemoveWallet(wallet); sendCoinsDialog.setModel(&walletModel); transactionView.setModel(&walletModel); { // Check balance in send dialog QLabel* balanceLabel = sendCoinsDialog.findChild<QLabel*>("labelBalance"); QString balanceText = balanceLabel->text(); int unit = walletModel.getOptionsModel()->getDisplayUnit(); CAmount balance = walletModel.wallet().getBalance(); QString balanceComparison = BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways); QCOMPARE(balanceText, balanceComparison); } // Send two transactions, and verify they are added to transaction list. TransactionTableModel* transactionTableModel = walletModel.getTransactionTableModel(); QCOMPARE(transactionTableModel->rowCount({}), 105); uint256 txid1 = SendCoins(*wallet.get(), sendCoinsDialog, PKHash(), 5 * COIN, false /* rbf */); uint256 txid2 = SendCoins(*wallet.get(), sendCoinsDialog, PKHash(), 10 * COIN, true /* rbf */); QCOMPARE(transactionTableModel->rowCount({}), 107); QVERIFY(FindTx(*transactionTableModel, txid1).isValid()); QVERIFY(FindTx(*transactionTableModel, txid2).isValid()); // Call bumpfee. Test disabled, canceled, enabled, then failing cases. BumpFee(transactionView, txid1, true /* expect disabled */, "not BIP 125 replaceable" /* expected error */, false /* cancel */); BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, true /* cancel */); BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, false /* cancel */); BumpFee(transactionView, txid2, true /* expect disabled */, "already bumped" /* expected error */, false /* cancel */); // Check current balance on OverviewPage OverviewPage overviewPage(platformStyle.get()); overviewPage.setWalletModel(&walletModel); QLabel* balanceLabel = overviewPage.findChild<QLabel*>("labelBalance"); QString balanceText = balanceLabel->text(); int unit = walletModel.getOptionsModel()->getDisplayUnit(); CAmount balance = walletModel.wallet().getBalance(); QString balanceComparison = BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways); QCOMPARE(balanceText, balanceComparison); // Check Request Payment button ReceiveCoinsDialog receiveCoinsDialog(platformStyle.get()); receiveCoinsDialog.setModel(&walletModel); RecentRequestsTableModel* requestTableModel = walletModel.getRecentRequestsTableModel(); // Label input QLineEdit* labelInput = receiveCoinsDialog.findChild<QLineEdit*>("reqLabel"); labelInput->setText("TEST_LABEL_1"); // Amount input BitcoinAmountField* amountInput = receiveCoinsDialog.findChild<BitcoinAmountField*>("reqAmount"); amountInput->setValue(1); // Message input QLineEdit* messageInput = receiveCoinsDialog.findChild<QLineEdit*>("reqMessage"); messageInput->setText("TEST_MESSAGE_1"); int initialRowCount = requestTableModel->rowCount({}); QPushButton* requestPaymentButton = receiveCoinsDialog.findChild<QPushButton*>("receiveButton"); requestPaymentButton->click(); for (QWidget* widget : QApplication::topLevelWidgets()) { if (widget->inherits("ReceiveRequestDialog")) { ReceiveRequestDialog* receiveRequestDialog = qobject_cast<ReceiveRequestDialog*>(widget); QTextEdit* rlist = receiveRequestDialog->QObject::findChild<QTextEdit*>("outUri"); QString paymentText = rlist->toPlainText(); QStringList paymentTextList = paymentText.split('\n'); QCOMPARE(paymentTextList.at(0), QString("Payment information")); QVERIFY(paymentTextList.at(1).indexOf(QString("URI: bitcoin:")) != -1); QVERIFY(paymentTextList.at(2).indexOf(QString("Address:")) != -1); QCOMPARE(paymentTextList.at(3), QString("Amount: 0.00000001 ") + QString::fromStdString(CURRENCY_UNIT)); QCOMPARE(paymentTextList.at(4), QString("Label: TEST_LABEL_1")); QCOMPARE(paymentTextList.at(5), QString("Message: TEST_MESSAGE_1")); } } // Clear button QPushButton* clearButton = receiveCoinsDialog.findChild<QPushButton*>("clearButton"); clearButton->click(); QCOMPARE(labelInput->text(), QString("")); QCOMPARE(amountInput->value(), CAmount(0)); QCOMPARE(messageInput->text(), QString("")); // Check addition to history int currentRowCount = requestTableModel->rowCount({}); QCOMPARE(currentRowCount, initialRowCount+1); // Check Remove button QTableView* table = receiveCoinsDialog.findChild<QTableView*>("recentRequestsView"); table->selectRow(currentRowCount-1); QPushButton* removeRequestButton = receiveCoinsDialog.findChild<QPushButton*>("removeRequestButton"); removeRequestButton->click(); QCOMPARE(requestTableModel->rowCount({}), currentRowCount-1); } } // namespace void WalletTests::walletTests() { #ifdef Q_OS_MAC if (QApplication::platformName() == "minimal") { // Disable for mac on "minimal" platform to avoid crashes inside the Qt // framework when it tries to look up unimplemented cocoa functions, // and fails to handle returned nulls // (https://bugreports.qt.io/browse/QTBUG-49686). QWARN("Skipping WalletTests on mac build with 'minimal' platform set due to Qt bugs. To run AppTests, invoke " "with 'QT_QPA_PLATFORM=cocoa test_bitcoin-qt' on mac, or else use a linux or windows build."); return; } #endif TestGUI(m_node); } <|endoftext|>
<commit_before>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; #if defined(__GNUC__) inline bool savestate(statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\r" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { register bool r; __asm { push ebp mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: pop ebp mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "jmp *%1" \ : \ : "m" (ssb.sp), "m" (ssb.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <commit_msg>some fixes<commit_after>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; #if defined(__GNUC__) inline bool __attribute__((always_inline)) savestate(statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\r" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { register bool r; __asm { push ebp mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: pop ebp mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "jmp *%1" \ : \ : "m" (SSB.sp), "m" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include "iree/compiler/Dialect/Flow/Analysis/Dispatchability.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "iree/compiler/Dialect/Flow/Utils/DispatchUtils.h" #include "iree/compiler/Dialect/Flow/Utils/WorkloadUtils.h" #include "iree/compiler/Utils/GraphUtils.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Support/LLVM.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Transforms/Utils.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { namespace { // Returns true if the given |op| can be dispatched in all cases. // Other passes may handle special cases of these ops but this initial // identification is conservative. bool isDispatchableOp(Operation *op, Dispatchability &dispatchability) { // TODO(b/144530470): replace with tablegen attributes/interfaces. if (FlowDialect::isDialectOp(op)) { // Ignore things we've already produced as they should only relate to // sequencer operations. return false; } else if (op->isKnownTerminator()) { // Currently we skip all terminators as we want to leave them in the block // to keep it valid. Future folding passes may take care of them if they are // worth bringing into the dispatch region. return false; } else if (auto callOp = dyn_cast<CallOp>(op)) { return dispatchability.isDispatchable(callOp.getCallee()); } else if (isa<CallIndirectOp>(op)) { // Indirect calls are not supported in dispatch code. return false; } else if (isa<ConstantOp>(op)) { // Constants are handled in the RematerializeDispatchConstants pass. // We do that independently so that we can more easily see the use of // constants across all dispatches instead of just on an individual basis // as we do here. return false; } else if (op->getNumResults() && !op->getResult(0).getType().isa<ShapedType>()) { // We don't put scalar manipulation into dispatch regions. return false; } else if (!isOpOfKnownDialect(op)) { // Probably a custom op. return false; } return true; } // Returns true if the given |op| can have other ops fused into it. // This is sketchy and it'd be nice to define this as an op property instead. // // What we are looking for in foldable ops is whether the execution of the op // when fused has some possible benefit (or at least, a non-negative cost). // Eventually we want to allow backends to vote on this and allow multiple // folding strategies within the same executable. For now we just hardcode what // we know for the ops we have. // // Preconditions: isDispatchableOp(op) == true. bool isFusionRootOp(Operation *op) { // TODO(b/144530470): replace with tablegen attributes/interfaces. if (isa<xla_hlo::DotOp>(op) || isa<xla_hlo::ConvOp>(op)) { // We have hand-written kernels for these right now we want to stand alone. // When we do a bit more magic we should allow these ops to fold. return false; } return true; } // Returns true if the given |op| can be fused into other ops. // // Ops that perform narrowing on shapes (such as reduction ops) should not // generally be fused with other downstream ops (probably...). This avoids // potential oversampling and indexing issues and allows backends to perform // more efficient rooted cascading reduction dispatches. // // Preconditions: isDispatchableOp(op) == true. bool isFusableOp(Operation *op) { // TODO(b/144530470): replace with tablegen attributes/interfaces. if (isa<xla_hlo::DotOp>(op) || isa<xla_hlo::ConvOp>(op)) { return false; } else if (isa<xla_hlo::ReduceOp>(op)) { // Reduction is usually a dedicated root operation - we can shove things in // the front of it but not behind. return false; } return true; } // Recursively traverses the IR DAG along the operand edges to find ops we are // able to fuse and appends them to |subgraph|. void gatherFusionOps(Operation *op, Dispatchability &dispatchability, llvm::SetVector<Operation *> *subgraph) { // Skip ops that are used outside of the subgraph we are building. for (auto result : op->getResults()) { if (result.use_empty() || result.hasOneUse()) continue; for (auto *user : result.getUsers()) { if (subgraph->count(user) == 0) { // Op that consumes the result is not (yet) in the subgraph. // For now we'll ignore these as it may represent a fork that we don't // want to join too early. return; } } } // Walk backward up to ops providing our input operands. for (auto operand : op->getOperands()) { auto *sourceOp = operand.getDefiningOp(); if (!sourceOp) continue; if (subgraph->count(sourceOp) == 0) { if (isDispatchableOp(sourceOp, dispatchability) && isFusableOp(sourceOp)) { gatherFusionOps(sourceOp, dispatchability, subgraph); } } } subgraph->insert(op); } // Finds all ops that can be fused together with the given |rootOp| by searching // backwards in the op order through input edges. // Returns a topologically sorted list of all fused ops with |rootOp| at the // end. std::vector<Operation *> findFusionSubgraphFromRoot( Operation *rootOp, Dispatchability &dispatchability) { if (!isFusionRootOp(rootOp)) { return {rootOp}; } llvm::SetVector<Operation *> subgraph; subgraph.insert(rootOp); gatherFusionOps(rootOp, dispatchability, &subgraph); return sortOpsTopologically(subgraph); } // Identifies ranges of dispatchable ops and moves them into dispatch regions. LogicalResult identifyBlockDispatchRegions(Block *block, Dispatchability &dispatchability) { // Fixed point iteration until we can no longer fuse anything. bool didFindAnyNewRegions; do { // Iterate in reverse so we root further along in the op list. didFindAnyNewRegions = false; for (auto &rootOp : llvm::reverse(*block)) { if (!isDispatchableOp(&rootOp, dispatchability)) { // Op should remain at the sequencer level. continue; } // Attempt to find all operations, including rootOp, that can be fused. // The ops will be sorted in topological order with rootOp as the last op. // Worst case we may end up with a subgraph of only the rootOp. auto fusedSubgraph = findFusionSubgraphFromRoot(&rootOp, dispatchability); // Compute the workload based on the output shape. // When variadic all output shapes match so we can just take the first. auto workload = calculateWorkload(&rootOp, rootOp.getResult(0)); if (!workload) { return failure(); } // Try to build a dispatch region from this root. if (failed(buildDispatchRegion(block, workload, fusedSubgraph))) { return failure(); } // Successfully created a dispatch region from the ops and we must now // start over again as we've likely trashed the whole block structure. didFindAnyNewRegions = true; break; } } while (didFindAnyNewRegions); return success(); } } // namespace // Identifies dispatchable ops and moves them into dispatch regions. // Some ops, such as call, will be deferred until following passes. class IdentifyDispatchRegionsPass : public FunctionPass<IdentifyDispatchRegionsPass> { public: void runOnFunction() override { // NOTE: we require the DispatchabilityAnalysisPass to have run first. auto dispatchability = getCachedParentAnalysis<Dispatchability>(); if (!dispatchability.hasValue()) { getFunction().emitError() << "dispatchability analysis not performed " "on module; run -iree-flow-dispatchability-analysis first"; return signalPassFailure(); } for (auto &block : getFunction()) { if (failed(identifyBlockDispatchRegions(&block, dispatchability.getValue()))) { return signalPassFailure(); } } } }; std::unique_ptr<OpPassBase<FuncOp>> createIdentifyDispatchRegionsPass() { return std::make_unique<IdentifyDispatchRegionsPass>(); } static PassRegistration<IdentifyDispatchRegionsPass> pass( "iree-flow-identify-dispatch-regions", "Conservatively identifies dispatch regions in functions"); } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir <commit_msg>Add some LLVM_DEBUG logging to the dispatch region analysis.<commit_after>// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include "iree/compiler/Dialect/Flow/Analysis/Dispatchability.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "iree/compiler/Dialect/Flow/Utils/DispatchUtils.h" #include "iree/compiler/Dialect/Flow/Utils/WorkloadUtils.h" #include "iree/compiler/Utils/GraphUtils.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Debug.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Support/LLVM.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Transforms/Utils.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" #define DEBUG_TYPE "iree-dispatch" namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { namespace { // Returns true if the given |op| can be dispatched in all cases. // Other passes may handle special cases of these ops but this initial // identification is conservative. bool isDispatchableOp(Operation *op, Dispatchability &dispatchability) { // TODO(b/144530470): replace with tablegen attributes/interfaces. if (FlowDialect::isDialectOp(op)) { // Ignore things we've already produced as they should only relate to // sequencer operations. LLVM_DEBUG(llvm::dbgs() << "NOT DISPATCHABLE (Flow Dialect): " << op->getName() << "\n"); return false; } else if (op->isKnownTerminator()) { // Currently we skip all terminators as we want to leave them in the block // to keep it valid. Future folding passes may take care of them if they are // worth bringing into the dispatch region. LLVM_DEBUG(llvm::dbgs() << "NOT DISPATCHABLE (Known Terminator): " << op->getName() << "\n"); return false; } else if (auto callOp = dyn_cast<CallOp>(op)) { bool dispatchable = dispatchability.isDispatchable(callOp.getCallee()); LLVM_DEBUG(llvm::dbgs() << (dispatchable ? "" : "NOT ") << "DISPATCHABLE (Call): " << op->getName() << "\n"); return dispatchable; } else if (isa<CallIndirectOp>(op)) { // Indirect calls are not supported in dispatch code. LLVM_DEBUG(llvm::dbgs() << "NOT DISPATCHABLE (Call Indirect): " << op->getName() << "\n"); return false; } else if (isa<ConstantOp>(op)) { // Constants are handled in the RematerializeDispatchConstants pass. // We do that independently so that we can more easily see the use of // constants across all dispatches instead of just on an individual basis // as we do here. LLVM_DEBUG(llvm::dbgs() << "NOT DISPATCHABLE (Constant): " << op->getName() << "\n"); return false; } else if (op->getNumResults() && !op->getResult(0).getType().isa<ShapedType>()) { // We don't put scalar manipulation into dispatch regions. LLVM_DEBUG(llvm::dbgs() << "NOT DISPATCHABLE (Non Shaped): " << op->getName() << "\n"); return false; } else if (!isOpOfKnownDialect(op)) { // Probably a custom op. LLVM_DEBUG(llvm::dbgs() << "NOT DISPATCHABLE (Unknown Dialect): " << op->getName() << "\n"); return false; } LLVM_DEBUG(llvm::dbgs() << "DISPATCHABLE: " << op->getName() << "\n"); return true; } // Returns true if the given |op| can have other ops fused into it. // This is sketchy and it'd be nice to define this as an op property instead. // // What we are looking for in foldable ops is whether the execution of the op // when fused has some possible benefit (or at least, a non-negative cost). // Eventually we want to allow backends to vote on this and allow multiple // folding strategies within the same executable. For now we just hardcode what // we know for the ops we have. // // Preconditions: isDispatchableOp(op) == true. bool isFusionRootOp(Operation *op) { // TODO(b/144530470): replace with tablegen attributes/interfaces. if (isa<xla_hlo::DotOp>(op) || isa<xla_hlo::ConvOp>(op)) { // We have hand-written kernels for these right now we want to stand alone. // When we do a bit more magic we should allow these ops to fold. return false; } return true; } // Returns true if the given |op| can be fused into other ops. // // Ops that perform narrowing on shapes (such as reduction ops) should not // generally be fused with other downstream ops (probably...). This avoids // potential oversampling and indexing issues and allows backends to perform // more efficient rooted cascading reduction dispatches. // // Preconditions: isDispatchableOp(op) == true. bool isFusableOp(Operation *op) { // TODO(b/144530470): replace with tablegen attributes/interfaces. if (isa<xla_hlo::DotOp>(op) || isa<xla_hlo::ConvOp>(op)) { return false; } else if (isa<xla_hlo::ReduceOp>(op)) { // Reduction is usually a dedicated root operation - we can shove things in // the front of it but not behind. return false; } return true; } // Recursively traverses the IR DAG along the operand edges to find ops we are // able to fuse and appends them to |subgraph|. void gatherFusionOps(Operation *op, Dispatchability &dispatchability, llvm::SetVector<Operation *> *subgraph) { // Skip ops that are used outside of the subgraph we are building. for (auto result : op->getResults()) { if (result.use_empty() || result.hasOneUse()) continue; for (auto *user : result.getUsers()) { if (subgraph->count(user) == 0) { // Op that consumes the result is not (yet) in the subgraph. // For now we'll ignore these as it may represent a fork that we don't // want to join too early. return; } } } // Walk backward up to ops providing our input operands. for (auto operand : op->getOperands()) { auto *sourceOp = operand.getDefiningOp(); if (!sourceOp) continue; if (subgraph->count(sourceOp) == 0) { if (isDispatchableOp(sourceOp, dispatchability) && isFusableOp(sourceOp)) { gatherFusionOps(sourceOp, dispatchability, subgraph); } } } subgraph->insert(op); } // Finds all ops that can be fused together with the given |rootOp| by searching // backwards in the op order through input edges. // Returns a topologically sorted list of all fused ops with |rootOp| at the // end. std::vector<Operation *> findFusionSubgraphFromRoot( Operation *rootOp, Dispatchability &dispatchability) { if (!isFusionRootOp(rootOp)) { return {rootOp}; } llvm::SetVector<Operation *> subgraph; subgraph.insert(rootOp); gatherFusionOps(rootOp, dispatchability, &subgraph); return sortOpsTopologically(subgraph); } // Identifies ranges of dispatchable ops and moves them into dispatch regions. LogicalResult identifyBlockDispatchRegions(Block *block, Dispatchability &dispatchability) { // Fixed point iteration until we can no longer fuse anything. bool didFindAnyNewRegions; do { // Iterate in reverse so we root further along in the op list. didFindAnyNewRegions = false; for (auto &rootOp : llvm::reverse(*block)) { if (!isDispatchableOp(&rootOp, dispatchability)) { // Op should remain at the sequencer level. continue; } // Attempt to find all operations, including rootOp, that can be fused. // The ops will be sorted in topological order with rootOp as the last op. // Worst case we may end up with a subgraph of only the rootOp. auto fusedSubgraph = findFusionSubgraphFromRoot(&rootOp, dispatchability); // Compute the workload based on the output shape. // When variadic all output shapes match so we can just take the first. auto workload = calculateWorkload(&rootOp, rootOp.getResult(0)); if (!workload) { return failure(); } // Try to build a dispatch region from this root. if (failed(buildDispatchRegion(block, workload, fusedSubgraph))) { return failure(); } // Successfully created a dispatch region from the ops and we must now // start over again as we've likely trashed the whole block structure. didFindAnyNewRegions = true; break; } } while (didFindAnyNewRegions); return success(); } } // namespace // Identifies dispatchable ops and moves them into dispatch regions. // Some ops, such as call, will be deferred until following passes. class IdentifyDispatchRegionsPass : public FunctionPass<IdentifyDispatchRegionsPass> { public: void runOnFunction() override { // NOTE: we require the DispatchabilityAnalysisPass to have run first. auto dispatchability = getCachedParentAnalysis<Dispatchability>(); if (!dispatchability.hasValue()) { getFunction().emitError() << "dispatchability analysis not performed " "on module; run -iree-flow-dispatchability-analysis first"; return signalPassFailure(); } for (auto &block : getFunction()) { if (failed(identifyBlockDispatchRegions(&block, dispatchability.getValue()))) { return signalPassFailure(); } } } }; std::unique_ptr<OpPassBase<FuncOp>> createIdentifyDispatchRegionsPass() { return std::make_unique<IdentifyDispatchRegionsPass>(); } static PassRegistration<IdentifyDispatchRegionsPass> pass( "iree-flow-identify-dispatch-regions", "Conservatively identifies dispatch regions in functions"); } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>#include<iostream> #include<cstdio> #include<cctype> #include<string> #include<cstring> using namespace std; const int MAXN = 200 + 10; int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}}; int m, n; int graph[MAXN][MAXN]; char alpha[7] = "ADJKSW"; int con[6]; int dic[6][2] = {{1, 0}, {3, 2}, {5, 1}, {4, 4}, {0, 5}, {2, 3}}; int num[16][4] = {{0,0,0,0},{0,0,0,1},{0,0,1,0},{0,0,1,1}, {0,1,0,0},{0,1,0,1},{0,1,1,0},{0,1,1,1}, {1,0,0,0},{1,0,0,1},{1,0,1,0},{1,0,1,1}, {1,1,0,0},{1,1,0,1},{1,1,1,0},{1,1,1,1}}; int cnt; void dfs_zero(int r, int c) { if (r < 0 || r >= n || c < 0 || c >= m || graph[r][c] != 0) { return; } graph[r][c] = -1; for (int i = 0; i < 4; i ++) { int xx = r + dir[i][0]; int yy = c + dir[i][1]; dfs_zero(xx, yy); } } void dfs(int r, int c) { if (r < 0 || r >= n || c < 0 || c >= m || graph[r][c] == -1) { return; } if (graph[r][c] == 0) { cnt ++; dfs_zero(r, c); return; } graph[r][c] = -1; for (int i = 0; i < 4; i ++) { int xx = r + dir[i][0]; int yy = c + dir[i][1]; dfs(xx, yy); } } int main() { int cas = 0; while (cin >> n >> m && n && m) { memset(graph, 0, sizeof(graph)); memset(con, 0, sizeof(con)); char str[MAXN]; for (int i = 0; i < n; i ++) { cin >> str; int len = 0; for (int j = 0; j < m; j ++) { if (str[j] == '0') { for (int k = 0; k < 4; k ++) { graph[i][len ++] = 0; continue; } } int tmp; if (isalpha(str[j])) { tmp = str[j] - 'a' + 10; } else { tmp = str[j] - '0'; } for (int k = 0; k < 4; k ++) { graph[i][len ++] = num[tmp][k]; } } } m *= 4; for (int i = 0; i < n; i ++) { if (graph[i][0] == 0) { dfs_zero(i, 0); } if (graph[i][m - 1] == 0) { dfs_zero(i, m - 1); } } for (int j = 0; j < m; j ++) { if (graph[0][j] == 0) { dfs_zero(0, j); } if (graph[n - 1][j] == 0) { dfs_zero(n - 1, j); } } for (int i = 0; i < n; i ++) { for (int j = 0; j < m; j ++) { if (graph[i][j] == 1) { cnt = 0; dfs(i, j); for (int k = 1; k < 6; k ++) { if (cnt == dic[k][0]) { con[dic[k][1]] ++; break; } } } } } cout << "Case " << ++ cas << ": "; for (int i = 0; i < 6; i ++) { for (int j = 0; j < con[i]; j ++) { cout << alpha[i]; } } cout << endl; } } <commit_msg>Completed Uva1103<commit_after>#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <cstdlib> #include <stack> #include <cctype> #include <string> #include <malloc.h> #include <queue> #include <map> using namespace std; const int INF = 0xffffff; const double Pi = 4 * atan(1); const int Maxn = 200 + 10; int dir2[8][2] = {{-1,0},{0,-1},{-1,1},{1,-1},{-1,-1},{1,0},{0,1},{1,1}}; int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}}; int m,n; int graph[Maxn][Maxn]; char alpha[] = "ADJKSW"; int con[6]; int dic[6][2] = {{1,0},{3,2},{5,1},{4,4},{0,5},{2,3}}; int num[16][4] = {{0,0,0,0},{0,0,0,1},{0,0,1,0},{0,0,1,1}, {0,1,0,0},{0,1,0,1},{0,1,1,0},{0,1,1,1}, {1,0,0,0},{1,0,0,1},{1,0,1,0},{1,0,1,1}, {1,1,0,0},{1,1,0,1},{1,1,1,0},{1,1,1,1}}; int cnt; void dfsZero(int r,int c){ if(r < 0 || r >= n || c < 0 || c >= m || graph[r][c] != 0) return; graph[r][c] = -1; for(int i = 0;i < 4;i++){ int xx = dir[i][0] + r; int yy = dir[i][1] + c; dfsZero(xx,yy); } } void dfs(int r,int c){ if(r < 0 || r >= n || c < 0 || c >= m || graph[r][c] == -1) return; if(graph[r][c] == 0){ cnt++; dfsZero(r,c); return; } graph[r][c] = -1; for(int i = 0;i < 4;i++){ int xx = dir[i][0] + r; int yy = dir[i][1] + c; dfs(xx,yy); } } int main() { #ifndef ONLINE_JUDGE freopen("inpt.txt","r",stdin); #endif int cas = 0; while(cin >> n >> m && n && m){ memset(graph,0,sizeof(graph)); memset(con,0,sizeof(con)); char str[Maxn]; for(int i = 0;i < n;i++){ cin >> str; int len = 0; for(int j = 0;j < m;j++){ if(str[j] == '0'){ for(int k = 0;k < 4;k++) graph[i][len++] = 0; continue; } int tmp; if(isalpha(str[j])) tmp = str[j] - 'a' + 10; else tmp = str[j] - '0'; for(int k = 0;k < 4;k++){ graph[i][len++] = num[tmp][k]; } } } m *= 4; for(int i = 0;i < n;i++){ if(graph[i][0] == 0) dfsZero(i,0); if(graph[i][m-1] == 0) dfsZero(i,m-1); } for(int j = 0;j < m;j++){ if(graph[0][j] == 0) dfsZero(0,j); if(graph[n-1][j] == 0) dfsZero(n-1,j); } for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ if(graph[i][j] == 1){ cnt = 0; dfs(i,j); for(int k = 0;k < 6;k++){ if(cnt == dic[k][0]){ con[ dic[k][1] ]++; break; } } } } } cout << "Case " << ++cas << ": "; for(int i = 0;i < 6;i++){ for(int j = 0;j < con[i];j++){ cout << alpha[i]; } } cout << endl; } return 0; }<|endoftext|>
<commit_before>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <iostream> #include <qi/log.hpp> #include <qimessaging/session.hpp> #include <qimessaging/url.hpp> #include "transportserver_p.hpp" #include "transportserverdummy_p.hpp" namespace qi { bool TransportServerDummyPrivate::listen() { qiLogWarning("TransportServer") << "listen: You are currently running on dummy" << " TransportServer!"; return true; } void TransportServerDummyPrivate::close() { } TransportServerDummyPrivate::TransportServerDummyPrivate(TransportServer* self, const qi::Url &url, EventLoop* ctx) : TransportServerPrivate(self, url, ctx) { } void TransportServerDummyPrivate::destroy() { delete this; } TransportServerDummyPrivate::~TransportServerDummyPrivate() { } } <commit_msg>Revert "TransportServerDummy: no log on close"<commit_after>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <iostream> #include <qi/log.hpp> #include <qimessaging/session.hpp> #include <qimessaging/url.hpp> #include "transportserver_p.hpp" #include "transportserverdummy_p.hpp" namespace qi { bool TransportServerDummyPrivate::listen() { qiLogWarning("TransportServer") << "listen: You are currently running on dummy" << " TransportServer!"; return true; } void TransportServerDummyPrivate::close() { qiLogVerbose("TransportServer") << "close: You are currently running on dummy" << " TransportServer!"; } TransportServerDummyPrivate::TransportServerDummyPrivate(TransportServer* self, const qi::Url &url, EventLoop* ctx) : TransportServerPrivate(self, url, ctx) { } void TransportServerDummyPrivate::destroy() { delete this; } TransportServerDummyPrivate::~TransportServerDummyPrivate() { } } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include "zlib.h" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/io.hpp" namespace { enum { udp_connection_retries = 4, udp_announce_retries = 15, udp_connect_timeout = 15, udp_announce_timeout = 10, udp_buffer_size = 2048 }; } using namespace boost::posix_time; namespace libtorrent { udp_tracker_connection::udp_tracker_connection( tracker_request const& req , std::string const& hostname , unsigned short port , boost::weak_ptr<request_callback> c , const http_settings& stn) : tracker_connection(c) , m_request_time(second_clock::universal_time()) , m_request(req) , m_transaction_id(0) , m_connection_id(0) , m_settings(stn) , m_attempts(0) { // TODO: this is a problem. DNS-lookup is blocking! // (may block up to 5 seconds) address a(hostname.c_str(), port); if (has_requester()) requester().m_tracker_address = a; m_socket.reset(new socket(socket::udp, false)); m_socket->connect(a); send_udp_connect(); } bool udp_tracker_connection::send_finished() const { using namespace boost::posix_time; time_duration d = second_clock::universal_time() - m_request_time; return (m_transaction_id != 0 && m_connection_id != 0) || d > seconds(m_settings.tracker_timeout); } bool udp_tracker_connection::tick() { using namespace boost::posix_time; time_duration d = second_clock::universal_time() - m_request_time; if (m_connection_id == 0 && d > seconds(udp_connect_timeout)) { if (m_attempts >= udp_connection_retries) { if (has_requester()) requester().tracker_request_timed_out(m_request); return true; } send_udp_connect(); return false; } if (m_connection_id != 0 && d > seconds(udp_announce_timeout)) { if (m_attempts >= udp_announce_retries) { if (has_requester()) requester().tracker_request_timed_out(m_request); return true; } if (m_request.kind == tracker_request::announce_request) send_udp_announce(); else if (m_request.kind == tracker_request::scrape_request) send_udp_scrape(); return false; } char buf[udp_buffer_size]; int ret = m_socket->receive(buf, udp_buffer_size); // if there was nothing to receive, return if (ret == 0) return false; if (ret < 0) { socket::error_code err = m_socket->last_error(); if (err == socket::would_block) return false; throw network_error(m_socket->last_error()); } if (ret == udp_buffer_size) { if (has_requester()) requester().tracker_request_error( m_request, -1, "tracker reply too big"); return true; } if (m_connection_id == 0) { return parse_connect_response(buf, ret); } else if (m_request.kind == tracker_request::announce_request) { return parse_announce_response(buf, ret); } else if (m_request.kind == tracker_request::scrape_request) { return parse_scrape_response(buf, ret); } assert(false); return false; } void udp_tracker_connection::send_udp_announce() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); // connection_id detail::write_int64(m_connection_id, out); // action (announce) detail::write_int32(announce, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out); // peer_id std::copy(m_request.id.begin(), m_request.id.end(), out); // downloaded detail::write_int64(m_request.downloaded, out); // left detail::write_int64(m_request.left, out); // uploaded detail::write_int64(m_request.uploaded, out); // event detail::write_int32(m_request.event, out); // ip address detail::write_int32(0, out); // key detail::write_int32(m_request.key, out); // num_want detail::write_int32(m_request.num_want, out); // port detail::write_uint16(m_request.listen_port, out); // extensions detail::write_uint16(0, out); m_socket->send(&buf[0], buf.size()); m_request_time = second_clock::universal_time(); ++m_attempts; } void udp_tracker_connection::send_udp_scrape() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); // connection_id detail::write_int64(m_connection_id, out); // action (scrape) detail::write_int32(scrape, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out); m_socket->send(&buf[0], buf.size()); m_request_time = second_clock::universal_time(); ++m_attempts; } void udp_tracker_connection::send_udp_connect() { char send_buf[16]; char* ptr = send_buf; if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); // connection_id detail::write_int64(0x41727101980, ptr); // action (connect) detail::write_int32(connect, ptr); // transaction_id detail::write_int32(m_transaction_id, ptr); m_socket->send(send_buf, 16); m_request_time = second_clock::universal_time(); ++m_attempts; } bool udp_tracker_connection::parse_announce_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { return false; } if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(buf, buf + len - 8)); return true; } if (action != announce) return false; if (len < 20) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 20, ignoring"); #endif return false; } int interval = detail::read_int32(buf); int incomplete = detail::read_int32(buf); int complete = detail::read_int32(buf); int num_peers = (len - 20) / 6; if ((len - 20) % 6 != 0) { if (has_requester()) requester().tracker_request_error( m_request, -1, "invalid tracker response"); return true; } if (!has_requester()) return true; std::vector<peer_entry> peer_list; for (int i = 0; i < num_peers; ++i) { peer_entry e; std::stringstream s; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf); e.ip = s.str(); e.port = detail::read_uint16(buf); e.id.clear(); peer_list.push_back(e); } requester().tracker_response(m_request, peer_list, interval , complete, incomplete); return true; } bool udp_tracker_connection::parse_scrape_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { return false; } if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(buf, buf + len - 8)); return true; } if (action != scrape) return false; if (len < 20) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 20, ignoring"); #endif return false; } int complete = detail::read_int32(buf); /*int downloaded = */detail::read_int32(buf); int incomplete = detail::read_int32(buf); if (!has_requester()) return true; std::vector<peer_entry> peer_list; requester().tracker_response(m_request, peer_list, 0 , complete, incomplete); return true; } bool udp_tracker_connection::parse_connect_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } const char* ptr = buf; int action = detail::read_int32(ptr); int transaction = detail::read_int32(ptr); if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(ptr, buf + len)); return true; } if (action != connect) return false; if (m_transaction_id != transaction) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with incorrect transaction id, ignoring"); #endif return false; } if (len < 16) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a connection message size < 16, ignoring"); #endif return false; } // reset transaction m_transaction_id = 0; m_attempts = 0; m_connection_id = detail::read_int64(ptr); if (m_request.kind == tracker_request::announce_request) send_udp_announce(); else if (m_request.kind == tracker_request::scrape_request) send_udp_scrape(); return false; } } <commit_msg>*** empty log message ***<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include "zlib.h" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/io.hpp" namespace { enum { udp_connection_retries = 4, udp_announce_retries = 15, udp_connect_timeout = 15, udp_announce_timeout = 10, udp_buffer_size = 2048 }; } using namespace boost::posix_time; namespace libtorrent { udp_tracker_connection::udp_tracker_connection( tracker_request const& req , std::string const& hostname , unsigned short port , boost::weak_ptr<request_callback> c , const http_settings& stn) : tracker_connection(c) , m_request_time(second_clock::universal_time()) , m_request(req) , m_transaction_id(0) , m_connection_id(0) , m_settings(stn) , m_attempts(0) { // TODO: this is a problem. DNS-lookup is blocking! // (may block up to 5 seconds) address a(hostname.c_str(), port); if (has_requester()) requester().m_tracker_address = a; m_socket.reset(new socket(socket::udp, false)); m_socket->connect(a); send_udp_connect(); } bool udp_tracker_connection::send_finished() const { using namespace boost::posix_time; time_duration d = second_clock::universal_time() - m_request_time; return (m_transaction_id != 0 && m_connection_id != 0) || d > seconds(m_settings.tracker_timeout); } bool udp_tracker_connection::tick() { using namespace boost::posix_time; time_duration d = second_clock::universal_time() - m_request_time; if (m_connection_id == 0 && d > seconds(udp_connect_timeout)) { if (m_attempts >= udp_connection_retries) { if (has_requester()) requester().tracker_request_timed_out(m_request); return true; } send_udp_connect(); return false; } if (m_connection_id != 0 && d > seconds(udp_announce_timeout)) { if (m_attempts >= udp_announce_retries) { if (has_requester()) requester().tracker_request_timed_out(m_request); return true; } if (m_request.kind == tracker_request::announce_request) send_udp_announce(); else if (m_request.kind == tracker_request::scrape_request) send_udp_scrape(); return false; } char buf[udp_buffer_size]; int ret = m_socket->receive(buf, udp_buffer_size); // if there was nothing to receive, return if (ret == 0) return false; if (ret < 0) { socket::error_code err = m_socket->last_error(); if (err == socket::would_block) return false; throw network_error(m_socket->last_error()); } if (ret == udp_buffer_size) { if (has_requester()) requester().tracker_request_error( m_request, -1, "tracker reply too big"); return true; } if (m_connection_id == 0) { return parse_connect_response(buf, ret); } else if (m_request.kind == tracker_request::announce_request) { return parse_announce_response(buf, ret); } else if (m_request.kind == tracker_request::scrape_request) { return parse_scrape_response(buf, ret); } assert(false); return false; } void udp_tracker_connection::send_udp_announce() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); // connection_id detail::write_int64(m_connection_id, out); // action (announce) detail::write_int32(announce, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out); // peer_id std::copy(m_request.id.begin(), m_request.id.end(), out); // downloaded detail::write_int64(m_request.downloaded, out); // left detail::write_int64(m_request.left, out); // uploaded detail::write_int64(m_request.uploaded, out); // event detail::write_int32(m_request.event, out); // ip address detail::write_int32(0, out); // key detail::write_int32(m_request.key, out); // num_want detail::write_int32(m_request.num_want, out); // port detail::write_uint16(m_request.listen_port, out); // extensions detail::write_uint16(0, out); m_socket->send(&buf[0], buf.size()); m_request_time = second_clock::universal_time(); ++m_attempts; } void udp_tracker_connection::send_udp_scrape() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); // connection_id detail::write_int64(m_connection_id, out); // action (scrape) detail::write_int32(scrape, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out); m_socket->send(&buf[0], buf.size()); m_request_time = second_clock::universal_time(); ++m_attempts; } void udp_tracker_connection::send_udp_connect() { char send_buf[16]; char* ptr = send_buf; if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); // connection_id detail::write_uint32(0x417, ptr); detail::write_uint32(0x27101980, ptr); // action (connect) detail::write_int32(connect, ptr); // transaction_id detail::write_int32(m_transaction_id, ptr); m_socket->send(send_buf, 16); m_request_time = second_clock::universal_time(); ++m_attempts; } bool udp_tracker_connection::parse_announce_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { return false; } if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(buf, buf + len - 8)); return true; } if (action != announce) return false; if (len < 20) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 20, ignoring"); #endif return false; } int interval = detail::read_int32(buf); int incomplete = detail::read_int32(buf); int complete = detail::read_int32(buf); int num_peers = (len - 20) / 6; if ((len - 20) % 6 != 0) { if (has_requester()) requester().tracker_request_error( m_request, -1, "invalid tracker response"); return true; } if (!has_requester()) return true; std::vector<peer_entry> peer_list; for (int i = 0; i < num_peers; ++i) { peer_entry e; std::stringstream s; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf); e.ip = s.str(); e.port = detail::read_uint16(buf); e.id.clear(); peer_list.push_back(e); } requester().tracker_response(m_request, peer_list, interval , complete, incomplete); return true; } bool udp_tracker_connection::parse_scrape_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { return false; } if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(buf, buf + len - 8)); return true; } if (action != scrape) return false; if (len < 20) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 20, ignoring"); #endif return false; } int complete = detail::read_int32(buf); /*int downloaded = */detail::read_int32(buf); int incomplete = detail::read_int32(buf); if (!has_requester()) return true; std::vector<peer_entry> peer_list; requester().tracker_response(m_request, peer_list, 0 , complete, incomplete); return true; } bool udp_tracker_connection::parse_connect_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } const char* ptr = buf; int action = detail::read_int32(ptr); int transaction = detail::read_int32(ptr); if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(ptr, buf + len)); return true; } if (action != connect) return false; if (m_transaction_id != transaction) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with incorrect transaction id, ignoring"); #endif return false; } if (len < 16) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a connection message size < 16, ignoring"); #endif return false; } // reset transaction m_transaction_id = 0; m_attempts = 0; m_connection_id = detail::read_int64(ptr); if (m_request.kind == tracker_request::announce_request) send_udp_announce(); else if (m_request.kind == tracker_request::scrape_request) send_udp_scrape(); return false; } } <|endoftext|>
<commit_before>//===-- OptionGroupFormat.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-python.h" #include "lldb/Interpreter/OptionGroupFormat.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/ArchSpec.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Target.h" #include "lldb/Utility/Utils.h" using namespace lldb; using namespace lldb_private; OptionGroupFormat::OptionGroupFormat (lldb::Format default_format, uint64_t default_byte_size, uint64_t default_count) : m_format (default_format, default_format), m_byte_size (default_byte_size, default_byte_size), m_count (default_count, default_count), m_prev_gdb_format('x'), m_prev_gdb_size('w') { } OptionGroupFormat::~OptionGroupFormat () { } static OptionDefinition g_option_table[] = { { LLDB_OPT_SET_1, false, "format" ,'f', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFormat , "Specify a format to be used for display."}, { LLDB_OPT_SET_2, false, "gdb-format",'G', OptionParser::eRequiredArgument, NULL, 0, eArgTypeGDBFormat, "Specify a format using a GDB format specifier string."}, { LLDB_OPT_SET_3, false, "size" ,'s', OptionParser::eRequiredArgument, NULL, 0, eArgTypeByteSize , "The size in bytes to use when displaying with the selected format."}, { LLDB_OPT_SET_4, false, "count" ,'c', OptionParser::eRequiredArgument, NULL, 0, eArgTypeCount , "The number of total items to display."}, }; uint32_t OptionGroupFormat::GetNumDefinitions () { if (m_byte_size.GetDefaultValue() < UINT64_MAX) { if (m_count.GetDefaultValue() < UINT64_MAX) return 4; else return 3; } return 2; } const OptionDefinition * OptionGroupFormat::GetDefinitions () { return g_option_table; } Error OptionGroupFormat::SetOptionValue (CommandInterpreter &interpreter, uint32_t option_idx, const char *option_arg) { Error error; const int short_option = g_option_table[option_idx].short_option; switch (short_option) { case 'f': error = m_format.SetValueFromCString (option_arg); break; case 'c': if (m_count.GetDefaultValue() == 0) { error.SetErrorString ("--count option is disabled"); } else { error = m_count.SetValueFromCString (option_arg); if (m_count.GetCurrentValue() == 0) error.SetErrorStringWithFormat("invalid --count option value '%s'", option_arg); } break; case 's': if (m_byte_size.GetDefaultValue() == 0) { error.SetErrorString ("--size option is disabled"); } else { error = m_byte_size.SetValueFromCString (option_arg); if (m_byte_size.GetCurrentValue() == 0) error.SetErrorStringWithFormat("invalid --size option value '%s'", option_arg); } break; case 'G': { char *end = NULL; const char *gdb_format_cstr = option_arg; uint64_t count = 0; if (::isdigit (gdb_format_cstr[0])) { count = strtoull (gdb_format_cstr, &end, 0); if (option_arg != end) gdb_format_cstr = end; // We have a valid count, advance the string position else count = 0; } Format format = eFormatDefault; uint32_t byte_size = 0; while (ParserGDBFormatLetter (interpreter, gdb_format_cstr[0], format, byte_size)) { ++gdb_format_cstr; } // We the first character of the "gdb_format_cstr" is not the // NULL terminator, we didn't consume the entire string and // something is wrong. Also, if none of the format, size or count // was specified correctly, then abort. if (gdb_format_cstr[0] || (format == eFormatInvalid && byte_size == 0 && count == 0)) { // Nothing got set correctly error.SetErrorStringWithFormat ("invalid gdb format string '%s'", option_arg); return error; } // At least one of the format, size or count was set correctly. // Anything that wasn't set correctly should be set to the // previous default if (format == eFormatInvalid) ParserGDBFormatLetter (interpreter, m_prev_gdb_format, format, byte_size); const bool byte_size_enabled = m_byte_size.GetDefaultValue() < UINT64_MAX; const bool count_enabled = m_count.GetDefaultValue() < UINT64_MAX; if (byte_size_enabled) { // Byte size is enabled if (byte_size == 0) ParserGDBFormatLetter (interpreter, m_prev_gdb_size, format, byte_size); } else { // Byte size is disabled, make sure it wasn't specified if (byte_size > 0) { error.SetErrorString ("this command doesn't support specifying a byte size"); return error; } } if (count_enabled) { // Count is enabled and was not set, set it to the default for gdb format statements (which is 1). if (count == 0) count = 1; } else { // Count is disabled, make sure it wasn't specified if (count > 0) { error.SetErrorString ("this command doesn't support specifying a count"); return error; } } m_format.SetCurrentValue (format); m_format.SetOptionWasSet (); if (byte_size_enabled) { m_byte_size.SetCurrentValue (byte_size); m_byte_size.SetOptionWasSet (); } if (count_enabled) { m_count.SetCurrentValue(count); m_count.SetOptionWasSet (); } } break; default: error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); break; } return error; } bool OptionGroupFormat::ParserGDBFormatLetter (CommandInterpreter &interpreter, char format_letter, Format &format, uint32_t &byte_size) { m_has_gdb_format = true; switch (format_letter) { case 'o': format = eFormatOctal; m_prev_gdb_format = format_letter; return true; case 'x': format = eFormatHex; m_prev_gdb_format = format_letter; return true; case 'd': format = eFormatDecimal; m_prev_gdb_format = format_letter; return true; case 'u': format = eFormatUnsigned; m_prev_gdb_format = format_letter; return true; case 't': format = eFormatBinary; m_prev_gdb_format = format_letter; return true; case 'f': format = eFormatFloat; m_prev_gdb_format = format_letter; return true; case 'a': format = eFormatAddressInfo; { ExecutionContext exe_ctx(interpreter.GetExecutionContext()); Target *target = exe_ctx.GetTargetPtr(); if (target) byte_size = target->GetArchitecture().GetAddressByteSize(); m_prev_gdb_format = format_letter; return true; } case 'i': format = eFormatInstruction; m_prev_gdb_format = format_letter; return true; case 'c': format = eFormatChar; m_prev_gdb_format = format_letter; return true; case 's': format = eFormatCString; m_prev_gdb_format = format_letter; return true; case 'T': format = eFormatOSType; m_prev_gdb_format = format_letter; return true; case 'A': format = eFormatHexFloat; m_prev_gdb_format = format_letter; return true; case 'b': byte_size = 1; m_prev_gdb_size = format_letter; return true; case 'h': byte_size = 2; m_prev_gdb_size = format_letter; return true; case 'w': byte_size = 4; m_prev_gdb_size = format_letter; return true; case 'g': byte_size = 8; m_prev_gdb_size = format_letter; return true; default: break; } return false; } void OptionGroupFormat::OptionParsingStarting (CommandInterpreter &interpreter) { m_format.Clear(); m_byte_size.Clear(); m_count.Clear(); m_has_gdb_format = false; } <commit_msg><rdar://problem/15192088><commit_after>//===-- OptionGroupFormat.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-python.h" #include "lldb/Interpreter/OptionGroupFormat.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/ArchSpec.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Target.h" #include "lldb/Utility/Utils.h" using namespace lldb; using namespace lldb_private; OptionGroupFormat::OptionGroupFormat (lldb::Format default_format, uint64_t default_byte_size, uint64_t default_count) : m_format (default_format, default_format), m_byte_size (default_byte_size, default_byte_size), m_count (default_count, default_count), m_prev_gdb_format('x'), m_prev_gdb_size('w') { } OptionGroupFormat::~OptionGroupFormat () { } static OptionDefinition g_option_table[] = { { LLDB_OPT_SET_1, false, "format" ,'f', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFormat , "Specify a format to be used for display."}, { LLDB_OPT_SET_2, false, "gdb-format",'G', OptionParser::eRequiredArgument, NULL, 0, eArgTypeGDBFormat, "Specify a format using a GDB format specifier string."}, { LLDB_OPT_SET_3, false, "size" ,'s', OptionParser::eRequiredArgument, NULL, 0, eArgTypeByteSize , "The size in bytes to use when displaying with the selected format."}, { LLDB_OPT_SET_4, false, "count" ,'c', OptionParser::eRequiredArgument, NULL, 0, eArgTypeCount , "The number of total items to display."}, }; uint32_t OptionGroupFormat::GetNumDefinitions () { if (m_byte_size.GetDefaultValue() < UINT64_MAX) { if (m_count.GetDefaultValue() < UINT64_MAX) return 4; else return 3; } return 2; } const OptionDefinition * OptionGroupFormat::GetDefinitions () { return g_option_table; } Error OptionGroupFormat::SetOptionValue (CommandInterpreter &interpreter, uint32_t option_idx, const char *option_arg) { Error error; const int short_option = g_option_table[option_idx].short_option; switch (short_option) { case 'f': error = m_format.SetValueFromCString (option_arg); break; case 'c': if (m_count.GetDefaultValue() == 0) { error.SetErrorString ("--count option is disabled"); } else { error = m_count.SetValueFromCString (option_arg); if (m_count.GetCurrentValue() == 0) error.SetErrorStringWithFormat("invalid --count option value '%s'", option_arg); } break; case 's': if (m_byte_size.GetDefaultValue() == 0) { error.SetErrorString ("--size option is disabled"); } else { error = m_byte_size.SetValueFromCString (option_arg); if (m_byte_size.GetCurrentValue() == 0) error.SetErrorStringWithFormat("invalid --size option value '%s'", option_arg); } break; case 'G': { char *end = NULL; const char *gdb_format_cstr = option_arg; uint64_t count = 0; if (::isdigit (gdb_format_cstr[0])) { count = strtoull (gdb_format_cstr, &end, 0); if (option_arg != end) gdb_format_cstr = end; // We have a valid count, advance the string position else count = 0; } Format format = eFormatDefault; uint32_t byte_size = 0; while (ParserGDBFormatLetter (interpreter, gdb_format_cstr[0], format, byte_size)) { ++gdb_format_cstr; } // We the first character of the "gdb_format_cstr" is not the // NULL terminator, we didn't consume the entire string and // something is wrong. Also, if none of the format, size or count // was specified correctly, then abort. if (gdb_format_cstr[0] || (format == eFormatInvalid && byte_size == 0 && count == 0)) { // Nothing got set correctly error.SetErrorStringWithFormat ("invalid gdb format string '%s'", option_arg); return error; } // At least one of the format, size or count was set correctly. // Anything that wasn't set correctly should be set to the // previous default if (format == eFormatInvalid) ParserGDBFormatLetter (interpreter, m_prev_gdb_format, format, byte_size); const bool byte_size_enabled = m_byte_size.GetDefaultValue() < UINT64_MAX; const bool count_enabled = m_count.GetDefaultValue() < UINT64_MAX; if (byte_size_enabled) { // Byte size is enabled if (byte_size == 0) ParserGDBFormatLetter (interpreter, m_prev_gdb_size, format, byte_size); } else { // Byte size is disabled, make sure it wasn't specified // but if this is an address, it's actually necessary to // specify one so don't error out if (byte_size > 0 && format != lldb::eFormatAddressInfo) { error.SetErrorString ("this command doesn't support specifying a byte size"); return error; } } if (count_enabled) { // Count is enabled and was not set, set it to the default for gdb format statements (which is 1). if (count == 0) count = 1; } else { // Count is disabled, make sure it wasn't specified if (count > 0) { error.SetErrorString ("this command doesn't support specifying a count"); return error; } } m_format.SetCurrentValue (format); m_format.SetOptionWasSet (); if (byte_size_enabled) { m_byte_size.SetCurrentValue (byte_size); m_byte_size.SetOptionWasSet (); } if (count_enabled) { m_count.SetCurrentValue(count); m_count.SetOptionWasSet (); } } break; default: error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option); break; } return error; } bool OptionGroupFormat::ParserGDBFormatLetter (CommandInterpreter &interpreter, char format_letter, Format &format, uint32_t &byte_size) { m_has_gdb_format = true; switch (format_letter) { case 'o': format = eFormatOctal; m_prev_gdb_format = format_letter; return true; case 'x': format = eFormatHex; m_prev_gdb_format = format_letter; return true; case 'd': format = eFormatDecimal; m_prev_gdb_format = format_letter; return true; case 'u': format = eFormatUnsigned; m_prev_gdb_format = format_letter; return true; case 't': format = eFormatBinary; m_prev_gdb_format = format_letter; return true; case 'f': format = eFormatFloat; m_prev_gdb_format = format_letter; return true; case 'a': format = eFormatAddressInfo; { ExecutionContext exe_ctx(interpreter.GetExecutionContext()); Target *target = exe_ctx.GetTargetPtr(); if (target) byte_size = target->GetArchitecture().GetAddressByteSize(); m_prev_gdb_format = format_letter; return true; } case 'i': format = eFormatInstruction; m_prev_gdb_format = format_letter; return true; case 'c': format = eFormatChar; m_prev_gdb_format = format_letter; return true; case 's': format = eFormatCString; m_prev_gdb_format = format_letter; return true; case 'T': format = eFormatOSType; m_prev_gdb_format = format_letter; return true; case 'A': format = eFormatHexFloat; m_prev_gdb_format = format_letter; return true; case 'b': byte_size = 1; m_prev_gdb_size = format_letter; return true; case 'h': byte_size = 2; m_prev_gdb_size = format_letter; return true; case 'w': byte_size = 4; m_prev_gdb_size = format_letter; return true; case 'g': byte_size = 8; m_prev_gdb_size = format_letter; return true; default: break; } return false; } void OptionGroupFormat::OptionParsingStarting (CommandInterpreter &interpreter) { m_format.Clear(); m_byte_size.Clear(); m_count.Clear(); m_has_gdb_format = false; } <|endoftext|>
<commit_before>#include "QXmppInformationRequestResult.h" #include "QXmppConstants.h" #include <QXmlStreamWriter> QXmppInformationRequestResult::QXmppInformationRequestResult() : QXmppIq(QXmppIq::Result) { } void QXmppInformationRequestResult::toXmlElementFromChild(QXmlStreamWriter *writer) const { writer->writeStartElement("query"); writer->writeAttribute("xmlns", ns_disco_info ); writer->writeStartElement("feature"); writer->writeAttribute("var", ns_disco_info ); writer->writeEndElement(); writer->writeStartElement("feature"); writer->writeAttribute("var", ns_ibb ); writer->writeEndElement(); writer->writeStartElement("feature"); writer->writeAttribute("var", ns_rpc); writer->writeEndElement(); writer->writeStartElement("identity"); writer->writeAttribute("category", "automation" ); writer->writeAttribute("type", "rpc" ); writer->writeEndElement(); writer->writeEndElement(); } <commit_msg>Add XEP-0199:XMPP Ping support http://xmpp.org/extensions/xep-0199.html#disco<commit_after>#include "QXmppInformationRequestResult.h" #include "QXmppConstants.h" #include <QXmlStreamWriter> QXmppInformationRequestResult::QXmppInformationRequestResult() : QXmppIq(QXmppIq::Result) { } void QXmppInformationRequestResult::toXmlElementFromChild(QXmlStreamWriter *writer) const { writer->writeStartElement("query"); writer->writeAttribute("xmlns", ns_disco_info ); writer->writeStartElement("feature"); writer->writeAttribute("var", ns_disco_info ); writer->writeEndElement(); writer->writeStartElement("feature"); writer->writeAttribute("var", ns_ibb ); writer->writeEndElement(); writer->writeStartElement("feature"); writer->writeAttribute("var", ns_rpc); writer->writeEndElement(); writer->writeStartElement("identity"); writer->writeAttribute("category", "automation" ); writer->writeAttribute("type", "rpc" ); writer->writeEndElement(); writer->writeStartElement("feature"); writer->writeAttribute("var", ns_ping); writer->writeEndElement(); writer->writeEndElement(); } <|endoftext|>
<commit_before>#include "emu.h" #include <cstdio> #include "../fs/load.h" #include "../fs/util.h" EmuModule::EmuModule(SharedState& gui) : GUIModule(gui) { /*------------------------------- SDL init -------------------------------*/ fprintf(stderr, "[GUI][Emu] Initializing...\n"); // make window this->sdl.window = SDL_CreateWindow( "anese", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 256 * this->gui.config.window_scale, 240 * this->gui.config.window_scale, SDL_WINDOW_RESIZABLE ); // make renderer this->sdl.renderer = SDL_CreateRenderer( this->sdl.window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); // make screen rect (to render texture onto) this->sdl.screen_rect.x = 0; this->sdl.screen_rect.y = 0; this->sdl.screen_rect.w = 256 * this->gui.config.window_scale; this->sdl.screen_rect.h = 240 * this->gui.config.window_scale; // Letterbox the screen in the window SDL_RenderSetLogicalSize(this->sdl.renderer, 256 * this->gui.config.window_scale, 240 * this->gui.config.window_scale); // Allow opacity SDL_SetRenderDrawBlendMode(this->sdl.renderer, SDL_BLENDMODE_BLEND); // NES screen texture this->sdl.screen_texture = SDL_CreateTexture( this->sdl.renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 256, 240 ); // SDL_AudioSpec as, have; // as.freq = SDL_GUI::SAMPLE_RATE; // as.format = AUDIO_F32SYS; // as.channels = 1; // as.samples = 4096; // as.callback = nullptr; // use SDL_QueueAudio // this->sdl_common.nes_audiodev = SDL_OpenAudioDevice(NULL, 0, &as, &have, 0); // SDL_PauseAudioDevice(this->sdl_common.nes_audiodev, 0); // this->sdl.sound_queue.init(this->gui.nes_params.apu_sample_rate); /*---------- Submodule Init ----------*/ this->menu_submodule = new MenuSubModule(gui, this->sdl.window, this->sdl.renderer); /*---------- NES Init ----------*/ this->gui.nes.attach_joy(0, &this->joy_1); this->gui.nes.attach_joy(1, &this->zap_2); // ---------------------------- Movie Support ----------------------------- // if (this->gui.config.cli.replay_fm2_path != "") { bool did_load = this->fm2_replay.init(this->gui.config.cli.replay_fm2_path.c_str()); if (!did_load) fprintf(stderr, "[Replay][fm2] Movie loading failed!\n"); else fprintf(stderr, "[Replay][fm2] Movie successfully loaded!\n"); } if (this->gui.config.cli.record_fm2_path != "") { bool did_load = this->fm2_record.init(this->gui.config.cli.record_fm2_path.c_str()); if (!did_load) fprintf(stderr, "[Record][fm2] Failed to setup Movie recording!\n"); else fprintf(stderr, "[Record][fm2] Movie recording is setup!\n"); } // pass controllers to this->fm2_record if (this->fm2_record.is_enabled()) { this->fm2_record.set_joy(0, FM2_Controller::SI_GAMEPAD, &this->joy_1); this->fm2_record.set_joy(1, FM2_Controller::SI_GAMEPAD, &this->joy_2); } // attach fm2_replay controllers (if needed) if (this->fm2_replay.is_enabled()) { this->gui.nes.attach_joy(0, this->fm2_replay.get_joy(0)); this->gui.nes.attach_joy(1, this->fm2_replay.get_joy(1)); } } EmuModule::~EmuModule() { fprintf(stderr, "[GUI][Emu] Shutting down...\n"); delete this->menu_submodule; /*------------------------------ SDL Cleanup -----------------------------*/ SDL_DestroyTexture(this->sdl.screen_texture); SDL_DestroyRenderer(this->sdl.renderer); SDL_DestroyWindow(this->sdl.window); } void EmuModule::input(const SDL_Event& event) { this->menu_submodule->input(event); if (this->gui.status.in_menu) return; // Update from Controllers if (event.type == SDL_CONTROLLERBUTTONDOWN || event.type == SDL_CONTROLLERBUTTONUP) { bool new_state = (event.type == SDL_CONTROLLERBUTTONDOWN) ? true : false; using namespace JOY_Standard_Button; // Player 1 switch (event.cbutton.button) { case SDL_CONTROLLER_BUTTON_A: this->joy_1.set_button(A, new_state); break; case SDL_CONTROLLER_BUTTON_X: this->joy_1.set_button(B, new_state); break; case SDL_CONTROLLER_BUTTON_START: this->joy_1.set_button(Start, new_state); break; case SDL_CONTROLLER_BUTTON_BACK: this->joy_1.set_button(Select, new_state); break; case SDL_CONTROLLER_BUTTON_DPAD_UP: this->joy_1.set_button(Up, new_state); break; case SDL_CONTROLLER_BUTTON_DPAD_DOWN: this->joy_1.set_button(Down, new_state); break; case SDL_CONTROLLER_BUTTON_DPAD_LEFT: this->joy_1.set_button(Left, new_state); break; case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: this->joy_1.set_button(Right, new_state); break; } // Player 2 // switch (event.cbutton.button) { // case SDL_CONTROLLER_BUTTON_A: this->joy_2.set_button(A, new_state); break; // case SDL_CONTROLLER_BUTTON_X: this->joy_2.set_button(B, new_state); break; // case SDL_CONTROLLER_BUTTON_START: this->joy_2.set_button(Start, new_state); break; // case SDL_CONTROLLER_BUTTON_BACK: this->joy_2.set_button(Select, new_state); break; // case SDL_CONTROLLER_BUTTON_DPAD_UP: this->joy_2.set_button(Up, new_state); break; // case SDL_CONTROLLER_BUTTON_DPAD_DOWN: this->joy_2.set_button(Down, new_state); break; // case SDL_CONTROLLER_BUTTON_DPAD_LEFT: this->joy_2.set_button(Left, new_state); break; // case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: this->joy_2.set_button(Right, new_state); break; // } } // Update from Keyboard if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) { // ------ Keyboard controls ------ // bool new_state = (event.type == SDL_KEYDOWN) ? true : false; using namespace JOY_Standard_Button; // Player 1 switch (event.key.keysym.sym) { case SDLK_z: this->joy_1.set_button(A, new_state); break; case SDLK_x: this->joy_1.set_button(B, new_state); break; case SDLK_RETURN: this->joy_1.set_button(Start, new_state); break; case SDLK_RSHIFT: this->joy_1.set_button(Select, new_state); break; case SDLK_UP: this->joy_1.set_button(Up, new_state); break; case SDLK_DOWN: this->joy_1.set_button(Down, new_state); break; case SDLK_LEFT: this->joy_1.set_button(Left, new_state); break; case SDLK_RIGHT: this->joy_1.set_button(Right, new_state); break; } // Player 2 // switch (event.key.keysym.sym) { // case SDLK_z: this->joy_2.set_button(A, new_state); break; // case SDLK_x: this->joy_2.set_button(B, new_state); break; // case SDLK_RETURN: this->joy_2.set_button(Start, new_state); break; // case SDLK_RSHIFT: this->joy_2.set_button(Select, new_state); break; // case SDLK_UP: this->joy_2.set_button(Up, new_state); break; // case SDLK_DOWN: this->joy_2.set_button(Down, new_state); break; // case SDLK_LEFT: this->joy_2.set_button(Left, new_state); break; // case SDLK_RIGHT: this->joy_2.set_button(Right, new_state); break; // } } // Zapper // if (event.type == SDL_MOUSEMOTION) { // // getting the light from the screen is a bit trickier... // const u8* screen; // this->gui.nes.getFramebuff(screen); // const uint offset = (256 * 4 * (event.motion.y / this->gui.config.window_scale)) // + ( 4 * (event.motion.x / this->gui.config.window_scale)); // const bool new_light = screen[offset+ 0] // R // | screen[offset+ 1] // G // | screen[offset+ 2]; // B // this->zap_2.set_light(new_light); // } // if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP) { // bool new_state = (event.type == SDL_MOUSEBUTTONDOWN) ? true : false; // this->zap_2.set_trigger(new_state); // } // Handle Key-events if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) { bool mod_shift = event.key.keysym.mod & KMOD_SHIFT; // Use CMD on macOS, and CTRL on windows / linux bool mod_ctrl = strcmp(SDL_GetPlatform(), "Mac OS X") == 0 ? event.key.keysym.mod & (KMOD_LGUI | KMOD_RGUI) : event.key.keysym.mod & (KMOD_LCTRL | KMOD_RCTRL); // Regular 'ol keys switch (event.key.keysym.sym) { case SDLK_SPACE: // Fast-Forward this->speed_counter = 0; this->gui.nes_params.speed = (event.type == SDL_KEYDOWN) ? 200 : 100; this->gui.nes.updated_params(); break; } // Controller if (event.type == SDL_CONTROLLERBUTTONDOWN || event.type == SDL_CONTROLLERBUTTONUP) { switch (event.cbutton.button) { case SDL_CONTROLLER_BUTTON_RIGHTSTICK: this->speed_counter = 0; this->gui.nes_params.speed = (event.type == SDL_CONTROLLERBUTTONDOWN) ? 200 : 100; this->gui.nes.updated_params(); break; } } // Meta Modified keys if (event.type == SDL_KEYDOWN && mod_ctrl) { #define SAVESTATE(i) do { \ if (mod_shift) { \ delete this->gui.savestate[i]; \ this->gui.savestate[i] = this->gui.nes.serialize(); \ } else this->gui.nes.deserialize(this->gui.savestate[i]); \ } while(0); switch (event.key.keysym.sym) { case SDLK_1: SAVESTATE(0); break; // Savestate Slot 1 case SDLK_2: SAVESTATE(1); break; // Savestate Slot 2 case SDLK_3: SAVESTATE(2); break; // Savestate Slot 3 case SDLK_4: SAVESTATE(3); break; // Savestate Slot 4 case SDLK_r: this->gui.nes.reset(); break; // Reset case SDLK_p: this->gui.nes.power_cycle(); break; // Power-Cycle case SDLK_EQUALS: // Speed up this->speed_counter = 0; this->gui.nes_params.speed += 25; this->gui.nes.updated_params(); break; case SDLK_MINUS: // Speed down if (this->gui.nes_params.speed - 25 != 0) { this->speed_counter = 0; this->gui.nes_params.speed -= 25; this->gui.nes.updated_params(); } break; case SDLK_c: { // Toggle CPU trace bool log = this->gui.nes_params.log_cpu = !this->gui.nes_params.log_cpu; this->gui.nes.updated_params(); fprintf(stderr, "NESTEST CPU logging: %s\n", log ? "ON" : "OFF"); } break; default: break; } } } } void EmuModule::update() { this->menu_submodule->update(); if (this->gui.status.in_menu) return; // log frame to fm2 if (this->fm2_record.is_enabled()) this->fm2_record.step_frame(); // set input from fm2 if (this->fm2_replay.is_enabled()) this->fm2_replay.step_frame(); } void EmuModule::output() { /^ // output audio! float* samples = nullptr; uint count = 0; this->gui.nes.getAudiobuff(&samples, &count); // SDL_QueueAudio(this->gui.sdl.nes_audiodev, samples, count * sizeof(float)); if (count) this->sdl.sound_queue.write(samples, count); ^/ // output video! const u8* framebuffer; this->gui.nes.getFramebuff(&framebuffer); SDL_UpdateTexture(this->sdl.screen_texture, nullptr, framebuffer, 256 * 4); // actual NES screen SDL_SetRenderDrawColor(this->sdl.renderer, 0, 0, 0, 0xff); SDL_RenderClear(this->sdl.renderer); SDL_RenderCopy(this->sdl.renderer, this->sdl.screen_texture, nullptr, &this->sdl.screen_rect); this->menu_submodule->output(); SDL_RenderPresent(this->sdl.renderer); // Present fups though the title of the main window char window_title [64]; sprintf(window_title, "anese - %u fups - %u%% speed", uint(this->gui.status.avg_fps), this->gui.nes_params.speed); SDL_SetWindowTitle(this->sdl.window, window_title); } <commit_msg>Update emu.cc<commit_after>#include "emu.h" #include <cstdio> #include "../fs/load.h" #include "../fs/util.h" EmuModule::EmuModule(SharedState& gui) : GUIModule(gui) { /*------------------------------- SDL init -------------------------------*/ fprintf(stderr, "[GUI][Emu] Initializing...\n"); // make window this->sdl.window = SDL_CreateWindow( "anese", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 256 * this->gui.config.window_scale, 240 * this->gui.config.window_scale, SDL_WINDOW_RESIZABLE ); // make renderer this->sdl.renderer = SDL_CreateRenderer( this->sdl.window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); // make screen rect (to render texture onto) this->sdl.screen_rect.x = 0; this->sdl.screen_rect.y = 0; this->sdl.screen_rect.w = 256 * this->gui.config.window_scale; this->sdl.screen_rect.h = 240 * this->gui.config.window_scale; // Letterbox the screen in the window SDL_RenderSetLogicalSize(this->sdl.renderer, 256 * this->gui.config.window_scale, 240 * this->gui.config.window_scale); // Allow opacity SDL_SetRenderDrawBlendMode(this->sdl.renderer, SDL_BLENDMODE_BLEND); // NES screen texture this->sdl.screen_texture = SDL_CreateTexture( this->sdl.renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 256, 240 ); // SDL_AudioSpec as, have; // as.freq = SDL_GUI::SAMPLE_RATE; // as.format = AUDIO_F32SYS; // as.channels = 1; // as.samples = 4096; // as.callback = nullptr; // use SDL_QueueAudio // this->sdl_common.nes_audiodev = SDL_OpenAudioDevice(NULL, 0, &as, &have, 0); // SDL_PauseAudioDevice(this->sdl_common.nes_audiodev, 0); // this->sdl.sound_queue.init(this->gui.nes_params.apu_sample_rate); /*---------- Submodule Init ----------*/ this->menu_submodule = new MenuSubModule(gui, this->sdl.window, this->sdl.renderer); /*---------- NES Init ----------*/ this->gui.nes.attach_joy(0, &this->joy_1); this->gui.nes.attach_joy(1, &this->zap_2); // ---------------------------- Movie Support ----------------------------- // if (this->gui.config.cli.replay_fm2_path != "") { bool did_load = this->fm2_replay.init(this->gui.config.cli.replay_fm2_path.c_str()); if (!did_load) fprintf(stderr, "[Replay][fm2] Movie loading failed!\n"); else fprintf(stderr, "[Replay][fm2] Movie successfully loaded!\n"); } if (this->gui.config.cli.record_fm2_path != "") { bool did_load = this->fm2_record.init(this->gui.config.cli.record_fm2_path.c_str()); if (!did_load) fprintf(stderr, "[Record][fm2] Failed to setup Movie recording!\n"); else fprintf(stderr, "[Record][fm2] Movie recording is setup!\n"); } // pass controllers to this->fm2_record if (this->fm2_record.is_enabled()) { this->fm2_record.set_joy(0, FM2_Controller::SI_GAMEPAD, &this->joy_1); this->fm2_record.set_joy(1, FM2_Controller::SI_GAMEPAD, &this->joy_2); } // attach fm2_replay controllers (if needed) if (this->fm2_replay.is_enabled()) { this->gui.nes.attach_joy(0, this->fm2_replay.get_joy(0)); this->gui.nes.attach_joy(1, this->fm2_replay.get_joy(1)); } } EmuModule::~EmuModule() { fprintf(stderr, "[GUI][Emu] Shutting down...\n"); delete this->menu_submodule; /*------------------------------ SDL Cleanup -----------------------------*/ SDL_DestroyTexture(this->sdl.screen_texture); SDL_DestroyRenderer(this->sdl.renderer); SDL_DestroyWindow(this->sdl.window); } void EmuModule::input(const SDL_Event& event) { this->menu_submodule->input(event); if (this->gui.status.in_menu) return; // Update from Controllers if (event.type == SDL_CONTROLLERBUTTONDOWN || event.type == SDL_CONTROLLERBUTTONUP) { bool new_state = (event.type == SDL_CONTROLLERBUTTONDOWN) ? true : false; using namespace JOY_Standard_Button; // Player 1 switch (event.cbutton.button) { case SDL_CONTROLLER_BUTTON_A: this->joy_1.set_button(A, new_state); break; case SDL_CONTROLLER_BUTTON_X: this->joy_1.set_button(B, new_state); break; case SDL_CONTROLLER_BUTTON_START: this->joy_1.set_button(Start, new_state); break; case SDL_CONTROLLER_BUTTON_BACK: this->joy_1.set_button(Select, new_state); break; case SDL_CONTROLLER_BUTTON_DPAD_UP: this->joy_1.set_button(Up, new_state); break; case SDL_CONTROLLER_BUTTON_DPAD_DOWN: this->joy_1.set_button(Down, new_state); break; case SDL_CONTROLLER_BUTTON_DPAD_LEFT: this->joy_1.set_button(Left, new_state); break; case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: this->joy_1.set_button(Right, new_state); break; } // Player 2 // switch (event.cbutton.button) { // case SDL_CONTROLLER_BUTTON_A: this->joy_2.set_button(A, new_state); break; // case SDL_CONTROLLER_BUTTON_X: this->joy_2.set_button(B, new_state); break; // case SDL_CONTROLLER_BUTTON_START: this->joy_2.set_button(Start, new_state); break; // case SDL_CONTROLLER_BUTTON_BACK: this->joy_2.set_button(Select, new_state); break; // case SDL_CONTROLLER_BUTTON_DPAD_UP: this->joy_2.set_button(Up, new_state); break; // case SDL_CONTROLLER_BUTTON_DPAD_DOWN: this->joy_2.set_button(Down, new_state); break; // case SDL_CONTROLLER_BUTTON_DPAD_LEFT: this->joy_2.set_button(Left, new_state); break; // case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: this->joy_2.set_button(Right, new_state); break; // } } // Update from Keyboard if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) { // ------ Keyboard controls ------ // bool new_state = (event.type == SDL_KEYDOWN) ? true : false; using namespace JOY_Standard_Button; // Player 1 switch (event.key.keysym.sym) { case SDLK_z: this->joy_1.set_button(A, new_state); break; case SDLK_x: this->joy_1.set_button(B, new_state); break; case SDLK_RETURN: this->joy_1.set_button(Start, new_state); break; case SDLK_RSHIFT: this->joy_1.set_button(Select, new_state); break; case SDLK_UP: this->joy_1.set_button(Up, new_state); break; case SDLK_DOWN: this->joy_1.set_button(Down, new_state); break; case SDLK_LEFT: this->joy_1.set_button(Left, new_state); break; case SDLK_RIGHT: this->joy_1.set_button(Right, new_state); break; } // Player 2 // switch (event.key.keysym.sym) { // case SDLK_z: this->joy_2.set_button(A, new_state); break; // case SDLK_x: this->joy_2.set_button(B, new_state); break; // case SDLK_RETURN: this->joy_2.set_button(Start, new_state); break; // case SDLK_RSHIFT: this->joy_2.set_button(Select, new_state); break; // case SDLK_UP: this->joy_2.set_button(Up, new_state); break; // case SDLK_DOWN: this->joy_2.set_button(Down, new_state); break; // case SDLK_LEFT: this->joy_2.set_button(Left, new_state); break; // case SDLK_RIGHT: this->joy_2.set_button(Right, new_state); break; // } } // Zapper // if (event.type == SDL_MOUSEMOTION) { // // getting the light from the screen is a bit trickier... // const u8* screen; // this->gui.nes.getFramebuff(screen); // const uint offset = (256 * 4 * (event.motion.y / this->gui.config.window_scale)) // + ( 4 * (event.motion.x / this->gui.config.window_scale)); // const bool new_light = screen[offset+ 0] // R // | screen[offset+ 1] // G // | screen[offset+ 2]; // B // this->zap_2.set_light(new_light); // } // if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP) { // bool new_state = (event.type == SDL_MOUSEBUTTONDOWN) ? true : false; // this->zap_2.set_trigger(new_state); // } // Handle Key-events if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) { bool mod_shift = event.key.keysym.mod & KMOD_SHIFT; // Use CMD on macOS, and CTRL on windows / linux bool mod_ctrl = strcmp(SDL_GetPlatform(), "Mac OS X") == 0 ? event.key.keysym.mod & (KMOD_LGUI | KMOD_RGUI) : event.key.keysym.mod & (KMOD_LCTRL | KMOD_RCTRL); // Regular 'ol keys switch (event.key.keysym.sym) { case SDLK_SPACE: // Fast-Forward this->speed_counter = 0; this->gui.nes_params.speed = (event.type == SDL_KEYDOWN) ? 200 : 100; this->gui.nes.updated_params(); break; } // Controller if (event.type == SDL_CONTROLLERBUTTONDOWN || event.type == SDL_CONTROLLERBUTTONUP) { switch (event.cbutton.button) { case SDL_CONTROLLER_BUTTON_RIGHTSTICK: this->speed_counter = 0; this->gui.nes_params.speed = (event.type == SDL_CONTROLLERBUTTONDOWN) ? 200 : 100; this->gui.nes.updated_params(); break; } } // Meta Modified keys if (event.type == SDL_KEYDOWN && mod_ctrl) { #define SAVESTATE(i) do { \ if (mod_shift) { \ delete this->gui.savestate[i]; \ this->gui.savestate[i] = this->gui.nes.serialize(); \ } else this->gui.nes.deserialize(this->gui.savestate[i]); \ } while(0); switch (event.key.keysym.sym) { case SDLK_1: SAVESTATE(0); break; // Savestate Slot 1 case SDLK_2: SAVESTATE(1); break; // Savestate Slot 2 case SDLK_3: SAVESTATE(2); break; // Savestate Slot 3 case SDLK_4: SAVESTATE(3); break; // Savestate Slot 4 case SDLK_r: this->gui.nes.reset(); break; // Reset case SDLK_p: this->gui.nes.power_cycle(); break; // Power-Cycle case SDLK_EQUALS: // Speed up this->speed_counter = 0; this->gui.nes_params.speed += 25; this->gui.nes.updated_params(); break; case SDLK_MINUS: // Speed down if (this->gui.nes_params.speed - 25 != 0) { this->speed_counter = 0; this->gui.nes_params.speed -= 25; this->gui.nes.updated_params(); } break; case SDLK_c: { // Toggle CPU trace bool log = this->gui.nes_params.log_cpu = !this->gui.nes_params.log_cpu; this->gui.nes.updated_params(); fprintf(stderr, "NESTEST CPU logging: %s\n", log ? "ON" : "OFF"); } break; default: break; } } } } void EmuModule::update() { this->menu_submodule->update(); if (this->gui.status.in_menu) return; // log frame to fm2 if (this->fm2_record.is_enabled()) this->fm2_record.step_frame(); // set input from fm2 if (this->fm2_replay.is_enabled()) this->fm2_replay.step_frame(); } void EmuModule::output() { /* // output audio! float* samples = nullptr; uint count = 0; this->gui.nes.getAudiobuff(&samples, &count); // SDL_QueueAudio(this->gui.sdl.nes_audiodev, samples, count * sizeof(float)); if (count) this->sdl.sound_queue.write(samples, count); */ // output video! const u8* framebuffer; this->gui.nes.getFramebuff(&framebuffer); SDL_UpdateTexture(this->sdl.screen_texture, nullptr, framebuffer, 256 * 4); // actual NES screen SDL_SetRenderDrawColor(this->sdl.renderer, 0, 0, 0, 0xff); SDL_RenderClear(this->sdl.renderer); SDL_RenderCopy(this->sdl.renderer, this->sdl.screen_texture, nullptr, &this->sdl.screen_rect); this->menu_submodule->output(); SDL_RenderPresent(this->sdl.renderer); // Present fups though the title of the main window char window_title [64]; sprintf(window_title, "anese - %u fups - %u%% speed", uint(this->gui.status.avg_fps), this->gui.nes_params.speed); SDL_SetWindowTitle(this->sdl.window, window_title); } <|endoftext|>
<commit_before>#ifndef FULL_MATRIX_HPP_ #define FULL_MATRIX_HPP_ #include <vector> #include <string> #include <iostream> #include <algorithm> #include "../Matrix.hpp" namespace aff3ct { namespace tools { /* * \param T must be int8_t or int16_t or int32_t or int64_t * Warning ! Never call modification methods (resize, erase, push_back and so on), on the second dimension of the Full_matrix * always pass through Full_matrix methods, else you may obtain runtime errors */ template <typename T = int32_t> class Full_matrix : public Matrix, public std::vector<std::vector<T>> { public: using Container = std::vector<std::vector<T>>; using value_type = T; Full_matrix(const unsigned n_rows = 0, const unsigned n_cols = 1); virtual ~Full_matrix() = default; /* * return true if there is a connection there */ bool at(const size_t row_index, const size_t col_index) const; /* * Add a connection and update the rows and cols degrees values */ void add_connection(const size_t row_index, const size_t col_index); /* * Remove the connection and update the rows and cols degrees values */ void rm_connection(const size_t row_index, const size_t col_index); /* * Resize the matrix to the new dimensions in function of the part of the matrix considered as the origin * Ex: if o == BOTTOM_RIGHT, and need to extend the matrix then add rows on the top and columns on the left */ void self_resize(const size_t n_rows, const size_t n_cols, Origin o); /* * Resize the matrix by calling self_resize on a copy matrix */ Full_matrix resize(const size_t n_rows, const size_t n_cols, Origin o) const; /* * Erase the 'n_rows' rows from the given index 'row_index' */ void erase_row(const size_t row_index, const size_t n_rows = 1); /* * Erase the 'n_cols' cols from the given index 'col_index' */ void erase_col(const size_t col_index, const size_t n_cols = 1); void erase(); // never use 'erase' methods, use instead erase_col or erase_row /* * Compute the rows and cols degrees values when the matrix values have been modified * without the use of 'add_connection' and 'rm_connection' interface, so after any modification * call this function if you need degrees information */ void parse_connections(); /* * Return the transposed matrix of this matrix */ Full_matrix transpose() const; /* * Transpose internally this matrix */ void self_transpose(); /* * Return turn the matrix in horizontal or vertical way */ Full_matrix turn(Way w) const; /* * Sort the matrix per density of lines in ascending or descending order * You need to call 'parse_connections()' before to assure good work. */ void sort_cols_per_density(Sort order); /* * Print the matrix in its full view with 0s and 1s. * 'transpose' allow the print in its transposed view */ void print(bool transpose = false, std::ostream& os = std::cout) const; /* * \brief create a matrix of the given size filled with identity diagonal * \return the identity matrix */ static Full_matrix<T> identity(const size_t n_rows, const size_t n_cols); /* * \brief create a matrix of the given size filled with only zeros * \return the zero matrix */ static Full_matrix<T> zero(const size_t n_rows, const size_t n_cols); private: std::vector<size_t> rows_degrees; std::vector<size_t> cols_degrees; }; } } #endif /* FULL_MATRIX_HPP_ */ <commit_msg>Set the inheritance of the Full_matrix container as private and use as public only size() and operator[]<commit_after>#ifndef FULL_MATRIX_HPP_ #define FULL_MATRIX_HPP_ #include <vector> #include <string> #include <iostream> #include <algorithm> #include "../Matrix.hpp" namespace aff3ct { namespace tools { /* * \param T must be int8_t or int16_t or int32_t or int64_t * Warning ! Never call modification methods (resize, erase, push_back and so on), on the second dimension of the Full_matrix * always pass through Full_matrix methods, else you may obtain runtime errors */ template <typename T = int32_t> class Full_matrix : public Matrix, private std::vector<std::vector<T>> { public: using Container = std::vector<std::vector<T>>; using value_type = T; explicit Full_matrix(const unsigned n_rows = 0, const unsigned n_cols = 1); virtual ~Full_matrix() = default; /* * return true if there is a connection there */ bool at(const size_t row_index, const size_t col_index) const; /* * Add a connection and update the rows and cols degrees values */ void add_connection(const size_t row_index, const size_t col_index); /* * Remove the connection and update the rows and cols degrees values */ void rm_connection(const size_t row_index, const size_t col_index); /* * Resize the matrix to the new dimensions in function of the part of the matrix considered as the origin * Ex: if o == BOTTOM_RIGHT, and need to extend the matrix then add rows on the top and columns on the left */ void self_resize(const size_t n_rows, const size_t n_cols, Origin o); /* * Resize the matrix by calling self_resize on a copy matrix */ Full_matrix resize(const size_t n_rows, const size_t n_cols, Origin o) const; /* * Erase the 'n_rows' rows from the given index 'row_index' */ void erase_row(const size_t row_index, const size_t n_rows = 1); /* * Erase the 'n_cols' cols from the given index 'col_index' */ void erase_col(const size_t col_index, const size_t n_cols = 1); using Container::size; using Container::operator[]; /* * Compute the rows and cols degrees values when the matrix values have been modified * without the use of 'add_connection' and 'rm_connection' interface, so after any modification * call this function if you need degrees information */ void parse_connections(); /* * Return the transposed matrix of this matrix */ Full_matrix transpose() const; /* * Transpose internally this matrix */ void self_transpose(); /* * Return turn the matrix in horizontal or vertical way */ Full_matrix turn(Way w) const; /* * Sort the matrix per density of lines in ascending or descending order * You need to call 'parse_connections()' before to assure good work. */ void sort_cols_per_density(Sort order); /* * Print the matrix in its full view with 0s and 1s. * 'transpose' allow the print in its transposed view */ void print(bool transpose = false, std::ostream& os = std::cout) const; /* * \brief create a matrix of the given size filled with identity diagonal * \return the identity matrix */ static Full_matrix<T> identity(const size_t n_rows, const size_t n_cols); /* * \brief create a matrix of the given size filled with only zeros * \return the zero matrix */ static Full_matrix<T> zero(const size_t n_rows, const size_t n_cols); private: std::vector<size_t> rows_degrees; std::vector<size_t> cols_degrees; }; } } #endif /* FULL_MATRIX_HPP_ */ <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/guardian/guardian.h" #include <cmath> #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/guardian/common/guardian_gflags.h" #include "ros/include/ros/ros.h" namespace apollo { namespace guardian { using apollo::canbus::Chassis; using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::adapter::AdapterManager; using apollo::control::ControlCommand; using apollo::guardian::GuardianCommand; using apollo::monitor::SystemStatus; std::string Guardian::Name() const { return FLAGS_module_name; } Status Guardian::Init() { AdapterManager::Init(FLAGS_adapter_config_filename); CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized."; CHECK(AdapterManager::GetSystemStatus()) << "SystemStatus is not initialized."; CHECK(AdapterManager::GetControlCommand()) << "Control is not initialized."; return Status::OK(); } Status Guardian::Start() { AdapterManager::AddChassisCallback(&Guardian::OnChassis, this); AdapterManager::AddSystemStatusCallback(&Guardian::OnSystemStatus, this); AdapterManager::AddControlCommandCallback(&Guardian::OnControl, this); const double duration = 1.0 / FLAGS_guardian_cmd_freq; timer_ = AdapterManager::CreateTimer(ros::Duration(duration), &Guardian::OnTimer, this); return Status::OK(); } void Guardian::Stop() { timer_.stop(); } void Guardian::OnTimer(const ros::TimerEvent&) { ADEBUG << "Timer is triggered: publish Guardian result"; bool safety_mode_triggered = false; if (FLAGS_guardian_enabled) { std::lock_guard<std::mutex> lock(mutex_); safety_mode_triggered = system_status_.has_safety_mode_trigger_time(); } if (safety_mode_triggered) { ADEBUG << "Safety mode triggerd, enable safty mode"; TriggerSafetyMode(); } else { ADEBUG << "Safety mode not triggerd, bypass control command"; ByPassControlCommand(); } AdapterManager::FillGuardianHeader(FLAGS_node_name, &guardian_cmd_); AdapterManager::PublishGuardian(guardian_cmd_); } void Guardian::OnChassis(const Chassis& message) { ADEBUG << "Received chassis data: run chassis callback."; std::lock_guard<std::mutex> lock(mutex_); chassis_.CopyFrom(message); } void Guardian::OnSystemStatus(const SystemStatus& message) { ADEBUG << "Received monitor data: run monitor callback."; std::lock_guard<std::mutex> lock(mutex_); system_status_.CopyFrom(message); } void Guardian::OnControl(const ControlCommand& message) { ADEBUG << "Received control data: run control command callback."; std::lock_guard<std::mutex> lock(mutex_); control_cmd_.CopyFrom(message); } void Guardian::ByPassControlCommand() { std::lock_guard<std::mutex> lock(mutex_); guardian_cmd_.mutable_control_command()->CopyFrom(control_cmd_); } void Guardian::TriggerSafetyMode() { ADEBUG << "Received chassis data: run chassis callback."; std::lock_guard<std::mutex> lock(mutex_); bool sensor_malfunction = false, obstacle_detected = false; if (!chassis_.surround().sonar_enabled() || chassis_.surround().sonar_fault()) { AINFO << "Ultrasonic sensor not enabled for faulted, will do emergency " "stop!"; sensor_malfunction = true; } else { // TODO(QiL) : Load for config for (int i = 0; i < chassis_.surround().sonar_range_size(); ++i) { if ((chassis_.surround().sonar_range(i) > 0.0 && chassis_.surround().sonar_range(i) < 2.5) || chassis_.surround().sonar_range(i) > 30) { AINFO << "Object detected or ultrasonic sensor fault output, will do " "emergency stop!"; obstacle_detected = true; } } } guardian_cmd_.mutable_control_command()->set_throttle(0.0); guardian_cmd_.mutable_control_command()->set_steering_target(0.0); guardian_cmd_.mutable_control_command()->set_steering_rate(0.0); guardian_cmd_.mutable_control_command()->set_is_in_safe_mode(true); if (system_status_.require_emergency_stop() || sensor_malfunction || obstacle_detected) { AINFO << "Emergency stop triggered! with system status from monitor as : " << system_status_.require_emergency_stop(); guardian_cmd_.mutable_control_command()->set_brake( FLAGS_guardian_cmd_emergency_stop_percentage); } else { AINFO << "Soft stop triggered! with system status from monitor as : " << system_status_.require_emergency_stop(); guardian_cmd_.mutable_control_command()->set_brake( FLAGS_guardian_cmd_soft_stop_percentage); } } } // namespace guardian } // namespace apollo <commit_msg>Guardian : neglect ultrasonic reading temporarily<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/guardian/guardian.h" #include <cmath> #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/log.h" #include "modules/guardian/common/guardian_gflags.h" #include "ros/include/ros/ros.h" namespace apollo { namespace guardian { using apollo::canbus::Chassis; using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::adapter::AdapterManager; using apollo::control::ControlCommand; using apollo::guardian::GuardianCommand; using apollo::monitor::SystemStatus; std::string Guardian::Name() const { return FLAGS_module_name; } Status Guardian::Init() { AdapterManager::Init(FLAGS_adapter_config_filename); CHECK(AdapterManager::GetChassis()) << "Chassis is not initialized."; CHECK(AdapterManager::GetSystemStatus()) << "SystemStatus is not initialized."; CHECK(AdapterManager::GetControlCommand()) << "Control is not initialized."; return Status::OK(); } Status Guardian::Start() { AdapterManager::AddChassisCallback(&Guardian::OnChassis, this); AdapterManager::AddSystemStatusCallback(&Guardian::OnSystemStatus, this); AdapterManager::AddControlCommandCallback(&Guardian::OnControl, this); const double duration = 1.0 / FLAGS_guardian_cmd_freq; timer_ = AdapterManager::CreateTimer(ros::Duration(duration), &Guardian::OnTimer, this); return Status::OK(); } void Guardian::Stop() { timer_.stop(); } void Guardian::OnTimer(const ros::TimerEvent&) { ADEBUG << "Timer is triggered: publish Guardian result"; bool safety_mode_triggered = false; if (FLAGS_guardian_enabled) { std::lock_guard<std::mutex> lock(mutex_); safety_mode_triggered = system_status_.has_safety_mode_trigger_time(); } if (safety_mode_triggered) { ADEBUG << "Safety mode triggerd, enable safty mode"; TriggerSafetyMode(); } else { ADEBUG << "Safety mode not triggerd, bypass control command"; ByPassControlCommand(); } AdapterManager::FillGuardianHeader(FLAGS_node_name, &guardian_cmd_); AdapterManager::PublishGuardian(guardian_cmd_); } void Guardian::OnChassis(const Chassis& message) { ADEBUG << "Received chassis data: run chassis callback."; std::lock_guard<std::mutex> lock(mutex_); chassis_.CopyFrom(message); } void Guardian::OnSystemStatus(const SystemStatus& message) { ADEBUG << "Received monitor data: run monitor callback."; std::lock_guard<std::mutex> lock(mutex_); system_status_.CopyFrom(message); } void Guardian::OnControl(const ControlCommand& message) { ADEBUG << "Received control data: run control command callback."; std::lock_guard<std::mutex> lock(mutex_); control_cmd_.CopyFrom(message); } void Guardian::ByPassControlCommand() { std::lock_guard<std::mutex> lock(mutex_); guardian_cmd_.mutable_control_command()->CopyFrom(control_cmd_); } void Guardian::TriggerSafetyMode() { AINFO << "Safety state triggered, with system safety mode trigger time : " << system_status_.safety_mode_trigger_time(); std::lock_guard<std::mutex> lock(mutex_); bool sensor_malfunction = false, obstacle_detected = false; if (!chassis_.surround().sonar_enabled() || chassis_.surround().sonar_fault()) { AINFO << "Ultrasonic sensor not enabled for faulted, will do emergency " "stop!"; sensor_malfunction = true; } else { // TODO(QiL) : Load for config for (int i = 0; i < chassis_.surround().sonar_range_size(); ++i) { if ((chassis_.surround().sonar_range(i) > 0.0 && chassis_.surround().sonar_range(i) < 2.5) || chassis_.surround().sonar_range(i) > 30) { AINFO << "Object detected or ultrasonic sensor fault output, will do " "emergency stop!"; obstacle_detected = true; } } } guardian_cmd_.mutable_control_command()->set_throttle(0.0); guardian_cmd_.mutable_control_command()->set_steering_target(0.0); guardian_cmd_.mutable_control_command()->set_steering_rate(0.0); guardian_cmd_.mutable_control_command()->set_is_in_safe_mode(true); // TODO(QiL) : Remove this one once hardware re-alignment is done. sensor_malfunction = false; obstacle_detected = false; AINFO << "Temperarily ignore the ultrasonic sensor output during hardware " "re-alignment!"; if (system_status_.require_emergency_stop() || sensor_malfunction || obstacle_detected) { AINFO << "Emergency stop triggered! with system status from monitor as : " << system_status_.require_emergency_stop(); guardian_cmd_.mutable_control_command()->set_brake( FLAGS_guardian_cmd_emergency_stop_percentage); } else { AINFO << "Soft stop triggered! with system status from monitor as : " << system_status_.require_emergency_stop(); guardian_cmd_.mutable_control_command()->set_brake( FLAGS_guardian_cmd_soft_stop_percentage); } } } // namespace guardian } // namespace apollo <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #ifndef _Stroika_Foundation_Characters_StringBuilder_inl_ #define _Stroika_Foundation_Characters_StringBuilder_inl_ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <memory> #include "../Debug/Assertions.h" namespace Stroika { namespace Foundation { namespace Characters { /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ inline StringBuilder::StringBuilder () : fData_ (0) , fLength_ (0) { } inline StringBuilder::StringBuilder (const String& initialValue) : fData_ (0) , fLength_ (0) { operator+= (initialValue); } inline StringBuilder& StringBuilder::operator+= (const wchar_t* s) { lock_guard<Execution::ExternallySynchronizedLock> critSec (fLock_); size_t i = fLength_; size_t l = ::wcslen (s); fData_.GrowToSize (i + l); fLength_ = i + i; memcpy (fData_.begin () + i, s, sizeof (wchar_t) * l); } inline StringBuilder& StringBuilder::operator+= (const String& s) { return operator+= (s.c_str ()); } inline StringBuilder& StringBuilder::operator<< (const String& s) { return operator+= (s.c_str ()); } inline StringBuilder& StringBuilder::operator<< (const wchar_t* s) { return operator+= (s); } inline StringBuilder::operator String () const { return str (); } inline const wchar_t* StringBuilder::c_str () const { lock_guard<Execution::ExternallySynchronizedLock> critSec (fLock_); fData_.GrowToSize (fLength_ + 1); fData_[fLength_] = '\0'; return fData_.begin (); } inline String StringBuilder::str () const { lock_guard<Execution::ExternallySynchronizedLock> critSec (fLock_); size_t l = fLength_; return String (fData_.begin (), fData_.begin () + l); } } } } #endif // _Stroika_Foundation_Characters_StringBuilder_inl_ <commit_msg>fixed small bug with StringBuilder<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #ifndef _Stroika_Foundation_Characters_StringBuilder_inl_ #define _Stroika_Foundation_Characters_StringBuilder_inl_ /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <memory> #include "../Debug/Assertions.h" namespace Stroika { namespace Foundation { namespace Characters { /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ inline StringBuilder::StringBuilder () : fData_ (0) , fLength_ (0) { } inline StringBuilder::StringBuilder (const String& initialValue) : fData_ (0) , fLength_ (0) { operator+= (initialValue); } inline StringBuilder& StringBuilder::operator+= (const wchar_t* s) { lock_guard<Execution::ExternallySynchronizedLock> critSec (fLock_); size_t i = fLength_; size_t l = ::wcslen (s); fData_.GrowToSize (i + l); fLength_ = i + i; memcpy (fData_.begin () + i, s, sizeof (wchar_t) * l); return *this; } inline StringBuilder& StringBuilder::operator+= (const String& s) { return operator+= (s.c_str ()); } inline StringBuilder& StringBuilder::operator<< (const String& s) { return operator+= (s.c_str ()); } inline StringBuilder& StringBuilder::operator<< (const wchar_t* s) { return operator+= (s); } inline StringBuilder::operator String () const { return str (); } inline const wchar_t* StringBuilder::c_str () const { lock_guard<Execution::ExternallySynchronizedLock> critSec (fLock_); fData_.GrowToSize (fLength_ + 1); fData_[fLength_] = '\0'; return fData_.begin (); } inline String StringBuilder::str () const { lock_guard<Execution::ExternallySynchronizedLock> critSec (fLock_); size_t l = fLength_; return String (fData_.begin (), fData_.begin () + l); } } } } #endif // _Stroika_Foundation_Characters_StringBuilder_inl_ <|endoftext|>
<commit_before>#include <algorithm> #include <vector> #include "unittest/gtest.hpp" #include "btree/node.hpp" #include "btree/leaf_node.hpp" namespace unittest { // TODO: This is rather duplicative of fsck::check_value. void expect_valid_value_shallowly(const btree_value *value) { EXPECT_EQ(0, value->metadata_flags & ~(MEMCACHED_FLAGS | MEMCACHED_CAS | MEMCACHED_EXPTIME | LARGE_VALUE)); size_t size = value->value_size(); if (value->is_large()) { EXPECT_GT(size, MAX_IN_NODE_VALUE_SIZE); // This isn't fsck, we can't follow large buf pointers. } else { EXPECT_LE(size, MAX_IN_NODE_VALUE_SIZE); } } // TODO: This is rather duplicative of fsck::check_subtree_leaf_node. void verify(block_size_t block_size, const leaf_node_t *buf, int expected_free_space) { int end_of_pair_offsets = offsetof(leaf_node_t, pair_offsets) + buf->npairs * 2; ASSERT_LE(end_of_pair_offsets, buf->frontmost_offset); ASSERT_LE(buf->frontmost_offset, block_size.value()); ASSERT_EQ(expected_free_space, buf->frontmost_offset - end_of_pair_offsets); std::vector<uint16_t> offsets(buf->pair_offsets, buf->pair_offsets + buf->npairs); std::sort(offsets.begin(), offsets.end()); uint16_t expected = buf->frontmost_offset; for (std::vector<uint16_t>::const_iterator p = offsets.begin(), e = offsets.end(); p < e; ++p) { ASSERT_LE(expected, block_size.value()); ASSERT_EQ(expected, *p); expected += leaf_node_handler::pair_size(leaf_node_handler::get_pair(buf, *p)); } ASSERT_EQ(block_size.value(), expected); const btree_key *last_key = NULL; for (const uint16_t *p = buf->pair_offsets, *e = p + buf->npairs; p < e; ++p) { const btree_leaf_pair *pair = leaf_node_handler::get_pair(buf, *p); if (last_key != NULL) { const btree_key *next_key = &pair->key; EXPECT_LT(leaf_key_comp::compare(last_key, next_key), 0); last_key = next_key; } expect_valid_value_shallowly(pair->value()); } } TEST(LeafNodeTest, Offsets) { // Check leaf_node_t. EXPECT_EQ(0, offsetof(leaf_node_t, magic)); EXPECT_EQ(4, offsetof(leaf_node_t, times)); EXPECT_EQ(12, offsetof(leaf_node_t, npairs)); EXPECT_EQ(14, offsetof(leaf_node_t, frontmost_offset)); EXPECT_EQ(16, offsetof(leaf_node_t, pair_offsets)); EXPECT_EQ(16, sizeof(leaf_node_t)); // Check leaf_timestamps_t, since that's specifically part of leaf_node_t. EXPECT_EQ(0, offsetof(leaf_timestamps_t, last_modified)); EXPECT_EQ(4, offsetof(leaf_timestamps_t, earlier)); // Changing NUM_LEAF_NODE_EARLIER_TIMES changes the disk format. EXPECT_EQ(2, NUM_LEAF_NODE_EARLIER_TIMES); EXPECT_EQ(8, sizeof(leaf_timestamps_t)); // Check btree_leaf_pair. EXPECT_EQ(0, offsetof(btree_leaf_pair, key)); btree_leaf_pair p; p.key.size = 173; EXPECT_EQ(174, reinterpret_cast<byte *>(p.value()) - reinterpret_cast<byte *>(&p)); EXPECT_EQ(1, sizeof(btree_key)); EXPECT_EQ(1, offsetof(btree_key, contents)); EXPECT_EQ(2, sizeof(btree_value)); } class Value { public: Value(const std::string& data = "", mcflags_t mcflags = 0, cas_t cas = 0, bool has_cas = false, exptime_t exptime = 0) : mcflags_(mcflags), cas_(cas), exptime_(exptime), has_cas_(has_cas), data_(data) { EXPECT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE); } void WriteBtreeValue(btree_value *out) const { out->size = 0; out->metadata_flags = 0; ASSERT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE); out->value_size(data_.size()); out->set_mcflags(mcflags_); out->set_exptime(exptime_); if (has_cas_) { out->set_cas(cas_); } memcpy(out->value(), data_.c_str(), data_.size()); } static Value Make(const btree_value *v) { EXPECT_FALSE(v->is_large()); return Value(std::string(v->value(), v->value() + v->value_size()), v->mcflags(), v->has_cas() ? v->cas() : 0, v->has_cas(), v->exptime()); } bool operator==(const Value& rhs) const { return mcflags_ == rhs.mcflags_ && exptime_ == rhs.exptime_ && data_ == rhs.data_ && has_cas_ == rhs.has_cas_ && (has_cas_ ? cas_ == rhs.cas_ : true); } int full_size() const { return sizeof(btree_value) + (mcflags_ ? sizeof(mcflags_t) : 0) + (has_cas_ ? sizeof(cas_t) : 0) + (exptime_ ? sizeof(exptime_t) : 0) + data_.size(); } friend std::ostream& operator<<(std::ostream&, const Value&); private: mcflags_t mcflags_; cas_t cas_; exptime_t exptime_; bool has_cas_; std::string data_; }; std::ostream& operator<<(std::ostream& out, const Value& v) { out << "Value[mcflags=" << v.mcflags_; if (v.has_cas_) { out << " cas=" << v.cas_; } // TODO: string escape v.data_. out << " exptime=" << v.exptime_ << " data='" << v.data_ << "']"; return out; } class StackKey { public: explicit StackKey(const std::string& key) { EXPECT_LE(key.size(), MAX_KEY_SIZE); keyval.size = key.size(); memcpy(keyval.contents, key.c_str(), key.size()); } const btree_key *look() const { return &keyval; } private: union { byte keyval_padding[sizeof(btree_key) + MAX_KEY_SIZE]; btree_key keyval; }; }; class StackValue { public: StackValue() { memset(val_padding, 0, sizeof(val_padding)); } explicit StackValue(const Value& value) { value.WriteBtreeValue(&val); } const btree_value *look() const { return &val; } btree_value *look_write() { return &val; } private: union { byte val_padding[sizeof(btree_value) + MAX_TOTAL_NODE_CONTENTS_SIZE]; btree_value val; }; }; template <int block_size> class LeafNodeGrinder { block_size_t bs; typedef std::map<std::string, Value> expected_t; expected_t expected; int expected_frontmost_offset; int expected_npairs; leaf_node_t *node; public: LeafNodeGrinder() : bs(block_size_t::unsafe_make(block_size)), expected(), expected_frontmost_offset(bs.value()), expected_npairs(0), node(reinterpret_cast<leaf_node_t *>(malloc(bs.value()))) { } ~LeafNodeGrinder() { free(node); } int expected_space() const { return expected_frontmost_offset - (offsetof(leaf_node_t, pair_offsets) + sizeof(*node->pair_offsets) * expected_npairs); } void init() { SCOPED_TRACE("init"); leaf_node_handler::init(bs, node, repli_timestamp::invalid); validate(); } void insert(const std::string& k, const Value& v) { SCOPED_TRACE("insert"); StackKey skey(k); StackValue sval(v); if (expected_space() < int((1 + k.size()) + v.full_size() + sizeof(*node->pair_offsets))) { ASSERT_FALSE(leaf_node_handler::insert(bs, node, skey.look(), sval.look(), repli_timestamp::invalid)); } else { ASSERT_TRUE(leaf_node_handler::insert(bs, node, skey.look(), sval.look(), repli_timestamp::invalid)); std::pair<expected_t::iterator, bool> res = expected.insert(std::make_pair(k, v)); if (res.second) { // The key didn't previously exist. expected_frontmost_offset -= (1 + k.size()) + v.full_size(); expected_npairs++; } else { // The key previously existed. expected_frontmost_offset += res.first->second.full_size(); expected_frontmost_offset -= v.full_size(); res.first->second = v; } } validate(); } void lookup(const std::string& k, const Value& expected) const { StackKey skey(k); StackValue sval; ASSERT_TRUE(leaf_node_handler::lookup(node, skey.look(), sval.look_write())); ASSERT_EQ(expected, Value::Make(sval.look())); } // Expects the key to be in the node. void remove(const std::string& k) { SCOPED_TRACE("remove"); expected_t::iterator p = expected.find(k); // There's a bug in the test if we're trying to remove a key that's not there. ASSERT_TRUE(p != expected.end()); // The key should be in there. StackKey skey(k); StackValue sval; ASSERT_TRUE(leaf_node_handler::lookup(node, skey.look(), sval.look_write())); leaf_node_handler::remove(bs, node, skey.look()); expected.erase(p); expected_frontmost_offset += (1 + k.size()) + sval.look()->full_size(); -- expected_npairs; validate(); } void validate() const { ASSERT_EQ(expected_npairs, node->npairs); ASSERT_EQ(expected_frontmost_offset, node->frontmost_offset); verify(bs, node, expected_space()); for (expected_t::const_iterator p = expected.begin(), e = expected.end(); p != e; ++p) { lookup(p->first, p->second); } // We're confident there are no bad keys because // expected_free_space matched up. } }; block_size_t make_bs() { // TODO: Test weird block sizes. return block_size_t::unsafe_make(4096); } leaf_node_t *malloc_leaf_node(block_size_t bs) { return reinterpret_cast<leaf_node_t *>(malloc(bs.value())); } btree_key *malloc_key(const char *s) { size_t origlen = strlen(s); EXPECT_LE(origlen, MAX_KEY_SIZE); size_t len = std::min<size_t>(origlen, MAX_KEY_SIZE); btree_key *k = reinterpret_cast<btree_key *>(malloc(sizeof(btree_key) + len)); k->size = len; memcpy(k->contents, s, len); return k; } btree_value *malloc_value(const char *s) { size_t origlen = strlen(s); EXPECT_LE(origlen, MAX_IN_NODE_VALUE_SIZE); size_t len = std::min<size_t>(origlen, MAX_IN_NODE_VALUE_SIZE); btree_value *v = reinterpret_cast<btree_value *>(malloc(sizeof(btree_value) + len)); v->size = len; v->metadata_flags = 0; memcpy(v->value(), s, len); return v; } TEST(LeafNodeTest, Initialization) { block_size_t bs = make_bs(); leaf_node_t *node = malloc_leaf_node(bs); leaf_node_handler::init(bs, node, repli_timestamp::invalid); verify(bs, node, bs.value() - offsetof(leaf_node_t, pair_offsets)); free(node); } void InsertLookupRemoveHelper(const std::string& key, const char *value) { LeafNodeGrinder<4096> gr; Value v(value); gr.init(); gr.insert(key, v); gr.lookup(key, v); gr.remove(key); } TEST(LeafNodeTest, ElementaryInsertLookupRemove) { InsertLookupRemoveHelper("the_key", "the_value"); } TEST(LeafNodeTest, EmptyValueInsertLookupRemove) { InsertLookupRemoveHelper("the_key", ""); } TEST(LeafNodeTest, EmptyKeyInsertLookupRemove) { InsertLookupRemoveHelper("", "the_value"); } TEST(LeafNodeTest, EmptyKeyValueInsertLookupRemove) { InsertLookupRemoveHelper("", ""); } } // namespace unittest <commit_msg>Made lookup private, moved variables around.<commit_after>#include <algorithm> #include <vector> #include "unittest/gtest.hpp" #include "btree/node.hpp" #include "btree/leaf_node.hpp" namespace unittest { // TODO: This is rather duplicative of fsck::check_value. void expect_valid_value_shallowly(const btree_value *value) { EXPECT_EQ(0, value->metadata_flags & ~(MEMCACHED_FLAGS | MEMCACHED_CAS | MEMCACHED_EXPTIME | LARGE_VALUE)); size_t size = value->value_size(); if (value->is_large()) { EXPECT_GT(size, MAX_IN_NODE_VALUE_SIZE); // This isn't fsck, we can't follow large buf pointers. } else { EXPECT_LE(size, MAX_IN_NODE_VALUE_SIZE); } } // TODO: This is rather duplicative of fsck::check_subtree_leaf_node. void verify(block_size_t block_size, const leaf_node_t *buf, int expected_free_space) { int end_of_pair_offsets = offsetof(leaf_node_t, pair_offsets) + buf->npairs * 2; ASSERT_LE(end_of_pair_offsets, buf->frontmost_offset); ASSERT_LE(buf->frontmost_offset, block_size.value()); ASSERT_EQ(expected_free_space, buf->frontmost_offset - end_of_pair_offsets); std::vector<uint16_t> offsets(buf->pair_offsets, buf->pair_offsets + buf->npairs); std::sort(offsets.begin(), offsets.end()); uint16_t expected = buf->frontmost_offset; for (std::vector<uint16_t>::const_iterator p = offsets.begin(), e = offsets.end(); p < e; ++p) { ASSERT_LE(expected, block_size.value()); ASSERT_EQ(expected, *p); expected += leaf_node_handler::pair_size(leaf_node_handler::get_pair(buf, *p)); } ASSERT_EQ(block_size.value(), expected); const btree_key *last_key = NULL; for (const uint16_t *p = buf->pair_offsets, *e = p + buf->npairs; p < e; ++p) { const btree_leaf_pair *pair = leaf_node_handler::get_pair(buf, *p); if (last_key != NULL) { const btree_key *next_key = &pair->key; EXPECT_LT(leaf_key_comp::compare(last_key, next_key), 0); last_key = next_key; } expect_valid_value_shallowly(pair->value()); } } TEST(LeafNodeTest, Offsets) { // Check leaf_node_t. EXPECT_EQ(0, offsetof(leaf_node_t, magic)); EXPECT_EQ(4, offsetof(leaf_node_t, times)); EXPECT_EQ(12, offsetof(leaf_node_t, npairs)); EXPECT_EQ(14, offsetof(leaf_node_t, frontmost_offset)); EXPECT_EQ(16, offsetof(leaf_node_t, pair_offsets)); EXPECT_EQ(16, sizeof(leaf_node_t)); // Check leaf_timestamps_t, since that's specifically part of leaf_node_t. EXPECT_EQ(0, offsetof(leaf_timestamps_t, last_modified)); EXPECT_EQ(4, offsetof(leaf_timestamps_t, earlier)); // Changing NUM_LEAF_NODE_EARLIER_TIMES changes the disk format. EXPECT_EQ(2, NUM_LEAF_NODE_EARLIER_TIMES); EXPECT_EQ(8, sizeof(leaf_timestamps_t)); // Check btree_leaf_pair. EXPECT_EQ(0, offsetof(btree_leaf_pair, key)); btree_leaf_pair p; p.key.size = 173; EXPECT_EQ(174, reinterpret_cast<byte *>(p.value()) - reinterpret_cast<byte *>(&p)); EXPECT_EQ(1, sizeof(btree_key)); EXPECT_EQ(1, offsetof(btree_key, contents)); EXPECT_EQ(2, sizeof(btree_value)); } class Value { public: Value(const std::string& data = "", mcflags_t mcflags = 0, cas_t cas = 0, bool has_cas = false, exptime_t exptime = 0) : mcflags_(mcflags), cas_(cas), exptime_(exptime), has_cas_(has_cas), data_(data) { EXPECT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE); } void WriteBtreeValue(btree_value *out) const { out->size = 0; out->metadata_flags = 0; ASSERT_LE(data_.size(), MAX_IN_NODE_VALUE_SIZE); out->value_size(data_.size()); out->set_mcflags(mcflags_); out->set_exptime(exptime_); if (has_cas_) { out->set_cas(cas_); } memcpy(out->value(), data_.c_str(), data_.size()); } static Value Make(const btree_value *v) { EXPECT_FALSE(v->is_large()); return Value(std::string(v->value(), v->value() + v->value_size()), v->mcflags(), v->has_cas() ? v->cas() : 0, v->has_cas(), v->exptime()); } bool operator==(const Value& rhs) const { return mcflags_ == rhs.mcflags_ && exptime_ == rhs.exptime_ && data_ == rhs.data_ && has_cas_ == rhs.has_cas_ && (has_cas_ ? cas_ == rhs.cas_ : true); } int full_size() const { return sizeof(btree_value) + (mcflags_ ? sizeof(mcflags_t) : 0) + (has_cas_ ? sizeof(cas_t) : 0) + (exptime_ ? sizeof(exptime_t) : 0) + data_.size(); } friend std::ostream& operator<<(std::ostream&, const Value&); private: mcflags_t mcflags_; cas_t cas_; exptime_t exptime_; bool has_cas_; std::string data_; }; std::ostream& operator<<(std::ostream& out, const Value& v) { out << "Value[mcflags=" << v.mcflags_; if (v.has_cas_) { out << " cas=" << v.cas_; } // TODO: string escape v.data_. out << " exptime=" << v.exptime_ << " data='" << v.data_ << "']"; return out; } class StackKey { public: explicit StackKey(const std::string& key) { EXPECT_LE(key.size(), MAX_KEY_SIZE); keyval.size = key.size(); memcpy(keyval.contents, key.c_str(), key.size()); } const btree_key *look() const { return &keyval; } private: union { byte keyval_padding[sizeof(btree_key) + MAX_KEY_SIZE]; btree_key keyval; }; }; class StackValue { public: StackValue() { memset(val_padding, 0, sizeof(val_padding)); } explicit StackValue(const Value& value) { value.WriteBtreeValue(&val); } const btree_value *look() const { return &val; } btree_value *look_write() { return &val; } private: union { byte val_padding[sizeof(btree_value) + MAX_TOTAL_NODE_CONTENTS_SIZE]; btree_value val; }; }; template <int block_size> class LeafNodeGrinder { public: LeafNodeGrinder() : bs(block_size_t::unsafe_make(block_size)), expected(), expected_frontmost_offset(bs.value()), expected_npairs(0), node(reinterpret_cast<leaf_node_t *>(malloc(bs.value()))) { } ~LeafNodeGrinder() { free(node); } int expected_space() const { return expected_frontmost_offset - (offsetof(leaf_node_t, pair_offsets) + sizeof(*node->pair_offsets) * expected_npairs); } void init() { SCOPED_TRACE("init"); leaf_node_handler::init(bs, node, repli_timestamp::invalid); validate(); } void insert(const std::string& k, const Value& v) { SCOPED_TRACE("insert"); StackKey skey(k); StackValue sval(v); if (expected_space() < int((1 + k.size()) + v.full_size() + sizeof(*node->pair_offsets))) { ASSERT_FALSE(leaf_node_handler::insert(bs, node, skey.look(), sval.look(), repli_timestamp::invalid)); } else { ASSERT_TRUE(leaf_node_handler::insert(bs, node, skey.look(), sval.look(), repli_timestamp::invalid)); std::pair<expected_t::iterator, bool> res = expected.insert(std::make_pair(k, v)); if (res.second) { // The key didn't previously exist. expected_frontmost_offset -= (1 + k.size()) + v.full_size(); expected_npairs++; } else { // The key previously existed. expected_frontmost_offset += res.first->second.full_size(); expected_frontmost_offset -= v.full_size(); res.first->second = v; } } validate(); } // Expects the key to be in the node. void remove(const std::string& k) { SCOPED_TRACE("remove"); expected_t::iterator p = expected.find(k); // There's a bug in the test if we're trying to remove a key that's not there. ASSERT_TRUE(p != expected.end()); // The key should be in there. StackKey skey(k); StackValue sval; ASSERT_TRUE(leaf_node_handler::lookup(node, skey.look(), sval.look_write())); leaf_node_handler::remove(bs, node, skey.look()); expected.erase(p); expected_frontmost_offset += (1 + k.size()) + sval.look()->full_size(); -- expected_npairs; validate(); } void validate() const { ASSERT_EQ(expected_npairs, node->npairs); ASSERT_EQ(expected_frontmost_offset, node->frontmost_offset); verify(bs, node, expected_space()); for (expected_t::const_iterator p = expected.begin(), e = expected.end(); p != e; ++p) { lookup(p->first, p->second); } // We're confident there are no bad keys because // expected_free_space matched up. } private: void lookup(const std::string& k, const Value& expected) const { StackKey skey(k); StackValue sval; ASSERT_TRUE(leaf_node_handler::lookup(node, skey.look(), sval.look_write())); ASSERT_EQ(expected, Value::Make(sval.look())); } block_size_t bs; typedef std::map<std::string, Value> expected_t; expected_t expected; int expected_frontmost_offset; int expected_npairs; leaf_node_t *node; }; block_size_t make_bs() { // TODO: Test weird block sizes. return block_size_t::unsafe_make(4096); } leaf_node_t *malloc_leaf_node(block_size_t bs) { return reinterpret_cast<leaf_node_t *>(malloc(bs.value())); } btree_key *malloc_key(const char *s) { size_t origlen = strlen(s); EXPECT_LE(origlen, MAX_KEY_SIZE); size_t len = std::min<size_t>(origlen, MAX_KEY_SIZE); btree_key *k = reinterpret_cast<btree_key *>(malloc(sizeof(btree_key) + len)); k->size = len; memcpy(k->contents, s, len); return k; } btree_value *malloc_value(const char *s) { size_t origlen = strlen(s); EXPECT_LE(origlen, MAX_IN_NODE_VALUE_SIZE); size_t len = std::min<size_t>(origlen, MAX_IN_NODE_VALUE_SIZE); btree_value *v = reinterpret_cast<btree_value *>(malloc(sizeof(btree_value) + len)); v->size = len; v->metadata_flags = 0; memcpy(v->value(), s, len); return v; } TEST(LeafNodeTest, Initialization) { block_size_t bs = make_bs(); leaf_node_t *node = malloc_leaf_node(bs); leaf_node_handler::init(bs, node, repli_timestamp::invalid); verify(bs, node, bs.value() - offsetof(leaf_node_t, pair_offsets)); free(node); } void InsertLookupRemoveHelper(const std::string& key, const char *value) { LeafNodeGrinder<4096> gr; Value v(value); gr.init(); gr.insert(key, v); gr.remove(key); } TEST(LeafNodeTest, ElementaryInsertLookupRemove) { InsertLookupRemoveHelper("the_key", "the_value"); } TEST(LeafNodeTest, EmptyValueInsertLookupRemove) { InsertLookupRemoveHelper("the_key", ""); } TEST(LeafNodeTest, EmptyKeyInsertLookupRemove) { InsertLookupRemoveHelper("", "the_value"); } TEST(LeafNodeTest, EmptyKeyValueInsertLookupRemove) { InsertLookupRemoveHelper("", ""); } } // namespace unittest <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "XercesBridgeNavigator.hpp" #include <XalanDOM/XalanNode.hpp> #include "XercesAttrBridge.hpp" #include "XercesDocumentBridge.hpp" #include "XercesTextBridge.hpp" #include "XercesDOMException.hpp" // I'm using this to distinguish between null nodes, which are valid, and // an uninitialized cached node address. This is probably bogus, and I'll // probably just change this to 0, but this is experimental anyway... #if defined(XALAN_OLD_STYLE_CASTS) static XalanNode* const invalidNodeAddress = (XalanNode*)1; #else static XalanNode* const invalidNodeAddress = reinterpret_cast<XalanNode*>(1); #endif XercesBridgeNavigator::XercesBridgeNavigator( XercesDocumentBridge* theOwnerDocument, bool mappingMode) : m_ownerDocument(theOwnerDocument), m_parentNode(mappingMode == true ? invalidNodeAddress : 0), m_previousSibling(mappingMode == true ? invalidNodeAddress : 0), m_nextSibling(mappingMode == true ? invalidNodeAddress : 0), m_firstChild(mappingMode == true ? invalidNodeAddress : 0), m_lastChild(mappingMode == true ? invalidNodeAddress : 0), m_index(UINT_MAX) { } XercesBridgeNavigator::XercesBridgeNavigator(const XercesBridgeNavigator& theSource) : m_ownerDocument(theSource.m_ownerDocument), m_parentNode(theSource.m_parentNode), m_previousSibling(theSource.m_previousSibling), m_nextSibling(theSource.m_nextSibling), m_firstChild(theSource.m_firstChild), m_lastChild(theSource.m_lastChild), m_index(theSource.m_index) { } XercesBridgeNavigator::~XercesBridgeNavigator() { } XalanNode* XercesBridgeNavigator::mapNode(const DOM_Node& theXercesNode) const { return m_ownerDocument->mapNode(theXercesNode); } XalanAttr* XercesBridgeNavigator::mapNode(const DOM_Attr& theXercesNode) const { return m_ownerDocument->mapNode(theXercesNode); } DOM_Node XercesBridgeNavigator::mapNode(const XalanNode* theXalanNode) const { return m_ownerDocument->mapNode(theXalanNode); } DOM_Attr XercesBridgeNavigator::mapNode(const XalanAttr* theXalanNode) const { return m_ownerDocument->mapNode(theXalanNode); } XalanNode* XercesBridgeNavigator::getParentNode(const DOM_Node& theXercesNode) const { if (m_parentNode == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_parentNode = m_ownerDocument->mapNode(theXercesNode.getParentNode()); #else m_parentNode = m_ownerDocument->mapNode(theXercesNode.getParentNode()); #endif } return m_parentNode; } XalanNode* XercesBridgeNavigator::getPreviousSibling(const DOM_Node& theXercesNode) const { if (m_previousSibling == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_previousSibling = m_ownerDocument->mapNode(theXercesNode.getPreviousSibling()); #else m_previousSibling = m_ownerDocument->mapNode(theXercesNode.getPreviousSibling()); #endif } return m_previousSibling; } XalanNode* XercesBridgeNavigator::getNextSibling(const DOM_Node& theXercesNode) const { if (m_nextSibling == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_nextSibling = m_ownerDocument->mapNode(theXercesNode.getNextSibling()); #else m_nextSibling = m_ownerDocument->mapNode(theXercesNode.getNextSibling()); #endif } return m_nextSibling; } XalanNode* XercesBridgeNavigator::getFirstChild(const DOM_Node& theXercesNode) const { if (m_firstChild == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_firstChild = m_ownerDocument->mapNode(theXercesNode.getFirstChild()); #else m_firstChild = m_ownerDocument->mapNode(theXercesNode.getFirstChild()); #endif } return m_firstChild; } XalanNode* XercesBridgeNavigator::getLastChild(const DOM_Node& theXercesNode) const { if (m_lastChild == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_lastChild = m_ownerDocument->mapNode(theXercesNode.getLastChild()); #else m_lastChild = m_ownerDocument->mapNode(theXercesNode.getLastChild()); #endif } return m_lastChild; } XalanNode* XercesBridgeNavigator::insertBefore( DOM_Node& theXercesParent, XalanNode* newChild, XalanNode* refChild) const { assert(newChild != 0); // Get the corresponding Xerces nodes... const DOM_Node theNewChild = m_ownerDocument->mapNode(newChild); const DOM_Node theRefChild = m_ownerDocument->mapNode(refChild); try { const DOM_Node theXercesResult = theXercesParent.insertBefore(theNewChild, theRefChild); assert(m_ownerDocument->mapNode(theXercesResult) == newChild); } catch(const DOM_DOMException& theException) { throw XercesDOMException(theException); } return newChild; } XalanNode* XercesBridgeNavigator:: replaceChild( DOM_Node& theXercesParent, XalanNode* newChild, XalanNode* oldChild) const { assert(newChild != 0); assert(oldChild != 0); // Get the corresponding Xerces nodes... const DOM_Node theNewChild = m_ownerDocument->mapNode(newChild); const DOM_Node theOldChild = m_ownerDocument->mapNode(oldChild); try { const DOM_Node theXercesResult = theXercesParent.replaceChild(theNewChild, theOldChild); assert(m_ownerDocument->mapNode(theXercesResult) == oldChild); } catch(const DOM_DOMException& theException) { throw XercesDOMException(theException); } return oldChild; } XalanNode* XercesBridgeNavigator::removeChild( DOM_Node& theXercesParent, XalanNode* oldChild) const { assert(oldChild != 0); // Get the corresponding Xerces nodes... const DOM_Node theOldChild = m_ownerDocument->mapNode(oldChild); try { const DOM_Node theXercesResult = theXercesParent.removeChild(theOldChild); assert(m_ownerDocument->mapNode(theXercesResult) == oldChild); } catch(const DOM_DOMException& theException) { throw XercesDOMException(theException); } return oldChild; } XalanNode* XercesBridgeNavigator::appendChild( DOM_Node& theXercesParent, XalanNode* newChild) const { return insertBefore(theXercesParent, newChild, 0); } XalanElement* XercesBridgeNavigator::getOwnerElement(const DOM_Attr& theXercesAttr) const { return m_ownerDocument->mapNode(theXercesAttr.getOwnerElement()); } XalanNode* XercesBridgeNavigator::cloneNode( const XalanNode* theXalanNode, const DOM_Node& theXercesNode, bool deep) const { return m_ownerDocument->internalCloneNode(theXalanNode, theXercesNode, deep); } XalanText* XercesBridgeNavigator::splitText( DOM_Text& theXercesText, unsigned int offset) const { XalanText* theXalanText = 0; try { DOM_Text theNewXercesText = theXercesText.splitText(offset); assert(theXercesText.isNull() == false); theXalanText = m_ownerDocument->createBridgeNode(theNewXercesText, 0, true); } catch(const DOM_DOMException& theException) { throw XercesDOMException(theException); } return theXalanText; } const XalanDOMString& XercesBridgeNavigator::getPooledString(const XalanDOMString& theString) const { return m_ownerDocument->getPooledString(theString); } const XalanDOMString& XercesBridgeNavigator:: getPooledString(const XalanDOMChar* theString) const { return m_ownerDocument->getPooledString(theString); } <commit_msg>Return parent element if already know<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "XercesBridgeNavigator.hpp" #include <XalanDOM/XalanNode.hpp> #include "XercesAttrBridge.hpp" #include "XercesDocumentBridge.hpp" #include "XercesTextBridge.hpp" #include "XercesDOMException.hpp" // I'm using this to distinguish between null nodes, which are valid, and // an uninitialized cached node address. This is probably bogus, and I'll // probably just change this to 0, but this is experimental anyway... #if defined(XALAN_OLD_STYLE_CASTS) static XalanNode* const invalidNodeAddress = (XalanNode*)1; #else static XalanNode* const invalidNodeAddress = reinterpret_cast<XalanNode*>(1); #endif XercesBridgeNavigator::XercesBridgeNavigator( XercesDocumentBridge* theOwnerDocument, bool mappingMode) : m_ownerDocument(theOwnerDocument), m_parentNode(mappingMode == true ? invalidNodeAddress : 0), m_previousSibling(mappingMode == true ? invalidNodeAddress : 0), m_nextSibling(mappingMode == true ? invalidNodeAddress : 0), m_firstChild(mappingMode == true ? invalidNodeAddress : 0), m_lastChild(mappingMode == true ? invalidNodeAddress : 0), m_index(UINT_MAX) { } XercesBridgeNavigator::XercesBridgeNavigator(const XercesBridgeNavigator& theSource) : m_ownerDocument(theSource.m_ownerDocument), m_parentNode(theSource.m_parentNode), m_previousSibling(theSource.m_previousSibling), m_nextSibling(theSource.m_nextSibling), m_firstChild(theSource.m_firstChild), m_lastChild(theSource.m_lastChild), m_index(theSource.m_index) { } XercesBridgeNavigator::~XercesBridgeNavigator() { } XalanNode* XercesBridgeNavigator::mapNode(const DOM_Node& theXercesNode) const { return m_ownerDocument->mapNode(theXercesNode); } XalanAttr* XercesBridgeNavigator::mapNode(const DOM_Attr& theXercesNode) const { return m_ownerDocument->mapNode(theXercesNode); } DOM_Node XercesBridgeNavigator::mapNode(const XalanNode* theXalanNode) const { return m_ownerDocument->mapNode(theXalanNode); } DOM_Attr XercesBridgeNavigator::mapNode(const XalanAttr* theXalanNode) const { return m_ownerDocument->mapNode(theXalanNode); } XalanNode* XercesBridgeNavigator::getParentNode(const DOM_Node& theXercesNode) const { if (m_parentNode == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_parentNode = m_ownerDocument->mapNode(theXercesNode.getParentNode()); #else m_parentNode = m_ownerDocument->mapNode(theXercesNode.getParentNode()); #endif } return m_parentNode; } XalanNode* XercesBridgeNavigator::getPreviousSibling(const DOM_Node& theXercesNode) const { if (m_previousSibling == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_previousSibling = m_ownerDocument->mapNode(theXercesNode.getPreviousSibling()); #else m_previousSibling = m_ownerDocument->mapNode(theXercesNode.getPreviousSibling()); #endif } return m_previousSibling; } XalanNode* XercesBridgeNavigator::getNextSibling(const DOM_Node& theXercesNode) const { if (m_nextSibling == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_nextSibling = m_ownerDocument->mapNode(theXercesNode.getNextSibling()); #else m_nextSibling = m_ownerDocument->mapNode(theXercesNode.getNextSibling()); #endif } return m_nextSibling; } XalanNode* XercesBridgeNavigator::getFirstChild(const DOM_Node& theXercesNode) const { if (m_firstChild == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_firstChild = m_ownerDocument->mapNode(theXercesNode.getFirstChild()); #else m_firstChild = m_ownerDocument->mapNode(theXercesNode.getFirstChild()); #endif } return m_firstChild; } XalanNode* XercesBridgeNavigator::getLastChild(const DOM_Node& theXercesNode) const { if (m_lastChild == invalidNodeAddress) { #if defined(XALAN_NO_MUTABLE) ((XercesBridgeNavigator*)this)->m_lastChild = m_ownerDocument->mapNode(theXercesNode.getLastChild()); #else m_lastChild = m_ownerDocument->mapNode(theXercesNode.getLastChild()); #endif } return m_lastChild; } XalanNode* XercesBridgeNavigator::insertBefore( DOM_Node& theXercesParent, XalanNode* newChild, XalanNode* refChild) const { assert(newChild != 0); // Get the corresponding Xerces nodes... const DOM_Node theNewChild = m_ownerDocument->mapNode(newChild); const DOM_Node theRefChild = m_ownerDocument->mapNode(refChild); try { const DOM_Node theXercesResult = theXercesParent.insertBefore(theNewChild, theRefChild); assert(m_ownerDocument->mapNode(theXercesResult) == newChild); } catch(const DOM_DOMException& theException) { throw XercesDOMException(theException); } return newChild; } XalanNode* XercesBridgeNavigator:: replaceChild( DOM_Node& theXercesParent, XalanNode* newChild, XalanNode* oldChild) const { assert(newChild != 0); assert(oldChild != 0); // Get the corresponding Xerces nodes... const DOM_Node theNewChild = m_ownerDocument->mapNode(newChild); const DOM_Node theOldChild = m_ownerDocument->mapNode(oldChild); try { const DOM_Node theXercesResult = theXercesParent.replaceChild(theNewChild, theOldChild); assert(m_ownerDocument->mapNode(theXercesResult) == oldChild); } catch(const DOM_DOMException& theException) { throw XercesDOMException(theException); } return oldChild; } XalanNode* XercesBridgeNavigator::removeChild( DOM_Node& theXercesParent, XalanNode* oldChild) const { assert(oldChild != 0); // Get the corresponding Xerces nodes... const DOM_Node theOldChild = m_ownerDocument->mapNode(oldChild); try { const DOM_Node theXercesResult = theXercesParent.removeChild(theOldChild); assert(m_ownerDocument->mapNode(theXercesResult) == oldChild); } catch(const DOM_DOMException& theException) { throw XercesDOMException(theException); } return oldChild; } XalanNode* XercesBridgeNavigator::appendChild( DOM_Node& theXercesParent, XalanNode* newChild) const { return insertBefore(theXercesParent, newChild, 0); } XalanElement* XercesBridgeNavigator::getOwnerElement(const DOM_Attr& theXercesAttr) const { if (m_parentNode != 0) { assert(m_parentNode->getNodeType() == XalanNode::ELEMENT_NODE); #if defined(XALAN_OLD_STYLE_CASTS) return (XalanElement*)m_parentNode; #else return static_cast<XalanElement*>(m_parentNode); #endif } else { return m_ownerDocument->mapNode(theXercesAttr.getOwnerElement()); } } XalanNode* XercesBridgeNavigator::cloneNode( const XalanNode* theXalanNode, const DOM_Node& theXercesNode, bool deep) const { return m_ownerDocument->internalCloneNode(theXalanNode, theXercesNode, deep); } XalanText* XercesBridgeNavigator::splitText( DOM_Text& theXercesText, unsigned int offset) const { XalanText* theXalanText = 0; try { DOM_Text theNewXercesText = theXercesText.splitText(offset); assert(theXercesText.isNull() == false); theXalanText = m_ownerDocument->createBridgeNode(theNewXercesText, 0, true); } catch(const DOM_DOMException& theException) { throw XercesDOMException(theException); } return theXalanText; } const XalanDOMString& XercesBridgeNavigator::getPooledString(const XalanDOMString& theString) const { return m_ownerDocument->getPooledString(theString); } const XalanDOMString& XercesBridgeNavigator:: getPooledString(const XalanDOMChar* theString) const { return m_ownerDocument->getPooledString(theString); } <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "unittest/unittest_utils.hpp" #include <stdlib.h> #include "errors.hpp" #include <boost/bind.hpp> // These unit tests need to access some private methods. #include "arch/timing.hpp" #include "arch/runtime/starter.hpp" #include "rdb_protocol/protocol.hpp" #include "unittest/gtest.hpp" #include "utils.hpp" namespace unittest { rdb_protocol_t::read_t make_sindex_read( counted_t<const ql::datum_t> key, const std::string &id) { using namespace rdb_protocol_details; datum_range_t rng(key, key_range_t::closed, key, key_range_t::closed); return rdb_protocol_t::read_t( rdb_protocol_t::rget_read_t( rdb_protocol_t::region_t::universe(), std::map<std::string, ql::wire_func_t>(), ql::batchspec_t::user(ql::batch_type_t::NORMAL, counted_t<const ql::datum_t>()), transform_t(), boost::optional<terminal_t>(), rdb_protocol_t::sindex_rangespec_t( id, rdb_protocol_t::region_t(rng.to_sindex_keyrange()), rng), sorting_t::UNORDERED), profile_bool_t::PROFILE); } serializer_filepath_t manual_serializer_filepath(const std::string &permanent_path, const std::string &temporary_path) { return serializer_filepath_t(permanent_path, temporary_path); } static const char *const temp_file_create_suffix = ".create"; temp_file_t::temp_file_t() { for (;;) { char tmpl[] = "/tmp/rdb_unittest.XXXXXX"; const int fd = mkstemp(tmpl); guarantee_err(fd != -1, "Couldn't create a temporary file"); close(fd); // Check that both the permanent and temporary file paths are unused. const std::string tmpfilename = std::string(tmpl) + temp_file_create_suffix; if (::access(tmpfilename.c_str(), F_OK) == -1 && errno == ENOENT) { filename = tmpl; break; } else { const int unlink_res = ::unlink(tmpl); EXPECT_EQ(0, unlink_res); } } } temp_file_t::~temp_file_t() { // Unlink both possible locations of the file. const int res1 = ::unlink(name().temporary_path().c_str()); EXPECT_TRUE(res1 == 0 || errno == ENOENT); const int res2 = ::unlink(name().permanent_path().c_str()); EXPECT_TRUE(res2 == 0 || errno == ENOENT); } serializer_filepath_t temp_file_t::name() const { return manual_serializer_filepath(filename, filename + temp_file_create_suffix); } void let_stuff_happen() { #ifdef VALGRIND nap(2000); #else nap(100); #endif } std::set<ip_address_t> get_unittest_addresses() { return get_local_ips(std::set<ip_address_t>(), false); } void run_in_thread_pool(const boost::function<void()>& fun, int num_workers) { ::run_in_thread_pool(fun, num_workers); } } // namespace unittest <commit_msg>Fixed more style problems.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "unittest/unittest_utils.hpp" #include <stdlib.h> #include "errors.hpp" #include <boost/bind.hpp> // These unit tests need to access some private methods. #include "arch/timing.hpp" #include "arch/runtime/starter.hpp" #include "rdb_protocol/protocol.hpp" #include "unittest/gtest.hpp" #include "utils.hpp" namespace unittest { rdb_protocol_t::read_t make_sindex_read( counted_t<const ql::datum_t> key, const std::string &id) { datum_range_t rng(key, key_range_t::closed, key, key_range_t::closed); return rdb_protocol_t::read_t( rdb_protocol_t::rget_read_t( rdb_protocol_t::region_t::universe(), std::map<std::string, ql::wire_func_t>(), ql::batchspec_t::user(ql::batch_type_t::NORMAL, counted_t<const ql::datum_t>()), rdb_protocol_details::transform_t(), boost::optional<rdb_protocol_details::terminal_t>(), rdb_protocol_t::sindex_rangespec_t( id, rdb_protocol_t::region_t(rng.to_sindex_keyrange()), rng), sorting_t::UNORDERED), profile_bool_t::PROFILE); } serializer_filepath_t manual_serializer_filepath(const std::string &permanent_path, const std::string &temporary_path) { return serializer_filepath_t(permanent_path, temporary_path); } static const char *const temp_file_create_suffix = ".create"; temp_file_t::temp_file_t() { for (;;) { char tmpl[] = "/tmp/rdb_unittest.XXXXXX"; const int fd = mkstemp(tmpl); guarantee_err(fd != -1, "Couldn't create a temporary file"); close(fd); // Check that both the permanent and temporary file paths are unused. const std::string tmpfilename = std::string(tmpl) + temp_file_create_suffix; if (::access(tmpfilename.c_str(), F_OK) == -1 && errno == ENOENT) { filename = tmpl; break; } else { const int unlink_res = ::unlink(tmpl); EXPECT_EQ(0, unlink_res); } } } temp_file_t::~temp_file_t() { // Unlink both possible locations of the file. const int res1 = ::unlink(name().temporary_path().c_str()); EXPECT_TRUE(res1 == 0 || errno == ENOENT); const int res2 = ::unlink(name().permanent_path().c_str()); EXPECT_TRUE(res2 == 0 || errno == ENOENT); } serializer_filepath_t temp_file_t::name() const { return manual_serializer_filepath(filename, filename + temp_file_create_suffix); } void let_stuff_happen() { #ifdef VALGRIND nap(2000); #else nap(100); #endif } std::set<ip_address_t> get_unittest_addresses() { return get_local_ips(std::set<ip_address_t>(), false); } void run_in_thread_pool(const boost::function<void()>& fun, int num_workers) { ::run_in_thread_pool(fun, num_workers); } } // namespace unittest <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "supservs.hxx" #include <com/sun/star/lang/Locale.hpp> #include <comphelper/sharedmutex.hxx> #include <cppuhelper/supportsservice.hxx> #include <cppuhelper/queryinterface.hxx> #include <i18nlangtag/mslangid.hxx> #include <tools/debug.hxx> #include <osl/mutex.hxx> #include <osl/diagnose.h> #include <tools/stream.hxx> #include <svl/instrm.hxx> #include <registerservices.hxx> #include <strmadpt.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::io; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::util; using namespace ::utl; Reference< XInterface > SAL_CALL SvNumberFormatsSupplierServiceObject_CreateInstance(const Reference< XMultiServiceFactory >& _rxFactory) { return static_cast< ::cppu::OWeakObject* >(new SvNumberFormatsSupplierServiceObject( comphelper::getComponentContext(_rxFactory) )); } SvNumberFormatsSupplierServiceObject::SvNumberFormatsSupplierServiceObject(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxORB) :m_pOwnFormatter(NULL) ,m_xORB(_rxORB) { } SvNumberFormatsSupplierServiceObject::~SvNumberFormatsSupplierServiceObject() { if (m_pOwnFormatter) { delete m_pOwnFormatter; m_pOwnFormatter = NULL; } } Any SAL_CALL SvNumberFormatsSupplierServiceObject::queryAggregation( const Type& _rType ) throw (RuntimeException, std::exception) { Any aReturn = ::cppu::queryInterface(_rType, static_cast< XInitialization* >(this), static_cast< XServiceInfo* >(this) ); if (!aReturn.hasValue()) aReturn = SvNumberFormatsSupplierObj::queryAggregation(_rType); return aReturn; } void SAL_CALL SvNumberFormatsSupplierServiceObject::initialize( const Sequence< Any >& _rArguments ) throw(Exception, RuntimeException, std::exception) { ::osl::MutexGuard aGuard( getSharedMutex() ); DBG_ASSERT(m_pOwnFormatter == NULL, "SvNumberFormatsSupplierServiceObject::initialize : already initialized !"); // maybe you already called a method which needed the formatter // you should use XMultiServiceFactory::createInstanceWithArguments to avoid that if (m_pOwnFormatter) { // !!! this is only a emergency handling, normally this should not occur !!! delete m_pOwnFormatter; m_pOwnFormatter = NULL; SetNumberFormatter(m_pOwnFormatter); } Type aExpectedArgType = ::cppu::UnoType<Locale>::get(); LanguageType eNewFormatterLanguage = LANGUAGE_ENGLISH_US; // the default const Any* pArgs = _rArguments.getConstArray(); for (sal_Int32 i=0; i<_rArguments.getLength(); ++i, ++pArgs) { if (pArgs->getValueType().equals(aExpectedArgType)) { Locale aLocale; *pArgs >>= aLocale; eNewFormatterLanguage = LanguageTag::convertToLanguageType( aLocale, false); } #ifdef DBG_UTIL else { OSL_FAIL("SvNumberFormatsSupplierServiceObject::initialize : unknown argument !"); } #endif } m_pOwnFormatter = new SvNumberFormatter( m_xORB, eNewFormatterLanguage); m_pOwnFormatter->SetEvalDateFormat( NF_EVALDATEFORMAT_FORMAT_INTL ); SetNumberFormatter(m_pOwnFormatter); } OUString SAL_CALL SvNumberFormatsSupplierServiceObject::getImplementationName( ) throw(RuntimeException, std::exception) { return OUString("com.sun.star.uno.util.numbers.SvNumberFormatsSupplierServiceObject"); } sal_Bool SAL_CALL SvNumberFormatsSupplierServiceObject::supportsService( const OUString& _rServiceName ) throw(RuntimeException, std::exception) { return cppu::supportsService(this, _rServiceName); } Sequence< OUString > SAL_CALL SvNumberFormatsSupplierServiceObject::getSupportedServiceNames( ) throw(RuntimeException, std::exception) { Sequence< OUString > aSupported(1); aSupported.getArray()[0] = "com.sun.star.util.NumberFormatsSupplier"; return aSupported; } Reference< XPropertySet > SAL_CALL SvNumberFormatsSupplierServiceObject::getNumberFormatSettings() throw(RuntimeException, std::exception) { ::osl::MutexGuard aGuard( getSharedMutex() ); implEnsureFormatter(); return SvNumberFormatsSupplierObj::getNumberFormatSettings(); } Reference< XNumberFormats > SAL_CALL SvNumberFormatsSupplierServiceObject::getNumberFormats() throw(RuntimeException, std::exception) { ::osl::MutexGuard aGuard( getSharedMutex() ); implEnsureFormatter(); return SvNumberFormatsSupplierObj::getNumberFormats(); } sal_Int64 SAL_CALL SvNumberFormatsSupplierServiceObject::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw (RuntimeException, std::exception) { sal_Int64 nReturn = SvNumberFormatsSupplierObj::getSomething( aIdentifier ); if ( nReturn ) // if somebody accesses internals then we should have the formatter implEnsureFormatter(); return nReturn; } void SvNumberFormatsSupplierServiceObject::implEnsureFormatter() { if (!m_pOwnFormatter) { // get the office's UI locale SvtSysLocale aSysLocale; Locale aOfficeLocale = aSysLocale.GetLocaleData().getLanguageTag().getLocale(); // initi with this locale Sequence< Any > aFakedInitProps( 1 ); aFakedInitProps[0] <<= aOfficeLocale; initialize( aFakedInitProps ); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>yet another Windows build fix<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "supservs.hxx" #include <com/sun/star/lang/Locale.hpp> #include <comphelper/sharedmutex.hxx> #include <cppuhelper/supportsservice.hxx> #include <cppuhelper/queryinterface.hxx> #include <i18nlangtag/mslangid.hxx> #include <tools/debug.hxx> #include <osl/mutex.hxx> #include <osl/diagnose.h> #include <tools/stream.hxx> #include <svl/instrm.hxx> #include <registerservices.hxx> #include <strmadpt.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::io; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::util; using namespace ::utl; Reference< XInterface > SAL_CALL SvNumberFormatsSupplierServiceObject_CreateInstance(const Reference< XMultiServiceFactory >& _rxFactory) { return static_cast< ::cppu::OWeakObject* >(new SvNumberFormatsSupplierServiceObject( comphelper::getComponentContext(_rxFactory) )); } SvNumberFormatsSupplierServiceObject::SvNumberFormatsSupplierServiceObject(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxORB) :m_pOwnFormatter(NULL) ,m_xORB(_rxORB) { } SvNumberFormatsSupplierServiceObject::~SvNumberFormatsSupplierServiceObject() { if (m_pOwnFormatter) { delete m_pOwnFormatter; m_pOwnFormatter = NULL; } } Any SAL_CALL SvNumberFormatsSupplierServiceObject::queryAggregation( const Type& _rType ) throw (RuntimeException, std::exception) { Any aReturn = ::cppu::queryInterface(_rType, static_cast< XInitialization* >(this), static_cast< XServiceInfo* >(this) ); if (!aReturn.hasValue()) aReturn = SvNumberFormatsSupplierObj::queryAggregation(_rType); return aReturn; } void SAL_CALL SvNumberFormatsSupplierServiceObject::initialize( const Sequence< Any >& _rArguments ) throw(Exception, RuntimeException, std::exception) { ::osl::MutexGuard aGuard( getSharedMutex() ); DBG_ASSERT(m_pOwnFormatter == NULL, "SvNumberFormatsSupplierServiceObject::initialize : already initialized !"); // maybe you already called a method which needed the formatter // you should use XMultiServiceFactory::createInstanceWithArguments to avoid that if (m_pOwnFormatter) { // !!! this is only a emergency handling, normally this should not occur !!! delete m_pOwnFormatter; m_pOwnFormatter = NULL; SetNumberFormatter(m_pOwnFormatter); } Type aExpectedArgType = ::cppu::UnoType<css::lang::Locale>::get(); LanguageType eNewFormatterLanguage = LANGUAGE_ENGLISH_US; // the default const Any* pArgs = _rArguments.getConstArray(); for (sal_Int32 i=0; i<_rArguments.getLength(); ++i, ++pArgs) { if (pArgs->getValueType().equals(aExpectedArgType)) { css::lang::Locale aLocale; *pArgs >>= aLocale; eNewFormatterLanguage = LanguageTag::convertToLanguageType( aLocale, false); } #ifdef DBG_UTIL else { OSL_FAIL("SvNumberFormatsSupplierServiceObject::initialize : unknown argument !"); } #endif } m_pOwnFormatter = new SvNumberFormatter( m_xORB, eNewFormatterLanguage); m_pOwnFormatter->SetEvalDateFormat( NF_EVALDATEFORMAT_FORMAT_INTL ); SetNumberFormatter(m_pOwnFormatter); } OUString SAL_CALL SvNumberFormatsSupplierServiceObject::getImplementationName( ) throw(RuntimeException, std::exception) { return OUString("com.sun.star.uno.util.numbers.SvNumberFormatsSupplierServiceObject"); } sal_Bool SAL_CALL SvNumberFormatsSupplierServiceObject::supportsService( const OUString& _rServiceName ) throw(RuntimeException, std::exception) { return cppu::supportsService(this, _rServiceName); } Sequence< OUString > SAL_CALL SvNumberFormatsSupplierServiceObject::getSupportedServiceNames( ) throw(RuntimeException, std::exception) { Sequence< OUString > aSupported(1); aSupported.getArray()[0] = "com.sun.star.util.NumberFormatsSupplier"; return aSupported; } Reference< XPropertySet > SAL_CALL SvNumberFormatsSupplierServiceObject::getNumberFormatSettings() throw(RuntimeException, std::exception) { ::osl::MutexGuard aGuard( getSharedMutex() ); implEnsureFormatter(); return SvNumberFormatsSupplierObj::getNumberFormatSettings(); } Reference< XNumberFormats > SAL_CALL SvNumberFormatsSupplierServiceObject::getNumberFormats() throw(RuntimeException, std::exception) { ::osl::MutexGuard aGuard( getSharedMutex() ); implEnsureFormatter(); return SvNumberFormatsSupplierObj::getNumberFormats(); } sal_Int64 SAL_CALL SvNumberFormatsSupplierServiceObject::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw (RuntimeException, std::exception) { sal_Int64 nReturn = SvNumberFormatsSupplierObj::getSomething( aIdentifier ); if ( nReturn ) // if somebody accesses internals then we should have the formatter implEnsureFormatter(); return nReturn; } void SvNumberFormatsSupplierServiceObject::implEnsureFormatter() { if (!m_pOwnFormatter) { // get the office's UI locale SvtSysLocale aSysLocale; css::lang::Locale aOfficeLocale = aSysLocale.GetLocaleData().getLanguageTag().getLocale(); // initi with this locale Sequence< Any > aFakedInitProps( 1 ); aFakedInitProps[0] <<= aOfficeLocale; initialize( aFakedInitProps ); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "lua.hpp" #include <osg/MatrixTransform> #include "osgLuaBinding.h" osg::Node* swig_lua_toOsgNode(lua_State* L, int index); osg::Node* lua_toOsgNode(lua_State *L, int index) { osg::ref_ptr<osg::Node> node = swig_lua_toOsgNode(L, index); if (!node && lua_istable(L, index) && lua_checkstack(L, 2)) { osg::ref_ptr<osg::Group> group = new osg::Group; lua_pushnil(L); /* first key */ int tableIndex = index >= 0 ? index : index-1; while (lua_next(L, tableIndex) != 0) { osg::ref_ptr<osg::Node> tableNode = lua_toOsgNode(L, -1); if (tableNode.valid()) { osg::ref_ptr<osg::Group> indexNode = lua_toOsgMatrixTransform(L, -2); if (indexNode.valid()) { indexNode->addChild(tableNode); tableNode = indexNode; } group->addChild(tableNode); } lua_pop(L, 1); } if (group->getNumChildren() == 1) { node = group->getChild(0); } else if (group->getNumChildren() > 0) { node = group; } } return node.release(); } osg::Group* lua_toOsgMatrixTransform(lua_State *L, int index) { if(lua_istable(L, index)) { osg::Vec3 vec3 = lua_toOsgVec3(L, index); if (vec3.valid()) { osg::Matrix matrix; matrix.setTrans(vec3); osg::ref_ptr<osg::MatrixTransform> matrixTransform = new osg::MatrixTransform(matrix); return matrixTransform.release(); } } return 0; } template <class V> const V lua_toOsgVec(lua_State *L, int index, char firstComponentName) { V vec; if (lua_istable(L, index) && lua_checkstack(L, 2)) { unsigned int vecComponentMask = 0; const unsigned int vecComponentCompleteMask = (1 << vec.num_components) - 1; lua_pushnil(L); /* first key */ int tableIndex = index >= 0 ? index : index-1; while (lua_next(L, tableIndex) != 0) { int vecComponentPos = -1; if (lua_isnumber(L, -2)) { vecComponentPos = lua_tonumber(L, -2) - 1; } else if(lua_isstring(L, -2) && lua_objlen(L, -2) == 1) { vecComponentPos = lua_tostring(L, -2)[0] - firstComponentName; } if (vecComponentPos >= 0 && vecComponentPos < vec.num_components) { vecComponentMask |= 1 << vecComponentPos; if (lua_isnumber(L, -1)) { vec[vecComponentPos] = lua_tonumber(L, -1); } else { vec[vecComponentPos] = NAN; } } lua_pop(L, 1); if (vecComponentMask == vecComponentCompleteMask) { lua_pop(L, 1); break; } } } else { vec[0] = NAN; } return vec; } <commit_msg>adding inline fonction to decrement lua stack index<commit_after>#include "lua.hpp" #include <osg/MatrixTransform> #include "osgLuaBinding.h" static inline int lua_decrement(int index) { return index < 0 && index > LUA_REGISTRYINDEX ? index-1 : index; } osg::Node* swig_lua_toOsgNode(lua_State* L, int index); osg::Node* lua_toOsgNode(lua_State *L, int index) { osg::ref_ptr<osg::Node> node = swig_lua_toOsgNode(L, index); if (!node && lua_istable(L, index) && lua_checkstack(L, 2)) { osg::ref_ptr<osg::Group> group = new osg::Group; lua_pushnil(L); /* first key */ int tableIndex = lua_decrement(index); while (lua_next(L, tableIndex) != 0) { osg::ref_ptr<osg::Node> tableNode = lua_toOsgNode(L, -1); if (tableNode.valid()) { osg::ref_ptr<osg::Group> indexNode = lua_toOsgMatrixTransform(L, -2); if (indexNode.valid()) { indexNode->addChild(tableNode); tableNode = indexNode; } group->addChild(tableNode); } lua_pop(L, 1); } if (group->getNumChildren() == 1) { node = group->getChild(0); } else if (group->getNumChildren() > 0) { node = group; } } return node.release(); } osg::Group* lua_toOsgMatrixTransform(lua_State *L, int index) { if(lua_istable(L, index)) { osg::Vec3 vec3 = lua_toOsgVec3(L, index); if (vec3.valid()) { osg::Matrix matrix; matrix.setTrans(vec3); osg::ref_ptr<osg::MatrixTransform> matrixTransform = new osg::MatrixTransform(matrix); return matrixTransform.release(); } } return 0; } template <class V> const V lua_toOsgVec(lua_State *L, int index, char firstComponentName) { V vec; if (lua_istable(L, index) && lua_checkstack(L, 2)) { unsigned int vecComponentMask = 0; const unsigned int vecComponentCompleteMask = (1 << vec.num_components) - 1; lua_pushnil(L); /* first key */ int tableIndex = lua_decrement(index); while (lua_next(L, tableIndex) != 0) { int vecComponentPos = -1; if (lua_isnumber(L, -2)) { vecComponentPos = lua_tonumber(L, -2) - 1; } else if(lua_isstring(L, -2) && lua_objlen(L, -2) == 1) { vecComponentPos = lua_tostring(L, -2)[0] - firstComponentName; } if (vecComponentPos >= 0 && vecComponentPos < vec.num_components) { vecComponentMask |= 1 << vecComponentPos; if (lua_isnumber(L, -1)) { vec[vecComponentPos] = lua_tonumber(L, -1); } else { vec[vecComponentPos] = NAN; } } lua_pop(L, 1); if (vecComponentMask == vecComponentCompleteMask) { lua_pop(L, 1); break; } } } else { vec[0] = NAN; } return vec; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "NetworkStateNotifier.h" namespace WebCore { // Chromium doesn't currently support network state notifications. This causes // an extra DLL to get loaded into the renderer which can slow things down a // bit. We may want an alternate design. void NetworkStateNotifier::updateState() { } NetworkStateNotifier::NetworkStateNotifier() : m_isOnLine(true) { } } <commit_msg>Fix assert in debug. I had this change locally and forgot to include it in the CL that landed the merge. Fixes test_shell_tests crash as well.<commit_after>/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "NetworkStateNotifier.h" namespace WebCore { // Chromium doesn't currently support network state notifications. This causes // an extra DLL to get loaded into the renderer which can slow things down a // bit. We may want an alternate design. void NetworkStateNotifier::updateState() { } NetworkStateNotifier::NetworkStateNotifier() : m_isOnLine(true) , m_networkStateChangedFunction(0) { } } <|endoftext|>
<commit_before>#pragma once #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/version.hpp> #include "blackhole/error.hpp" #include "blackhole/factory.hpp" #include "blackhole/sink/files/rotation.hpp" namespace blackhole { namespace sink { class boost_backend_t { const boost::filesystem::path m_path; boost::filesystem::ofstream m_file; public: boost_backend_t(const std::string& path) : m_path(path) { } bool opened() const { return m_file.is_open(); } bool exists(const std::string& filename) const { return boost::filesystem::exists(m_path.parent_path() / filename); } std::vector<std::string> listdir() const { //!@todo: Implement me! return std::vector<std::string>(); } std::time_t changed(const std::string&) const { //!@todo: Implement me! return std::time(nullptr); } bool open() { if (!create_directories(m_path.parent_path())) { return false; } m_file.open(m_path, std::ios_base::out | std::ios_base::app); return m_file.is_open(); } void close() { m_file.close(); } void rename(const std::string& oldname, const std::string& newname) { const boost::filesystem::path& path = m_path.parent_path(); boost::filesystem::rename(path / oldname, path / newname); } std::string filename() const { #if BOOST_VERSION >= 104600 return m_path.filename().string(); #else return m_path.filename(); #endif } std::string path() const { return m_path.string(); } void write(const std::string& message) { m_file.write(message.data(), static_cast<std::streamsize>(message.size())); m_file.put('\n'); } void flush() { m_file.flush(); } private: template<typename Path> bool create_directories(const Path& path) { try { boost::filesystem::create_directories(path); } catch (const boost::filesystem::filesystem_error&) { return false; } return true; } }; namespace file { template<class Rotator = NoRotation> struct config_t { std::string path; bool autoflush; config_t(const std::string& path = "/dev/stdout", bool autoflush = true) : path(path), autoflush(autoflush) {} }; template<class Backend, class Watcher, class Timer> struct config_t<rotator_t<Backend, Watcher, Timer>> { std::string path; bool autoflush; rotation::config_t rotator; config_t(const std::string& path = "/dev/stdout", bool autoflush = true, const rotation::config_t& rotator = rotation::config_t()) : path(path), autoflush(autoflush), rotator(rotator) {} }; } // namespace file template<class Backend> class writer_t { Backend& backend; public: writer_t(Backend& backend) : backend(backend) {} void write(const std::string& message) { if (!backend.opened()) { if (!backend.open()) { throw error_t("failed to open file '%s' for writing", backend.path()); } } backend.write(message); } }; template<class Backend> class flusher_t { bool autoflush; Backend& backend; public: flusher_t(bool autoflush, Backend& backend) : autoflush(autoflush), backend(backend) {} void flush() { if (autoflush) { backend.flush(); } } }; template<class Backend = boost_backend_t, class Rotator = NoRotation, typename = void> class file_t; template<class Backend> class file_t<Backend, NoRotation, void> { Backend m_backend; writer_t<Backend> m_writer; flusher_t<Backend> m_flusher; public: typedef file::config_t<NoRotation> config_type; static const char* name() { return "files"; } file_t(const config_type& config) : m_backend(config.path), m_writer(m_backend), m_flusher(config.autoflush, m_backend) {} void consume(const std::string& message) { m_writer.write(message); m_flusher.flush(); } Backend& backend() { return m_backend; } }; //template<template<typename...> class T, template<typename...> class U> struct is_same : public std::false_type {}; //template<template<typename...> class T> struct is_same<T, T> : public std::true_type {}; template<class Backend, class Rotator> class file_t< Backend, Rotator, typename std::enable_if< !std::is_same<Rotator, NoRotation>::value >::type> { Backend m_backend; writer_t<Backend> m_writer; flusher_t<Backend> m_flusher; Rotator m_rotator; public: typedef file::config_t<Rotator> config_type; static const char* name() { return "files"; } file_t(const config_type& config) : m_backend(config.path), m_writer(m_backend), m_flusher(config.autoflush, m_backend), m_rotator(config.rotator, m_backend) {} void consume(const std::string& message) { m_writer.write(message); m_flusher.flush(); if (m_rotator.necessary()) { m_rotator.rotate(); } } Backend& backend() { return m_backend; } }; } // namespace sink namespace generator { const uint ROTATOR_POS = 2; //template<class Backend, class Rotator> //struct id<sink::file_t<Backend, Rotator>> { // static std::string extract(const boost::any& config) { // std::vector<boost::any> cfg; // aux::any_to(config, cfg); // std::string rotator; // if (cfg.size() > ROTATOR_POS && aux::is<std::vector<boost::any>>(cfg.at(ROTATOR_POS))) { // rotator += "/"; // rotator += Rotator::name(); // } // return utils::format("%s%s", sink::file_t<Backend, Rotator>::name(), rotator); // } //}; template<class Backend, class Watcher> struct id<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> { static std::string extract(const boost::any& config) { typedef sink::rotator_t<Backend, Watcher> rotator_type; std::vector<boost::any> cfg; aux::any_to(config, cfg); std::string rotator; if (cfg.size() > ROTATOR_POS && aux::is<std::vector<boost::any>>(cfg.at(ROTATOR_POS))) { rotator += "/"; rotator += rotator_type::name(); } return utils::format("%s%s", sink::file_t<Backend, rotator_type>::name(), rotator); } }; } // namespace generator template<class Backend> struct config_traits<sink::file_t<Backend, sink::NoRotation>> { static std::string name() { return sink::file_t<Backend, sink::NoRotation>::name(); } }; template<class Backend, class Rotator> struct config_traits<sink::file_t<Backend, Rotator>> { static std::string name() { return utils::format("%s/%s", sink::file_t<Backend, Rotator>::name(), Rotator::name()); } }; template<class Backend> struct factory_traits<sink::file_t<Backend>> { typedef typename sink::file_t<Backend>::config_type config_type; static config_type map_config(const boost::any& config) { config_type cfg; aux::vector_to(config, cfg.path, cfg.autoflush); return cfg; } }; template<class Backend, class Watcher> struct factory_traits<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> { typedef typename sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>::config_type config_type; static config_type map_config(const boost::any& config) { config_type cfg; std::vector<boost::any> rotator; aux::vector_to(config, cfg.path, cfg.autoflush, rotator); aux::vector_to(rotator, cfg.rotator.size, cfg.rotator.backups); return cfg; } }; } // namespace blackhole <commit_msg>Drop dead code.<commit_after>#pragma once #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/version.hpp> #include "blackhole/error.hpp" #include "blackhole/factory.hpp" #include "blackhole/sink/files/rotation.hpp" namespace blackhole { namespace sink { class boost_backend_t { const boost::filesystem::path m_path; boost::filesystem::ofstream m_file; public: boost_backend_t(const std::string& path) : m_path(path) { } bool opened() const { return m_file.is_open(); } bool exists(const std::string& filename) const { return boost::filesystem::exists(m_path.parent_path() / filename); } std::vector<std::string> listdir() const { //!@todo: Implement me! return std::vector<std::string>(); } std::time_t changed(const std::string&) const { //!@todo: Implement me! return std::time(nullptr); } bool open() { if (!create_directories(m_path.parent_path())) { return false; } m_file.open(m_path, std::ios_base::out | std::ios_base::app); return m_file.is_open(); } void close() { m_file.close(); } void rename(const std::string& oldname, const std::string& newname) { const boost::filesystem::path& path = m_path.parent_path(); boost::filesystem::rename(path / oldname, path / newname); } std::string filename() const { #if BOOST_VERSION >= 104600 return m_path.filename().string(); #else return m_path.filename(); #endif } std::string path() const { return m_path.string(); } void write(const std::string& message) { m_file.write(message.data(), static_cast<std::streamsize>(message.size())); m_file.put('\n'); } void flush() { m_file.flush(); } private: template<typename Path> bool create_directories(const Path& path) { try { boost::filesystem::create_directories(path); } catch (const boost::filesystem::filesystem_error&) { return false; } return true; } }; namespace file { template<class Rotator = NoRotation> struct config_t { std::string path; bool autoflush; config_t(const std::string& path = "/dev/stdout", bool autoflush = true) : path(path), autoflush(autoflush) {} }; template<class Backend, class Watcher, class Timer> struct config_t<rotator_t<Backend, Watcher, Timer>> { std::string path; bool autoflush; rotation::config_t rotator; config_t(const std::string& path = "/dev/stdout", bool autoflush = true, const rotation::config_t& rotator = rotation::config_t()) : path(path), autoflush(autoflush), rotator(rotator) {} }; } // namespace file template<class Backend> class writer_t { Backend& backend; public: writer_t(Backend& backend) : backend(backend) {} void write(const std::string& message) { if (!backend.opened()) { if (!backend.open()) { throw error_t("failed to open file '%s' for writing", backend.path()); } } backend.write(message); } }; template<class Backend> class flusher_t { bool autoflush; Backend& backend; public: flusher_t(bool autoflush, Backend& backend) : autoflush(autoflush), backend(backend) {} void flush() { if (autoflush) { backend.flush(); } } }; template<class Backend = boost_backend_t, class Rotator = NoRotation, typename = void> class file_t; template<class Backend> class file_t<Backend, NoRotation, void> { Backend m_backend; writer_t<Backend> m_writer; flusher_t<Backend> m_flusher; public: typedef file::config_t<NoRotation> config_type; static const char* name() { return "files"; } file_t(const config_type& config) : m_backend(config.path), m_writer(m_backend), m_flusher(config.autoflush, m_backend) {} void consume(const std::string& message) { m_writer.write(message); m_flusher.flush(); } Backend& backend() { return m_backend; } }; //template<template<typename...> class T, template<typename...> class U> struct is_same : public std::false_type {}; //template<template<typename...> class T> struct is_same<T, T> : public std::true_type {}; template<class Backend, class Rotator> class file_t< Backend, Rotator, typename std::enable_if< !std::is_same<Rotator, NoRotation>::value >::type> { Backend m_backend; writer_t<Backend> m_writer; flusher_t<Backend> m_flusher; Rotator m_rotator; public: typedef file::config_t<Rotator> config_type; static const char* name() { return "files"; } file_t(const config_type& config) : m_backend(config.path), m_writer(m_backend), m_flusher(config.autoflush, m_backend), m_rotator(config.rotator, m_backend) {} void consume(const std::string& message) { m_writer.write(message); m_flusher.flush(); if (m_rotator.necessary()) { m_rotator.rotate(); } } Backend& backend() { return m_backend; } }; } // namespace sink namespace generator { const uint ROTATOR_POS = 2; template<class Backend, class Watcher> struct id<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> { static std::string extract(const boost::any& config) { typedef sink::rotator_t<Backend, Watcher> rotator_type; std::vector<boost::any> cfg; aux::any_to(config, cfg); std::string rotator; if (cfg.size() > ROTATOR_POS && aux::is<std::vector<boost::any>>(cfg.at(ROTATOR_POS))) { rotator += "/"; rotator += rotator_type::name(); } return utils::format("%s%s", sink::file_t<Backend, rotator_type>::name(), rotator); } }; } // namespace generator template<class Backend> struct config_traits<sink::file_t<Backend, sink::NoRotation>> { static std::string name() { return sink::file_t<Backend, sink::NoRotation>::name(); } }; template<class Backend, class Rotator> struct config_traits<sink::file_t<Backend, Rotator>> { static std::string name() { return utils::format("%s/%s", sink::file_t<Backend, Rotator>::name(), Rotator::name()); } }; template<class Backend> struct factory_traits<sink::file_t<Backend>> { typedef typename sink::file_t<Backend>::config_type config_type; static config_type map_config(const boost::any& config) { config_type cfg; aux::vector_to(config, cfg.path, cfg.autoflush); return cfg; } }; template<class Backend, class Watcher> struct factory_traits<sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>> { typedef typename sink::file_t<Backend, sink::rotator_t<Backend, Watcher>>::config_type config_type; static config_type map_config(const boost::any& config) { config_type cfg; std::vector<boost::any> rotator; aux::vector_to(config, cfg.path, cfg.autoflush, rotator); aux::vector_to(rotator, cfg.rotator.size, cfg.rotator.backups); return cfg; } }; } // namespace blackhole <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2014 Ulrich von Zadow // // 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 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "DisplayEngine.h" #include "../avgconfigwrapper.h" #ifdef __APPLE__ #include "SDLMain.h" #endif #include "Event.h" #include "MouseEvent.h" #include "KeyEvent.h" #include "SDLWindow.h" #include "DisplayParams.h" #ifndef AVG_ENABLE_EGL #include "SecondaryWindow.h" #endif #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/ScopeTimer.h" #include "../base/TimeSource.h" #include "../graphics/Display.h" #include "../graphics/BitmapLoader.h" #include "../graphics/Bitmap.h" #include "../graphics/GLContext.h" #include "../video/VideoDecoder.h" #ifdef __APPLE__ #include <ApplicationServices/ApplicationServices.h> #endif #include <SDL/SDL.h> #ifdef __APPLE__ #include <OpenGL/OpenGL.h> #endif #ifdef AVG_ENABLE_XINERAMA #include <X11/extensions/Xinerama.h> #endif #include <signal.h> #include <iostream> #ifdef _WIN32 #include <windows.h> #endif using namespace std; namespace avg { void DisplayEngine::initSDL() { #ifdef __APPLE__ static bool bSDLInitialized = false; if (!bSDLInitialized) { CustomSDLMain(); bSDLInitialized = true; } #endif #ifdef __linux__ // Disable all other video drivers (DirectFB, libcaca, ...) to avoid confusing // error messages. SDL_putenv((char*)"SDL_VIDEODRIVER=x11"); #endif int err = SDL_InitSubSystem(SDL_INIT_VIDEO); if (err == -1) { throw Exception(AVG_ERR_VIDEO_INIT_FAILED, SDL_GetError()); } } void DisplayEngine::quitSDL() { SDL_QuitSubSystem(SDL_INIT_VIDEO); } DisplayEngine::DisplayEngine() : InputDevice("DisplayEngine"), m_Size(0,0), m_NumFrames(0), m_VBRate(0), m_Framerate(60), m_bInitialized(false), m_EffFramerate(0) { initSDL(); m_Gamma[0] = 1.0; m_Gamma[1] = 1.0; m_Gamma[2] = 1.0; } DisplayEngine::~DisplayEngine() { } void DisplayEngine::init(const DisplayParams& dp, GLConfig glConfig) { if (m_Gamma[0] != 1.0f || m_Gamma[1] != 1.0f || m_Gamma[2] != 1.0f) { internalSetGamma(1.0f, 1.0f, 1.0f); } m_pWindows.push_back(WindowPtr(new SDLWindow(dp, glConfig))); #ifndef AVG_ENABLE_EGL for (int i=1; i<dp.getNumWindows(); ++i) { m_pWindows.push_back(WindowPtr(new SecondaryWindow(dp.getWindowParams(i), dp.isFullscreen(), glConfig))); } #endif Display::get()->getRefreshRate(); setGamma(dp.getGamma(0), dp.getGamma(1), dp.getGamma(2)); showCursor(dp.isCursorVisible()); if (dp.getFramerate() == 0) { setVBlankRate(dp.getVBRate()); } else { setFramerate(dp.getFramerate()); } // SDL sets up a signal handler we really don't want. signal(SIGSEGV, SIG_DFL); VideoDecoder::logConfig(); SDL_EnableUNICODE(1); } void DisplayEngine::teardown() { m_pWindows.clear(); } void DisplayEngine::initRender() { m_NumFrames = 0; m_FramesTooLate = 0; m_TimeSpentWaiting = 0; m_StartTime = TimeSource::get()->getCurrentMicrosecs(); m_LastFrameTime = m_StartTime; m_bInitialized = true; if (m_VBRate != 0) { setVBlankRate(m_VBRate); } else { setFramerate(m_Framerate); } } void DisplayEngine::deinitRender() { AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, "Framerate statistics: "); AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Total frames: " <<m_NumFrames); float TotalTime = float(TimeSource::get()->getCurrentMicrosecs() -m_StartTime)/1000000; AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Total time: " << TotalTime << " seconds"); float actualFramerate = (m_NumFrames+1)/TotalTime; AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Framerate achieved: " << actualFramerate); AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Frames too late: " << m_FramesTooLate); AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Percent of time spent waiting: " << float (m_TimeSpentWaiting)/(10000*TotalTime)); if (m_Framerate != 0) { AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Framerate goal was: " << m_Framerate); if (m_Framerate*2 < actualFramerate && m_NumFrames > 10) { AVG_LOG_WARNING("Actual framerate was a lot higher than framerate goal.\ Is vblank sync forced off?"); } } m_bInitialized = false; } void DisplayEngine::setFramerate(float rate) { if (rate != 0 && m_bInitialized) { for (unsigned i=0; i<m_pWindows.size(); ++i) { GLContext* pContext = m_pWindows[i]->getGLContext(); pContext->activate(); pContext->initVBlank(0); } } m_Framerate = rate; m_VBRate = 0; } float DisplayEngine::getFramerate() { return m_Framerate; } float DisplayEngine::getEffectiveFramerate() { return m_EffFramerate; } void DisplayEngine::setVBlankRate(int rate) { m_VBRate = rate; if (m_bInitialized) { GLContext* pContext = m_pWindows[0]->getGLContext(); pContext->activate(); bool bOK = pContext->initVBlank(rate); m_Framerate = Display::get()->getRefreshRate()/m_VBRate; if (!bOK || rate == 0) { AVG_LOG_WARNING("Using framerate of " << m_Framerate << " instead of VBRate of " << m_VBRate); m_VBRate = 0; } } } bool DisplayEngine::wasFrameLate() { return m_bFrameLate; } void DisplayEngine::setGamma(float red, float green, float blue) { if (red > 0) { bool bOk = internalSetGamma(red, green, blue); m_Gamma[0] = red; m_Gamma[1] = green; m_Gamma[2] = blue; if (!bOk) { AVG_LOG_WARNING("Unable to set display gamma."); } } } void DisplayEngine::setMousePos(const IntPoint& pos) { SDL_WarpMouse(pos.x, pos.y); } int DisplayEngine::getKeyModifierState() const { return SDL_GetModState(); } void DisplayEngine::setWindowTitle(const string& sTitle) { SDL_WM_SetCaption(sTitle.c_str(), 0); } unsigned DisplayEngine::getNumWindows() const { return m_pWindows.size(); } const WindowPtr DisplayEngine::getWindow(unsigned i) const { return m_pWindows[i]; } SDLWindowPtr DisplayEngine::getSDLWindow() const { return boost::dynamic_pointer_cast<SDLWindow>(m_pWindows[0]); } static ProfilingZoneID WaitProfilingZone("Render - wait"); void DisplayEngine::frameWait() { ScopeTimer Timer(WaitProfilingZone); m_NumFrames++; m_FrameWaitStartTime = TimeSource::get()->getCurrentMicrosecs(); m_TargetTime = m_LastFrameTime+(long long)(1000000/m_Framerate); m_bFrameLate = false; if (m_VBRate == 0) { if (m_FrameWaitStartTime <= m_TargetTime) { long long WaitTime = (m_TargetTime-m_FrameWaitStartTime)/1000; if (WaitTime > 5000) { AVG_LOG_WARNING("DisplayEngine: waiting " << WaitTime << " ms."); } TimeSource::get()->sleepUntil(m_TargetTime/1000); } } } void DisplayEngine::swapBuffers() { for (unsigned i=0; i<m_pWindows.size(); ++i) { m_pWindows[i]->swapBuffers(); } } void DisplayEngine::checkJitter() { if (m_LastFrameTime == 0) { m_EffFramerate = 0; } else { long long curIntervalTime = TimeSource::get()->getCurrentMicrosecs() -m_LastFrameTime; m_EffFramerate = 1000000.0f/curIntervalTime; } long long frameTime = TimeSource::get()->getCurrentMicrosecs(); int maxDelay; if (m_VBRate == 0) { maxDelay = 2; } else { maxDelay = 6; } if ((frameTime - m_TargetTime)/1000 > maxDelay || m_bFrameLate) { m_bFrameLate = true; m_FramesTooLate++; } m_LastFrameTime = frameTime; m_TimeSpentWaiting += m_LastFrameTime-m_FrameWaitStartTime; // cerr << m_LastFrameTime << ", m_FrameWaitStartTime=" << m_FrameWaitStartTime << endl; // cerr << m_TimeSpentWaiting << endl; } long long DisplayEngine::getDisplayTime() { return (m_LastFrameTime-m_StartTime)/1000; } const IntPoint& DisplayEngine::getSize() const { return m_Size; } IntPoint DisplayEngine::getWindowSize() const { if (m_pWindows.empty()) { return IntPoint(0,0); } else { return m_pWindows[0]->getSize(); } } bool DisplayEngine::isFullscreen() const { AVG_ASSERT(!m_pWindows.empty()); return m_pWindows[0]->isFullscreen(); } void DisplayEngine::showCursor(bool bShow) { #ifdef _WIN32 #define MAX_CORE_POINTERS 6 // Hack to fix a pointer issue with fullscreen, SDL and touchscreens // Refer to Mantis bug #140 for (int i = 0; i < MAX_CORE_POINTERS; ++i) { ShowCursor(bShow); } #else if (bShow) { SDL_ShowCursor(SDL_ENABLE); } else { SDL_ShowCursor(SDL_DISABLE); } #endif } BitmapPtr DisplayEngine::screenshot(int buffer) { IntRect destRect; for (unsigned i=0; i != m_pWindows.size(); ++i) { IntRect winDims(m_pWindows[i]->getPos(), m_pWindows[i]->getPos()+m_pWindows[i]->getSize()); destRect.expand(winDims); } BitmapPtr pDestBmp = BitmapPtr(new Bitmap(destRect.size(), BitmapLoader::get()->getDefaultPixelFormat(false))); for (unsigned i=0; i != m_pWindows.size(); ++i) { BitmapPtr pWinBmp = m_pWindows[i]->screenshot(buffer); IntPoint pos = m_pWindows[i]->getPos() - destRect.tl; pDestBmp->blt(*pWinBmp, pos); } return pDestBmp; } vector<EventPtr> DisplayEngine::pollEvents() { vector<EventPtr> pEvents; for (unsigned i=0; i != m_pWindows.size(); ++i) { vector<EventPtr> pWinEvents = m_pWindows[i]->pollEvents(); pEvents.insert(pEvents.end(), pWinEvents.begin(), pWinEvents.end()); } return pEvents; } bool DisplayEngine::internalSetGamma(float red, float green, float blue) { #ifdef __APPLE__ // Workaround for broken SDL_SetGamma for libSDL 1.2.15 under Lion CGError err = CGSetDisplayTransferByFormula(kCGDirectMainDisplay, 0, 1, 1/red, 0, 1, 1/green, 0, 1, 1/blue); return (err == CGDisplayNoErr); #else int err = SDL_SetGamma(float(red), float(green), float(blue)); return (err != -1); #endif } } <commit_msg>Fixes dead member variable m_Size<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2014 Ulrich von Zadow // // 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 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "DisplayEngine.h" #include "../avgconfigwrapper.h" #ifdef __APPLE__ #include "SDLMain.h" #endif #include "Event.h" #include "MouseEvent.h" #include "KeyEvent.h" #include "SDLWindow.h" #include "DisplayParams.h" #ifndef AVG_ENABLE_EGL #include "SecondaryWindow.h" #endif #include "../base/Exception.h" #include "../base/Logger.h" #include "../base/ScopeTimer.h" #include "../base/TimeSource.h" #include "../graphics/Display.h" #include "../graphics/BitmapLoader.h" #include "../graphics/Bitmap.h" #include "../graphics/GLContext.h" #include "../video/VideoDecoder.h" #ifdef __APPLE__ #include <ApplicationServices/ApplicationServices.h> #endif #include <SDL/SDL.h> #ifdef __APPLE__ #include <OpenGL/OpenGL.h> #endif #ifdef AVG_ENABLE_XINERAMA #include <X11/extensions/Xinerama.h> #endif #include <signal.h> #include <iostream> #ifdef _WIN32 #include <windows.h> #endif using namespace std; namespace avg { void DisplayEngine::initSDL() { #ifdef __APPLE__ static bool bSDLInitialized = false; if (!bSDLInitialized) { CustomSDLMain(); bSDLInitialized = true; } #endif #ifdef __linux__ // Disable all other video drivers (DirectFB, libcaca, ...) to avoid confusing // error messages. SDL_putenv((char*)"SDL_VIDEODRIVER=x11"); #endif int err = SDL_InitSubSystem(SDL_INIT_VIDEO); if (err == -1) { throw Exception(AVG_ERR_VIDEO_INIT_FAILED, SDL_GetError()); } } void DisplayEngine::quitSDL() { SDL_QuitSubSystem(SDL_INIT_VIDEO); } DisplayEngine::DisplayEngine() : InputDevice("DisplayEngine"), m_Size(0,0), m_NumFrames(0), m_VBRate(0), m_Framerate(60), m_bInitialized(false), m_EffFramerate(0) { initSDL(); m_Gamma[0] = 1.0; m_Gamma[1] = 1.0; m_Gamma[2] = 1.0; } DisplayEngine::~DisplayEngine() { } void DisplayEngine::init(const DisplayParams& dp, GLConfig glConfig) { if (m_Gamma[0] != 1.0f || m_Gamma[1] != 1.0f || m_Gamma[2] != 1.0f) { internalSetGamma(1.0f, 1.0f, 1.0f); } m_pWindows.push_back(WindowPtr(new SDLWindow(dp, glConfig))); #ifndef AVG_ENABLE_EGL for (int i=1; i<dp.getNumWindows(); ++i) { m_pWindows.push_back(WindowPtr(new SecondaryWindow(dp.getWindowParams(i), dp.isFullscreen(), glConfig))); } #endif m_Size = dp.getWindowParams(0).m_Viewport.size(); Display::get()->getRefreshRate(); setGamma(dp.getGamma(0), dp.getGamma(1), dp.getGamma(2)); showCursor(dp.isCursorVisible()); if (dp.getFramerate() == 0) { setVBlankRate(dp.getVBRate()); } else { setFramerate(dp.getFramerate()); } // SDL sets up a signal handler we really don't want. signal(SIGSEGV, SIG_DFL); VideoDecoder::logConfig(); SDL_EnableUNICODE(1); } void DisplayEngine::teardown() { m_pWindows.clear(); } void DisplayEngine::initRender() { m_NumFrames = 0; m_FramesTooLate = 0; m_TimeSpentWaiting = 0; m_StartTime = TimeSource::get()->getCurrentMicrosecs(); m_LastFrameTime = m_StartTime; m_bInitialized = true; if (m_VBRate != 0) { setVBlankRate(m_VBRate); } else { setFramerate(m_Framerate); } } void DisplayEngine::deinitRender() { AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, "Framerate statistics: "); AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Total frames: " <<m_NumFrames); float TotalTime = float(TimeSource::get()->getCurrentMicrosecs() -m_StartTime)/1000000; AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Total time: " << TotalTime << " seconds"); float actualFramerate = (m_NumFrames+1)/TotalTime; AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Framerate achieved: " << actualFramerate); AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Frames too late: " << m_FramesTooLate); AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Percent of time spent waiting: " << float (m_TimeSpentWaiting)/(10000*TotalTime)); if (m_Framerate != 0) { AVG_TRACE(Logger::category::PROFILE, Logger::severity::INFO, " Framerate goal was: " << m_Framerate); if (m_Framerate*2 < actualFramerate && m_NumFrames > 10) { AVG_LOG_WARNING("Actual framerate was a lot higher than framerate goal.\ Is vblank sync forced off?"); } } m_bInitialized = false; } void DisplayEngine::setFramerate(float rate) { if (rate != 0 && m_bInitialized) { for (unsigned i=0; i<m_pWindows.size(); ++i) { GLContext* pContext = m_pWindows[i]->getGLContext(); pContext->activate(); pContext->initVBlank(0); } } m_Framerate = rate; m_VBRate = 0; } float DisplayEngine::getFramerate() { return m_Framerate; } float DisplayEngine::getEffectiveFramerate() { return m_EffFramerate; } void DisplayEngine::setVBlankRate(int rate) { m_VBRate = rate; if (m_bInitialized) { GLContext* pContext = m_pWindows[0]->getGLContext(); pContext->activate(); bool bOK = pContext->initVBlank(rate); m_Framerate = Display::get()->getRefreshRate()/m_VBRate; if (!bOK || rate == 0) { AVG_LOG_WARNING("Using framerate of " << m_Framerate << " instead of VBRate of " << m_VBRate); m_VBRate = 0; } } } bool DisplayEngine::wasFrameLate() { return m_bFrameLate; } void DisplayEngine::setGamma(float red, float green, float blue) { if (red > 0) { bool bOk = internalSetGamma(red, green, blue); m_Gamma[0] = red; m_Gamma[1] = green; m_Gamma[2] = blue; if (!bOk) { AVG_LOG_WARNING("Unable to set display gamma."); } } } void DisplayEngine::setMousePos(const IntPoint& pos) { SDL_WarpMouse(pos.x, pos.y); } int DisplayEngine::getKeyModifierState() const { return SDL_GetModState(); } void DisplayEngine::setWindowTitle(const string& sTitle) { SDL_WM_SetCaption(sTitle.c_str(), 0); } unsigned DisplayEngine::getNumWindows() const { return m_pWindows.size(); } const WindowPtr DisplayEngine::getWindow(unsigned i) const { return m_pWindows[i]; } SDLWindowPtr DisplayEngine::getSDLWindow() const { return boost::dynamic_pointer_cast<SDLWindow>(m_pWindows[0]); } static ProfilingZoneID WaitProfilingZone("Render - wait"); void DisplayEngine::frameWait() { ScopeTimer Timer(WaitProfilingZone); m_NumFrames++; m_FrameWaitStartTime = TimeSource::get()->getCurrentMicrosecs(); m_TargetTime = m_LastFrameTime+(long long)(1000000/m_Framerate); m_bFrameLate = false; if (m_VBRate == 0) { if (m_FrameWaitStartTime <= m_TargetTime) { long long WaitTime = (m_TargetTime-m_FrameWaitStartTime)/1000; if (WaitTime > 5000) { AVG_LOG_WARNING("DisplayEngine: waiting " << WaitTime << " ms."); } TimeSource::get()->sleepUntil(m_TargetTime/1000); } } } void DisplayEngine::swapBuffers() { for (unsigned i=0; i<m_pWindows.size(); ++i) { m_pWindows[i]->swapBuffers(); } } void DisplayEngine::checkJitter() { if (m_LastFrameTime == 0) { m_EffFramerate = 0; } else { long long curIntervalTime = TimeSource::get()->getCurrentMicrosecs() -m_LastFrameTime; m_EffFramerate = 1000000.0f/curIntervalTime; } long long frameTime = TimeSource::get()->getCurrentMicrosecs(); int maxDelay; if (m_VBRate == 0) { maxDelay = 2; } else { maxDelay = 6; } if ((frameTime - m_TargetTime)/1000 > maxDelay || m_bFrameLate) { m_bFrameLate = true; m_FramesTooLate++; } m_LastFrameTime = frameTime; m_TimeSpentWaiting += m_LastFrameTime-m_FrameWaitStartTime; // cerr << m_LastFrameTime << ", m_FrameWaitStartTime=" << m_FrameWaitStartTime << endl; // cerr << m_TimeSpentWaiting << endl; } long long DisplayEngine::getDisplayTime() { return (m_LastFrameTime-m_StartTime)/1000; } const IntPoint& DisplayEngine::getSize() const { return m_Size; } IntPoint DisplayEngine::getWindowSize() const { if (m_pWindows.empty()) { return IntPoint(0,0); } else { return m_pWindows[0]->getSize(); } } bool DisplayEngine::isFullscreen() const { AVG_ASSERT(!m_pWindows.empty()); return m_pWindows[0]->isFullscreen(); } void DisplayEngine::showCursor(bool bShow) { #ifdef _WIN32 #define MAX_CORE_POINTERS 6 // Hack to fix a pointer issue with fullscreen, SDL and touchscreens // Refer to Mantis bug #140 for (int i = 0; i < MAX_CORE_POINTERS; ++i) { ShowCursor(bShow); } #else if (bShow) { SDL_ShowCursor(SDL_ENABLE); } else { SDL_ShowCursor(SDL_DISABLE); } #endif } BitmapPtr DisplayEngine::screenshot(int buffer) { IntRect destRect; for (unsigned i=0; i != m_pWindows.size(); ++i) { IntRect winDims(m_pWindows[i]->getPos(), m_pWindows[i]->getPos()+m_pWindows[i]->getSize()); destRect.expand(winDims); } BitmapPtr pDestBmp = BitmapPtr(new Bitmap(destRect.size(), BitmapLoader::get()->getDefaultPixelFormat(false))); for (unsigned i=0; i != m_pWindows.size(); ++i) { BitmapPtr pWinBmp = m_pWindows[i]->screenshot(buffer); IntPoint pos = m_pWindows[i]->getPos() - destRect.tl; pDestBmp->blt(*pWinBmp, pos); } return pDestBmp; } vector<EventPtr> DisplayEngine::pollEvents() { vector<EventPtr> pEvents; for (unsigned i=0; i != m_pWindows.size(); ++i) { vector<EventPtr> pWinEvents = m_pWindows[i]->pollEvents(); pEvents.insert(pEvents.end(), pWinEvents.begin(), pWinEvents.end()); } return pEvents; } bool DisplayEngine::internalSetGamma(float red, float green, float blue) { #ifdef __APPLE__ // Workaround for broken SDL_SetGamma for libSDL 1.2.15 under Lion CGError err = CGSetDisplayTransferByFormula(kCGDirectMainDisplay, 0, 1, 1/red, 0, 1, 1/green, 0, 1, 1/blue); return (err == CGDisplayNoErr); #else int err = SDL_SetGamma(float(red), float(green), float(blue)); return (err != -1); #endif } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //testing headers #include <mitkTestingMacros.h> #include <mitkTestFixture.h> #include <mitkIOUtil.h> #include <mitkIGTException.h> #include <mitkNavigationToolStorageTestHelper.h> //headers of IGT classes releated to the tested class #include <mitkNavigationToolStorageSerializer.h> #include <Poco/Path.h> class mitkNavigationToolStorageSerializerTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkNavigationToolStorageSerializerTestSuite); MITK_TEST(TestInstantiationSerializer); MITK_TEST(TestWriteSimpleToolStorage); MITK_TEST(TestWriteComplexToolStorage); MITK_TEST(TestWriteStorageToInvalidFile); MITK_TEST(TestWriteEmptyToolStorage); MITK_TEST(TestSerializerForExceptions); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different test methods. All members are initialized via setUp().*/ std::string m_FileName1; mitk::NavigationToolStorageSerializer::Pointer m_Serializer; public: /**@brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members for a new test case. (If the members are not used in a test, the method does not need to be called).*/ void setUp() { try { m_FileName1 = mitk::IOUtil::CreateTemporaryFile(); std::ofstream file; file.open(m_FileName1.c_str()); if (!file.good()) {MITK_ERROR <<"Could not create a valid file during setUp() method.";} file.close(); } catch (std::exception& e) { MITK_ERROR << "File access Exception: " << e.what(); MITK_ERROR <<"Could not create filename during setUp() method."; } m_Serializer = mitk::NavigationToolStorageSerializer::New(); } void tearDown() { m_Serializer = NULL; try { std::remove(m_FileName1.c_str()); } catch(...) { MITK_ERROR << "Warning: Error occured when deleting test file!"; } } void TestInstantiationSerializer() { // let's create objects of our classes mitk::NavigationToolStorageSerializer::Pointer testSerializer = mitk::NavigationToolStorageSerializer::New(); CPPUNIT_ASSERT_MESSAGE("Testing instantiation of NavigationToolStorageSerializer",testSerializer.IsNotNull()); } void TestWriteSimpleToolStorage() { //create Tool Storage mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_SimpleStorage(); //test serialization bool success = m_Serializer->Serialize(m_FileName1,myStorage); CPPUNIT_ASSERT_MESSAGE("Testing serialization of simple tool storage",success); } void TestWriteComplexToolStorage() { //create navigation tool storage mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_ComplexStorage(GetTestDataFilePath("ClaronTool"),GetTestDataFilePath("IGT-Data/ClaronTool.stl"),GetTestDataFilePath("IGT-Data/EMTool.stl")); //test serialization bool success = m_Serializer->Serialize(m_FileName1,myStorage); CPPUNIT_ASSERT_MESSAGE("Testing serialization of complex tool storage",success); } void TestWriteStorageToInvalidFile() { //create Tool Storage mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_SimpleStorage(); //create invalid filename #ifdef WIN32 std::string filename = "C:\342INVALIDFILE<>.storage"; //invalid filename for windows #else std::string filename = "/dsfdsf:$�$342INVALIDFILE.storage"; //invalid filename for linux #endif //test serialization (should throw exception) CPPUNIT_ASSERT_THROW_MESSAGE("Test serialization with simple storage and invalid filename, an exception is expected.",m_Serializer->Serialize(filename,myStorage),mitk::IGTException); } void TestWriteEmptyToolStorage() { //create Tool Storage mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New(); //test serialization bool success = m_Serializer->Serialize(m_FileName1,myStorage); CPPUNIT_ASSERT_MESSAGE("Testing serialization of simple tool storage",success); } void TestSerializerForExceptions() { mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New(); //create an invalid filename std::string filename = std::string( MITK_TEST_OUTPUT_DIR )+Poco::Path::separator()+""; //now try to serialize an check if an exception is thrown CPPUNIT_ASSERT_THROW_MESSAGE("Test serialization with empty storage and invalid filename, an exception is expected.",m_Serializer->Serialize(filename,myStorage),mitk::IGTException); } }; MITK_TEST_SUITE_REGISTRATION(mitkNavigationToolStorageSerializer) <commit_msg>also changed name and path of the temporary file of the test<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //testing headers #include <mitkTestingMacros.h> #include <mitkTestFixture.h> #include <mitkIOUtil.h> #include <mitkIGTException.h> #include <mitkNavigationToolStorageTestHelper.h> //headers of IGT classes releated to the tested class #include <mitkNavigationToolStorageSerializer.h> #include <Poco/Path.h> class mitkNavigationToolStorageSerializerTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkNavigationToolStorageSerializerTestSuite); MITK_TEST(TestInstantiationSerializer); MITK_TEST(TestWriteSimpleToolStorage); MITK_TEST(TestWriteComplexToolStorage); MITK_TEST(TestWriteStorageToInvalidFile); MITK_TEST(TestWriteEmptyToolStorage); MITK_TEST(TestSerializerForExceptions); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different test methods. All members are initialized via setUp().*/ std::string m_FileName1; mitk::NavigationToolStorageSerializer::Pointer m_Serializer; public: /**@brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members for a new test case. (If the members are not used in a test, the method does not need to be called).*/ void setUp() { try { m_FileName1 = mitk::IOUtil::CreateTemporaryFile("NavigationToolStorageSerializerTestTmp_XXXXXX.IGTToolStorage",mitk::IOUtil::GetProgramPath()); std::ofstream file; file.open(m_FileName1.c_str()); if (!file.good()) {MITK_ERROR <<"Could not create a valid file during setUp() method.";} file.close(); } catch (std::exception& e) { MITK_ERROR << "File access Exception: " << e.what(); MITK_ERROR <<"Could not create filename during setUp() method."; } m_Serializer = mitk::NavigationToolStorageSerializer::New(); } void tearDown() { m_Serializer = NULL; try { std::remove(m_FileName1.c_str()); } catch(...) { MITK_ERROR << "Warning: Error occured when deleting test file!"; } } void TestInstantiationSerializer() { // let's create objects of our classes mitk::NavigationToolStorageSerializer::Pointer testSerializer = mitk::NavigationToolStorageSerializer::New(); CPPUNIT_ASSERT_MESSAGE("Testing instantiation of NavigationToolStorageSerializer",testSerializer.IsNotNull()); } void TestWriteSimpleToolStorage() { //create Tool Storage mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_SimpleStorage(); //test serialization bool success = m_Serializer->Serialize(m_FileName1,myStorage); CPPUNIT_ASSERT_MESSAGE("Testing serialization of simple tool storage",success); } void TestWriteComplexToolStorage() { //create navigation tool storage mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_ComplexStorage(GetTestDataFilePath("ClaronTool"),GetTestDataFilePath("IGT-Data/ClaronTool.stl"),GetTestDataFilePath("IGT-Data/EMTool.stl")); //test serialization bool success = m_Serializer->Serialize(m_FileName1,myStorage); CPPUNIT_ASSERT_MESSAGE("Testing serialization of complex tool storage",success); } void TestWriteStorageToInvalidFile() { //create Tool Storage mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorageTestHelper::CreateTestData_SimpleStorage(); //create invalid filename #ifdef WIN32 std::string filename = "C:\342INVALIDFILE<>.storage"; //invalid filename for windows #else std::string filename = "/dsfdsf:$�$342INVALIDFILE.storage"; //invalid filename for linux #endif //test serialization (should throw exception) CPPUNIT_ASSERT_THROW_MESSAGE("Test serialization with simple storage and invalid filename, an exception is expected.",m_Serializer->Serialize(filename,myStorage),mitk::IGTException); } void TestWriteEmptyToolStorage() { //create Tool Storage mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New(); //test serialization bool success = m_Serializer->Serialize(m_FileName1,myStorage); CPPUNIT_ASSERT_MESSAGE("Testing serialization of simple tool storage",success); } void TestSerializerForExceptions() { mitk::NavigationToolStorage::Pointer myStorage = mitk::NavigationToolStorage::New(); //create an invalid filename std::string filename = std::string( MITK_TEST_OUTPUT_DIR )+Poco::Path::separator()+""; //now try to serialize an check if an exception is thrown CPPUNIT_ASSERT_THROW_MESSAGE("Test serialization with empty storage and invalid filename, an exception is expected.",m_Serializer->Serialize(filename,myStorage),mitk::IGTException); } }; MITK_TEST_SUITE_REGISTRATION(mitkNavigationToolStorageSerializer) <|endoftext|>
<commit_before> #include <gtest/gtest.h> #include <iostream> #include <array> #include "geometry.hpp" #include "origin.hpp" #include "point.hpp" #include "vector.hpp" TEST(Line, ShiftOrigin) { static constexpr const int dim = 3; using fptype = float; const fptype eps = 1e-4; struct TestCase { std::array<fptype, dim> newOrigin; std::array<fptype, dim> origOffset; std::array<fptype, dim> dir; std::array<fptype, dim> expectedOffset; }; struct TestCase tests[] = { {{{0.0, 0.0, 0.0}}, {{0.0, 0.0, 0.0}}, {{0.0, 0.0, 1.0}}, {{0.0, 0.0, 0.0}}}, {{{0.0, 0.0, 0.0}}, {{1.0, 0.0, 0.0}}, {{0.0, 1.0, 1.0}}, {{1.0, 0.0, 0.0}}}, {{{2.0, 0.0, 0.0}}, {{1.0, 0.0, 0.0}}, {{0.0, 1.0, 1.0}}, {{-1.0, 0.0, 0.0}}}, {{{1.0, 0.0, 0.0}}, {{1.0, 0.0, 0.0}}, {{0.0, 1.0, 1.0}}, {{0.0, 0.0, 0.0}}}, {{{0.0, 0.0, 0.0}}, {{1.0, 1.0, 0.0}}, {{0.0, 1.0, 1.0}}, {{1.0, 0.5, -0.5}}}, }; Geometry::Origin<dim, fptype> defOrigin; for(auto t : tests) { Geometry::Point<dim, fptype> intersect( defOrigin, Geometry::Vector<dim, fptype>(t.origOffset)); Geometry::Vector<dim, fptype> dir( Geometry::Vector<dim, fptype>(t.dir).normalize()); Geometry::Line<dim, fptype> line(intersect, dir); Geometry::Origin<dim, fptype> o(t.newOrigin); line.shiftOrigin(o); Geometry::Vector<dim, fptype> newOff( line.getIntercept().getOffset()); for(unsigned i = 0; i < dim; i++) { EXPECT_NEAR(newOff(i), t.expectedOffset[i], eps); } } } <commit_msg>Added test for computing a point at a given distance along a line computation<commit_after> #include <gtest/gtest.h> #include <iostream> #include <array> #include "geometry.hpp" #include "origin.hpp" #include "point.hpp" #include "vector.hpp" TEST(Line, ShiftOrigin) { static constexpr const int dim = 3; using fptype = float; const fptype eps = 1e-4; struct TestCase { std::array<fptype, dim> newOrigin; std::array<fptype, dim> origOffset; std::array<fptype, dim> dir; std::array<fptype, dim> expectedOffset; }; struct TestCase tests[] = { {{{0.0, 0.0, 0.0}}, {{0.0, 0.0, 0.0}}, {{0.0, 0.0, 1.0}}, {{0.0, 0.0, 0.0}}}, {{{0.0, 0.0, 0.0}}, {{1.0, 0.0, 0.0}}, {{0.0, 1.0, 1.0}}, {{1.0, 0.0, 0.0}}}, {{{2.0, 0.0, 0.0}}, {{1.0, 0.0, 0.0}}, {{0.0, 1.0, 1.0}}, {{-1.0, 0.0, 0.0}}}, {{{1.0, 0.0, 0.0}}, {{1.0, 0.0, 0.0}}, {{0.0, 1.0, 1.0}}, {{0.0, 0.0, 0.0}}}, {{{0.0, 0.0, 0.0}}, {{1.0, 1.0, 0.0}}, {{0.0, 1.0, 1.0}}, {{1.0, 0.5, -0.5}}}, }; Geometry::Origin<dim, fptype> defOrigin; for(auto t : tests) { Geometry::Point<dim, fptype> intersect( defOrigin, Geometry::Vector<dim, fptype>(t.origOffset)); Geometry::Vector<dim, fptype> dir( Geometry::Vector<dim, fptype>(t.dir).normalize()); Geometry::Line<dim, fptype> line(intersect, dir); Geometry::Origin<dim, fptype> o(t.newOrigin); line.shiftOrigin(o); Geometry::Vector<dim, fptype> newOff( line.getIntercept().getOffset()); for(unsigned i = 0; i < dim; i++) { EXPECT_NEAR(newOff(i), t.expectedOffset[i], eps); } } } TEST(Line, CalcPointAtDistance) { static constexpr const int dim = 3; using fptype = float; const fptype eps = 1e-6; struct TestCase { fptype distance; std::array<fptype, dim> offset; std::array<fptype, dim> dir; std::array<fptype, dim> expected; }; struct TestCase tests[] = { {0.0, {{0.0, 0.0, 0.0}}, {{0.0, 0.0, 1.0}}, {{0.0, 0.0, 0.0}}}, {1.0, {{0.0, 0.0, 0.0}}, {{0.0, 0.0, 1.0}}, {{0.0, 0.0, 1.0}}}, {std::sqrt(2), {{0.0, 0.0, 0.0}}, {{1.0, 0.0, 1.0}}, {{1.0, 0.0, 1.0}}}, {3 * std::sqrt(2), {{0.0, 0.0, 0.0}}, {{1.0, 0.0, 1.0}}, {{3.0, 0.0, 3.0}}}, }; Geometry::Origin<dim, fptype> defOrigin; for(auto t : tests) { Geometry::Vector<dim, fptype> offset(t.offset); Geometry::Point<dim, fptype> intersect(defOrigin, offset); Geometry::Vector<dim, fptype> dir(t.dir); Geometry::Line<dim, fptype> line(intersect, dir); Geometry::Point<dim, fptype> pos = line.getPosAtDist(t.distance); Geometry::Vector<dim, fptype> off = pos.getOffset(); for(unsigned i = 0; i < dim; i++) { EXPECT_NEAR(off(i), t.expected[i], eps); } } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "dbmgr.hxx" #include <sfx2/app.hxx> #include <vcl/builder.hxx> #include <vcl/msgbox.hxx> #include <vcl/settings.hxx> #include <swwait.hxx> #include <viewopt.hxx> #include "wrtsh.hxx" #include "cmdid.h" #include "helpid.h" #include "envfmt.hxx" #include "envlop.hxx" #include "envprt.hxx" #include "fmtcol.hxx" #include "poolfmt.hxx" #include "view.hxx" #include <comphelper/processfactory.hxx> #include <comphelper/string.hxx> #include <unomid.h> using namespace ::com::sun::star::lang; using namespace ::com::sun::star::container; using namespace ::com::sun::star::uno; using namespace ::com::sun::star; using namespace ::rtl; //impl in envimg.cxx extern SW_DLLPUBLIC OUString MakeSender(); SwEnvPreview::SwEnvPreview(Window* pParent, WinBits nStyle) : Window(pParent, nStyle) { SetMapMode(MapMode(MAP_PIXEL)); } Size SwEnvPreview::GetOptimalSize() const { return LogicToPixel(Size(84 , 63), MAP_APPFONT); } extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeSwEnvPreview(Window *pParent, VclBuilder::stringmap &) { return new SwEnvPreview(pParent, 0); } void SwEnvPreview::DataChanged( const DataChangedEvent& rDCEvt ) { Window::DataChanged( rDCEvt ); if ( DATACHANGED_SETTINGS == rDCEvt.GetType() ) SetBackground( GetSettings().GetStyleSettings().GetDialogColor() ); } void SwEnvPreview::Paint(const Rectangle &) { const StyleSettings& rSettings = GetSettings().GetStyleSettings(); const SwEnvItem& rItem = ((SwEnvDlg*) GetParentDialog())->aEnvItem; const long nPageW = std::max(rItem.lWidth, rItem.lHeight); const long nPageH = std::min(rItem.lWidth, rItem.lHeight); const float f = 0.8 * std::min( static_cast<float>(GetOutputSizePixel().Width())/static_cast<float>(nPageW), static_cast<float>(GetOutputSizePixel().Height())/static_cast<float>(nPageH)); Color aBack = rSettings.GetWindowColor( ); Color aFront = SwViewOption::GetFontColor(); Color aMedium = Color( ( aBack.GetRed() + aFront.GetRed() ) / 2, ( aBack.GetGreen() + aFront.GetGreen() ) / 2, ( aBack.GetBlue() + aFront.GetBlue() ) / 2 ); SetLineColor( aFront ); // Envelope const long nW = static_cast<long>(f * nPageW); const long nH = static_cast<long>(f * nPageH); const long nX = (GetOutputSizePixel().Width () - nW) / 2; const long nY = (GetOutputSizePixel().Height() - nH) / 2; SetFillColor( aBack ); DrawRect(Rectangle(Point(nX, nY), Size(nW, nH))); // Sender if (rItem.bSend) { const long nSendX = nX + static_cast<long>(f * rItem.lSendFromLeft); const long nSendY = nY + static_cast<long>(f * rItem.lSendFromTop ); const long nSendW = static_cast<long>(f * (rItem.lAddrFromLeft - rItem.lSendFromLeft)); const long nSendH = static_cast<long>(f * (rItem.lAddrFromTop - rItem.lSendFromTop - 566)); SetFillColor( aMedium ); DrawRect(Rectangle(Point(nSendX, nSendY), Size(nSendW, nSendH))); } // Addressee const long nAddrX = nX + static_cast<long>(f * rItem.lAddrFromLeft); const long nAddrY = nY + static_cast<long>(f * rItem.lAddrFromTop ); const long nAddrW = static_cast<long>(f * (nPageW - rItem.lAddrFromLeft - 566)); const long nAddrH = static_cast<long>(f * (nPageH - rItem.lAddrFromTop - 566)); SetFillColor( aMedium ); DrawRect(Rectangle(Point(nAddrX, nAddrY), Size(nAddrW, nAddrH))); // Stamp const long nStmpW = static_cast<long>(f * 1417 /* 2,5 cm */); const long nStmpH = static_cast<long>(f * 1701 /* 3,0 cm */); const long nStmpX = nX + nW - static_cast<long>(f * 566) - nStmpW; const long nStmpY = nY + static_cast<long>(f * 566); SetFillColor( aBack ); DrawRect(Rectangle(Point(nStmpX, nStmpY), Size(nStmpW, nStmpH))); } SwEnvDlg::SwEnvDlg(Window* pParent, const SfxItemSet& rSet, SwWrtShell* pWrtSh, Printer* pPrt, sal_Bool bInsert) : SfxTabDialog(pParent, "EnvDialog", "modules/swriter/ui/envdialog.ui", &rSet) , aEnvItem((const SwEnvItem&) rSet.Get(FN_ENVELOP)) , pSh(pWrtSh) , pPrinter(pPrt) , pAddresseeSet(0) , pSenderSet(0) , m_nEnvPrintId(0) { if (!bInsert) { GetUserButton()->SetText(get<PushButton>("modify")->GetText()); } AddTabPage("envelope", SwEnvPage ::Create, 0); AddTabPage("format", SwEnvFmtPage::Create, 0); m_nEnvPrintId = AddTabPage("printer", SwEnvPrtPage::Create, 0); } SwEnvDlg::~SwEnvDlg() { delete pAddresseeSet; delete pSenderSet; } void SwEnvDlg::PageCreated(sal_uInt16 nId, SfxTabPage &rPage) { if (nId == m_nEnvPrintId) { ((SwEnvPrtPage*)&rPage)->SetPrt(pPrinter); } } short SwEnvDlg::Ok() { short nRet = SfxTabDialog::Ok(); if (nRet == RET_OK || nRet == RET_USER) { if (pAddresseeSet) { SwTxtFmtColl* pColl = pSh->GetTxtCollFromPool(RES_POOLCOLL_JAKETADRESS); pColl->SetFmtAttr(*pAddresseeSet); } if (pSenderSet) { SwTxtFmtColl* pColl = pSh->GetTxtCollFromPool(RES_POOLCOLL_SENDADRESS); pColl->SetFmtAttr(*pSenderSet); } } return nRet; } SwEnvPage::SwEnvPage(Window* pParent, const SfxItemSet& rSet) : SfxTabPage(pParent, "EnvAddressPage", "modules/swriter/ui/envaddresspage.ui", rSet) { get(m_pAddrEdit, "addredit"); get(m_pDatabaseLB, "database"); get(m_pTableLB, "table"); get(m_pDBFieldLB, "field"); get(m_pInsertBT, "insert"); get(m_pSenderBox, "sender"); get(m_pSenderEdit, "senderedit"); get(m_pPreview, "preview"); long nTextBoxHeight(m_pAddrEdit->GetTextHeight() * 10); long nTextBoxWidth(m_pAddrEdit->approximate_char_width() * 25); m_pAddrEdit->set_height_request(nTextBoxHeight); m_pAddrEdit->set_width_request(nTextBoxWidth); m_pSenderEdit->set_height_request(nTextBoxHeight); m_pSenderEdit->set_width_request(nTextBoxWidth); long nListBoxWidth = approximate_char_width() * 30; m_pTableLB->set_width_request(nListBoxWidth); m_pDatabaseLB->set_width_request(nListBoxWidth); m_pDBFieldLB->set_width_request(nListBoxWidth); SetExchangeSupport(); pSh = GetParentSwEnvDlg()->pSh; // Install handlers m_pDatabaseLB->SetSelectHdl(LINK(this, SwEnvPage, DatabaseHdl )); m_pTableLB->SetSelectHdl(LINK(this, SwEnvPage, DatabaseHdl )); m_pInsertBT->SetClickHdl (LINK(this, SwEnvPage, FieldHdl )); m_pSenderBox->SetClickHdl (LINK(this, SwEnvPage, SenderHdl )); m_pPreview->SetBorderStyle( WINDOW_BORDER_MONO ); SwDBData aData = pSh->GetDBData(); sActDBName = aData.sDataSource + OUString(DB_DELIM) + aData.sCommand; InitDatabaseBox(); } SwEnvPage::~SwEnvPage() { } IMPL_LINK( SwEnvPage, DatabaseHdl, ListBox *, pListBox ) { SwWait aWait( *pSh->GetView().GetDocShell(), true ); if (pListBox == m_pDatabaseLB) { sActDBName = pListBox->GetSelectEntry(); pSh->GetNewDBMgr()->GetTableNames(m_pTableLB, sActDBName); sActDBName += OUString(DB_DELIM); } else { sActDBName = comphelper::string::setToken(sActDBName, 1, DB_DELIM, m_pTableLB->GetSelectEntry()); } pSh->GetNewDBMgr()->GetColumnNames(m_pDBFieldLB, m_pDatabaseLB->GetSelectEntry(), m_pTableLB->GetSelectEntry()); return 0; } IMPL_LINK_NOARG(SwEnvPage, FieldHdl) { OUString aStr("<" + m_pDatabaseLB->GetSelectEntry() + "." + m_pTableLB->GetSelectEntry() + "." + OUString(m_pTableLB->GetEntryData(m_pTableLB->GetSelectEntryPos()) == 0 ? '0' : '1') + "." + m_pDBFieldLB->GetSelectEntry() + ">"); m_pAddrEdit->ReplaceSelected(aStr); Selection aSel = m_pAddrEdit->GetSelection(); m_pAddrEdit->GrabFocus(); m_pAddrEdit->SetSelection(aSel); return 0; } IMPL_LINK_NOARG(SwEnvPage, SenderHdl) { const sal_Bool bEnable = m_pSenderBox->IsChecked(); GetParentSwEnvDlg()->aEnvItem.bSend = bEnable; m_pSenderEdit->Enable(bEnable); if ( bEnable ) { m_pSenderEdit->GrabFocus(); if(m_pSenderEdit->GetText().isEmpty()) m_pSenderEdit->SetText(MakeSender()); } m_pPreview->Invalidate(); return 0; } void SwEnvPage::InitDatabaseBox() { if (pSh->GetNewDBMgr()) { m_pDatabaseLB->Clear(); Sequence<OUString> aDataNames = SwNewDBMgr::GetExistingDatabaseNames(); const OUString* pDataNames = aDataNames.getConstArray(); for (long i = 0; i < aDataNames.getLength(); i++) m_pDatabaseLB->InsertEntry(pDataNames[i]); OUString sDBName = sActDBName.getToken( 0, DB_DELIM ); OUString sTableName = sActDBName.getToken( 1, DB_DELIM ); m_pDatabaseLB->SelectEntry(sDBName); if (pSh->GetNewDBMgr()->GetTableNames(m_pTableLB, sDBName)) { m_pTableLB->SelectEntry(sTableName); pSh->GetNewDBMgr()->GetColumnNames(m_pDBFieldLB, sDBName, sTableName); } else m_pDBFieldLB->Clear(); } } SfxTabPage* SwEnvPage::Create(Window* pParent, const SfxItemSet& rSet) { return new SwEnvPage(pParent, rSet); } void SwEnvPage::ActivatePage(const SfxItemSet& rSet) { SfxItemSet aSet(rSet); aSet.Put(GetParentSwEnvDlg()->aEnvItem); Reset(aSet); } int SwEnvPage::DeactivatePage(SfxItemSet* _pSet) { FillItem(GetParentSwEnvDlg()->aEnvItem); if( _pSet ) FillItemSet(*_pSet); return SfxTabPage::LEAVE_PAGE; } void SwEnvPage::FillItem(SwEnvItem& rItem) { rItem.aAddrText = m_pAddrEdit->GetText(); rItem.bSend = m_pSenderBox->IsChecked(); rItem.aSendText = m_pSenderEdit->GetText(); } bool SwEnvPage::FillItemSet(SfxItemSet& rSet) { FillItem(GetParentSwEnvDlg()->aEnvItem); rSet.Put(GetParentSwEnvDlg()->aEnvItem); return true; } void SwEnvPage::Reset(const SfxItemSet& rSet) { SwEnvItem aItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP); m_pAddrEdit->SetText(convertLineEnd(aItem.aAddrText, GetSystemLineEnd())); m_pSenderEdit->SetText(convertLineEnd(aItem.aSendText, GetSystemLineEnd())); m_pSenderBox->Check (aItem.bSend); m_pSenderBox->GetClickHdl().Call(m_pSenderBox); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>long to sal_Int32 as index for Sequence<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "dbmgr.hxx" #include <sfx2/app.hxx> #include <vcl/builder.hxx> #include <vcl/msgbox.hxx> #include <vcl/settings.hxx> #include <swwait.hxx> #include <viewopt.hxx> #include "wrtsh.hxx" #include "cmdid.h" #include "helpid.h" #include "envfmt.hxx" #include "envlop.hxx" #include "envprt.hxx" #include "fmtcol.hxx" #include "poolfmt.hxx" #include "view.hxx" #include <comphelper/processfactory.hxx> #include <comphelper/string.hxx> #include <unomid.h> using namespace ::com::sun::star::lang; using namespace ::com::sun::star::container; using namespace ::com::sun::star::uno; using namespace ::com::sun::star; using namespace ::rtl; //impl in envimg.cxx extern SW_DLLPUBLIC OUString MakeSender(); SwEnvPreview::SwEnvPreview(Window* pParent, WinBits nStyle) : Window(pParent, nStyle) { SetMapMode(MapMode(MAP_PIXEL)); } Size SwEnvPreview::GetOptimalSize() const { return LogicToPixel(Size(84 , 63), MAP_APPFONT); } extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeSwEnvPreview(Window *pParent, VclBuilder::stringmap &) { return new SwEnvPreview(pParent, 0); } void SwEnvPreview::DataChanged( const DataChangedEvent& rDCEvt ) { Window::DataChanged( rDCEvt ); if ( DATACHANGED_SETTINGS == rDCEvt.GetType() ) SetBackground( GetSettings().GetStyleSettings().GetDialogColor() ); } void SwEnvPreview::Paint(const Rectangle &) { const StyleSettings& rSettings = GetSettings().GetStyleSettings(); const SwEnvItem& rItem = ((SwEnvDlg*) GetParentDialog())->aEnvItem; const long nPageW = std::max(rItem.lWidth, rItem.lHeight); const long nPageH = std::min(rItem.lWidth, rItem.lHeight); const float f = 0.8 * std::min( static_cast<float>(GetOutputSizePixel().Width())/static_cast<float>(nPageW), static_cast<float>(GetOutputSizePixel().Height())/static_cast<float>(nPageH)); Color aBack = rSettings.GetWindowColor( ); Color aFront = SwViewOption::GetFontColor(); Color aMedium = Color( ( aBack.GetRed() + aFront.GetRed() ) / 2, ( aBack.GetGreen() + aFront.GetGreen() ) / 2, ( aBack.GetBlue() + aFront.GetBlue() ) / 2 ); SetLineColor( aFront ); // Envelope const long nW = static_cast<long>(f * nPageW); const long nH = static_cast<long>(f * nPageH); const long nX = (GetOutputSizePixel().Width () - nW) / 2; const long nY = (GetOutputSizePixel().Height() - nH) / 2; SetFillColor( aBack ); DrawRect(Rectangle(Point(nX, nY), Size(nW, nH))); // Sender if (rItem.bSend) { const long nSendX = nX + static_cast<long>(f * rItem.lSendFromLeft); const long nSendY = nY + static_cast<long>(f * rItem.lSendFromTop ); const long nSendW = static_cast<long>(f * (rItem.lAddrFromLeft - rItem.lSendFromLeft)); const long nSendH = static_cast<long>(f * (rItem.lAddrFromTop - rItem.lSendFromTop - 566)); SetFillColor( aMedium ); DrawRect(Rectangle(Point(nSendX, nSendY), Size(nSendW, nSendH))); } // Addressee const long nAddrX = nX + static_cast<long>(f * rItem.lAddrFromLeft); const long nAddrY = nY + static_cast<long>(f * rItem.lAddrFromTop ); const long nAddrW = static_cast<long>(f * (nPageW - rItem.lAddrFromLeft - 566)); const long nAddrH = static_cast<long>(f * (nPageH - rItem.lAddrFromTop - 566)); SetFillColor( aMedium ); DrawRect(Rectangle(Point(nAddrX, nAddrY), Size(nAddrW, nAddrH))); // Stamp const long nStmpW = static_cast<long>(f * 1417 /* 2,5 cm */); const long nStmpH = static_cast<long>(f * 1701 /* 3,0 cm */); const long nStmpX = nX + nW - static_cast<long>(f * 566) - nStmpW; const long nStmpY = nY + static_cast<long>(f * 566); SetFillColor( aBack ); DrawRect(Rectangle(Point(nStmpX, nStmpY), Size(nStmpW, nStmpH))); } SwEnvDlg::SwEnvDlg(Window* pParent, const SfxItemSet& rSet, SwWrtShell* pWrtSh, Printer* pPrt, sal_Bool bInsert) : SfxTabDialog(pParent, "EnvDialog", "modules/swriter/ui/envdialog.ui", &rSet) , aEnvItem((const SwEnvItem&) rSet.Get(FN_ENVELOP)) , pSh(pWrtSh) , pPrinter(pPrt) , pAddresseeSet(0) , pSenderSet(0) , m_nEnvPrintId(0) { if (!bInsert) { GetUserButton()->SetText(get<PushButton>("modify")->GetText()); } AddTabPage("envelope", SwEnvPage ::Create, 0); AddTabPage("format", SwEnvFmtPage::Create, 0); m_nEnvPrintId = AddTabPage("printer", SwEnvPrtPage::Create, 0); } SwEnvDlg::~SwEnvDlg() { delete pAddresseeSet; delete pSenderSet; } void SwEnvDlg::PageCreated(sal_uInt16 nId, SfxTabPage &rPage) { if (nId == m_nEnvPrintId) { ((SwEnvPrtPage*)&rPage)->SetPrt(pPrinter); } } short SwEnvDlg::Ok() { short nRet = SfxTabDialog::Ok(); if (nRet == RET_OK || nRet == RET_USER) { if (pAddresseeSet) { SwTxtFmtColl* pColl = pSh->GetTxtCollFromPool(RES_POOLCOLL_JAKETADRESS); pColl->SetFmtAttr(*pAddresseeSet); } if (pSenderSet) { SwTxtFmtColl* pColl = pSh->GetTxtCollFromPool(RES_POOLCOLL_SENDADRESS); pColl->SetFmtAttr(*pSenderSet); } } return nRet; } SwEnvPage::SwEnvPage(Window* pParent, const SfxItemSet& rSet) : SfxTabPage(pParent, "EnvAddressPage", "modules/swriter/ui/envaddresspage.ui", rSet) { get(m_pAddrEdit, "addredit"); get(m_pDatabaseLB, "database"); get(m_pTableLB, "table"); get(m_pDBFieldLB, "field"); get(m_pInsertBT, "insert"); get(m_pSenderBox, "sender"); get(m_pSenderEdit, "senderedit"); get(m_pPreview, "preview"); long nTextBoxHeight(m_pAddrEdit->GetTextHeight() * 10); long nTextBoxWidth(m_pAddrEdit->approximate_char_width() * 25); m_pAddrEdit->set_height_request(nTextBoxHeight); m_pAddrEdit->set_width_request(nTextBoxWidth); m_pSenderEdit->set_height_request(nTextBoxHeight); m_pSenderEdit->set_width_request(nTextBoxWidth); long nListBoxWidth = approximate_char_width() * 30; m_pTableLB->set_width_request(nListBoxWidth); m_pDatabaseLB->set_width_request(nListBoxWidth); m_pDBFieldLB->set_width_request(nListBoxWidth); SetExchangeSupport(); pSh = GetParentSwEnvDlg()->pSh; // Install handlers m_pDatabaseLB->SetSelectHdl(LINK(this, SwEnvPage, DatabaseHdl )); m_pTableLB->SetSelectHdl(LINK(this, SwEnvPage, DatabaseHdl )); m_pInsertBT->SetClickHdl (LINK(this, SwEnvPage, FieldHdl )); m_pSenderBox->SetClickHdl (LINK(this, SwEnvPage, SenderHdl )); m_pPreview->SetBorderStyle( WINDOW_BORDER_MONO ); SwDBData aData = pSh->GetDBData(); sActDBName = aData.sDataSource + OUString(DB_DELIM) + aData.sCommand; InitDatabaseBox(); } SwEnvPage::~SwEnvPage() { } IMPL_LINK( SwEnvPage, DatabaseHdl, ListBox *, pListBox ) { SwWait aWait( *pSh->GetView().GetDocShell(), true ); if (pListBox == m_pDatabaseLB) { sActDBName = pListBox->GetSelectEntry(); pSh->GetNewDBMgr()->GetTableNames(m_pTableLB, sActDBName); sActDBName += OUString(DB_DELIM); } else { sActDBName = comphelper::string::setToken(sActDBName, 1, DB_DELIM, m_pTableLB->GetSelectEntry()); } pSh->GetNewDBMgr()->GetColumnNames(m_pDBFieldLB, m_pDatabaseLB->GetSelectEntry(), m_pTableLB->GetSelectEntry()); return 0; } IMPL_LINK_NOARG(SwEnvPage, FieldHdl) { OUString aStr("<" + m_pDatabaseLB->GetSelectEntry() + "." + m_pTableLB->GetSelectEntry() + "." + OUString(m_pTableLB->GetEntryData(m_pTableLB->GetSelectEntryPos()) == 0 ? '0' : '1') + "." + m_pDBFieldLB->GetSelectEntry() + ">"); m_pAddrEdit->ReplaceSelected(aStr); Selection aSel = m_pAddrEdit->GetSelection(); m_pAddrEdit->GrabFocus(); m_pAddrEdit->SetSelection(aSel); return 0; } IMPL_LINK_NOARG(SwEnvPage, SenderHdl) { const sal_Bool bEnable = m_pSenderBox->IsChecked(); GetParentSwEnvDlg()->aEnvItem.bSend = bEnable; m_pSenderEdit->Enable(bEnable); if ( bEnable ) { m_pSenderEdit->GrabFocus(); if(m_pSenderEdit->GetText().isEmpty()) m_pSenderEdit->SetText(MakeSender()); } m_pPreview->Invalidate(); return 0; } void SwEnvPage::InitDatabaseBox() { if (pSh->GetNewDBMgr()) { m_pDatabaseLB->Clear(); Sequence<OUString> aDataNames = SwNewDBMgr::GetExistingDatabaseNames(); const OUString* pDataNames = aDataNames.getConstArray(); for (sal_Int32 i = 0; i < aDataNames.getLength(); i++) m_pDatabaseLB->InsertEntry(pDataNames[i]); OUString sDBName = sActDBName.getToken( 0, DB_DELIM ); OUString sTableName = sActDBName.getToken( 1, DB_DELIM ); m_pDatabaseLB->SelectEntry(sDBName); if (pSh->GetNewDBMgr()->GetTableNames(m_pTableLB, sDBName)) { m_pTableLB->SelectEntry(sTableName); pSh->GetNewDBMgr()->GetColumnNames(m_pDBFieldLB, sDBName, sTableName); } else m_pDBFieldLB->Clear(); } } SfxTabPage* SwEnvPage::Create(Window* pParent, const SfxItemSet& rSet) { return new SwEnvPage(pParent, rSet); } void SwEnvPage::ActivatePage(const SfxItemSet& rSet) { SfxItemSet aSet(rSet); aSet.Put(GetParentSwEnvDlg()->aEnvItem); Reset(aSet); } int SwEnvPage::DeactivatePage(SfxItemSet* _pSet) { FillItem(GetParentSwEnvDlg()->aEnvItem); if( _pSet ) FillItemSet(*_pSet); return SfxTabPage::LEAVE_PAGE; } void SwEnvPage::FillItem(SwEnvItem& rItem) { rItem.aAddrText = m_pAddrEdit->GetText(); rItem.bSend = m_pSenderBox->IsChecked(); rItem.aSendText = m_pSenderEdit->GetText(); } bool SwEnvPage::FillItemSet(SfxItemSet& rSet) { FillItem(GetParentSwEnvDlg()->aEnvItem); rSet.Put(GetParentSwEnvDlg()->aEnvItem); return true; } void SwEnvPage::Reset(const SfxItemSet& rSet) { SwEnvItem aItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP); m_pAddrEdit->SetText(convertLineEnd(aItem.aAddrText, GetSystemLineEnd())); m_pSenderEdit->SetText(convertLineEnd(aItem.aSendText, GetSystemLineEnd())); m_pSenderBox->Check (aItem.bSend); m_pSenderBox->GetClickHdl().Call(m_pSenderBox); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #if !defined(CPPLINQ_LINQ_SELECT_HPP) #define CPPLINQ_LINQ_SELECT_HPP #pragma once namespace cpplinq { template <class Collection, class Selector> class linq_select { typedef typename Collection::cursor inner_cursor; public: struct cursor { typedef typename util::result_of<Selector(typename inner_cursor::element_type)>::type reference_type; typedef typename std::remove_reference<reference_type>::type element_type; typedef typename inner_cursor::cursor_category cursor_category; cursor(const inner_cursor& cur, Selector sel) : cur(cur), sel(std::move(sel)) {} void forget() { cur.forget(); } bool empty() const { return cur.empty(); } void inc() { cur.inc(); } reference_type get() const { return sel(cur.get()); } bool atbegin() const { return cur.atbegin(); } void dec() { cur.dec(); } void skip(size_t n) { cur.skip(n); } size_t position() const { return cur.position(); } size_t size() const { return cur.size(); } private: inner_cursor cur; Selector sel; }; linq_select(const Collection& c, Selector sel) : c(c), sel(sel) {} cursor get_cursor() const { return cursor(c.get_cursor(), sel); } private: Collection c; Selector sel; }; } #endif // defined(CPPLINQ_LINQ_SELECT_HPP) <commit_msg>Update linq_select.hpp<commit_after>// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #if !defined(CPPLINQ_LINQ_SELECT_HPP) #define CPPLINQ_LINQ_SELECT_HPP #pragma once #include <cstddef> namespace cpplinq { template <class Collection, class Selector> class linq_select { typedef typename Collection::cursor inner_cursor; public: struct cursor { typedef typename util::result_of<Selector(typename inner_cursor::element_type)>::type reference_type; typedef typename std::remove_reference<reference_type>::type element_type; typedef typename inner_cursor::cursor_category cursor_category; cursor(const inner_cursor& cur, Selector sel) : cur(cur), sel(std::move(sel)) {} void forget() { cur.forget(); } bool empty() const { return cur.empty(); } void inc() { cur.inc(); } reference_type get() const { return sel(cur.get()); } bool atbegin() const { return cur.atbegin(); } void dec() { cur.dec(); } void skip(std::size_t n) { cur.skip(n); } std::size_t position() const { return cur.position(); } std::size_t size() const { return cur.size(); } private: inner_cursor cur; Selector sel; }; linq_select(const Collection& c, Selector sel) : c(c), sel(sel) {} cursor get_cursor() const { return cursor(c.get_cursor(), sel); } private: Collection c; Selector sel; }; } #endif // defined(CPPLINQ_LINQ_SELECT_HPP) <|endoftext|>
<commit_before>// RaceDetector.cpp (Oclgrind) // Copyright (c) 2013-2015, James Price and Simon McIntosh-Smith, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "core/common.h" #include "core/Context.h" #include "core/KernelInvocation.h" #include "core/Memory.h" #include "core/WorkGroup.h" #include "core/WorkItem.h" #include "RaceDetector.h" using namespace oclgrind; using namespace std; THREAD_LOCAL RaceDetector::WorkerState RaceDetector::m_state = {NULL}; #define STATE(workgroup) ((*m_state.groups)[workgroup]) // Use a bank of mutexes to reduce unnecessary synchronisation #define NUM_GLOBAL_MUTEXES 4096 // Must be power of two #define GLOBAL_MUTEX(buffer,offset) \ m_globalMutexes[buffer][offset & (NUM_GLOBAL_MUTEXES-1)] RaceDetector::RaceDetector(const Context *context) : Plugin(context) { m_kernelInvocation = NULL; m_allowUniformWrites = !checkEnv("OCLGRIND_UNIFORM_WRITES"); } void RaceDetector::kernelBegin(const KernelInvocation *kernelInvocation) { m_kernelInvocation = kernelInvocation; } void RaceDetector::kernelEnd(const KernelInvocation *kernelInvocation) { // Clear all global memory accesses for (auto buffer = m_globalAccesses.begin(); buffer != m_globalAccesses.end(); buffer++) { size_t sz = buffer->second.size(); buffer->second.clear(); buffer->second.resize(sz); } m_kernelInvocation = NULL; } void RaceDetector::memoryAllocated(const Memory *memory, size_t address, size_t size, cl_mem_flags flags, const uint8_t *initData) { if (memory->getAddressSpace() == AddrSpaceGlobal) { m_globalAccesses[EXTRACT_BUFFER(address)].resize(size); m_globalMutexes[EXTRACT_BUFFER(address)] = new mutex[NUM_GLOBAL_MUTEXES]; } } void RaceDetector::memoryAtomicLoad(const Memory *memory, const WorkItem *workItem, AtomicOp op, size_t address, size_t size) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, true); } void RaceDetector::memoryAtomicStore(const Memory *memory, const WorkItem *workItem, AtomicOp op, size_t address, size_t size) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, true, (const uint8_t*)memory->getPointer(address)); } void RaceDetector::memoryDeallocated(const Memory *memory, size_t address) { if (memory->getAddressSpace() == AddrSpaceGlobal) { m_globalAccesses.erase(EXTRACT_BUFFER(address)); delete[] m_globalMutexes[EXTRACT_BUFFER(address)]; m_globalMutexes.erase(EXTRACT_BUFFER(address)); } } void RaceDetector::memoryLoad(const Memory *memory, const WorkItem *workItem, size_t address, size_t size) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, false, NULL); } void RaceDetector::memoryLoad(const Memory *memory, const WorkGroup *workGroup, size_t address, size_t size) { registerAccess(memory, workGroup, NULL, address, size, false); } void RaceDetector::memoryStore(const Memory *memory, const WorkItem *workItem, size_t address, size_t size, const uint8_t *storeData) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, false, storeData); } void RaceDetector::memoryStore(const Memory *memory, const WorkGroup *workGroup, size_t address, size_t size, const uint8_t *storeData) { registerAccess(memory, workGroup, NULL, address, size, false, storeData); } void RaceDetector::workGroupBarrier(const WorkGroup *workGroup, uint32_t flags) { if (flags & CLK_LOCAL_MEM_FENCE) { syncWorkItems(workGroup->getLocalMemory(), STATE(workGroup), STATE(workGroup).wiLocal); } if (flags & CLK_GLOBAL_MEM_FENCE) { syncWorkItems(m_context->getGlobalMemory(), STATE(workGroup), STATE(workGroup).wiGlobal); } } void RaceDetector::workGroupBegin(const WorkGroup *workGroup) { // Create worker state if haven't already if (!m_state.groups) { m_state.groups = new unordered_map<const WorkGroup*,WorkGroupState>; } // Initialize work-group state WorkGroupState& state = STATE(workGroup); Size3 wgsize = workGroup->getGroupSize(); state.numWorkItems = wgsize.x*wgsize.y*wgsize.z; state.wiGlobal.resize(state.numWorkItems+1); state.wiLocal.resize(state.numWorkItems+1); } void RaceDetector::workGroupComplete(const WorkGroup *workGroup) { WorkGroupState& state = STATE(workGroup); syncWorkItems(workGroup->getLocalMemory(), state, state.wiLocal); syncWorkItems(m_context->getGlobalMemory(), state, state.wiGlobal); // Merge global accesses across kernel invocation Size3 group = workGroup->getGroupID(); for (auto record = state.wgGlobal.begin(); record != state.wgGlobal.end(); record++) { size_t address = record->first; size_t buffer = EXTRACT_BUFFER(address); size_t offset = EXTRACT_OFFSET(address); lock_guard<mutex> lock(GLOBAL_MUTEX(buffer, offset)); AccessRecord& a = record->second; AccessRecord& b = m_globalAccesses[buffer][offset]; // Check for races with previous accesses if (getAccessWorkGroup(b.store) != group && check(a.load, b.store)) logRace(m_context->getGlobalMemory(), address, a.load, b.store); if (getAccessWorkGroup(b.load) != group && check(a.store, b.load)) logRace(m_context->getGlobalMemory(), address, a.store, b.load); if (getAccessWorkGroup(b.store) != group && check(a.store, b.store)) logRace(m_context->getGlobalMemory(), address, a.store, b.store); // Insert accesses if (a.load.isSet()) insert(b, a.load); if (a.store.isSet()) insert(b, a.store); } state.wgGlobal.clear(); // Clean-up work-group state m_state.groups->erase(workGroup); if (m_state.groups->empty()) { delete m_state.groups; m_state.groups = NULL; } } bool RaceDetector::check(const MemoryAccess& a, const MemoryAccess& b) const { // Ensure both accesses are valid if (!a.isSet() || !b.isSet()) return false; // No race if same work-item if (a.isWorkItem() && b.isWorkItem() && (a.getEntity() == b.getEntity())) return false; // No race if both operations are atomics if (a.isAtomic() && b.isAtomic()) return false; // Potential race if at least one store if (a.isStore() || b.isStore()) { // Read-write race if one is a load if (a.isLoad() || b.isLoad()) return true; // Write-write race if not uniform if (!m_allowUniformWrites || (a.getStoreData() != b.getStoreData())) return true; } return false; } Size3 RaceDetector::getAccessWorkGroup(const MemoryAccess& access) const { if (access.isWorkItem()) { Size3 wi(access.getEntity(), m_kernelInvocation->getGlobalSize()); Size3 wgsize = m_kernelInvocation->getLocalSize(); return Size3(wi.x/wgsize.x, wi.y/wgsize.y, wi.z/wgsize.z); } else { return Size3(access.getEntity(), m_kernelInvocation->getLocalSize()); } } void RaceDetector::insert(AccessRecord& record, const MemoryAccess& access) const { if (access.isLoad()) { if (!record.load.isSet() || record.load.isAtomic()) record.load = access; } else if (access.isStore()) { if (!record.store.isSet() || record.store.isAtomic()) record.store = access; } } void RaceDetector::logRace(const Memory *memory, size_t address, const MemoryAccess& first, const MemoryAccess& second) const { const char *raceType; if (first.isLoad() || second.isLoad()) raceType = "Read-write"; else raceType = "Write-write"; Context::Message msg(ERROR, m_context); msg << raceType << " data race at " << getAddressSpaceName(memory->getAddressSpace()) << " memory address 0x" << hex << address << endl << msg.INDENT << "Kernel: " << msg.CURRENT_KERNEL << endl << endl << "First entity: "; if (first.isWorkItem()) { Size3 wgsize = m_kernelInvocation->getLocalSize(); Size3 global(first.getEntity(), m_kernelInvocation->getGlobalSize()); Size3 local(global.x%wgsize.x, global.y%wgsize.y, global.z%wgsize.z); Size3 group(global.x/wgsize.x, global.y/wgsize.y, global.z/wgsize.z); msg << "Global" << global << " Local" << local << " Group" << group; } else { msg << "Group" << Size3(first.getEntity(), m_kernelInvocation->getLocalSize()); } msg << endl << first.getInstruction() << endl << endl << "Second entity: "; // Show details of other entity involved in race if (second.isWorkItem()) { Size3 wgsize = m_kernelInvocation->getLocalSize(); Size3 global(second.getEntity(), m_kernelInvocation->getGlobalSize()); Size3 local(global.x%wgsize.x, global.y%wgsize.y, global.z%wgsize.z); Size3 group(global.x/wgsize.x, global.y/wgsize.y, global.z/wgsize.z); msg << "Global" << global << " Local" << local << " Group" << group; } else { msg << "Group" << Size3(second.getEntity(), m_kernelInvocation->getLocalSize()); } msg << endl << second.getInstruction() << endl; msg.send(); } void RaceDetector::registerAccess(const Memory *memory, const WorkGroup *workGroup, const WorkItem *workItem, size_t address, size_t size, bool atomic, const uint8_t *storeData) { unsigned addrSpace = memory->getAddressSpace(); if (addrSpace == AddrSpacePrivate || addrSpace == AddrSpaceConstant) return; if (!memory->isAddressValid(address, size)) return; // Construct access MemoryAccess access(workGroup, workItem, storeData != NULL, atomic); size_t index; if (workItem) { Size3 wgsize = workGroup->getGroupSize(); Size3 lid = workItem->getLocalID(); index = lid.x + (lid.y + lid.z*wgsize.y)*wgsize.x; } else { index = STATE(workGroup).wiLocal.size() - 1; } AccessMap& accesess = (addrSpace == AddrSpaceGlobal) ? STATE(workGroup).wiGlobal[index] : STATE(workGroup).wiLocal[index]; for (size_t i = 0; i < size; i++) { if (storeData) access.setStoreData(storeData[i]); insert(accesess[address+i], access); } } void RaceDetector::syncWorkItems(const Memory *memory, WorkGroupState& state, vector<AccessMap>& accesses) { AccessMap wgAccesses; for (size_t i = 0; i < state.numWorkItems + 1; i++) { for (auto record = accesses[i].begin(); record != accesses[i].end(); record++) { size_t address = record->first; AccessRecord& a = record->second; AccessRecord& b = wgAccesses[address]; if (check(a.load, b.store)) logRace(memory, address, a.load, b.store); if (check(a.store, b.load)) logRace(memory, address, a.store, b.load); if (check(a.store, b.store)) logRace(memory, address, a.store, b.store); if (a.load.isSet()) { insert(b, a.load); if (memory->getAddressSpace() == AddrSpaceGlobal) insert(state.wgGlobal[address], a.load); } if (a.store.isSet()) { insert(b, a.store); if (memory->getAddressSpace() == AddrSpaceGlobal) insert(state.wgGlobal[address], a.store); } } accesses[i].clear(); } } RaceDetector::MemoryAccess::MemoryAccess() { this->info = 0; this->instruction = NULL; } RaceDetector::MemoryAccess::MemoryAccess(const WorkGroup *workGroup, const WorkItem *workItem, bool store, bool atomic) { this->info = 0; this->info |= 1 << SET_BIT; this->info |= store << STORE_BIT; this->info |= atomic << ATOMIC_BIT; if (workItem) { this->entity = workItem->getGlobalIndex(); this->instruction = workItem->getCurrentInstruction(); } else { this->info |= (1<<WG_BIT); this->entity = workGroup->getGroupIndex(); this->instruction = NULL; // TODO? } } void RaceDetector::MemoryAccess::clear() { this->info = 0; this->instruction = NULL; } bool RaceDetector::MemoryAccess::isSet() const { return this->info & (1<<SET_BIT); } bool RaceDetector::MemoryAccess::isAtomic() const { return this->info & (1<<ATOMIC_BIT); } bool RaceDetector::MemoryAccess::isLoad() const { return !isStore(); } bool RaceDetector::MemoryAccess::isStore() const { return this->info & (1<<STORE_BIT); } bool RaceDetector::MemoryAccess::isWorkGroup() const { return this->info & (1<<WG_BIT); } bool RaceDetector::MemoryAccess::isWorkItem() const { return !isWorkGroup(); } bool RaceDetector::MemoryAccess::hasWorkGroupSync() const { return this->info & (1<<WG_SYNC_BIT); } void RaceDetector::MemoryAccess::setWorkGroupSync() { this->info |= (1<<WG_SYNC_BIT); } size_t RaceDetector::MemoryAccess::getEntity() const { return this->entity; } const llvm::Instruction* RaceDetector::MemoryAccess::getInstruction() const { return this->instruction; } uint8_t RaceDetector::MemoryAccess::getStoreData() const { return this->storeData; } void RaceDetector::MemoryAccess::setStoreData(uint8_t data) { this->storeData = data; } <commit_msg>DRD: Reordered race vs same WG checks on global accesses.<commit_after>// RaceDetector.cpp (Oclgrind) // Copyright (c) 2013-2015, James Price and Simon McIntosh-Smith, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "core/common.h" #include "core/Context.h" #include "core/KernelInvocation.h" #include "core/Memory.h" #include "core/WorkGroup.h" #include "core/WorkItem.h" #include "RaceDetector.h" using namespace oclgrind; using namespace std; THREAD_LOCAL RaceDetector::WorkerState RaceDetector::m_state = {NULL}; #define STATE(workgroup) ((*m_state.groups)[workgroup]) // Use a bank of mutexes to reduce unnecessary synchronisation #define NUM_GLOBAL_MUTEXES 4096 // Must be power of two #define GLOBAL_MUTEX(buffer,offset) \ m_globalMutexes[buffer][offset & (NUM_GLOBAL_MUTEXES-1)] RaceDetector::RaceDetector(const Context *context) : Plugin(context) { m_kernelInvocation = NULL; m_allowUniformWrites = !checkEnv("OCLGRIND_UNIFORM_WRITES"); } void RaceDetector::kernelBegin(const KernelInvocation *kernelInvocation) { m_kernelInvocation = kernelInvocation; } void RaceDetector::kernelEnd(const KernelInvocation *kernelInvocation) { // Clear all global memory accesses for (auto buffer = m_globalAccesses.begin(); buffer != m_globalAccesses.end(); buffer++) { size_t sz = buffer->second.size(); buffer->second.clear(); buffer->second.resize(sz); } m_kernelInvocation = NULL; } void RaceDetector::memoryAllocated(const Memory *memory, size_t address, size_t size, cl_mem_flags flags, const uint8_t *initData) { if (memory->getAddressSpace() == AddrSpaceGlobal) { m_globalAccesses[EXTRACT_BUFFER(address)].resize(size); m_globalMutexes[EXTRACT_BUFFER(address)] = new mutex[NUM_GLOBAL_MUTEXES]; } } void RaceDetector::memoryAtomicLoad(const Memory *memory, const WorkItem *workItem, AtomicOp op, size_t address, size_t size) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, true); } void RaceDetector::memoryAtomicStore(const Memory *memory, const WorkItem *workItem, AtomicOp op, size_t address, size_t size) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, true, (const uint8_t*)memory->getPointer(address)); } void RaceDetector::memoryDeallocated(const Memory *memory, size_t address) { if (memory->getAddressSpace() == AddrSpaceGlobal) { m_globalAccesses.erase(EXTRACT_BUFFER(address)); delete[] m_globalMutexes[EXTRACT_BUFFER(address)]; m_globalMutexes.erase(EXTRACT_BUFFER(address)); } } void RaceDetector::memoryLoad(const Memory *memory, const WorkItem *workItem, size_t address, size_t size) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, false, NULL); } void RaceDetector::memoryLoad(const Memory *memory, const WorkGroup *workGroup, size_t address, size_t size) { registerAccess(memory, workGroup, NULL, address, size, false); } void RaceDetector::memoryStore(const Memory *memory, const WorkItem *workItem, size_t address, size_t size, const uint8_t *storeData) { registerAccess(memory, workItem->getWorkGroup(), workItem, address, size, false, storeData); } void RaceDetector::memoryStore(const Memory *memory, const WorkGroup *workGroup, size_t address, size_t size, const uint8_t *storeData) { registerAccess(memory, workGroup, NULL, address, size, false, storeData); } void RaceDetector::workGroupBarrier(const WorkGroup *workGroup, uint32_t flags) { if (flags & CLK_LOCAL_MEM_FENCE) { syncWorkItems(workGroup->getLocalMemory(), STATE(workGroup), STATE(workGroup).wiLocal); } if (flags & CLK_GLOBAL_MEM_FENCE) { syncWorkItems(m_context->getGlobalMemory(), STATE(workGroup), STATE(workGroup).wiGlobal); } } void RaceDetector::workGroupBegin(const WorkGroup *workGroup) { // Create worker state if haven't already if (!m_state.groups) { m_state.groups = new unordered_map<const WorkGroup*,WorkGroupState>; } // Initialize work-group state WorkGroupState& state = STATE(workGroup); Size3 wgsize = workGroup->getGroupSize(); state.numWorkItems = wgsize.x*wgsize.y*wgsize.z; state.wiGlobal.resize(state.numWorkItems+1); state.wiLocal.resize(state.numWorkItems+1); } void RaceDetector::workGroupComplete(const WorkGroup *workGroup) { WorkGroupState& state = STATE(workGroup); syncWorkItems(workGroup->getLocalMemory(), state, state.wiLocal); syncWorkItems(m_context->getGlobalMemory(), state, state.wiGlobal); // Merge global accesses across kernel invocation Size3 group = workGroup->getGroupID(); for (auto record = state.wgGlobal.begin(); record != state.wgGlobal.end(); record++) { size_t address = record->first; size_t buffer = EXTRACT_BUFFER(address); size_t offset = EXTRACT_OFFSET(address); lock_guard<mutex> lock(GLOBAL_MUTEX(buffer, offset)); AccessRecord& a = record->second; AccessRecord& b = m_globalAccesses[buffer][offset]; // Check for races with previous accesses if (check(a.load, b.store) && getAccessWorkGroup(b.store) != group) logRace(m_context->getGlobalMemory(), address, a.load, b.store); if (check(a.store, b.load) && getAccessWorkGroup(b.load) != group) logRace(m_context->getGlobalMemory(), address, a.store, b.load); if (check(a.store, b.store) && getAccessWorkGroup(b.store) != group) logRace(m_context->getGlobalMemory(), address, a.store, b.store); // Insert accesses if (a.load.isSet()) insert(b, a.load); if (a.store.isSet()) insert(b, a.store); } state.wgGlobal.clear(); // Clean-up work-group state m_state.groups->erase(workGroup); if (m_state.groups->empty()) { delete m_state.groups; m_state.groups = NULL; } } bool RaceDetector::check(const MemoryAccess& a, const MemoryAccess& b) const { // Ensure both accesses are valid if (!a.isSet() || !b.isSet()) return false; // No race if same work-item if (a.isWorkItem() && b.isWorkItem() && (a.getEntity() == b.getEntity())) return false; // No race if both operations are atomics if (a.isAtomic() && b.isAtomic()) return false; // Potential race if at least one store if (a.isStore() || b.isStore()) { // Read-write race if one is a load if (a.isLoad() || b.isLoad()) return true; // Write-write race if not uniform if (!m_allowUniformWrites || (a.getStoreData() != b.getStoreData())) return true; } return false; } Size3 RaceDetector::getAccessWorkGroup(const MemoryAccess& access) const { if (access.isWorkItem()) { Size3 wi(access.getEntity(), m_kernelInvocation->getGlobalSize()); Size3 wgsize = m_kernelInvocation->getLocalSize(); return Size3(wi.x/wgsize.x, wi.y/wgsize.y, wi.z/wgsize.z); } else { return Size3(access.getEntity(), m_kernelInvocation->getLocalSize()); } } void RaceDetector::insert(AccessRecord& record, const MemoryAccess& access) const { if (access.isLoad()) { if (!record.load.isSet() || record.load.isAtomic()) record.load = access; } else if (access.isStore()) { if (!record.store.isSet() || record.store.isAtomic()) record.store = access; } } void RaceDetector::logRace(const Memory *memory, size_t address, const MemoryAccess& first, const MemoryAccess& second) const { const char *raceType; if (first.isLoad() || second.isLoad()) raceType = "Read-write"; else raceType = "Write-write"; Context::Message msg(ERROR, m_context); msg << raceType << " data race at " << getAddressSpaceName(memory->getAddressSpace()) << " memory address 0x" << hex << address << endl << msg.INDENT << "Kernel: " << msg.CURRENT_KERNEL << endl << endl << "First entity: "; if (first.isWorkItem()) { Size3 wgsize = m_kernelInvocation->getLocalSize(); Size3 global(first.getEntity(), m_kernelInvocation->getGlobalSize()); Size3 local(global.x%wgsize.x, global.y%wgsize.y, global.z%wgsize.z); Size3 group(global.x/wgsize.x, global.y/wgsize.y, global.z/wgsize.z); msg << "Global" << global << " Local" << local << " Group" << group; } else { msg << "Group" << Size3(first.getEntity(), m_kernelInvocation->getLocalSize()); } msg << endl << first.getInstruction() << endl << endl << "Second entity: "; // Show details of other entity involved in race if (second.isWorkItem()) { Size3 wgsize = m_kernelInvocation->getLocalSize(); Size3 global(second.getEntity(), m_kernelInvocation->getGlobalSize()); Size3 local(global.x%wgsize.x, global.y%wgsize.y, global.z%wgsize.z); Size3 group(global.x/wgsize.x, global.y/wgsize.y, global.z/wgsize.z); msg << "Global" << global << " Local" << local << " Group" << group; } else { msg << "Group" << Size3(second.getEntity(), m_kernelInvocation->getLocalSize()); } msg << endl << second.getInstruction() << endl; msg.send(); } void RaceDetector::registerAccess(const Memory *memory, const WorkGroup *workGroup, const WorkItem *workItem, size_t address, size_t size, bool atomic, const uint8_t *storeData) { unsigned addrSpace = memory->getAddressSpace(); if (addrSpace == AddrSpacePrivate || addrSpace == AddrSpaceConstant) return; if (!memory->isAddressValid(address, size)) return; // Construct access MemoryAccess access(workGroup, workItem, storeData != NULL, atomic); size_t index; if (workItem) { Size3 wgsize = workGroup->getGroupSize(); Size3 lid = workItem->getLocalID(); index = lid.x + (lid.y + lid.z*wgsize.y)*wgsize.x; } else { index = STATE(workGroup).wiLocal.size() - 1; } AccessMap& accesess = (addrSpace == AddrSpaceGlobal) ? STATE(workGroup).wiGlobal[index] : STATE(workGroup).wiLocal[index]; for (size_t i = 0; i < size; i++) { if (storeData) access.setStoreData(storeData[i]); insert(accesess[address+i], access); } } void RaceDetector::syncWorkItems(const Memory *memory, WorkGroupState& state, vector<AccessMap>& accesses) { AccessMap wgAccesses; for (size_t i = 0; i < state.numWorkItems + 1; i++) { for (auto record = accesses[i].begin(); record != accesses[i].end(); record++) { size_t address = record->first; AccessRecord& a = record->second; AccessRecord& b = wgAccesses[address]; if (check(a.load, b.store)) logRace(memory, address, a.load, b.store); if (check(a.store, b.load)) logRace(memory, address, a.store, b.load); if (check(a.store, b.store)) logRace(memory, address, a.store, b.store); if (a.load.isSet()) { insert(b, a.load); if (memory->getAddressSpace() == AddrSpaceGlobal) insert(state.wgGlobal[address], a.load); } if (a.store.isSet()) { insert(b, a.store); if (memory->getAddressSpace() == AddrSpaceGlobal) insert(state.wgGlobal[address], a.store); } } accesses[i].clear(); } } RaceDetector::MemoryAccess::MemoryAccess() { this->info = 0; this->instruction = NULL; } RaceDetector::MemoryAccess::MemoryAccess(const WorkGroup *workGroup, const WorkItem *workItem, bool store, bool atomic) { this->info = 0; this->info |= 1 << SET_BIT; this->info |= store << STORE_BIT; this->info |= atomic << ATOMIC_BIT; if (workItem) { this->entity = workItem->getGlobalIndex(); this->instruction = workItem->getCurrentInstruction(); } else { this->info |= (1<<WG_BIT); this->entity = workGroup->getGroupIndex(); this->instruction = NULL; // TODO? } } void RaceDetector::MemoryAccess::clear() { this->info = 0; this->instruction = NULL; } bool RaceDetector::MemoryAccess::isSet() const { return this->info & (1<<SET_BIT); } bool RaceDetector::MemoryAccess::isAtomic() const { return this->info & (1<<ATOMIC_BIT); } bool RaceDetector::MemoryAccess::isLoad() const { return !isStore(); } bool RaceDetector::MemoryAccess::isStore() const { return this->info & (1<<STORE_BIT); } bool RaceDetector::MemoryAccess::isWorkGroup() const { return this->info & (1<<WG_BIT); } bool RaceDetector::MemoryAccess::isWorkItem() const { return !isWorkGroup(); } bool RaceDetector::MemoryAccess::hasWorkGroupSync() const { return this->info & (1<<WG_SYNC_BIT); } void RaceDetector::MemoryAccess::setWorkGroupSync() { this->info |= (1<<WG_SYNC_BIT); } size_t RaceDetector::MemoryAccess::getEntity() const { return this->entity; } const llvm::Instruction* RaceDetector::MemoryAccess::getInstruction() const { return this->instruction; } uint8_t RaceDetector::MemoryAccess::getStoreData() const { return this->storeData; } void RaceDetector::MemoryAccess::setStoreData(uint8_t data) { this->storeData = data; } <|endoftext|>
<commit_before>#pragma once #include <eosio/chain/types.hpp> #include <eosio/chain/webassembly/common.hpp> #include <eosio/chain/webassembly/eos-vm.hpp> #include <eosio/vm/backend.hpp> #include <eosio/vm/host_function.hpp> namespace eosio { namespace chain { namespace webassembly { namespace detail { template <typename T, std::size_t A> constexpr std::integral_constant<bool, A != 0> is_legacy_ptr(legacy_ptr<T, A>); template <typename T> constexpr std::false_type is_legacy_ptr(T); template <typename T, std::size_t A> constexpr std::integral_constant<bool, A != 0> is_legacy_array_ptr(legacy_array_ptr<T, A>); template <typename T> constexpr std::false_type is_legacy_array_ptr(T); template <typename T> constexpr std::true_type is_unvalidated_ptr(unvalidated_ptr<T>); template <typename T> constexpr std::false_type is_unvalidated_ptr(T); template <typename T> struct is_whitelisted_legacy_type { static constexpr bool value = std::is_same_v<float128_t, T> || std::is_same_v<null_terminated_ptr, T> || std::is_same_v<decltype(is_legacy_ptr(std::declval<T>())), std::true_type> || std::is_same_v<decltype(is_legacy_array_ptr(std::declval<T>())), std::true_type> || std::is_same_v<decltype(is_unvalidated_ptr(std::declval<T>())), std::true_type> || std::is_same_v<name, T> || std::is_arithmetic_v<T>; }; template <typename T> struct is_whitelisted_type { static constexpr bool value = std::is_arithmetic_v<std::decay_t<T>> || std::is_same_v<std::decay_t<T>, name> || std::is_pointer_v<T> || std::is_lvalue_reference_v<T> || std::is_same_v<std::decay_t<T>, float128_t> || eosio::vm::is_span_type_v<std::decay_t<T>>; }; } template <typename T> inline static constexpr bool is_whitelisted_type_v = detail::is_whitelisted_type<T>::value; template <typename T> inline static constexpr bool is_whitelisted_legacy_type_v = detail::is_whitelisted_legacy_type<T>::value; template <typename... Ts> inline static constexpr bool are_whitelisted_types_v = true; //(... && detail::is_whitelisted_type<Ts>::value); template <typename... Ts> inline static constexpr bool are_whitelisted_legacy_types_v = (... && detail::is_whitelisted_legacy_type<Ts>::value); template <typename T, typename U> inline static bool is_aliasing(const T& a, const U& b) { std::uintptr_t a_ui = reinterpret_cast<std::uintptr_t>(a.data()); std::uintptr_t b_ui = reinterpret_cast<std::uintptr_t>(b.data()); return a_ui < b_ui ? a_ui + a.size() >= b_ui : b_ui + b.size() >= a_ui; } inline static bool is_nan( const float32_t f ) { return f32_is_nan( f ); } inline static bool is_nan( const float64_t f ) { return f64_is_nan( f ); } inline static bool is_nan( const float128_t& f ) { return f128_is_nan( f ); } EOS_VM_PRECONDITION(early_validate_pointers, EOS_VM_INVOKE_ON_ALL([&](auto&& arg, auto&&... rest) { using namespace eosio::vm; using arg_t = std::decay_t<decltype(arg)>; if constexpr (is_reference_proxy_type_v<arg_t>) { if constexpr (is_span_type_v<dependent_type_t<arg_t>>) { using dep_t = dependent_type_t<arg_t>; const dep_t& s = arg; EOS_ASSERT( s.size() <= std::numeric_limits<wasm_size_t>::max() / (wasm_size_t)sizeof(dependent_type_t<dep_t>), wasm_execution_error, "length will overflow" ); volatile auto check = *(reinterpret_cast<const char*>(arg.original_ptr) + s.size_bytes() - 1); ignore_unused_variable_warning(check); } else { EOS_ASSERT(arg.original_ptr != ctx.get_interface().get_memory(), wasm_execution_error, "references cannot be created for null pointers"); } } else if constexpr (vm::is_reference_type_v<arg_t>) { EOS_ASSERT(arg.value != ctx.get_interface().get_memory(), wasm_execution_error, "references cannot be created for null pointers"); } })); EOS_VM_PRECONDITION(context_free_check, EOS_VM_INVOKE_ONCE([&](auto&&...) { EOS_ASSERT(ctx.get_host().get_context().is_context_free(), unaccessible_api, "this API may only be called from context_free apply"); })); EOS_VM_PRECONDITION(context_aware_check, EOS_VM_INVOKE_ONCE([&](auto&&...) { EOS_ASSERT(!ctx.get_host().get_context().is_context_free(), unaccessible_api, "only context free api's can be used in this context"); })); EOS_VM_PRECONDITION(privileged_check, EOS_VM_INVOKE_ONCE([&](auto&&...) { EOS_ASSERT(ctx.get_host().get_context().is_privileged(), unaccessible_api, "${code} does not have permission to call this API", ("code", ctx.get_host().get_context().get_receiver())); })); EOS_VM_PRECONDITION(alias_check, EOS_VM_INVOKE_ON_ALL(([&](auto&& arg, auto&&... rest) { using namespace eosio::vm; using arg_t = std::decay_t<decltype(arg)>; if constexpr (is_span_type_v<arg_t>) { // check alignment while we are here EOS_ASSERT( reinterpret_cast<std::uintptr_t>(arg.data()) % alignof(dependent_type_t<arg_t>) == 0, wasm_exception, "memory not aligned" ); eosio::vm::invoke_on<false, eosio::vm::invoke_on_all_t>([&](auto&& narg, auto&&... nrest) { using nested_arg_t = std::decay_t<decltype(arg)>; if constexpr (eosio::vm::is_span_type_v<nested_arg_t>) EOS_ASSERT(!is_aliasing(arg, narg), wasm_exception, "arrays not allowed to alias"); }, rest...); } }))); template<typename T> inline constexpr bool should_check_nan_v = std::is_same_v<T, float32_t> || std::is_same_v<T, float64_t> || std::is_same_v<T, float128_t>; template<typename T> struct remove_reference_proxy { using type = T; }; template<typename T, std::size_t A> struct remove_reference_proxy<vm::reference_proxy<T, A>> { using type = T; }; template<typename T> struct remove_reference_proxy<vm::reference<T>> { using type = T; }; EOS_VM_PRECONDITION(is_nan_check, EOS_VM_INVOKE_ON_ALL([&](auto&& arg, auto&&... rest) { if constexpr (should_check_nan_v<std::remove_cv_t<typename remove_reference_proxy<std::decay_t<decltype(arg)>>::type>>) { EOS_ASSERT(!webassembly::is_nan(arg), transaction_exception, "NaN is not an allowed value for a secondary key"); } })); EOS_VM_PRECONDITION(legacy_static_check_wl_args, EOS_VM_INVOKE_ONCE([&](auto&&... args) { static_assert( are_whitelisted_legacy_types_v<std::decay_t<decltype(args)>...>, "legacy whitelisted type violation"); })); EOS_VM_PRECONDITION(static_check_wl_args, EOS_VM_INVOKE_ONCE([&](auto&&... args) { static_assert( are_whitelisted_types_v<std::decay_t<decltype(args)>...>, "whitelisted type violation"); })); }}} // ns eosio::chain::webassembly <commit_msg>Remove uses vm::reference. It has no alignment guarantees and is unusable for nodeos.<commit_after>#pragma once #include <eosio/chain/types.hpp> #include <eosio/chain/webassembly/common.hpp> #include <eosio/chain/webassembly/eos-vm.hpp> #include <eosio/vm/backend.hpp> #include <eosio/vm/host_function.hpp> namespace eosio { namespace chain { namespace webassembly { namespace detail { template <typename T, std::size_t A> constexpr std::integral_constant<bool, A != 0> is_legacy_ptr(legacy_ptr<T, A>); template <typename T> constexpr std::false_type is_legacy_ptr(T); template <typename T, std::size_t A> constexpr std::integral_constant<bool, A != 0> is_legacy_array_ptr(legacy_array_ptr<T, A>); template <typename T> constexpr std::false_type is_legacy_array_ptr(T); template <typename T> constexpr std::true_type is_unvalidated_ptr(unvalidated_ptr<T>); template <typename T> constexpr std::false_type is_unvalidated_ptr(T); template <typename T> struct is_whitelisted_legacy_type { static constexpr bool value = std::is_same_v<float128_t, T> || std::is_same_v<null_terminated_ptr, T> || std::is_same_v<decltype(is_legacy_ptr(std::declval<T>())), std::true_type> || std::is_same_v<decltype(is_legacy_array_ptr(std::declval<T>())), std::true_type> || std::is_same_v<decltype(is_unvalidated_ptr(std::declval<T>())), std::true_type> || std::is_same_v<name, T> || std::is_arithmetic_v<T>; }; template <typename T> struct is_whitelisted_type { static constexpr bool value = std::is_arithmetic_v<std::decay_t<T>> || std::is_same_v<std::decay_t<T>, name> || std::is_pointer_v<T> || std::is_lvalue_reference_v<T> || std::is_same_v<std::decay_t<T>, float128_t> || eosio::vm::is_span_type_v<std::decay_t<T>>; }; } template <typename T> inline static constexpr bool is_whitelisted_type_v = detail::is_whitelisted_type<T>::value; template <typename T> inline static constexpr bool is_whitelisted_legacy_type_v = detail::is_whitelisted_legacy_type<T>::value; template <typename... Ts> inline static constexpr bool are_whitelisted_types_v = true; //(... && detail::is_whitelisted_type<Ts>::value); template <typename... Ts> inline static constexpr bool are_whitelisted_legacy_types_v = (... && detail::is_whitelisted_legacy_type<Ts>::value); template <typename T, typename U> inline static bool is_aliasing(const T& a, const U& b) { std::uintptr_t a_ui = reinterpret_cast<std::uintptr_t>(a.data()); std::uintptr_t b_ui = reinterpret_cast<std::uintptr_t>(b.data()); return a_ui < b_ui ? a_ui + a.size() >= b_ui : b_ui + b.size() >= a_ui; } inline static bool is_nan( const float32_t f ) { return f32_is_nan( f ); } inline static bool is_nan( const float64_t f ) { return f64_is_nan( f ); } inline static bool is_nan( const float128_t& f ) { return f128_is_nan( f ); } EOS_VM_PRECONDITION(early_validate_pointers, EOS_VM_INVOKE_ON_ALL([&](auto&& arg, auto&&... rest) { using namespace eosio::vm; using arg_t = std::decay_t<decltype(arg)>; if constexpr (is_reference_proxy_type_v<arg_t>) { if constexpr (is_span_type_v<dependent_type_t<arg_t>>) { using dep_t = dependent_type_t<arg_t>; const dep_t& s = arg; EOS_ASSERT( s.size() <= std::numeric_limits<wasm_size_t>::max() / (wasm_size_t)sizeof(dependent_type_t<dep_t>), wasm_execution_error, "length will overflow" ); volatile auto check = *(reinterpret_cast<const char*>(arg.original_ptr) + s.size_bytes() - 1); ignore_unused_variable_warning(check); } else { EOS_ASSERT(arg.original_ptr != ctx.get_interface().get_memory(), wasm_execution_error, "references cannot be created for null pointers"); } } })); EOS_VM_PRECONDITION(context_free_check, EOS_VM_INVOKE_ONCE([&](auto&&...) { EOS_ASSERT(ctx.get_host().get_context().is_context_free(), unaccessible_api, "this API may only be called from context_free apply"); })); EOS_VM_PRECONDITION(context_aware_check, EOS_VM_INVOKE_ONCE([&](auto&&...) { EOS_ASSERT(!ctx.get_host().get_context().is_context_free(), unaccessible_api, "only context free api's can be used in this context"); })); EOS_VM_PRECONDITION(privileged_check, EOS_VM_INVOKE_ONCE([&](auto&&...) { EOS_ASSERT(ctx.get_host().get_context().is_privileged(), unaccessible_api, "${code} does not have permission to call this API", ("code", ctx.get_host().get_context().get_receiver())); })); EOS_VM_PRECONDITION(alias_check, EOS_VM_INVOKE_ON_ALL(([&](auto&& arg, auto&&... rest) { using namespace eosio::vm; using arg_t = std::decay_t<decltype(arg)>; if constexpr (is_span_type_v<arg_t>) { // check alignment while we are here EOS_ASSERT( reinterpret_cast<std::uintptr_t>(arg.data()) % alignof(dependent_type_t<arg_t>) == 0, wasm_exception, "memory not aligned" ); eosio::vm::invoke_on<false, eosio::vm::invoke_on_all_t>([&](auto&& narg, auto&&... nrest) { using nested_arg_t = std::decay_t<decltype(arg)>; if constexpr (eosio::vm::is_span_type_v<nested_arg_t>) EOS_ASSERT(!is_aliasing(arg, narg), wasm_exception, "arrays not allowed to alias"); }, rest...); } }))); template<typename T> inline constexpr bool should_check_nan_v = std::is_same_v<T, float32_t> || std::is_same_v<T, float64_t> || std::is_same_v<T, float128_t>; template<typename T> struct remove_reference_proxy { using type = T; }; template<typename T, std::size_t A> struct remove_reference_proxy<vm::reference_proxy<T, A>> { using type = T; }; EOS_VM_PRECONDITION(is_nan_check, EOS_VM_INVOKE_ON_ALL([&](auto&& arg, auto&&... rest) { if constexpr (should_check_nan_v<std::remove_cv_t<typename remove_reference_proxy<std::decay_t<decltype(arg)>>::type>>) { EOS_ASSERT(!webassembly::is_nan(arg), transaction_exception, "NaN is not an allowed value for a secondary key"); } })); EOS_VM_PRECONDITION(legacy_static_check_wl_args, EOS_VM_INVOKE_ONCE([&](auto&&... args) { static_assert( are_whitelisted_legacy_types_v<std::decay_t<decltype(args)>...>, "legacy whitelisted type violation"); })); EOS_VM_PRECONDITION(static_check_wl_args, EOS_VM_INVOKE_ONCE([&](auto&&... args) { static_assert( are_whitelisted_types_v<std::decay_t<decltype(args)>...>, "whitelisted type violation"); })); }}} // ns eosio::chain::webassembly <|endoftext|>
<commit_before>/** * @file * @brief Parser */ #include <iostream> #include "parameter_parser.h" #include "parameters.h" taylortrack::utils::Parameters taylortrack::utils::ParameterParser::parse_streamer(int argc,const char **argv) { char *end; Parameters parameters; for(int i = 1; i < argc; i++) { if(argv[i][0] == '-') { switch(argv[i][1]) { // stream buffer size case 's': if(++i >= argc) { parameters.valid = false; } else { parameters.size = (int) strtol(argv[i], &end, 10); } break; // Output port case 'o': if(++i >= argc) { parameters.valid = false; } else { parameters.outport = argv[i]; } break; // Input port case 'i': if(++i >= argc) { parameters.valid = false; } else { parameters.inport = argv[i]; } break; default: parameters.valid = false; } }else { parameters.file = argv[i]; parameters.valid = true; } } return parameters; } // LCOV_EXCL_BR_LINE <commit_msg>fixed potentially not initialized variable warning<commit_after>/** * @file * @brief Parser */ #include <iostream> #include "parameter_parser.h" #include "parameters.h" taylortrack::utils::Parameters taylortrack::utils::ParameterParser::parse_streamer(int argc,const char **argv) { char *end; Parameters parameters = utils::Parameters(); for(int i = 1; i < argc; i++) { if(argv[i][0] == '-') { switch(argv[i][1]) { // stream buffer size case 's': if(++i >= argc) { parameters.valid = false; } else { parameters.size = (int) strtol(argv[i], &end, 10); } break; // Output port case 'o': if(++i >= argc) { parameters.valid = false; } else { parameters.outport = argv[i]; } break; // Input port case 'i': if(++i >= argc) { parameters.valid = false; } else { parameters.inport = argv[i]; } break; default: parameters.valid = false; } }else { parameters.file = argv[i]; parameters.valid = true; } } return parameters; } // LCOV_EXCL_BR_LINE <|endoftext|>
<commit_before>/******************************************************************** Software License Agreement (BSD License) Copyright (c) 2016, Syler Wagner. 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 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. ********************************************************************/ /** * utm_fcu_tf_broadcaster.cpp * Broadcast transform between local_origin and fcu. * * @author Syler Wagner <[email protected]> * @date 2016-07-18 syler creation * * This node listens for an initial odometry message on the * /mavros/global_position/local topic and then broadcasts a * transform between local_origin and fcu. **/ #include <utm_fcu_tf_broadcaster.h> #include <tf/transform_datatypes.h> //$ TODO: use mavros.get_namespace() instead of hardcoding LocalOriginToFCUBroadcaster::LocalOriginToFCUBroadcaster(ros::NodeHandle *n) { _n = n; _n->param<std::string>("frame_id", _frame_id, "fcu"); _n->param<std::string>("mavros_ns", _ns, "mavros"); ROS_WARN("Starting utm_fcu_tf_broadcaster with mavros namespace '%s'", _ns.c_str()); // _n->param<std::string>("frame_id", _frame_id, "fcu"); //$ transform is not initialized at startup _transform_initialized = false; _t_latest_error = ros::Time::now(); _message_count = 0; ros::NodeHandle mavros_nh(_ns); //$ node handle for mavros global position topic mavros_nh.param<std::string>("local_position/frame_id", _frame_id, "fcu"); mavros_nh.param<std::string>("global_position/frame_id", _utm_frame_id, "utm"); ROS_WARN("Trying to initialize transform between %s and %s", _utm_frame_id.c_str(), _frame_id.c_str()); //$ UTM odometry subscriber _odom_sub = mavros_nh.subscribe("global_position/local", 1, &LocalOriginToFCUBroadcaster::odometryCallback, this); } LocalOriginToFCUBroadcaster::~LocalOriginToFCUBroadcaster() {} bool LocalOriginToFCUBroadcaster::verifyOdometry(const nav_msgs::Odometry::ConstPtr& odom) { /*$ The first few messages on /mavros/global_position/local are usually invalid and will usually be something like x: 166021.443179 y: 0.000000 z: 0.210000 so the ones with bogus values need to be filtered out. */ ros::Duration time_since_first_callback; if (_message_count == 1) { _t_first_message = ros::Time::now(); ROS_WARN("Got first message on %s/global_position/local", _ns.c_str()); } else { time_since_first_callback = ros::Time::now() - _t_first_message; } if (odom->pose.pose.position.y < 1e-6) { ROS_ERROR("UTM messages on %s/global_position/local are invalid. Wait a second...", _ns.c_str()); return false; } else if (time_since_first_callback < ros::Duration(1)) { return false; } else { return true; } } /*$ * The odometryCallback() function initializes the transform between * local_origin and fcu. The data from the /mavros/global_position/local * topic is only read once. */ void LocalOriginToFCUBroadcaster::odometryCallback(const nav_msgs::Odometry::ConstPtr& odom) { _message_count += 1; if (_transform_initialized == false) { if (verifyOdometry(odom)) { _odom_trans.transform.translation.x = odom->pose.pose.position.x; _odom_trans.transform.translation.y = odom->pose.pose.position.y; _odom_trans.transform.translation.z = odom->pose.pose.position.z; //$ TODO: I don't think the rotation is necessary geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(0); _odom_trans.transform.rotation = odom_quat; ROS_WARN("Transform between %s and %s initialized!", _utm_frame_id.c_str(), _frame_id.c_str()); ROS_WARN("Translation: [x: %4.1f, y: %4.1f, z: %4.1f]", _odom_trans.transform.translation.x, _odom_trans.transform.translation.y, _odom_trans.transform.translation.z); ROS_WARN("Rotation: [x: %4.1f, y: %4.1f, z: %4.1f, w: %4.1f]", _odom_trans.transform.rotation.x, _odom_trans.transform.rotation.y, _odom_trans.transform.rotation.z, _odom_trans.transform.rotation.w); _transform_initialized = true; } } } /*$ * Send the transform between local_origin and fcu after it has been initialized. */ void LocalOriginToFCUBroadcaster::sendTransform() { if (_transform_initialized) { _odom_trans.header.stamp = ros::Time::now(); _odom_trans.header.frame_id = _utm_frame_id; _odom_trans.child_frame_id = _frame_id; _odom_broadcaster.sendTransform(_odom_trans); } else { ros::Duration time_since_last_error_message = ros::Time::now() - _t_latest_error; if (time_since_last_error_message > ros::Duration(5)) { _t_latest_error = ros::Time::now(); ROS_ERROR("No UTM odometry messages received from UAV. Are you in the air yet?"); } } } int main(int argc, char** argv) { ros::init(argc, argv, "utm_fcu_tf_broadcaster"); ros::NodeHandle* n = new ros::NodeHandle("~"); LocalOriginToFCUBroadcaster broadcaster(n); int rate; std::string frame_id; n->param("rated", rate, 100); ros::Rate r(rate); while (n->ok()) { ros::spinOnce(); broadcaster.sendTransform(); r.sleep(); } } <commit_msg>Fixed typo in utm_fcu_tf_broadcaster<commit_after>/******************************************************************** Software License Agreement (BSD License) Copyright (c) 2016, Syler Wagner. 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 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. ********************************************************************/ /** * utm_fcu_tf_broadcaster.cpp * Broadcast transform between local_origin and fcu. * * @author Syler Wagner <[email protected]> * @date 2016-07-18 syler creation * * This node listens for an initial odometry message on the * /mavros/global_position/local topic and then broadcasts a * transform between local_origin and fcu. **/ #include <utm_fcu_tf_broadcaster.h> #include <tf/transform_datatypes.h> //$ TODO: use mavros.get_namespace() instead of hardcoding LocalOriginToFCUBroadcaster::LocalOriginToFCUBroadcaster(ros::NodeHandle *n) { _n = n; _n->param<std::string>("frame_id", _frame_id, "fcu"); _n->param<std::string>("mavros_ns", _ns, "mavros"); ROS_WARN("Starting utm_fcu_tf_broadcaster with mavros namespace '%s'", _ns.c_str()); // _n->param<std::string>("frame_id", _frame_id, "fcu"); //$ transform is not initialized at startup _transform_initialized = false; _t_latest_error = ros::Time::now(); _message_count = 0; ros::NodeHandle mavros_nh(_ns); //$ node handle for mavros global position topic mavros_nh.param<std::string>("local_position/frame_id", _frame_id, "fcu"); mavros_nh.param<std::string>("global_position/frame_id", _utm_frame_id, "utm"); ROS_WARN("Trying to initialize transform between %s and %s", _utm_frame_id.c_str(), _frame_id.c_str()); //$ UTM odometry subscriber _odom_sub = mavros_nh.subscribe("global_position/local", 1, &LocalOriginToFCUBroadcaster::odometryCallback, this); } LocalOriginToFCUBroadcaster::~LocalOriginToFCUBroadcaster() {} bool LocalOriginToFCUBroadcaster::verifyOdometry(const nav_msgs::Odometry::ConstPtr& odom) { /*$ The first few messages on /mavros/global_position/local are usually invalid and will usually be something like x: 166021.443179 y: 0.000000 z: 0.210000 so the ones with bogus values need to be filtered out. */ ros::Duration time_since_first_callback; if (_message_count == 1) { _t_first_message = ros::Time::now(); ROS_WARN("Got first message on %s/global_position/local", _ns.c_str()); } else { time_since_first_callback = ros::Time::now() - _t_first_message; } if (odom->pose.pose.position.y < 1e-6) { ROS_ERROR("UTM messages on %s/global_position/local are invalid. Wait a second...", _ns.c_str()); return false; } else if (time_since_first_callback < ros::Duration(1)) { return false; } else { return true; } } /*$ * The odometryCallback() function initializes the transform between * local_origin and fcu. The data from the /mavros/global_position/local * topic is only read once. */ void LocalOriginToFCUBroadcaster::odometryCallback(const nav_msgs::Odometry::ConstPtr& odom) { _message_count += 1; if (_transform_initialized == false) { if (verifyOdometry(odom)) { _odom_trans.transform.translation.x = odom->pose.pose.position.x; _odom_trans.transform.translation.y = odom->pose.pose.position.y; _odom_trans.transform.translation.z = odom->pose.pose.position.z; //$ TODO: I don't think the rotation is necessary geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(0); _odom_trans.transform.rotation = odom_quat; ROS_WARN("Transform between %s and %s initialized!", _utm_frame_id.c_str(), _frame_id.c_str()); ROS_WARN("Translation: [x: %4.1f, y: %4.1f, z: %4.1f]", _odom_trans.transform.translation.x, _odom_trans.transform.translation.y, _odom_trans.transform.translation.z); ROS_WARN("Rotation: [x: %4.1f, y: %4.1f, z: %4.1f, w: %4.1f]", _odom_trans.transform.rotation.x, _odom_trans.transform.rotation.y, _odom_trans.transform.rotation.z, _odom_trans.transform.rotation.w); _transform_initialized = true; } } } /*$ * Send the transform between local_origin and fcu after it has been initialized. */ void LocalOriginToFCUBroadcaster::sendTransform() { if (_transform_initialized) { _odom_trans.header.stamp = ros::Time::now(); _odom_trans.header.frame_id = _utm_frame_id; _odom_trans.child_frame_id = _frame_id; _odom_broadcaster.sendTransform(_odom_trans); } else { ros::Duration time_since_last_error_message = ros::Time::now() - _t_latest_error; if (time_since_last_error_message > ros::Duration(5)) { _t_latest_error = ros::Time::now(); ROS_ERROR("No UTM odometry messages received from UAV. Are you in the air yet?"); } } } int main(int argc, char** argv) { ros::init(argc, argv, "utm_fcu_tf_broadcaster"); ros::NodeHandle* n = new ros::NodeHandle("~"); LocalOriginToFCUBroadcaster broadcaster(n); int rate; std::string frame_id; n->param("rate", rate, 100); ros::Rate r(rate); while (n->ok()) { ros::spinOnce(); broadcaster.sendTransform(); r.sleep(); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** 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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qversitdocument.h" #include "qversitdocument_p.h" #include "qmobilityglobal.h" #include <QTextCodec> QTM_BEGIN_NAMESPACE /*! \class QVersitDocument \brief The QVersitDocument class is a container for a list of versit properties. \ingroup versit \inmodule QtVersit A vCard is represented in abstract form as a QVersitDocument that consists of a number of properties such as a name (N), a telephone number (TEL) and an email address (EMAIL), for instance. Each of these properties is stored as an instance of a QVersitProperty in a QVersitDocument. In addition to the list of properties, QVersitDocument also records the type of the Versit document in two ways. The VersitType enum describes the format in which the document is to be serialized by QVersitWriter (or the format from which it was read by QVersitReader), and should not be used to infer any semantics about the document data. The componentType field is a string corresponding directly to the value of the BEGIN line in a document. For example, for a vCard, this will always be the string "VCARD"; for an iCalendar, it could be "VCALENDAR", "VEVENT", "VTODO", "VJOURNAL", "VALARM" or "VTIMEZONE". As well as properties, a QVersitDocument can hold other documents. For iCalendar, this is how a single VCALENDAR document can compose documents of type VEVENT, VTODO, etc. For example, for the following iCalendar: \code BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SUMMARY:Christmas DTSTART:20001225 END:VEVENT END:VCALENDAR \endcode This can be represented as a QVersitDocument of with componentType VCALENDAR and versitType ICalendar20Type. It contains no properties (note: the VERSION property is not stored explicitly as a property) and one sub-document. The sub-document has componentType VEVENT and versitType ICalendar20Type, and contains two properties. QVersitDocument supports implicit sharing. \sa QVersitProperty */ /*! \enum QVersitDocument::VersitType This enum describes a Versit document serialization format and version. \value InvalidType No type specified or a document with an invalid type was parsed \value VCard21Type vCard version 2.1 \value VCard30Type vCard version 3.0 \value VCard40Type vCard version 4.0 \value ICalendar20Type iCalendar version 2.0 */ /*! Constructs a new empty document */ QVersitDocument::QVersitDocument() : d(new QVersitDocumentPrivate()) { } /*! Constructs a new empty document with the type set to \a type */ QVersitDocument::QVersitDocument(VersitType type) : d(new QVersitDocumentPrivate()) { d->mVersitType = type; } /*! Constructs a document that is a copy of \a other */ QVersitDocument::QVersitDocument(const QVersitDocument& other) : d(other.d) { } /*! Frees the memory used by the document */ QVersitDocument::~QVersitDocument() { } /*! Assigns this document to \a other */ QVersitDocument& QVersitDocument::operator=(const QVersitDocument& other) { if (this != &other) d = other.d; return *this; } /*! Returns true if this is equal to \a other; false otherwise. */ bool QVersitDocument::operator==(const QVersitDocument& other) const { return d->mVersitType == other.d->mVersitType && d->mProperties == other.d->mProperties && d->mSubDocuments == other.d->mSubDocuments && d->mComponentType == other.d->mComponentType; } /*! Returns true if this is not equal to \a other; false otherwise. */ bool QVersitDocument::operator!=(const QVersitDocument& other) const { return !(*this == other); } /*! Returns the hash value for \a key. */ uint qHash(const QVersitDocument &key) { int hash = QT_PREPEND_NAMESPACE(qHash)(key.type()); hash += QT_PREPEND_NAMESPACE(qHash)(key.componentType()); foreach (const QVersitProperty& property, key.properties()) { hash += qHash(property); } foreach (const QVersitDocument& nested, key.subDocuments()) { hash += qHash(nested); } return hash; } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QVersitDocument& document) { dbg.nospace() << "QVersitDocument(" << document.type() << ", " << document.componentType() << ')'; foreach (const QVersitProperty& property, document.properties()) { dbg.space() << '\n' << property; } foreach (const QVersitDocument& nested, document.subDocuments()) { dbg.space() << '\n' << nested; } return dbg.maybeSpace(); } #endif /*! * Sets the versit document type to \a type. This determines the format in which the document is * to be serialized. */ void QVersitDocument::setType(VersitType type) { d->mVersitType = type; } /*! * Gets the versit document type. */ QVersitDocument::VersitType QVersitDocument::type() const { return d->mVersitType; } /*! * Sets the versit component type to \a componentType (eg. VCARD, VCALENDAR, VEVENT, etc.) */ void QVersitDocument::setComponentType(QString componentType) { d->mComponentType = componentType; } /*! * Gets the versit component type */ QString QVersitDocument::componentType() const { return d->mComponentType; } /*! * Add \a property to the list of contained versit properties. * The property is appended as the last property of the list. */ void QVersitDocument::addProperty(const QVersitProperty& property) { d->mProperties.append(property); } /*! * Removes the property \a property from the versit document. */ void QVersitDocument::removeProperty(const QVersitProperty& property) { d->mProperties.removeAll(property); } /*! * Removes all the properties with the given \a name from the versit document. */ void QVersitDocument::removeProperties(const QString& name) { for (int i=d->mProperties.count()-1; i >=0; i--) { if (d->mProperties[i].name() == name) { d->mProperties.removeAt(i); } } } /*! * Sets the list of properties to \a properties. Logically, all of the existing properties are * removed and all of the supplied \a properties are added. */ void QVersitDocument::setProperties(const QList<QVersitProperty>& properties) { d->mProperties = properties; } /*! * Gets the list of the contained versit properties. * Note that the actual properties cannot be modified using the copy. */ QList<QVersitProperty> QVersitDocument::properties() const { return d->mProperties; } /*! * Adds \a subdocument to the Versit document. */ void QVersitDocument::addSubDocument(const QVersitDocument& subdocument) { d->mSubDocuments.append(subdocument); } /*! * Removes the \a subdocument from the versit document. */ void QVersitDocument::removeSubDocument(const QVersitDocument& subdocument) { d->mSubDocuments.removeAll(subdocument); } /*! * Sets the list of subdocuments to \a documents. */ void QVersitDocument::setSubDocuments(const QList<QVersitDocument>& documents) { d->mSubDocuments = documents; } /*! * Returns the list of subdocuments contained within this Versit document. */ QList<QVersitDocument> QVersitDocument::subDocuments() const { return d->mSubDocuments; } /*! * Returns true if the document is empty. */ bool QVersitDocument::isEmpty() const { return d->mProperties.isEmpty() && d->mSubDocuments.isEmpty() && d->mVersitType == QVersitDocument::InvalidType; } /*! * Clears the document, removing all properties and metadata * and resetting the codec to the default. */ void QVersitDocument::clear() { d->mProperties.clear(); d->mSubDocuments.clear(); d->mVersitType = QVersitDocument::InvalidType; d->mComponentType.clear(); } QTM_END_NAMESPACE <commit_msg>A minor documentation fix.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** 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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qversitdocument.h" #include "qversitdocument_p.h" #include "qmobilityglobal.h" #include <QTextCodec> QTM_BEGIN_NAMESPACE /*! \class QVersitDocument \brief The QVersitDocument class is a container for a list of versit properties. \ingroup versit \inmodule QtVersit A vCard is represented in abstract form as a QVersitDocument that consists of a number of properties such as a name (N), a telephone number (TEL) and an email address (EMAIL), for instance. Each of these properties is stored as an instance of a QVersitProperty in a QVersitDocument. In addition to the list of properties, QVersitDocument also records the type of the Versit document in two ways. The VersitType enum describes the format in which the document is to be serialized by QVersitWriter (or the format from which it was read by QVersitReader), and should not be used to infer any semantics about the document data. The componentType field is a string corresponding directly to the value of the BEGIN line in a document. For example, for a vCard, this will always be the string "VCARD"; for an iCalendar, it could be "VCALENDAR", "VEVENT", "VTODO", "VJOURNAL", "VALARM" or "VTIMEZONE". As well as properties, a QVersitDocument can hold other documents. For iCalendar, this is how a single VCALENDAR document can compose documents of type VEVENT, VTODO, etc. For example, for the following iCalendar: \code BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SUMMARY:Christmas DTSTART:20001225 END:VEVENT END:VCALENDAR \endcode This can be represented as a QVersitDocument of with componentType VCALENDAR and versitType ICalendar20Type. It contains no properties (note: the VERSION property is not stored explicitly as a property) and one sub-document. The sub-document has componentType VEVENT and versitType ICalendar20Type, and contains two properties. QVersitDocument supports implicit sharing. \sa QVersitProperty */ /*! \enum QVersitDocument::VersitType This enum describes a Versit document serialization format and version. \value InvalidType No type specified or a document with an invalid type was parsed \value VCard21Type vCard version 2.1 \value VCard30Type vCard version 3.0 \value VCard40Type vCard version 4.0 \value ICalendar20Type iCalendar version 2.0 */ /*! Constructs a new empty document */ QVersitDocument::QVersitDocument() : d(new QVersitDocumentPrivate()) { } /*! Constructs a new empty document with the type set to \a type */ QVersitDocument::QVersitDocument(VersitType type) : d(new QVersitDocumentPrivate()) { d->mVersitType = type; } /*! Constructs a document that is a copy of \a other */ QVersitDocument::QVersitDocument(const QVersitDocument& other) : d(other.d) { } /*! Frees the memory used by the document */ QVersitDocument::~QVersitDocument() { } /*! Assigns this document to \a other */ QVersitDocument& QVersitDocument::operator=(const QVersitDocument& other) { if (this != &other) d = other.d; return *this; } /*! Returns true if this is equal to \a other; false otherwise. */ bool QVersitDocument::operator==(const QVersitDocument& other) const { return d->mVersitType == other.d->mVersitType && d->mProperties == other.d->mProperties && d->mSubDocuments == other.d->mSubDocuments && d->mComponentType == other.d->mComponentType; } /*! Returns true if this is not equal to \a other; false otherwise. */ bool QVersitDocument::operator!=(const QVersitDocument& other) const { return !(*this == other); } /*! Returns the hash value for \a key. */ uint qHash(const QVersitDocument &key) { int hash = QT_PREPEND_NAMESPACE(qHash)(key.type()); hash += QT_PREPEND_NAMESPACE(qHash)(key.componentType()); foreach (const QVersitProperty& property, key.properties()) { hash += qHash(property); } foreach (const QVersitDocument& nested, key.subDocuments()) { hash += qHash(nested); } return hash; } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QVersitDocument& document) { dbg.nospace() << "QVersitDocument(" << document.type() << ", " << document.componentType() << ')'; foreach (const QVersitProperty& property, document.properties()) { dbg.space() << '\n' << property; } foreach (const QVersitDocument& nested, document.subDocuments()) { dbg.space() << '\n' << nested; } return dbg.maybeSpace(); } #endif /*! * Sets the versit document type to \a type. This determines the format in which the document is * to be serialized. */ void QVersitDocument::setType(VersitType type) { d->mVersitType = type; } /*! * Gets the versit document type. */ QVersitDocument::VersitType QVersitDocument::type() const { return d->mVersitType; } /*! * Sets the versit component type to \a componentType (eg. VCARD, VCALENDAR, VEVENT, etc.) */ void QVersitDocument::setComponentType(QString componentType) { d->mComponentType = componentType; } /*! * Gets the versit component type */ QString QVersitDocument::componentType() const { return d->mComponentType; } /*! * Add \a property to the list of contained versit properties. * The property is appended as the last property of the list. */ void QVersitDocument::addProperty(const QVersitProperty& property) { d->mProperties.append(property); } /*! * Removes the property \a property from the versit document. */ void QVersitDocument::removeProperty(const QVersitProperty& property) { d->mProperties.removeAll(property); } /*! * Removes all the properties with the given \a name from the versit document. */ void QVersitDocument::removeProperties(const QString& name) { for (int i=d->mProperties.count()-1; i >=0; i--) { if (d->mProperties[i].name() == name) { d->mProperties.removeAt(i); } } } /*! * Sets the list of properties to \a properties. Logically, all of the existing properties are * removed and all of the supplied \a properties are added. */ void QVersitDocument::setProperties(const QList<QVersitProperty>& properties) { d->mProperties = properties; } /*! * Gets the list of the contained versit properties. * Note that the actual properties cannot be modified using the copy. */ QList<QVersitProperty> QVersitDocument::properties() const { return d->mProperties; } /*! * Adds \a subdocument to the Versit document. */ void QVersitDocument::addSubDocument(const QVersitDocument& subdocument) { d->mSubDocuments.append(subdocument); } /*! * Removes the \a subdocument from the versit document. */ void QVersitDocument::removeSubDocument(const QVersitDocument& subdocument) { d->mSubDocuments.removeAll(subdocument); } /*! * Sets the list of subdocuments to \a documents. */ void QVersitDocument::setSubDocuments(const QList<QVersitDocument>& documents) { d->mSubDocuments = documents; } /*! * Returns the list of subdocuments contained within this Versit document. */ QList<QVersitDocument> QVersitDocument::subDocuments() const { return d->mSubDocuments; } /*! * Returns true if the document is empty. */ bool QVersitDocument::isEmpty() const { return d->mProperties.isEmpty() && d->mSubDocuments.isEmpty() && d->mVersitType == QVersitDocument::InvalidType; } /*! * Clears the document, removing all properties, sub-documents and metadata. */ void QVersitDocument::clear() { d->mProperties.clear(); d->mSubDocuments.clear(); d->mVersitType = QVersitDocument::InvalidType; d->mComponentType.clear(); } QTM_END_NAMESPACE <|endoftext|>
<commit_before>/* This file is part of KDE Kontact. Copyright (C) 2003 Cornelius Schumacher <[email protected]> Copyright (C) 2008 Rafael Fernández López <[email protected]> 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; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "iconsidepane.h" #include "mainwindow.h" #include "plugin.h" #include "prefs.h" #include <QtGui/QStringListModel> #include <QtGui/QSortFilterProxyModel> #include <QtGui/QDragEnterEvent> #include <QtGui/QDragMoveEvent> #include <QtGui/QStyledItemDelegate> #include <QtGui/QScrollBar> #include <KLocalizedString> #include <KDialog> #include <KIcon> namespace Kontact { class Navigator; class Model : public QStringListModel { public: enum SpecialRoles { PluginName = Qt::UserRole }; Model( Navigator *parentNavigator = 0 ) : QStringListModel( parentNavigator ), mNavigator(parentNavigator) { } void setPluginList( const QList<Kontact::Plugin*> &list ) { pluginList = list; } virtual Qt::ItemFlags flags( const QModelIndex &index ) const { Qt::ItemFlags flags = QStringListModel::flags( index ); if ( index.isValid() ) { if ( static_cast<Kontact::Plugin*>( index.internalPointer() )->disabled() ) { flags &= ~Qt::ItemIsEnabled; flags &= ~Qt::ItemIsSelectable; flags &= ~Qt::ItemIsDropEnabled; } else { flags |= Qt::ItemIsDropEnabled; } } else { flags &= ~Qt::ItemIsDropEnabled; } return flags; } virtual QModelIndex index( int row, int column, const QModelIndex &parent = QModelIndex() ) const { Q_UNUSED( parent ); if ( row < 0 || row >= pluginList.count() ) { return QModelIndex(); } return createIndex( row, column, pluginList[row] ); } virtual QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const { if ( !index.isValid() || !index.internalPointer() ) { return QVariant(); } if ( role == Qt::DisplayRole ) { if ( !mNavigator->showText() ) { return QVariant(); } return static_cast<Kontact::Plugin*>( index.internalPointer() )->title(); } else if ( role == Qt::DecorationRole ) { if ( !mNavigator->showIcons() ) { return QVariant(); } return KIcon( static_cast<Kontact::Plugin*>( index.internalPointer() )->icon() ); } else if ( role == Qt::TextAlignmentRole ) { return Qt::AlignCenter; } else if ( role == Qt::ToolTipRole ) { if ( !mNavigator->showText() ) { return static_cast<Kontact::Plugin*>( index.internalPointer() )->title(); } return QVariant(); } else if ( role == PluginName ) { return static_cast<Kontact::Plugin*>( index.internalPointer() )->identifier(); } return QStringListModel::data( index, role ); } private: QList<Kontact::Plugin*> pluginList; Navigator *mNavigator; }; class SortFilterProxyModel : public QSortFilterProxyModel { public: SortFilterProxyModel( QObject *parent = 0 ): QSortFilterProxyModel( parent ) { setDynamicSortFilter( true ); sort ( 0 ); } protected: bool lessThan( const QModelIndex &left, const QModelIndex &right ) const { Kontact::Plugin *leftPlugin = static_cast<Kontact::Plugin*>( left.internalPointer() ); Kontact::Plugin *rightPlugin = static_cast<Kontact::Plugin*>( right.internalPointer() ); return leftPlugin->weight() < rightPlugin->weight(); } }; class Delegate : public QStyledItemDelegate { public: Delegate( Navigator *parentNavigator = 0 ) : QStyledItemDelegate( parentNavigator ), mNavigator( parentNavigator ) { } void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { if ( !index.isValid() || !index.internalPointer() ) { return; } QStyleOptionViewItemV4 optionCopy( *static_cast<const QStyleOptionViewItemV4*>( &option ) ); optionCopy.decorationPosition = QStyleOptionViewItem::Top; optionCopy.decorationSize = QSize( mNavigator->iconSize(), mNavigator->iconSize() ); optionCopy.textElideMode = Qt::ElideNone; QStyledItemDelegate::paint( painter, optionCopy, index ); } QSize sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const { if ( !index.isValid() || !index.internalPointer() ) { return QSize(); } QStyleOptionViewItemV4 optionCopy( *static_cast<const QStyleOptionViewItemV4*>( &option ) ); optionCopy.decorationPosition = QStyleOptionViewItem::Top; optionCopy.decorationSize = mNavigator->showIcons() ? QSize( mNavigator->iconSize(), mNavigator->iconSize() ) : QSize(); optionCopy.textElideMode = Qt::ElideNone; return QStyledItemDelegate::sizeHint( optionCopy, index ); } private: Navigator *mNavigator; }; Navigator::Navigator( SidePaneBase *parent ) : QListView( parent ), mSidePane( parent ) { setViewport( new QWidget( this ) ); setVerticalScrollMode( ScrollPerPixel ); setHorizontalScrollMode( ScrollPerPixel ); mIconSize = Prefs::self()->sidePaneIconSize(); mShowIcons = Prefs::self()->sidePaneShowIcons(); mShowText = Prefs::self()->sidePaneShowText(); QActionGroup *viewMode = new QActionGroup( this ); mShowIconsAction = new KAction( i18n( "Show Icons Only" ), this ); mShowIconsAction->setCheckable( true ); mShowIconsAction->setActionGroup( viewMode ); mShowIconsAction->setChecked( !mShowText && mShowIcons ); connect( mShowIconsAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); mShowTextAction = new KAction( i18n( "Show Text Only" ), this ); mShowTextAction->setCheckable( true ); mShowTextAction->setActionGroup( viewMode ); mShowTextAction->setChecked( mShowText && !mShowIcons ); connect( mShowTextAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); mShowBothAction = new KAction( i18n( "Show Icons and Text" ), this ); mShowBothAction->setCheckable( true ); mShowBothAction->setActionGroup( viewMode ); mShowBothAction->setChecked( mShowText && mShowIcons ); connect( mShowBothAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); KAction *sep = new KAction( this ); sep->setSeparator( true ); QActionGroup *iconSize = new QActionGroup( this ); mBigIconsAction = new KAction( i18n( "Big Icons" ), this ); mBigIconsAction->setCheckable( iconSize ); mBigIconsAction->setActionGroup( iconSize ); mBigIconsAction->setChecked( mIconSize == KIconLoader::SizeLarge ); connect( mBigIconsAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); mNormalIconsAction = new KAction( i18n( "Normal Icons" ), this ); mNormalIconsAction->setCheckable( true ); mNormalIconsAction->setActionGroup( iconSize ); mNormalIconsAction->setChecked( mIconSize == KIconLoader::SizeMedium ); connect( mNormalIconsAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); mSmallIconsAction = new KAction( i18n( "Small Icons" ), this ); mSmallIconsAction->setCheckable( true ); mSmallIconsAction->setActionGroup( iconSize ); mSmallIconsAction->setChecked( mIconSize == KIconLoader::SizeSmall ); connect( mSmallIconsAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); QList<QAction*> actionList; actionList << mShowIconsAction << mShowTextAction << mShowBothAction << sep << mBigIconsAction << mNormalIconsAction << mSmallIconsAction; insertActions( 0, actionList ); setContextMenuPolicy( Qt::ActionsContextMenu ); setViewMode( ListMode ); setItemDelegate( new Delegate( this ) ); mModel = new Model( this ); SortFilterProxyModel *sortFilterProxyModel = new SortFilterProxyModel; sortFilterProxyModel->setSourceModel( mModel ); setModel( sortFilterProxyModel ); setDragDropMode( DropOnly ); viewport()->setAcceptDrops( true ); setDropIndicatorShown( true ); connect( selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(slotCurrentChanged(QModelIndex)) ); } void Navigator::updatePlugins( QList<Kontact::Plugin*> plugins_ ) { QString currentPlugin; if ( currentIndex().isValid() ) { currentPlugin = currentIndex().model()->data( currentIndex(), Model::PluginName ).toString(); } QList<Kontact::Plugin*> pluginsToShow; foreach ( Kontact::Plugin *plugin, plugins_ ) { if ( plugin->showInSideBar() ) { pluginsToShow << plugin; } } mModel->setPluginList( pluginsToShow ); mModel->removeRows( 0, mModel->rowCount() ); mModel->insertRows( 0, pluginsToShow.count() ); // Restore the previous selected index, if any if ( !currentPlugin.isEmpty() ) { setCurrentPlugin(currentPlugin); } } void Navigator::setCurrentPlugin( const QString &plugin ) { for ( int i = 0; i < model()->rowCount(); i++ ) { const QModelIndex index = model()->index( i, 0 ); const QString pluginName = model()->data( index, Model::PluginName ).toString(); if ( plugin == pluginName ) { selectionModel()->setCurrentIndex( index, QItemSelectionModel::SelectCurrent ); break; } } } QSize Navigator::sizeHint() const { //### TODO: We can cache this value, so this reply is faster. Since here we won't // have too many elements, it is not that important. When caching this value // make sure it is updated correctly when new rows have been added or // removed. (ereslibre) int maxWidth = 0; for ( int i = 0; i < model()->rowCount(); i++ ) { const QModelIndex index = model()->index( i, 0 ); maxWidth = qMax( maxWidth, sizeHintForIndex( index ).width() ); } if ( !verticalScrollBar()->isVisible() ) { maxWidth += style()->pixelMetric( QStyle::PM_ScrollBarExtent ) * 2; } int viewHeight = QListView::sizeHint().height(); return QSize( maxWidth + rect().width() - contentsRect().width(), viewHeight ); } void Navigator::dragEnterEvent( QDragEnterEvent *event ) { if ( event->proposedAction() == Qt::IgnoreAction ) { return; } event->acceptProposedAction(); } void Navigator::dragMoveEvent( QDragMoveEvent *event ) { if ( event->proposedAction() == Qt::IgnoreAction ) { return; } const QModelIndex dropIndex = indexAt( event->pos() ); if ( !dropIndex.isValid() || !( dropIndex.model()->flags( dropIndex ) & Qt::ItemIsEnabled ) ) { event->setAccepted( false ); return; } else { const QModelIndex sourceIndex = static_cast<const QSortFilterProxyModel*>( model() )->mapToSource( dropIndex ); Kontact::Plugin *plugin = static_cast<Kontact::Plugin*>( sourceIndex.internalPointer() ); if ( !plugin->canDecodeMimeData( event->mimeData() ) ) { event->setAccepted( false ); return; } } event->acceptProposedAction(); } void Navigator::dropEvent( QDropEvent *event ) { if ( event->proposedAction() == Qt::IgnoreAction ) { return; } const QModelIndex dropIndex = indexAt( event->pos() ); if ( !dropIndex.isValid() ) { return; } else { const QModelIndex sourceIndex = static_cast<const QSortFilterProxyModel*>( model() )->mapToSource( dropIndex ); Kontact::Plugin *plugin = static_cast<Kontact::Plugin*>( sourceIndex.internalPointer() ); plugin->processDropEvent( event ); } } void Navigator::slotCurrentChanged( const QModelIndex &current ) { if ( !current.isValid() || !current.internalPointer() || !( current.model()->flags( current ) & Qt::ItemIsEnabled ) ) { return; } QModelIndex source = static_cast<const QSortFilterProxyModel*>( current.model() )->mapToSource( current ); emit pluginActivated( static_cast<Kontact::Plugin*>( source.internalPointer() ) ); } void Navigator::slotActionTriggered( bool checked ) { QObject *object = sender(); if ( object == mShowIconsAction ) { mShowIcons = checked; mShowText = !checked; } else if ( object == mShowTextAction ) { mShowIcons = !checked; mShowText = checked; } else if ( object == mShowBothAction ) { mShowIcons = checked; mShowText = checked; } else if ( object == mBigIconsAction ) { mIconSize = KIconLoader::SizeLarge; } else if ( object == mNormalIconsAction ) { mIconSize = KIconLoader::SizeMedium; } else if ( object == mSmallIconsAction ) { mIconSize = KIconLoader::SizeSmallMedium; } Prefs::self()->setSidePaneIconSize( mIconSize ); Prefs::self()->setSidePaneShowIcons( mShowIcons ); Prefs::self()->setSidePaneShowText( mShowText ); scheduleDelayedItemsLayout(); parentWidget()->setMaximumWidth( sizeHint().width() ); parentWidget()->setMinimumWidth( sizeHint().width() ); } IconSidePane::IconSidePane( Core *core, QWidget *parent ) : SidePaneBase( core, parent ) { mNavigator = new Navigator( this ); connect( mNavigator, SIGNAL(pluginActivated(Kontact::Plugin*)), SIGNAL(pluginSelected(Kontact::Plugin*)) ); } IconSidePane::~IconSidePane() { } void IconSidePane::setCurrentPlugin( const QString &plugin ) { mNavigator->setCurrentPlugin( plugin ); } void IconSidePane::updatePlugins() { mNavigator->updatePlugins( core()->pluginList() ); } } #include "iconsidepane.moc" // vim: sw=2 sts=2 et tw=80 <commit_msg>Ooops, coding style issue<commit_after>/* This file is part of KDE Kontact. Copyright (C) 2003 Cornelius Schumacher <[email protected]> Copyright (C) 2008 Rafael Fernández López <[email protected]> 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; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "iconsidepane.h" #include "mainwindow.h" #include "plugin.h" #include "prefs.h" #include <QtGui/QStringListModel> #include <QtGui/QSortFilterProxyModel> #include <QtGui/QDragEnterEvent> #include <QtGui/QDragMoveEvent> #include <QtGui/QStyledItemDelegate> #include <QtGui/QScrollBar> #include <KLocalizedString> #include <KDialog> #include <KIcon> namespace Kontact { class Navigator; class Model : public QStringListModel { public: enum SpecialRoles { PluginName = Qt::UserRole }; Model( Navigator *parentNavigator = 0 ) : QStringListModel( parentNavigator ), mNavigator(parentNavigator) { } void setPluginList( const QList<Kontact::Plugin*> &list ) { pluginList = list; } virtual Qt::ItemFlags flags( const QModelIndex &index ) const { Qt::ItemFlags flags = QStringListModel::flags( index ); if ( index.isValid() ) { if ( static_cast<Kontact::Plugin*>( index.internalPointer() )->disabled() ) { flags &= ~Qt::ItemIsEnabled; flags &= ~Qt::ItemIsSelectable; flags &= ~Qt::ItemIsDropEnabled; } else { flags |= Qt::ItemIsDropEnabled; } } else { flags &= ~Qt::ItemIsDropEnabled; } return flags; } virtual QModelIndex index( int row, int column, const QModelIndex &parent = QModelIndex() ) const { Q_UNUSED( parent ); if ( row < 0 || row >= pluginList.count() ) { return QModelIndex(); } return createIndex( row, column, pluginList[row] ); } virtual QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const { if ( !index.isValid() || !index.internalPointer() ) { return QVariant(); } if ( role == Qt::DisplayRole ) { if ( !mNavigator->showText() ) { return QVariant(); } return static_cast<Kontact::Plugin*>( index.internalPointer() )->title(); } else if ( role == Qt::DecorationRole ) { if ( !mNavigator->showIcons() ) { return QVariant(); } return KIcon( static_cast<Kontact::Plugin*>( index.internalPointer() )->icon() ); } else if ( role == Qt::TextAlignmentRole ) { return Qt::AlignCenter; } else if ( role == Qt::ToolTipRole ) { if ( !mNavigator->showText() ) { return static_cast<Kontact::Plugin*>( index.internalPointer() )->title(); } return QVariant(); } else if ( role == PluginName ) { return static_cast<Kontact::Plugin*>( index.internalPointer() )->identifier(); } return QStringListModel::data( index, role ); } private: QList<Kontact::Plugin*> pluginList; Navigator *mNavigator; }; class SortFilterProxyModel : public QSortFilterProxyModel { public: SortFilterProxyModel( QObject *parent = 0 ): QSortFilterProxyModel( parent ) { setDynamicSortFilter( true ); sort ( 0 ); } protected: bool lessThan( const QModelIndex &left, const QModelIndex &right ) const { Kontact::Plugin *leftPlugin = static_cast<Kontact::Plugin*>( left.internalPointer() ); Kontact::Plugin *rightPlugin = static_cast<Kontact::Plugin*>( right.internalPointer() ); return leftPlugin->weight() < rightPlugin->weight(); } }; class Delegate : public QStyledItemDelegate { public: Delegate( Navigator *parentNavigator = 0 ) : QStyledItemDelegate( parentNavigator ), mNavigator( parentNavigator ) { } void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { if ( !index.isValid() || !index.internalPointer() ) { return; } QStyleOptionViewItemV4 optionCopy( *static_cast<const QStyleOptionViewItemV4*>( &option ) ); optionCopy.decorationPosition = QStyleOptionViewItem::Top; optionCopy.decorationSize = QSize( mNavigator->iconSize(), mNavigator->iconSize() ); optionCopy.textElideMode = Qt::ElideNone; QStyledItemDelegate::paint( painter, optionCopy, index ); } QSize sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const { if ( !index.isValid() || !index.internalPointer() ) { return QSize(); } QStyleOptionViewItemV4 optionCopy( *static_cast<const QStyleOptionViewItemV4*>( &option ) ); optionCopy.decorationPosition = QStyleOptionViewItem::Top; optionCopy.decorationSize = mNavigator->showIcons() ? QSize( mNavigator->iconSize(), mNavigator->iconSize() ) : QSize(); optionCopy.textElideMode = Qt::ElideNone; return QStyledItemDelegate::sizeHint( optionCopy, index ); } private: Navigator *mNavigator; }; Navigator::Navigator( SidePaneBase *parent ) : QListView( parent ), mSidePane( parent ) { setViewport( new QWidget( this ) ); setVerticalScrollMode( ScrollPerPixel ); setHorizontalScrollMode( ScrollPerPixel ); mIconSize = Prefs::self()->sidePaneIconSize(); mShowIcons = Prefs::self()->sidePaneShowIcons(); mShowText = Prefs::self()->sidePaneShowText(); QActionGroup *viewMode = new QActionGroup( this ); mShowIconsAction = new KAction( i18n( "Show Icons Only" ), this ); mShowIconsAction->setCheckable( true ); mShowIconsAction->setActionGroup( viewMode ); mShowIconsAction->setChecked( !mShowText && mShowIcons ); connect( mShowIconsAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); mShowTextAction = new KAction( i18n( "Show Text Only" ), this ); mShowTextAction->setCheckable( true ); mShowTextAction->setActionGroup( viewMode ); mShowTextAction->setChecked( mShowText && !mShowIcons ); connect( mShowTextAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); mShowBothAction = new KAction( i18n( "Show Icons and Text" ), this ); mShowBothAction->setCheckable( true ); mShowBothAction->setActionGroup( viewMode ); mShowBothAction->setChecked( mShowText && mShowIcons ); connect( mShowBothAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); KAction *sep = new KAction( this ); sep->setSeparator( true ); QActionGroup *iconSize = new QActionGroup( this ); mBigIconsAction = new KAction( i18n( "Big Icons" ), this ); mBigIconsAction->setCheckable( iconSize ); mBigIconsAction->setActionGroup( iconSize ); mBigIconsAction->setChecked( mIconSize == KIconLoader::SizeLarge ); connect( mBigIconsAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); mNormalIconsAction = new KAction( i18n( "Normal Icons" ), this ); mNormalIconsAction->setCheckable( true ); mNormalIconsAction->setActionGroup( iconSize ); mNormalIconsAction->setChecked( mIconSize == KIconLoader::SizeMedium ); connect( mNormalIconsAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); mSmallIconsAction = new KAction( i18n( "Small Icons" ), this ); mSmallIconsAction->setCheckable( true ); mSmallIconsAction->setActionGroup( iconSize ); mSmallIconsAction->setChecked( mIconSize == KIconLoader::SizeSmall ); connect( mSmallIconsAction, SIGNAL(triggered(bool)), this, SLOT(slotActionTriggered(bool)) ); QList<QAction*> actionList; actionList << mShowIconsAction << mShowTextAction << mShowBothAction << sep << mBigIconsAction << mNormalIconsAction << mSmallIconsAction; insertActions( 0, actionList ); setContextMenuPolicy( Qt::ActionsContextMenu ); setViewMode( ListMode ); setItemDelegate( new Delegate( this ) ); mModel = new Model( this ); SortFilterProxyModel *sortFilterProxyModel = new SortFilterProxyModel; sortFilterProxyModel->setSourceModel( mModel ); setModel( sortFilterProxyModel ); setDragDropMode( DropOnly ); viewport()->setAcceptDrops( true ); setDropIndicatorShown( true ); connect( selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(slotCurrentChanged(QModelIndex)) ); } void Navigator::updatePlugins( QList<Kontact::Plugin*> plugins_ ) { QString currentPlugin; if ( currentIndex().isValid() ) { currentPlugin = currentIndex().model()->data( currentIndex(), Model::PluginName ).toString(); } QList<Kontact::Plugin*> pluginsToShow; foreach ( Kontact::Plugin *plugin, plugins_ ) { if ( plugin->showInSideBar() ) { pluginsToShow << plugin; } } mModel->setPluginList( pluginsToShow ); mModel->removeRows( 0, mModel->rowCount() ); mModel->insertRows( 0, pluginsToShow.count() ); // Restore the previous selected index, if any if ( !currentPlugin.isEmpty() ) { setCurrentPlugin( currentPlugin ); } } void Navigator::setCurrentPlugin( const QString &plugin ) { for ( int i = 0; i < model()->rowCount(); i++ ) { const QModelIndex index = model()->index( i, 0 ); const QString pluginName = model()->data( index, Model::PluginName ).toString(); if ( plugin == pluginName ) { selectionModel()->setCurrentIndex( index, QItemSelectionModel::SelectCurrent ); break; } } } QSize Navigator::sizeHint() const { //### TODO: We can cache this value, so this reply is faster. Since here we won't // have too many elements, it is not that important. When caching this value // make sure it is updated correctly when new rows have been added or // removed. (ereslibre) int maxWidth = 0; for ( int i = 0; i < model()->rowCount(); i++ ) { const QModelIndex index = model()->index( i, 0 ); maxWidth = qMax( maxWidth, sizeHintForIndex( index ).width() ); } if ( !verticalScrollBar()->isVisible() ) { maxWidth += style()->pixelMetric( QStyle::PM_ScrollBarExtent ) * 2; } int viewHeight = QListView::sizeHint().height(); return QSize( maxWidth + rect().width() - contentsRect().width(), viewHeight ); } void Navigator::dragEnterEvent( QDragEnterEvent *event ) { if ( event->proposedAction() == Qt::IgnoreAction ) { return; } event->acceptProposedAction(); } void Navigator::dragMoveEvent( QDragMoveEvent *event ) { if ( event->proposedAction() == Qt::IgnoreAction ) { return; } const QModelIndex dropIndex = indexAt( event->pos() ); if ( !dropIndex.isValid() || !( dropIndex.model()->flags( dropIndex ) & Qt::ItemIsEnabled ) ) { event->setAccepted( false ); return; } else { const QModelIndex sourceIndex = static_cast<const QSortFilterProxyModel*>( model() )->mapToSource( dropIndex ); Kontact::Plugin *plugin = static_cast<Kontact::Plugin*>( sourceIndex.internalPointer() ); if ( !plugin->canDecodeMimeData( event->mimeData() ) ) { event->setAccepted( false ); return; } } event->acceptProposedAction(); } void Navigator::dropEvent( QDropEvent *event ) { if ( event->proposedAction() == Qt::IgnoreAction ) { return; } const QModelIndex dropIndex = indexAt( event->pos() ); if ( !dropIndex.isValid() ) { return; } else { const QModelIndex sourceIndex = static_cast<const QSortFilterProxyModel*>( model() )->mapToSource( dropIndex ); Kontact::Plugin *plugin = static_cast<Kontact::Plugin*>( sourceIndex.internalPointer() ); plugin->processDropEvent( event ); } } void Navigator::slotCurrentChanged( const QModelIndex &current ) { if ( !current.isValid() || !current.internalPointer() || !( current.model()->flags( current ) & Qt::ItemIsEnabled ) ) { return; } QModelIndex source = static_cast<const QSortFilterProxyModel*>( current.model() )->mapToSource( current ); emit pluginActivated( static_cast<Kontact::Plugin*>( source.internalPointer() ) ); } void Navigator::slotActionTriggered( bool checked ) { QObject *object = sender(); if ( object == mShowIconsAction ) { mShowIcons = checked; mShowText = !checked; } else if ( object == mShowTextAction ) { mShowIcons = !checked; mShowText = checked; } else if ( object == mShowBothAction ) { mShowIcons = checked; mShowText = checked; } else if ( object == mBigIconsAction ) { mIconSize = KIconLoader::SizeLarge; } else if ( object == mNormalIconsAction ) { mIconSize = KIconLoader::SizeMedium; } else if ( object == mSmallIconsAction ) { mIconSize = KIconLoader::SizeSmallMedium; } Prefs::self()->setSidePaneIconSize( mIconSize ); Prefs::self()->setSidePaneShowIcons( mShowIcons ); Prefs::self()->setSidePaneShowText( mShowText ); scheduleDelayedItemsLayout(); parentWidget()->setMaximumWidth( sizeHint().width() ); parentWidget()->setMinimumWidth( sizeHint().width() ); } IconSidePane::IconSidePane( Core *core, QWidget *parent ) : SidePaneBase( core, parent ) { mNavigator = new Navigator( this ); connect( mNavigator, SIGNAL(pluginActivated(Kontact::Plugin*)), SIGNAL(pluginSelected(Kontact::Plugin*)) ); } IconSidePane::~IconSidePane() { } void IconSidePane::setCurrentPlugin( const QString &plugin ) { mNavigator->setCurrentPlugin( plugin ); } void IconSidePane::updatePlugins() { mNavigator->updatePlugins( core()->pluginList() ); } } #include "iconsidepane.moc" // vim: sw=2 sts=2 et tw=80 <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <[email protected]> Copyright (C) 2003-2004 Reinhold Kainhofer <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ // ArchiveDialog -- archive/delete past events. #include "archivedialog.h" #include "koprefs.h" #include "eventarchiver.h" #include <libkdepim/kdateedit.h> #include <kdebug.h> #include <klocale.h> #include <knuminput.h> #include <kurlrequester.h> #include <kmessagebox.h> #include <kfiledialog.h> #include <kurl.h> #include <klineedit.h> #include <kvbox.h> #include <KComboBox> #include <KTextBrowser> #include <QLabel> #include <QLayout> #include <QDateTime> #include <QCheckBox> #include <QVBoxLayout> #include <QFrame> #include <QHBoxLayout> #include <QButtonGroup> #include <QRadioButton> #include "archivedialog.moc" ArchiveDialog::ArchiveDialog(Calendar *cal,QWidget *parent) : KDialog (parent) { setCaption( i18nc( "@title:window", "Archive/Delete Past Events and To-dos" ) ); setButtons( User1|Cancel ); setDefaultButton( User1 ); setModal( false ); showButtonSeparator( true ); setButtonText( User1, i18nc( "@action:button", "&Archive" ) ); mCalendar = cal; QFrame *topFrame = new QFrame( this ); setMainWidget( topFrame ); QVBoxLayout *topLayout = new QVBoxLayout(topFrame); topLayout->setSpacing(spacingHint()); KTextBrowser *descLabel = new KTextBrowser(topFrame); descLabel->setText( i18nc( "@info:whatsthis", "Archiving saves old items into the given file and " "then deletes them in the current calendar. If the archive file " "already exists they will be added. " "(<link url=\"whatsthis:In order to add an archive " "to your calendar, use the &quot;Merge Calendar&quot; function. " "You can view an archive by opening it in KOrganizer like any " "other calendar. It is not saved in a special format, but as " "vCalendar.\">How to restore</link>)" ) ); descLabel->setTextInteractionFlags(Qt::TextSelectableByMouse|Qt::TextSelectableByKeyboard | Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard ); topLayout->addWidget(descLabel); QButtonGroup* radioBG = new QButtonGroup( this ); connect( radioBG, SIGNAL( buttonClicked( int ) ), SLOT( slotActionChanged() ) ); QHBoxLayout *dateLayout = new QHBoxLayout(); dateLayout->setMargin( 0 ); mArchiveOnceRB = new QRadioButton( i18nc( "@option:radio", "Archive now items older than:" ),topFrame ); dateLayout->addWidget(mArchiveOnceRB); radioBG->addButton(mArchiveOnceRB); mDateEdit = new KPIM::KDateEdit(topFrame); mDateEdit->setWhatsThis( i18nc( "@info:whatsthis", "The date before which items should be archived. All older events " "and to-dos will be saved and deleted, the newer (and events " "exactly on that date) will be kept." ) ); dateLayout->addWidget(mDateEdit); topLayout->addLayout(dateLayout); // Checkbox, numinput and combo for auto-archiving // (similar to kmail's mExpireFolderCheckBox/mReadExpiryTimeNumInput in kmfolderdia.cpp) KHBox* autoArchiveHBox = new KHBox(topFrame); topLayout->addWidget(autoArchiveHBox); mAutoArchiveRB = new QRadioButton( i18nc( "@option:radio", "Automaticall&y archive items older than:" ), autoArchiveHBox ); radioBG->addButton(mAutoArchiveRB); mAutoArchiveRB->setWhatsThis( i18nc( "@info:whatsthis", "If this feature is enabled, KOrganizer will regularly check if " "events and to-dos have to be archived; this means you will not " "need to use this dialog box again, except to change the settings." ) ); mExpiryTimeNumInput = new KIntNumInput(autoArchiveHBox); mExpiryTimeNumInput->setRange(1, 500, 1); mExpiryTimeNumInput->setSliderEnabled(false); mExpiryTimeNumInput->setEnabled(false); mExpiryTimeNumInput->setValue(7); mExpiryTimeNumInput->setWhatsThis( i18nc( "@info:whatsthis", "The age of the events and to-dos to archive. All older items " "will be saved and deleted, the newer will be kept." ) ); mExpiryUnitsComboBox = new KComboBox(autoArchiveHBox); // Those items must match the "Expiry Unit" enum in the kcfg file! mExpiryUnitsComboBox->addItem( i18nc( "@item:inlistbox expires in daily units", "Day(s)" ) ); mExpiryUnitsComboBox->addItem( i18nc( "@item:inlistbox expiration in weekly units", "Week(s)" ) ); mExpiryUnitsComboBox->addItem( i18nc( "@item:inlistbox expiration in monthly units", "Month(s)" ) ); mExpiryUnitsComboBox->setEnabled( false ); QHBoxLayout *fileLayout = new QHBoxLayout(); fileLayout->setMargin( 0 ); fileLayout->setSpacing(spacingHint()); QLabel *l = new QLabel( i18nc( "@label", "Archive &file:" ),topFrame ); fileLayout->addWidget(l); mArchiveFile = new KUrlRequester(KOPrefs::instance()->mArchiveFile,topFrame); mArchiveFile->setMode(KFile::File); mArchiveFile->setFilter( i18nc( "@label filter for KUrlRequester", "*.ics|iCalendar Files" ) ); mArchiveFile->setWhatsThis( i18nc( "@info:whatsthis", "The path of the archive. The events and to-dos will be added to " "the archive file, so any events that are already in the file " "will not be modified or deleted. You can later load or merge the " "file like any other calendar. It is not saved in a special " "format, it uses the iCalendar format." ) ); l->setBuddy(mArchiveFile->lineEdit()); fileLayout->addWidget(mArchiveFile); topLayout->addLayout(fileLayout); QGroupBox *typeBox = new QGroupBox( i18nc( "@title:group", "Type of Items to Archive" ) ); topLayout->addWidget( typeBox ); QBoxLayout *typeLayout = new QVBoxLayout( typeBox ); mEvents = new QCheckBox( i18nc( "@option:check", "&Events" ) ); typeLayout->addWidget( mEvents ); mTodos = new QCheckBox( i18nc( "@option:check", "&To-dos") ); typeLayout->addWidget( mTodos ); typeBox->setWhatsThis( i18nc( "@info:whatsthis", "Here you can select which items " "should be archived. Events are archived if they " "ended before the date given above; to-dos are archived if " "they were finished before the date.") ); mDeleteCb = new QCheckBox( i18nc( "@option:check", "&Delete only, do not save" ), topFrame ); mDeleteCb->setWhatsThis( i18nc( "@info:whatsthis", "Select this option to delete old events and to-dos without saving them. " "It is not possible to recover the events later." ) ); topLayout->addWidget(mDeleteCb); connect(mDeleteCb, SIGNAL(toggled(bool)), mArchiveFile, SLOT(setDisabled(bool))); connect(mDeleteCb, SIGNAL(toggled(bool)), this, SLOT(slotEnableUser1())); connect(mArchiveFile->lineEdit(),SIGNAL(textChanged ( const QString & )), this,SLOT(slotEnableUser1())); // Load settings from KOPrefs mExpiryTimeNumInput->setValue( KOPrefs::instance()->mExpiryTime ); mExpiryUnitsComboBox->setCurrentIndex( KOPrefs::instance()->mExpiryUnit ); mDeleteCb->setChecked( KOPrefs::instance()->mArchiveAction == KOPrefs::actionDelete ); mEvents->setChecked( KOPrefs::instance()->mArchiveEvents ); mTodos->setChecked( KOPrefs::instance()->mArchiveTodos ); slotEnableUser1(); // The focus should go to a useful field by default, not to the top richtext-label if ( KOPrefs::instance()->mAutoArchive ) { mAutoArchiveRB->setChecked( true ); mAutoArchiveRB->setFocus(); } else { mArchiveOnceRB->setChecked( true ); mArchiveOnceRB->setFocus(); } slotActionChanged(); connect(this,SIGNAL(user1Clicked()),this,SLOT(slotUser1())); } ArchiveDialog::~ArchiveDialog() { } void ArchiveDialog::slotEnableUser1() { bool state = ( mDeleteCb->isChecked() || !mArchiveFile->lineEdit()->text().isEmpty() ); enableButton(KDialog::User1,state); } void ArchiveDialog::slotActionChanged() { mDateEdit->setEnabled( mArchiveOnceRB->isChecked() ); mExpiryTimeNumInput->setEnabled( mAutoArchiveRB->isChecked() ); mExpiryUnitsComboBox->setEnabled( mAutoArchiveRB->isChecked() ); } // Archive old events void ArchiveDialog::slotUser1() { EventArchiver archiver; connect( &archiver, SIGNAL( eventsDeleted() ), this, SLOT( slotEventsDeleted() ) ); KOPrefs::instance()->mAutoArchive = mAutoArchiveRB->isChecked(); KOPrefs::instance()->mExpiryTime = mExpiryTimeNumInput->value(); KOPrefs::instance()->mExpiryUnit = mExpiryUnitsComboBox->currentIndex(); if (mDeleteCb->isChecked()) { KOPrefs::instance()->mArchiveAction = KOPrefs::actionDelete; } else { KOPrefs::instance()->mArchiveAction = KOPrefs::actionArchive; // Get destination URL KUrl destUrl( mArchiveFile->url() ); if ( !destUrl.isValid() ) { KMessageBox::sorry( this, i18nc( "@info", "The archive file name is not valid." ) ); return; } // Force filename to be ending with vCalendar extension QString filename = destUrl.fileName(); if (!filename.endsWith(".vcs") && !filename.endsWith(".ics")) { filename.append(".ics"); destUrl.setFileName(filename); } KOPrefs::instance()->mArchiveFile = destUrl.url(); } if ( KOPrefs::instance()->mAutoArchive ) { archiver.runAuto( mCalendar, this, true /*with gui*/ ); emit autoArchivingSettingsModified(); accept(); } else archiver.runOnce( mCalendar, mDateEdit->date(), this ); } void ArchiveDialog::slotEventsDeleted() { emit eventsDeleted(); if ( !KOPrefs::instance()->mAutoArchive ) accept(); } <commit_msg>minor coding style fixes SVN_SILENT:<commit_after>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <[email protected]> Copyright (C) 2003-2004 Reinhold Kainhofer <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ // ArchiveDialog -- archive/delete past events. #include "archivedialog.h" #include "koprefs.h" #include "eventarchiver.h" #include <libkdepim/kdateedit.h> #include <kdebug.h> #include <klocale.h> #include <knuminput.h> #include <kurlrequester.h> #include <kmessagebox.h> #include <kfiledialog.h> #include <kurl.h> #include <klineedit.h> #include <kvbox.h> #include <KComboBox> #include <KTextBrowser> #include <QLabel> #include <QLayout> #include <QDateTime> #include <QCheckBox> #include <QVBoxLayout> #include <QFrame> #include <QHBoxLayout> #include <QButtonGroup> #include <QRadioButton> #include "archivedialog.moc" ArchiveDialog::ArchiveDialog( Calendar *cal, QWidget *parent ) : KDialog (parent) { setCaption( i18nc( "@title:window", "Archive/Delete Past Events and To-dos" ) ); setButtons( User1|Cancel ); setDefaultButton( User1 ); setModal( false ); showButtonSeparator( true ); setButtonText( User1, i18nc( "@action:button", "&Archive" ) ); mCalendar = cal; QFrame *topFrame = new QFrame( this ); setMainWidget( topFrame ); QVBoxLayout *topLayout = new QVBoxLayout( topFrame ); topLayout->setSpacing( spacingHint() ); KTextBrowser *descLabel = new KTextBrowser( topFrame ); descLabel->setText( i18nc( "@info:whatsthis", "Archiving saves old items into the given file and " "then deletes them in the current calendar. If the archive file " "already exists they will be added. " "(<link url=\"whatsthis:In order to add an archive " "to your calendar, use the &quot;Merge Calendar&quot; function. " "You can view an archive by opening it in KOrganizer like any " "other calendar. It is not saved in a special format, but as " "vCalendar.\">How to restore</link>)" ) ); descLabel->setTextInteractionFlags( Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard | Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard ); topLayout->addWidget( descLabel ); QButtonGroup *radioBG = new QButtonGroup( this ); connect( radioBG, SIGNAL(buttonClicked(int)), SLOT(slotActionChanged()) ); QHBoxLayout *dateLayout = new QHBoxLayout(); dateLayout->setMargin( 0 ); mArchiveOnceRB = new QRadioButton( i18nc( "@option:radio", "Archive now items older than:" ), topFrame ); dateLayout->addWidget( mArchiveOnceRB ); radioBG->addButton( mArchiveOnceRB ); mDateEdit = new KPIM::KDateEdit( topFrame ); mDateEdit->setWhatsThis( i18nc( "@info:whatsthis", "The date before which items should be archived. All older events " "and to-dos will be saved and deleted, the newer (and events " "exactly on that date) will be kept." ) ); dateLayout->addWidget( mDateEdit ); topLayout->addLayout( dateLayout ); // Checkbox, numinput and combo for auto-archiving (similar to kmail's // mExpireFolderCheckBox/mReadExpiryTimeNumInput in kmfolderdia.cpp) KHBox *autoArchiveHBox = new KHBox( topFrame ); topLayout->addWidget( autoArchiveHBox ); mAutoArchiveRB = new QRadioButton( i18nc( "@option:radio", "Automaticall&y archive items older than:" ), autoArchiveHBox ); radioBG->addButton( mAutoArchiveRB ); mAutoArchiveRB->setWhatsThis( i18nc( "@info:whatsthis", "If this feature is enabled, KOrganizer will regularly check if " "events and to-dos have to be archived; this means you will not " "need to use this dialog box again, except to change the settings." ) ); mExpiryTimeNumInput = new KIntNumInput( autoArchiveHBox ); mExpiryTimeNumInput->setRange( 1, 500, 1 ); mExpiryTimeNumInput->setSliderEnabled( false ); mExpiryTimeNumInput->setEnabled( false ); mExpiryTimeNumInput->setValue( 7 ); mExpiryTimeNumInput->setWhatsThis( i18nc( "@info:whatsthis", "The age of the events and to-dos to archive. All older items " "will be saved and deleted, the newer will be kept." ) ); mExpiryUnitsComboBox = new KComboBox( autoArchiveHBox ); // Those items must match the "Expiry Unit" enum in the kcfg file! mExpiryUnitsComboBox->addItem( i18nc( "@item:inlistbox expires in daily units", "Day(s)" ) ); mExpiryUnitsComboBox->addItem( i18nc( "@item:inlistbox expiration in weekly units", "Week(s)" ) ); mExpiryUnitsComboBox->addItem( i18nc( "@item:inlistbox expiration in monthly units", "Month(s)" ) ); mExpiryUnitsComboBox->setEnabled( false ); QHBoxLayout *fileLayout = new QHBoxLayout(); fileLayout->setMargin( 0 ); fileLayout->setSpacing( spacingHint() ); QLabel *l = new QLabel( i18nc( "@label", "Archive &file:" ), topFrame ); fileLayout->addWidget(l); mArchiveFile = new KUrlRequester( KOPrefs::instance()->mArchiveFile, topFrame ); mArchiveFile->setMode( KFile::File ); mArchiveFile->setFilter( i18nc( "@label filter for KUrlRequester", "*.ics|iCalendar Files" ) ); mArchiveFile->setWhatsThis( i18nc( "@info:whatsthis", "The path of the archive. The events and to-dos will be added to " "the archive file, so any events that are already in the file " "will not be modified or deleted. You can later load or merge the " "file like any other calendar. It is not saved in a special " "format, it uses the iCalendar format." ) ); l->setBuddy( mArchiveFile->lineEdit() ); fileLayout->addWidget( mArchiveFile ); topLayout->addLayout( fileLayout ); QGroupBox *typeBox = new QGroupBox( i18nc( "@title:group", "Type of Items to Archive" ) ); topLayout->addWidget( typeBox ); QBoxLayout *typeLayout = new QVBoxLayout( typeBox ); mEvents = new QCheckBox( i18nc( "@option:check", "&Events" ) ); typeLayout->addWidget( mEvents ); mTodos = new QCheckBox( i18nc( "@option:check", "&To-dos" ) ); typeLayout->addWidget( mTodos ); typeBox->setWhatsThis( i18nc( "@info:whatsthis", "Here you can select which items " "should be archived. Events are archived if they " "ended before the date given above; to-dos are archived if " "they were finished before the date." ) ); mDeleteCb = new QCheckBox( i18nc( "@option:check", "&Delete only, do not save" ), topFrame ); mDeleteCb->setWhatsThis( i18nc( "@info:whatsthis", "Select this option to delete old events and to-dos without saving " "them. It is not possible to recover the events later." ) ); topLayout->addWidget(mDeleteCb); connect( mDeleteCb, SIGNAL(toggled(bool)), mArchiveFile, SLOT(setDisabled(bool)) ); connect( mDeleteCb, SIGNAL(toggled(bool)), this, SLOT(slotEnableUser1()) ); connect( mArchiveFile->lineEdit(), SIGNAL(textChanged(const QString &)), this, SLOT(slotEnableUser1()) ); // Load settings from KOPrefs mExpiryTimeNumInput->setValue( KOPrefs::instance()->mExpiryTime ); mExpiryUnitsComboBox->setCurrentIndex( KOPrefs::instance()->mExpiryUnit ); mDeleteCb->setChecked( KOPrefs::instance()->mArchiveAction == KOPrefs::actionDelete ); mEvents->setChecked( KOPrefs::instance()->mArchiveEvents ); mTodos->setChecked( KOPrefs::instance()->mArchiveTodos ); slotEnableUser1(); // The focus should go to a useful field by default, not to the top richtext-label if ( KOPrefs::instance()->mAutoArchive ) { mAutoArchiveRB->setChecked( true ); mAutoArchiveRB->setFocus(); } else { mArchiveOnceRB->setChecked( true ); mArchiveOnceRB->setFocus(); } slotActionChanged(); connect( this, SIGNAL(user1Clicked()), this, SLOT(slotUser1()) ); } ArchiveDialog::~ArchiveDialog() { } void ArchiveDialog::slotEnableUser1() { bool state = ( mDeleteCb->isChecked() || !mArchiveFile->lineEdit()->text().isEmpty() ); enableButton( KDialog::User1, state ); } void ArchiveDialog::slotActionChanged() { mDateEdit->setEnabled( mArchiveOnceRB->isChecked() ); mExpiryTimeNumInput->setEnabled( mAutoArchiveRB->isChecked() ); mExpiryUnitsComboBox->setEnabled( mAutoArchiveRB->isChecked() ); } // Archive old events void ArchiveDialog::slotUser1() { EventArchiver archiver; connect( &archiver, SIGNAL(eventsDeleted()), this, SLOT(slotEventsDeleted()) ); KOPrefs::instance()->mAutoArchive = mAutoArchiveRB->isChecked(); KOPrefs::instance()->mExpiryTime = mExpiryTimeNumInput->value(); KOPrefs::instance()->mExpiryUnit = mExpiryUnitsComboBox->currentIndex(); if ( mDeleteCb->isChecked() ) { KOPrefs::instance()->mArchiveAction = KOPrefs::actionDelete; } else { KOPrefs::instance()->mArchiveAction = KOPrefs::actionArchive; // Get destination URL KUrl destUrl( mArchiveFile->url() ); if ( !destUrl.isValid() ) { KMessageBox::sorry( this, i18nc( "@info", "The archive file name is not valid." ) ); return; } // Force filename to be ending with vCalendar extension QString filename = destUrl.fileName(); if ( !filename.endsWith( ".vcs" ) && !filename.endsWith( ".ics" ) ) { filename.append( ".ics" ); destUrl.setFileName( filename ); } KOPrefs::instance()->mArchiveFile = destUrl.url(); } if ( KOPrefs::instance()->mAutoArchive ) { archiver.runAuto( mCalendar, this, true /*with gui*/); emit autoArchivingSettingsModified(); accept(); } else { archiver.runOnce( mCalendar, mDateEdit->date(), this ); } } void ArchiveDialog::slotEventsDeleted() { emit eventsDeleted(); if ( !KOPrefs::instance()->mAutoArchive ) { accept(); } } <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <[email protected]> Copyright (c) 2004 David Faure <[email protected]> Copyright (C) 2004 Reinhold Kainhofer <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "eventarchiver.h" #include "koprefs.h" #include <kio/netaccess.h> #include <kcal/filestorage.h> #include <kcal/calendarlocal.h> #include <kcal/calendar.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #include <ktemporaryfile.h> #include <kmessagebox.h> EventArchiver::EventArchiver( QObject* parent, const char* name ) : QObject( parent ) { setObjectName( name ); } EventArchiver::~EventArchiver() { } void EventArchiver::runOnce( Calendar* calendar, const QDate& limitDate, QWidget* widget ) { run( calendar, limitDate, widget, true, true ); } void EventArchiver::runAuto( Calendar* calendar, QWidget* widget, bool withGUI ) { QDate limitDate( QDate::currentDate() ); int expiryTime = KOPrefs::instance()->mExpiryTime; switch (KOPrefs::instance()->mExpiryUnit) { case KOPrefs::UnitDays: // Days limitDate = limitDate.addDays( -expiryTime ); break; case KOPrefs::UnitWeeks: // Weeks limitDate = limitDate.addDays( -expiryTime*7 ); break; case KOPrefs::UnitMonths: // Months limitDate = limitDate.addMonths( -expiryTime ); break; default: return; } run( calendar, limitDate, widget, withGUI, false ); } void EventArchiver::run( Calendar* calendar, const QDate& limitDate, QWidget* widget, bool withGUI, bool errorIfNone ) { // We need to use rawEvents, otherwise events hidden by filters will not be archived. Incidence::List incidences; Event::List events; Todo::List todos; Journal::List journals; if ( KOPrefs::instance()->mArchiveEvents ) { events = calendar->rawEvents( QDate( 1769, 12, 1 ), // #29555, also advertised by the "limitDate not included" in the class docu limitDate.addDays( -1 ), true ); } if ( KOPrefs::instance()->mArchiveTodos ) { Todo::List t = calendar->rawTodos(); Todo::List::ConstIterator it; for( it = t.begin(); it != t.end(); ++it ) { if ( (*it) && ( (*it)->isCompleted() ) && ( (*it)->completed().date() < limitDate ) ) { todos.append( *it ); } } } incidences = Calendar::mergeIncidenceList( events, todos, journals ); kDebug(5850) << "EventArchiver: archiving incidences before " << limitDate << " -> " << incidences.count() << " incidences found." << endl; if ( incidences.isEmpty() ) { if ( withGUI && errorIfNone ) KMessageBox::information( widget, i18n("There are no items before %1", KGlobal::locale()->formatDate(limitDate)), "ArchiverNoIncidences" ); return; } switch ( KOPrefs::instance()->mArchiveAction ) { case KOPrefs::actionDelete: deleteIncidences( calendar, limitDate, widget, incidences, withGUI ); break; case KOPrefs::actionArchive: archiveIncidences( calendar, limitDate, widget, incidences, withGUI ); break; } } void EventArchiver::deleteIncidences( Calendar* calendar, const QDate& limitDate, QWidget* widget, const Incidence::List& incidences, bool withGUI ) { QStringList incidenceStrs; Incidence::List::ConstIterator it; for( it = incidences.begin(); it != incidences.end(); ++it ) { incidenceStrs.append( (*it)->summary() ); } if ( withGUI ) { int result = KMessageBox::warningContinueCancelList( widget, i18n("Delete all items before %1 without saving?\n" "The following items will be deleted:", KGlobal::locale()->formatDate(limitDate)), incidenceStrs, i18n("Delete Old Items"),KStandardGuiItem::del()); if (result != KMessageBox::Continue) return; } for( it = incidences.begin(); it != incidences.end(); ++it ) { calendar->deleteIncidence( *it ); } emit eventsDeleted(); } void EventArchiver::archiveIncidences( Calendar* calendar, const QDate& /*limitDate*/, QWidget* widget, const Incidence::List& incidences, bool /*withGUI*/) { FileStorage storage( calendar ); // Save current calendar to disk KTemporaryFile tmpFile; tmpFile.open(); storage.setFileName( tmpFile.fileName() ); if ( !storage.save() ) { kDebug(5850) << "EventArchiver::archiveEvents(): Can't save calendar to temp file" << endl; return; } // Duplicate current calendar by loading in new calendar object #ifdef __GNUC__ #warning Does the time zone specification serve any purpose? #endif CalendarLocal archiveCalendar( KOPrefs::instance()->timeSpec() ); FileStorage archiveStore( &archiveCalendar ); archiveStore.setFileName( tmpFile.fileName() ); if (!archiveStore.load()) { kDebug(5850) << "EventArchiver::archiveEvents(): Can't load calendar from temp file" << endl; return; } // Strip active events from calendar so that only events to be archived // remain. This is not really efficient, but there is no other easy way. QStringList uids; Incidence::List allIncidences = archiveCalendar.rawIncidences(); Incidence::List::ConstIterator it; for( it = incidences.begin(); it != incidences.end(); ++it ) { uids << (*it)->uid(); } for( it = allIncidences.begin(); it != allIncidences.end(); ++it ) { if ( !uids.contains( (*it)->uid() ) ) { archiveCalendar.deleteIncidence( *it ); } } // Get or create the archive file KUrl archiveURL( KOPrefs::instance()->mArchiveFile ); QString archiveFile; if ( KIO::NetAccess::exists( archiveURL, true, widget ) ) { if( !KIO::NetAccess::download( archiveURL, archiveFile, widget ) ) { kDebug(5850) << "EventArchiver::archiveEvents(): Can't download archive file" << endl; return; } // Merge with events to be archived. archiveStore.setFileName( archiveFile ); if ( !archiveStore.load() ) { kDebug(5850) << "EventArchiver::archiveEvents(): Can't merge with archive file" << endl; return; } } else { archiveFile = tmpFile.fileName(); } // Save archive calendar if ( !archiveStore.save() ) { KMessageBox::error(widget,i18n("Cannot write archive file %1.", archiveStore.fileName() )); return; } // Upload if necessary KUrl srcUrl; srcUrl.setPath(archiveFile); if (srcUrl != archiveURL) { if ( !KIO::NetAccess::upload( archiveFile, archiveURL, widget ) ) { KMessageBox::error(widget,i18n("Cannot write archive to final destination.")); return; } } KIO::NetAccess::removeTempFile(archiveFile); // Delete archived events from calendar for( it = incidences.begin(); it != incidences.end(); ++it ) { calendar->deleteIncidence( *it ); } emit eventsDeleted(); } #include "eventarchiver.moc" <commit_msg>Follow KCal::Calendar::rawEvents time zone changes<commit_after>/* This file is part of KOrganizer. Copyright (c) 2000,2001 Cornelius Schumacher <[email protected]> Copyright (c) 2004 David Faure <[email protected]> Copyright (C) 2004 Reinhold Kainhofer <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "eventarchiver.h" #include "koprefs.h" #include <kio/netaccess.h> #include <kcal/filestorage.h> #include <kcal/calendarlocal.h> #include <kcal/calendar.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #include <ktemporaryfile.h> #include <kmessagebox.h> EventArchiver::EventArchiver( QObject* parent, const char* name ) : QObject( parent ) { setObjectName( name ); } EventArchiver::~EventArchiver() { } void EventArchiver::runOnce( Calendar* calendar, const QDate& limitDate, QWidget* widget ) { run( calendar, limitDate, widget, true, true ); } void EventArchiver::runAuto( Calendar* calendar, QWidget* widget, bool withGUI ) { QDate limitDate( QDate::currentDate() ); int expiryTime = KOPrefs::instance()->mExpiryTime; switch (KOPrefs::instance()->mExpiryUnit) { case KOPrefs::UnitDays: // Days limitDate = limitDate.addDays( -expiryTime ); break; case KOPrefs::UnitWeeks: // Weeks limitDate = limitDate.addDays( -expiryTime*7 ); break; case KOPrefs::UnitMonths: // Months limitDate = limitDate.addMonths( -expiryTime ); break; default: return; } run( calendar, limitDate, widget, withGUI, false ); } void EventArchiver::run( Calendar* calendar, const QDate& limitDate, QWidget* widget, bool withGUI, bool errorIfNone ) { // We need to use rawEvents, otherwise events hidden by filters will not be archived. Incidence::List incidences; Event::List events; Todo::List todos; Journal::List journals; if ( KOPrefs::instance()->mArchiveEvents ) { events = calendar->rawEvents( QDate( 1769, 12, 1 ), // #29555, also advertised by the "limitDate not included" in the class docu limitDate.addDays( -1 ), KOPrefs::instance()->timeSpec(), true ); } if ( KOPrefs::instance()->mArchiveTodos ) { Todo::List t = calendar->rawTodos(); Todo::List::ConstIterator it; for( it = t.begin(); it != t.end(); ++it ) { if ( (*it) && ( (*it)->isCompleted() ) && ( (*it)->completed().date() < limitDate ) ) { todos.append( *it ); } } } incidences = Calendar::mergeIncidenceList( events, todos, journals ); kDebug(5850) << "EventArchiver: archiving incidences before " << limitDate << " -> " << incidences.count() << " incidences found." << endl; if ( incidences.isEmpty() ) { if ( withGUI && errorIfNone ) KMessageBox::information( widget, i18n("There are no items before %1", KGlobal::locale()->formatDate(limitDate)), "ArchiverNoIncidences" ); return; } switch ( KOPrefs::instance()->mArchiveAction ) { case KOPrefs::actionDelete: deleteIncidences( calendar, limitDate, widget, incidences, withGUI ); break; case KOPrefs::actionArchive: archiveIncidences( calendar, limitDate, widget, incidences, withGUI ); break; } } void EventArchiver::deleteIncidences( Calendar* calendar, const QDate& limitDate, QWidget* widget, const Incidence::List& incidences, bool withGUI ) { QStringList incidenceStrs; Incidence::List::ConstIterator it; for( it = incidences.begin(); it != incidences.end(); ++it ) { incidenceStrs.append( (*it)->summary() ); } if ( withGUI ) { int result = KMessageBox::warningContinueCancelList( widget, i18n("Delete all items before %1 without saving?\n" "The following items will be deleted:", KGlobal::locale()->formatDate(limitDate)), incidenceStrs, i18n("Delete Old Items"),KStandardGuiItem::del()); if (result != KMessageBox::Continue) return; } for( it = incidences.begin(); it != incidences.end(); ++it ) { calendar->deleteIncidence( *it ); } emit eventsDeleted(); } void EventArchiver::archiveIncidences( Calendar* calendar, const QDate& /*limitDate*/, QWidget* widget, const Incidence::List& incidences, bool /*withGUI*/) { FileStorage storage( calendar ); // Save current calendar to disk KTemporaryFile tmpFile; tmpFile.open(); storage.setFileName( tmpFile.fileName() ); if ( !storage.save() ) { kDebug(5850) << "EventArchiver::archiveEvents(): Can't save calendar to temp file" << endl; return; } // Duplicate current calendar by loading in new calendar object #ifdef __GNUC__ #warning Does the time zone specification serve any purpose? #endif CalendarLocal archiveCalendar( KOPrefs::instance()->timeSpec() ); FileStorage archiveStore( &archiveCalendar ); archiveStore.setFileName( tmpFile.fileName() ); if (!archiveStore.load()) { kDebug(5850) << "EventArchiver::archiveEvents(): Can't load calendar from temp file" << endl; return; } // Strip active events from calendar so that only events to be archived // remain. This is not really efficient, but there is no other easy way. QStringList uids; Incidence::List allIncidences = archiveCalendar.rawIncidences(); Incidence::List::ConstIterator it; for( it = incidences.begin(); it != incidences.end(); ++it ) { uids << (*it)->uid(); } for( it = allIncidences.begin(); it != allIncidences.end(); ++it ) { if ( !uids.contains( (*it)->uid() ) ) { archiveCalendar.deleteIncidence( *it ); } } // Get or create the archive file KUrl archiveURL( KOPrefs::instance()->mArchiveFile ); QString archiveFile; if ( KIO::NetAccess::exists( archiveURL, true, widget ) ) { if( !KIO::NetAccess::download( archiveURL, archiveFile, widget ) ) { kDebug(5850) << "EventArchiver::archiveEvents(): Can't download archive file" << endl; return; } // Merge with events to be archived. archiveStore.setFileName( archiveFile ); if ( !archiveStore.load() ) { kDebug(5850) << "EventArchiver::archiveEvents(): Can't merge with archive file" << endl; return; } } else { archiveFile = tmpFile.fileName(); } // Save archive calendar if ( !archiveStore.save() ) { KMessageBox::error(widget,i18n("Cannot write archive file %1.", archiveStore.fileName() )); return; } // Upload if necessary KUrl srcUrl; srcUrl.setPath(archiveFile); if (srcUrl != archiveURL) { if ( !KIO::NetAccess::upload( archiveFile, archiveURL, widget ) ) { KMessageBox::error(widget,i18n("Cannot write archive to final destination.")); return; } } KIO::NetAccess::removeTempFile(archiveFile); // Delete archived events from calendar for( it = incidences.begin(); it != incidences.end(); ++it ) { calendar->deleteIncidence( *it ); } emit eventsDeleted(); } #include "eventarchiver.moc" <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "iosprobe.h" #include <QDebug> #include <QFileInfo> #include <QProcess> #include <QDir> #include <QFileInfoList> static const bool debugProbe = false; namespace Ios { static QString qsystem(const QString &exe, const QStringList &args = QStringList()) { QProcess p; p.setProcessChannelMode(QProcess::MergedChannels); p.start(exe, args); p.waitForFinished(); return QString::fromLocal8Bit(p.readAll()); } QMap<QString, Platform> IosProbe::detectPlatforms(const QString &devPath) { IosProbe probe; probe.addDeveloperPath(devPath); probe.detectFirst(); return probe.detectedPlatforms(); } static int compareVersions(const QString &v1, const QString &v2) { QStringList v1L = v1.split(QLatin1Char('.')); QStringList v2L = v2.split(QLatin1Char('.')); int i = 0; while (v1.length() > i && v1.length() > i) { bool n1Ok, n2Ok; int n1 = v1L.value(i).toInt(&n1Ok); int n2 = v2L.value(i).toInt(&n2Ok); if (!(n1Ok && n2Ok)) { qDebug() << QString::fromLatin1("Failed to compare version %1 and %2").arg(v1, v2); return 0; } if (n1 > n2) return -1; else if (n1 < n2) return 1; ++i; } if (v1.length() > v2.length()) return -1; if (v1.length() < v2.length()) return 1; return 0; } void IosProbe::addDeveloperPath(const QString &path) { if (path.isEmpty()) return; QFileInfo pInfo(path); if (!pInfo.exists() || !pInfo.isDir()) return; if (m_developerPaths.contains(path)) return; m_developerPaths.append(path); if (debugProbe) qDebug() << QString::fromLatin1("Added developer path %1").arg(path); } void IosProbe::detectDeveloperPaths() { QProcess selectedXcode; QString program = QLatin1String("/usr/bin/xcode-select"); QStringList arguments(QLatin1String("--print-path")); selectedXcode.start(program, arguments, QProcess::ReadOnly); if (!selectedXcode.waitForFinished() || selectedXcode.exitCode()) { qDebug() << QString::fromLatin1("Could not detect selected xcode with /usr/bin/xcode-select"); } else { QString path = QString::fromLocal8Bit(selectedXcode.readAllStandardOutput()); addDeveloperPath(path); } addDeveloperPath(QLatin1String("/Applications/Xcode.app/Contents/Developer")); } void IosProbe::setupDefaultToolchains(const QString &devPath, const QString &xcodeName) { if (debugProbe) qDebug() << QString::fromLatin1("Setting up platform '%1'.").arg(xcodeName); QString indent = QLatin1String(" "); // detect clang (default toolchain) QFileInfo clangFileInfo(devPath + QLatin1String("/Toolchains/XcodeDefault.xctoolchain/usr/bin") + QLatin1String("/clang++")); bool hasClang = clangFileInfo.exists(); if (!hasClang) qDebug() << indent << QString::fromLatin1("Default toolchain %1 not found.") .arg(clangFileInfo.canonicalFilePath()); // Platforms QDir platformsDir(devPath + QLatin1String("/Platforms")); QFileInfoList platforms = platformsDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); foreach (const QFileInfo &fInfo, platforms) { if (fInfo.isDir() && fInfo.suffix() == QLatin1String("platform")) { if (debugProbe) qDebug() << indent << QString::fromLatin1("Setting up %1").arg(fInfo.fileName()); QSettingsPtr infoSettings(new QSettings( fInfo.absoluteFilePath() + QLatin1String("/Info.plist"), QSettings::NativeFormat)); if (!infoSettings->contains(QLatin1String("Name"))) { qDebug() << indent << QString::fromLatin1("Missing platform name in Info.plist of %1") .arg(fInfo.absoluteFilePath()); continue; } QString name = infoSettings->value(QLatin1String("Name")).toString(); if (name != QLatin1String("macosx") && name != QLatin1String("iphoneos") && name != QLatin1String("iphonesimulator")) { qDebug() << indent << QString::fromLatin1("Skipping unknown platform %1").arg(name); continue; } // prepare default platform properties QVariantMap defaultProp = infoSettings->value(QLatin1String("DefaultProperties")) .toMap(); QVariantMap overrideProp = infoSettings->value(QLatin1String("OverrideProperties")) .toMap(); QMapIterator<QString, QVariant> i(overrideProp); while (i.hasNext()) { i.next(); // use unite? might lead to double insertions... defaultProp[i.key()] = i.value(); } QString clangFullName = name + QLatin1String("-clang") + xcodeName; QString clang11FullName = name + QLatin1String("-clang11") + xcodeName; // detect gcc QFileInfo gccFileInfo(fInfo.absoluteFilePath() + QLatin1String("/Developer/usr/bin/g++")); QString gccFullName = name + QLatin1String("-gcc") + xcodeName; if (!gccFileInfo.exists()) gccFileInfo = QFileInfo(devPath + QLatin1String("/usr/bin/g++")); bool hasGcc = gccFileInfo.exists(); QStringList extraFlags; if (defaultProp.contains(QLatin1String("NATIVE_ARCH"))) { QString arch = defaultProp.value(QLatin1String("NATIVE_ARCH")).toString(); if (!arch.startsWith(QLatin1String("arm"))) qDebug() << indent << QString::fromLatin1("Expected arm architecture, not %1").arg(arch); extraFlags << QLatin1String("-arch") << arch; } else if (name == QLatin1String("iphonesimulator")) { QString arch = defaultProp.value(QLatin1String("ARCHS")).toString(); // don't generate a toolchain for 64 bit (to fix when we support that) extraFlags << QLatin1String("-arch") << QLatin1String("i386"); } if (hasClang) { Platform clangProfile; clangProfile.developerPath = Utils::FileName::fromString(devPath); clangProfile.platformKind = 0; clangProfile.name = clangFullName; clangProfile.platformPath = Utils::FileName(fInfo); clangProfile.platformInfo = infoSettings; clangProfile.compilerPath = Utils::FileName(clangFileInfo); QStringList flags = extraFlags; flags << QLatin1String("-dumpmachine"); QString compilerTriplet = qsystem(clangFileInfo.canonicalFilePath(), flags) .simplified(); QStringList compilerTripletl = compilerTriplet.split(QLatin1Char('-')); clangProfile.architecture = compilerTripletl.value(0); clangProfile.backendFlags = extraFlags; if (debugProbe) qDebug() << indent << QString::fromLatin1("* adding profile %1").arg(clangProfile.name); m_platforms[clangProfile.name] = clangProfile; clangProfile.platformKind |= Platform::Cxx11Support; clangProfile.backendFlags.append(QLatin1String("-std=c++11")); clangProfile.backendFlags.append(QLatin1String("-stdlib=libc++")); clangProfile.name = clang11FullName; m_platforms[clangProfile.name] = clangProfile; } if (hasGcc) { Platform gccProfile; gccProfile.developerPath = Utils::FileName::fromString(devPath); gccProfile.name = gccFullName; gccProfile.platformKind = 0; // use the arm-apple-darwin10-llvm-* variant and avoid the extraFlags if available??? gccProfile.platformPath = Utils::FileName(fInfo); gccProfile.platformInfo = infoSettings; gccProfile.compilerPath = Utils::FileName(gccFileInfo); QStringList flags = extraFlags; flags << QLatin1String("-dumpmachine"); QString compilerTriplet = qsystem(gccFileInfo.canonicalFilePath(), flags) .simplified(); QStringList compilerTripletl = compilerTriplet.split(QLatin1Char('-')); gccProfile.architecture = compilerTripletl.value(0); gccProfile.backendFlags = extraFlags; if (debugProbe) qDebug() << indent << QString::fromLatin1("* adding profile %1").arg(gccProfile.name); m_platforms[gccProfile.name] = gccProfile; } // set SDKs/sysroot QString sysRoot; QSettingsPtr sdkSettings; { QString sdkName; if (defaultProp.contains(QLatin1String("SDKROOT"))) sdkName = defaultProp.value(QLatin1String("SDKROOT")).toString(); QString sdkPath; QDir sdks(fInfo.absoluteFilePath() + QLatin1String("/Developer/SDKs")); QString maxVersion; foreach (const QFileInfo &sdkDirInfo, sdks.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) { indent = QLatin1String(" "); QSettingsPtr sdkInfo(new QSettings(sdkDirInfo.absoluteFilePath() + QLatin1String("/SDKSettings.plist"), QSettings::NativeFormat)); QString versionStr = sdkInfo->value(QLatin1String("Version")).toString(); QVariant currentSdkName = sdkInfo->value(QLatin1String("CanonicalName")); bool isBaseSdk = sdkInfo->value((QLatin1String("isBaseSDK"))).toString() .toLower() != QLatin1String("no"); if (!isBaseSdk) { if (debugProbe) qDebug() << indent << QString::fromLatin1("Skipping non base Sdk %1") .arg(currentSdkName.toString()); continue; } QString safeName = currentSdkName.toString().replace(QLatin1Char('-'), QLatin1Char('_')) .replace(QRegExp(QLatin1String("[^-a-zA-Z0-9]")), QLatin1String("-")); if (sdkName.isEmpty()) { if (compareVersions(maxVersion, versionStr) > 0) { maxVersion = versionStr; sdkPath = sdkDirInfo.canonicalFilePath(); sdkSettings = sdkInfo; } } else if (currentSdkName == sdkName) { sdkPath = sdkDirInfo.canonicalFilePath(); sdkSettings = sdkInfo; } } if (!sdkPath.isEmpty()) sysRoot = sdkPath; else if (!sdkName.isEmpty()) qDebug() << indent << QString::fromLatin1("Failed to find sysroot %1").arg(sdkName); } if (hasClang && !sysRoot.isEmpty()) { m_platforms[clangFullName].platformKind |= Platform::BasePlatform; m_platforms[clangFullName].sdkPath = Utils::FileName::fromString(sysRoot); m_platforms[clangFullName].sdkSettings = sdkSettings; m_platforms[clang11FullName].platformKind |= Platform::BasePlatform; m_platforms[clang11FullName].sdkPath = Utils::FileName::fromString(sysRoot); m_platforms[clang11FullName].sdkSettings = sdkSettings; } if (hasGcc && !sysRoot.isEmpty()) { m_platforms[gccFullName].platformKind |= Platform::BasePlatform; m_platforms[gccFullName].sdkPath = Utils::FileName::fromString(sysRoot); m_platforms[gccFullName].sdkSettings = sdkSettings; } } indent = QLatin1String(" "); } } void IosProbe::detectFirst() { detectDeveloperPaths(); if (!m_developerPaths.isEmpty()) setupDefaultToolchains(m_developerPaths.value(0),QLatin1String("")); } QMap<QString, Platform> IosProbe::detectedPlatforms() { return m_platforms; } } <commit_msg>ios: fix Xcode path detection<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "iosprobe.h" #include <QDebug> #include <QFileInfo> #include <QProcess> #include <QDir> #include <QFileInfoList> static const bool debugProbe = false; namespace Ios { static QString qsystem(const QString &exe, const QStringList &args = QStringList()) { QProcess p; p.setProcessChannelMode(QProcess::MergedChannels); p.start(exe, args); p.waitForFinished(); return QString::fromLocal8Bit(p.readAll()); } QMap<QString, Platform> IosProbe::detectPlatforms(const QString &devPath) { IosProbe probe; probe.addDeveloperPath(devPath); probe.detectFirst(); return probe.detectedPlatforms(); } static int compareVersions(const QString &v1, const QString &v2) { QStringList v1L = v1.split(QLatin1Char('.')); QStringList v2L = v2.split(QLatin1Char('.')); int i = 0; while (v1.length() > i && v1.length() > i) { bool n1Ok, n2Ok; int n1 = v1L.value(i).toInt(&n1Ok); int n2 = v2L.value(i).toInt(&n2Ok); if (!(n1Ok && n2Ok)) { qDebug() << QString::fromLatin1("Failed to compare version %1 and %2").arg(v1, v2); return 0; } if (n1 > n2) return -1; else if (n1 < n2) return 1; ++i; } if (v1.length() > v2.length()) return -1; if (v1.length() < v2.length()) return 1; return 0; } void IosProbe::addDeveloperPath(const QString &path) { if (path.isEmpty()) return; QFileInfo pInfo(path); if (!pInfo.exists() || !pInfo.isDir()) return; if (m_developerPaths.contains(path)) return; m_developerPaths.append(path); if (debugProbe) qDebug() << QString::fromLatin1("Added developer path %1").arg(path); } void IosProbe::detectDeveloperPaths() { QProcess selectedXcode; QString program = QLatin1String("/usr/bin/xcode-select"); QStringList arguments(QLatin1String("--print-path")); selectedXcode.start(program, arguments, QProcess::ReadOnly); if (!selectedXcode.waitForFinished() || selectedXcode.exitCode()) { qDebug() << QString::fromLatin1("Could not detect selected xcode with /usr/bin/xcode-select"); } else { QString path = QString::fromLocal8Bit(selectedXcode.readAllStandardOutput()); path.chop(1); addDeveloperPath(path); } addDeveloperPath(QLatin1String("/Applications/Xcode.app/Contents/Developer")); } void IosProbe::setupDefaultToolchains(const QString &devPath, const QString &xcodeName) { if (debugProbe) qDebug() << QString::fromLatin1("Setting up platform '%1'.").arg(xcodeName); QString indent = QLatin1String(" "); // detect clang (default toolchain) QFileInfo clangFileInfo(devPath + QLatin1String("/Toolchains/XcodeDefault.xctoolchain/usr/bin") + QLatin1String("/clang++")); bool hasClang = clangFileInfo.exists(); if (!hasClang) qDebug() << indent << QString::fromLatin1("Default toolchain %1 not found.") .arg(clangFileInfo.canonicalFilePath()); // Platforms QDir platformsDir(devPath + QLatin1String("/Platforms")); QFileInfoList platforms = platformsDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); foreach (const QFileInfo &fInfo, platforms) { if (fInfo.isDir() && fInfo.suffix() == QLatin1String("platform")) { if (debugProbe) qDebug() << indent << QString::fromLatin1("Setting up %1").arg(fInfo.fileName()); QSettingsPtr infoSettings(new QSettings( fInfo.absoluteFilePath() + QLatin1String("/Info.plist"), QSettings::NativeFormat)); if (!infoSettings->contains(QLatin1String("Name"))) { qDebug() << indent << QString::fromLatin1("Missing platform name in Info.plist of %1") .arg(fInfo.absoluteFilePath()); continue; } QString name = infoSettings->value(QLatin1String("Name")).toString(); if (name != QLatin1String("macosx") && name != QLatin1String("iphoneos") && name != QLatin1String("iphonesimulator")) { qDebug() << indent << QString::fromLatin1("Skipping unknown platform %1").arg(name); continue; } // prepare default platform properties QVariantMap defaultProp = infoSettings->value(QLatin1String("DefaultProperties")) .toMap(); QVariantMap overrideProp = infoSettings->value(QLatin1String("OverrideProperties")) .toMap(); QMapIterator<QString, QVariant> i(overrideProp); while (i.hasNext()) { i.next(); // use unite? might lead to double insertions... defaultProp[i.key()] = i.value(); } QString clangFullName = name + QLatin1String("-clang") + xcodeName; QString clang11FullName = name + QLatin1String("-clang11") + xcodeName; // detect gcc QFileInfo gccFileInfo(fInfo.absoluteFilePath() + QLatin1String("/Developer/usr/bin/g++")); QString gccFullName = name + QLatin1String("-gcc") + xcodeName; if (!gccFileInfo.exists()) gccFileInfo = QFileInfo(devPath + QLatin1String("/usr/bin/g++")); bool hasGcc = gccFileInfo.exists(); QStringList extraFlags; if (defaultProp.contains(QLatin1String("NATIVE_ARCH"))) { QString arch = defaultProp.value(QLatin1String("NATIVE_ARCH")).toString(); if (!arch.startsWith(QLatin1String("arm"))) qDebug() << indent << QString::fromLatin1("Expected arm architecture, not %1").arg(arch); extraFlags << QLatin1String("-arch") << arch; } else if (name == QLatin1String("iphonesimulator")) { QString arch = defaultProp.value(QLatin1String("ARCHS")).toString(); // don't generate a toolchain for 64 bit (to fix when we support that) extraFlags << QLatin1String("-arch") << QLatin1String("i386"); } if (hasClang) { Platform clangProfile; clangProfile.developerPath = Utils::FileName::fromString(devPath); clangProfile.platformKind = 0; clangProfile.name = clangFullName; clangProfile.platformPath = Utils::FileName(fInfo); clangProfile.platformInfo = infoSettings; clangProfile.compilerPath = Utils::FileName(clangFileInfo); QStringList flags = extraFlags; flags << QLatin1String("-dumpmachine"); QString compilerTriplet = qsystem(clangFileInfo.canonicalFilePath(), flags) .simplified(); QStringList compilerTripletl = compilerTriplet.split(QLatin1Char('-')); clangProfile.architecture = compilerTripletl.value(0); clangProfile.backendFlags = extraFlags; if (debugProbe) qDebug() << indent << QString::fromLatin1("* adding profile %1").arg(clangProfile.name); m_platforms[clangProfile.name] = clangProfile; clangProfile.platformKind |= Platform::Cxx11Support; clangProfile.backendFlags.append(QLatin1String("-std=c++11")); clangProfile.backendFlags.append(QLatin1String("-stdlib=libc++")); clangProfile.name = clang11FullName; m_platforms[clangProfile.name] = clangProfile; } if (hasGcc) { Platform gccProfile; gccProfile.developerPath = Utils::FileName::fromString(devPath); gccProfile.name = gccFullName; gccProfile.platformKind = 0; // use the arm-apple-darwin10-llvm-* variant and avoid the extraFlags if available??? gccProfile.platformPath = Utils::FileName(fInfo); gccProfile.platformInfo = infoSettings; gccProfile.compilerPath = Utils::FileName(gccFileInfo); QStringList flags = extraFlags; flags << QLatin1String("-dumpmachine"); QString compilerTriplet = qsystem(gccFileInfo.canonicalFilePath(), flags) .simplified(); QStringList compilerTripletl = compilerTriplet.split(QLatin1Char('-')); gccProfile.architecture = compilerTripletl.value(0); gccProfile.backendFlags = extraFlags; if (debugProbe) qDebug() << indent << QString::fromLatin1("* adding profile %1").arg(gccProfile.name); m_platforms[gccProfile.name] = gccProfile; } // set SDKs/sysroot QString sysRoot; QSettingsPtr sdkSettings; { QString sdkName; if (defaultProp.contains(QLatin1String("SDKROOT"))) sdkName = defaultProp.value(QLatin1String("SDKROOT")).toString(); QString sdkPath; QDir sdks(fInfo.absoluteFilePath() + QLatin1String("/Developer/SDKs")); QString maxVersion; foreach (const QFileInfo &sdkDirInfo, sdks.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) { indent = QLatin1String(" "); QSettingsPtr sdkInfo(new QSettings(sdkDirInfo.absoluteFilePath() + QLatin1String("/SDKSettings.plist"), QSettings::NativeFormat)); QString versionStr = sdkInfo->value(QLatin1String("Version")).toString(); QVariant currentSdkName = sdkInfo->value(QLatin1String("CanonicalName")); bool isBaseSdk = sdkInfo->value((QLatin1String("isBaseSDK"))).toString() .toLower() != QLatin1String("no"); if (!isBaseSdk) { if (debugProbe) qDebug() << indent << QString::fromLatin1("Skipping non base Sdk %1") .arg(currentSdkName.toString()); continue; } QString safeName = currentSdkName.toString().replace(QLatin1Char('-'), QLatin1Char('_')) .replace(QRegExp(QLatin1String("[^-a-zA-Z0-9]")), QLatin1String("-")); if (sdkName.isEmpty()) { if (compareVersions(maxVersion, versionStr) > 0) { maxVersion = versionStr; sdkPath = sdkDirInfo.canonicalFilePath(); sdkSettings = sdkInfo; } } else if (currentSdkName == sdkName) { sdkPath = sdkDirInfo.canonicalFilePath(); sdkSettings = sdkInfo; } } if (!sdkPath.isEmpty()) sysRoot = sdkPath; else if (!sdkName.isEmpty()) qDebug() << indent << QString::fromLatin1("Failed to find sysroot %1").arg(sdkName); } if (hasClang && !sysRoot.isEmpty()) { m_platforms[clangFullName].platformKind |= Platform::BasePlatform; m_platforms[clangFullName].sdkPath = Utils::FileName::fromString(sysRoot); m_platforms[clangFullName].sdkSettings = sdkSettings; m_platforms[clang11FullName].platformKind |= Platform::BasePlatform; m_platforms[clang11FullName].sdkPath = Utils::FileName::fromString(sysRoot); m_platforms[clang11FullName].sdkSettings = sdkSettings; } if (hasGcc && !sysRoot.isEmpty()) { m_platforms[gccFullName].platformKind |= Platform::BasePlatform; m_platforms[gccFullName].sdkPath = Utils::FileName::fromString(sysRoot); m_platforms[gccFullName].sdkSettings = sdkSettings; } } indent = QLatin1String(" "); } } void IosProbe::detectFirst() { detectDeveloperPaths(); if (!m_developerPaths.isEmpty()) setupDefaultToolchains(m_developerPaths.value(0),QLatin1String("")); } QMap<QString, Platform> IosProbe::detectedPlatforms() { return m_platforms; } } <|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * $Log$ * Revision 1.9 2004/04/13 10:05:51 strk * GeometryLocation constructor made const-correct. * Fixed erroneus down-casting in DistanceOp::computeMinDistancePoints. * * Revision 1.8 2004/04/05 06:35:14 ybychkov * "operation/distance" upgraded to JTS 1.4 * * Revision 1.7 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.6 2003/10/16 08:50:00 strk * Memory leak fixes. Improved performance by mean of more calls to * new getCoordinatesRO() when applicable. * **********************************************************************/ #include "../../headers/opDistance.h" #include "../../headers/geomUtil.h" namespace geos { /** * Compute the distance between the closest points of two geometries. * @param g0 a {@link Geometry} * @param g1 another {@link Geometry} * @return the distance between the geometries */ double DistanceOp::distance(Geometry *g0, Geometry *g1) { auto_ptr<DistanceOp> distOp(new DistanceOp(g0,g1)); return distOp->distance(); } /** * Compute the the closest points of two geometries. * The points are presented in the same order as the input Geometries. * * @param g0 a {@link Geometry} * @param g1 another {@link Geometry} * @return the closest points in the geometries */ CoordinateList* DistanceOp::closestPoints(Geometry *g0,Geometry *g1){ auto_ptr<DistanceOp> distOp(new DistanceOp(g0,g1)); return distOp->closestPoints(); } DistanceOp::DistanceOp(Geometry *g0, Geometry *g1){ ptLocator=new PointLocator(); minDistance=DoubleInfinity; geom=new vector<Geometry*>(2); // minDistanceLocation=new vector<GeometryLocation*>(); (*geom)[0]=g0; (*geom)[1]=g1; } DistanceOp::~DistanceOp(){ delete ptLocator; delete geom; // delete minDistanceLocation; } /** * Report the distance between the closest points on the input geometries. * * @return the distance between the geometries */ double DistanceOp::distance() { computeMinDistance(); return minDistance; } /** * Report the coordinates of the closest points in the input geometries. * The points are presented in the same order as the input Geometries. * * @return a pair of {@link Coordinate}s of the closest points */ CoordinateList* DistanceOp::closestPoints() { computeMinDistance(); CoordinateList* closestPts=CoordinateListFactory::internalFactory->createCoordinateList(); closestPts->add((*minDistanceLocation)[0]->getCoordinate()); closestPts->add((*minDistanceLocation)[1]->getCoordinate()); return closestPts; } /** * Report the locations of the closest points in the input geometries. * The locations are presented in the same order as the input Geometries. * * @return a pair of {@link GeometryLocation}s for the closest points */ vector<GeometryLocation*>* DistanceOp::closestLocations(){ computeMinDistance(); return minDistanceLocation; } void DistanceOp::updateMinDistance(double dist) { if (dist<minDistance) minDistance=dist; } void DistanceOp::updateMinDistance(vector<GeometryLocation*> *locGeom, bool flip){ // if not set then don't update if ((*locGeom)[0]==NULL) return; if (flip) { (*minDistanceLocation)[0]=(*locGeom)[1]; (*minDistanceLocation)[1]=(*locGeom)[0]; } else { (*minDistanceLocation)[0]=(*locGeom)[0]; (*minDistanceLocation)[1]=(*locGeom)[1]; } } void DistanceOp::computeMinDistance() { if (minDistanceLocation!=NULL) return; minDistanceLocation = new vector<GeometryLocation*>(); computeContainmentDistance(); if (minDistance<=0.0) return; computeLineDistance(); } void DistanceOp::computeContainmentDistance() { vector<Geometry*> *polys0 = PolygonExtracter::getPolygons((*geom)[0]); vector<Geometry*> *polys1 = PolygonExtracter::getPolygons((*geom)[1]); vector<GeometryLocation*> *locPtPoly = new vector<GeometryLocation*>(); // test if either geometry is wholely inside the other if (polys1->size()>0) { vector<GeometryLocation*> *insideLocs0 = ConnectedElementLocationFilter::getLocations((*geom)[0]); computeInside(insideLocs0, polys1, locPtPoly); if (minDistance <= 0.0) { (*minDistanceLocation)[0] = (*locPtPoly)[0]; (*minDistanceLocation)[1] = (*locPtPoly)[1]; delete polys0; delete polys1; delete locPtPoly; delete insideLocs0; return; } delete insideLocs0; } if (polys0->size()>0) { vector<GeometryLocation*> *insideLocs1 = ConnectedElementLocationFilter::getLocations((*geom)[1]); computeInside(insideLocs1, polys0, locPtPoly); if (minDistance <= 0.0) { // flip locations, since we are testing geom 1 VS geom 0 (*minDistanceLocation)[0] = (*locPtPoly)[1]; (*minDistanceLocation)[1] = (*locPtPoly)[0]; delete polys0; delete polys1; delete locPtPoly; delete insideLocs1; return; } delete insideLocs1; } delete polys0; delete polys1; delete locPtPoly; } void DistanceOp::computeInside(vector<GeometryLocation*> *locs,vector<Geometry*> *polys,vector<GeometryLocation*> *locPtPoly){ for (int i=0;i<(int)locs->size();i++) { GeometryLocation *loc=(*locs)[i]; for (int j=0;j<(int)polys->size();j++) { Polygon *poly=(Polygon*) (*polys)[j]; computeInside(loc,poly,locPtPoly); if (minDistance<=0.0) return; } } } void DistanceOp::computeInside(GeometryLocation *ptLoc,Polygon *poly,vector<GeometryLocation*> *locPtPoly){ Coordinate &pt=ptLoc->getCoordinate(); if (Location::EXTERIOR!=ptLocator->locate(pt, poly)) { minDistance = 0.0; (*locPtPoly)[0] = ptLoc; GeometryLocation *locPoly = new GeometryLocation(poly, pt); (*locPtPoly)[1] = locPoly; return; } } void DistanceOp::computeLineDistance() { vector<GeometryLocation*> *locGeom = new vector<GeometryLocation*>; /** * Geometries are not wholely inside, so compute distance from lines and points * of one to lines and points of the other */ vector<Geometry*> *lines0=LinearComponentExtracter::getLines((*geom)[0]); vector<Geometry*> *lines1=LinearComponentExtracter::getLines((*geom)[1]); vector<Geometry*> *pts0=PointExtracter::getPoints((*geom)[0]); vector<Geometry*> *pts1=PointExtracter::getPoints((*geom)[1]); // bail whenever minDistance goes to zero, since it can't get any less computeMinDistanceLines(lines0, lines1, locGeom); updateMinDistance(locGeom, false); if (minDistance <= 0.0) { delete lines0; delete lines1; delete pts0; delete pts1; return; }; (*locGeom)[0]=NULL; (*locGeom)[1]=NULL; computeMinDistanceLinesPoints(lines0, pts1, locGeom); updateMinDistance(locGeom, false); if (minDistance <= 0.0) { delete lines0; delete lines1; delete pts0; delete pts1; return; }; (*locGeom)[0]=NULL; (*locGeom)[1]=NULL; computeMinDistanceLinesPoints(lines1, pts0, locGeom); updateMinDistance(locGeom, true); if (minDistance <= 0.0){ delete lines0; delete lines1; delete pts0; delete pts1; return; }; (*locGeom)[0]=NULL; (*locGeom)[1]=NULL; computeMinDistancePoints(pts0, pts1, locGeom); updateMinDistance(locGeom, false); } void DistanceOp::computeMinDistanceLines(vector<Geometry*> *lines0,vector<Geometry*> *lines1,vector<GeometryLocation*> *locGeom){ for (int i=0;i<(int)lines0->size();i++) { LineString *line0=(LineString*) (*lines0)[i]; for (int j=0;j<(int)lines1->size();j++) { LineString *line1=(LineString*) (*lines1)[j]; computeMinDistance(line0,line1,locGeom); if (minDistance<=0.0) return; } } } void DistanceOp::computeMinDistancePoints(vector<Geometry*> *points0,vector<Geometry*> *points1,vector<GeometryLocation*> *locGeom){ for (int i=0;i<(int)points0->size();i++) { //Point *pt0=(Point*) (*points0)[i]; Geometry *pt0=(*points0)[i]; for (int j=0;j<(int)points1->size();j++) { //Point *pt1=(Point*) (*points1)[j]; Geometry *pt1=(*points1)[j]; double dist=pt0->getCoordinate()->distance(*(pt1->getCoordinate())); if (dist < minDistance) { minDistance = dist; // this is wrong - need to determine closest points on both segments!!! (*locGeom)[0] = new GeometryLocation(pt0, 0, *(pt0->getCoordinate())); (*locGeom)[1] = new GeometryLocation(pt1, 0, *(pt1->getCoordinate())); } if (minDistance<=0.0) return; } } } void DistanceOp::computeMinDistanceLinesPoints(vector<Geometry*> *lines,vector<Geometry*> *points,vector<GeometryLocation*> *locGeom){ for (int i=0;i<(int)lines->size();i++) { LineString *line=(LineString*) (*lines)[i]; for (int j=0;j<(int)points->size();j++) { Point *pt=(Point*) (*points)[j]; computeMinDistance(line,pt,locGeom); if (minDistance<=0.0) return; } } } void DistanceOp::computeMinDistance(LineString *line0, LineString *line1,vector<GeometryLocation*> *locGeom) { Envelope *env0=line0->getEnvelopeInternal(); Envelope *env1=line1->getEnvelopeInternal(); if (env0->distance(env1)>minDistance) { delete env0; delete env1; return; } delete env0; delete env1; CoordinateList *coord0=line0->getCoordinates(); CoordinateList *coord1=line1->getCoordinates(); // brute force approach! for(int i=0;i<coord0->getSize()-1;i++) { for(int j=0;j<coord1->getSize()-1;j++) { double dist=CGAlgorithms::distanceLineLine(coord0->getAt(i),coord0->getAt(i+1), coord1->getAt(j),coord1->getAt(j+1)); if (dist < minDistance) { minDistance = dist; LineSegment *seg0 = new LineSegment(coord0->getAt(i), coord0->getAt(i + 1)); LineSegment *seg1 = new LineSegment(coord1->getAt(j), coord1->getAt(j + 1)); CoordinateList* closestPt = seg0->closestPoints(seg1); (*locGeom)[0] = new GeometryLocation(line0, i, (Coordinate)closestPt->getAt(0)); (*locGeom)[1] = new GeometryLocation(line1, j, (Coordinate)closestPt->getAt(1)); } if (minDistance<=0.0) return; } } } void DistanceOp::computeMinDistance(LineString *line,Point *pt,vector<GeometryLocation*> *locGeom){ Envelope *env0=line->getEnvelopeInternal(); Envelope *env1=pt->getEnvelopeInternal(); if (env0->distance(env1)>minDistance) { delete env0; delete env1; return; } delete env0; delete env1; CoordinateList *coord0=line->getCoordinates(); const Coordinate *coord=pt->getCoordinate(); // brute force approach! for(int i=0;i<coord0->getSize()-1;i++) { double dist=CGAlgorithms::distancePointLine(*coord,coord0->getAt(i),coord0->getAt(i+1)); if (dist < minDistance) { minDistance = dist; LineSegment *seg = new LineSegment(coord0->getAt(i), coord0->getAt(i + 1)); const Coordinate *segClosestPoint = seg->closestPoint(*coord); (*locGeom)[0] = new GeometryLocation(line, i, (Coordinate)*segClosestPoint); (*locGeom)[1] = new GeometryLocation(pt, 0, (Coordinate)*coord); } if (minDistance<=0.0) return; } } } <commit_msg>Uncommented initializzazion and destruction of DistanceOp::minDistanceLocation<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * $Log$ * Revision 1.10 2004/04/14 10:56:38 strk * Uncommented initializzazion and destruction of DistanceOp::minDistanceLocation * * Revision 1.9 2004/04/13 10:05:51 strk * GeometryLocation constructor made const-correct. * Fixed erroneus down-casting in DistanceOp::computeMinDistancePoints. * * Revision 1.8 2004/04/05 06:35:14 ybychkov * "operation/distance" upgraded to JTS 1.4 * * Revision 1.7 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.6 2003/10/16 08:50:00 strk * Memory leak fixes. Improved performance by mean of more calls to * new getCoordinatesRO() when applicable. * **********************************************************************/ #include "../../headers/opDistance.h" #include "../../headers/geomUtil.h" namespace geos { /** * Compute the distance between the closest points of two geometries. * @param g0 a {@link Geometry} * @param g1 another {@link Geometry} * @return the distance between the geometries */ double DistanceOp::distance(Geometry *g0, Geometry *g1) { auto_ptr<DistanceOp> distOp(new DistanceOp(g0,g1)); return distOp->distance(); } /** * Compute the the closest points of two geometries. * The points are presented in the same order as the input Geometries. * * @param g0 a {@link Geometry} * @param g1 another {@link Geometry} * @return the closest points in the geometries */ CoordinateList* DistanceOp::closestPoints(Geometry *g0,Geometry *g1){ auto_ptr<DistanceOp> distOp(new DistanceOp(g0,g1)); return distOp->closestPoints(); } DistanceOp::DistanceOp(Geometry *g0, Geometry *g1){ ptLocator=new PointLocator(); minDistance=DoubleInfinity; geom=new vector<Geometry*>(2); minDistanceLocation=new vector<GeometryLocation*>(); (*geom)[0]=g0; (*geom)[1]=g1; } DistanceOp::~DistanceOp(){ delete ptLocator; delete geom; delete minDistanceLocation; } /** * Report the distance between the closest points on the input geometries. * * @return the distance between the geometries */ double DistanceOp::distance() { computeMinDistance(); return minDistance; } /** * Report the coordinates of the closest points in the input geometries. * The points are presented in the same order as the input Geometries. * * @return a pair of {@link Coordinate}s of the closest points */ CoordinateList* DistanceOp::closestPoints() { computeMinDistance(); CoordinateList* closestPts=CoordinateListFactory::internalFactory->createCoordinateList(); closestPts->add((*minDistanceLocation)[0]->getCoordinate()); closestPts->add((*minDistanceLocation)[1]->getCoordinate()); return closestPts; } /** * Report the locations of the closest points in the input geometries. * The locations are presented in the same order as the input Geometries. * * @return a pair of {@link GeometryLocation}s for the closest points */ vector<GeometryLocation*>* DistanceOp::closestLocations(){ computeMinDistance(); return minDistanceLocation; } void DistanceOp::updateMinDistance(double dist) { if (dist<minDistance) minDistance=dist; } void DistanceOp::updateMinDistance(vector<GeometryLocation*> *locGeom, bool flip){ // if not set then don't update if ((*locGeom)[0]==NULL) return; if (flip) { (*minDistanceLocation)[0]=(*locGeom)[1]; (*minDistanceLocation)[1]=(*locGeom)[0]; } else { (*minDistanceLocation)[0]=(*locGeom)[0]; (*minDistanceLocation)[1]=(*locGeom)[1]; } } void DistanceOp::computeMinDistance() { if (minDistanceLocation!=NULL) return; minDistanceLocation = new vector<GeometryLocation*>(); computeContainmentDistance(); if (minDistance<=0.0) return; computeLineDistance(); } void DistanceOp::computeContainmentDistance() { vector<Geometry*> *polys0 = PolygonExtracter::getPolygons((*geom)[0]); vector<Geometry*> *polys1 = PolygonExtracter::getPolygons((*geom)[1]); vector<GeometryLocation*> *locPtPoly = new vector<GeometryLocation*>(); // test if either geometry is wholely inside the other if (polys1->size()>0) { vector<GeometryLocation*> *insideLocs0 = ConnectedElementLocationFilter::getLocations((*geom)[0]); computeInside(insideLocs0, polys1, locPtPoly); if (minDistance <= 0.0) { (*minDistanceLocation)[0] = (*locPtPoly)[0]; (*minDistanceLocation)[1] = (*locPtPoly)[1]; delete polys0; delete polys1; delete locPtPoly; delete insideLocs0; return; } delete insideLocs0; } if (polys0->size()>0) { vector<GeometryLocation*> *insideLocs1 = ConnectedElementLocationFilter::getLocations((*geom)[1]); computeInside(insideLocs1, polys0, locPtPoly); if (minDistance <= 0.0) { // flip locations, since we are testing geom 1 VS geom 0 (*minDistanceLocation)[0] = (*locPtPoly)[1]; (*minDistanceLocation)[1] = (*locPtPoly)[0]; delete polys0; delete polys1; delete locPtPoly; delete insideLocs1; return; } delete insideLocs1; } delete polys0; delete polys1; delete locPtPoly; } void DistanceOp::computeInside(vector<GeometryLocation*> *locs,vector<Geometry*> *polys,vector<GeometryLocation*> *locPtPoly){ for (int i=0;i<(int)locs->size();i++) { GeometryLocation *loc=(*locs)[i]; for (int j=0;j<(int)polys->size();j++) { Polygon *poly=(Polygon*) (*polys)[j]; computeInside(loc,poly,locPtPoly); if (minDistance<=0.0) return; } } } void DistanceOp::computeInside(GeometryLocation *ptLoc,Polygon *poly,vector<GeometryLocation*> *locPtPoly){ Coordinate &pt=ptLoc->getCoordinate(); if (Location::EXTERIOR!=ptLocator->locate(pt, poly)) { minDistance = 0.0; (*locPtPoly)[0] = ptLoc; GeometryLocation *locPoly = new GeometryLocation(poly, pt); (*locPtPoly)[1] = locPoly; return; } } void DistanceOp::computeLineDistance() { vector<GeometryLocation*> *locGeom = new vector<GeometryLocation*>; /** * Geometries are not wholely inside, so compute distance from lines and points * of one to lines and points of the other */ vector<Geometry*> *lines0=LinearComponentExtracter::getLines((*geom)[0]); vector<Geometry*> *lines1=LinearComponentExtracter::getLines((*geom)[1]); vector<Geometry*> *pts0=PointExtracter::getPoints((*geom)[0]); vector<Geometry*> *pts1=PointExtracter::getPoints((*geom)[1]); // bail whenever minDistance goes to zero, since it can't get any less computeMinDistanceLines(lines0, lines1, locGeom); updateMinDistance(locGeom, false); if (minDistance <= 0.0) { delete lines0; delete lines1; delete pts0; delete pts1; return; }; (*locGeom)[0]=NULL; (*locGeom)[1]=NULL; computeMinDistanceLinesPoints(lines0, pts1, locGeom); updateMinDistance(locGeom, false); if (minDistance <= 0.0) { delete lines0; delete lines1; delete pts0; delete pts1; return; }; (*locGeom)[0]=NULL; (*locGeom)[1]=NULL; computeMinDistanceLinesPoints(lines1, pts0, locGeom); updateMinDistance(locGeom, true); if (minDistance <= 0.0){ delete lines0; delete lines1; delete pts0; delete pts1; return; }; (*locGeom)[0]=NULL; (*locGeom)[1]=NULL; computeMinDistancePoints(pts0, pts1, locGeom); updateMinDistance(locGeom, false); } void DistanceOp::computeMinDistanceLines(vector<Geometry*> *lines0,vector<Geometry*> *lines1,vector<GeometryLocation*> *locGeom){ for (int i=0;i<(int)lines0->size();i++) { LineString *line0=(LineString*) (*lines0)[i]; for (int j=0;j<(int)lines1->size();j++) { LineString *line1=(LineString*) (*lines1)[j]; computeMinDistance(line0,line1,locGeom); if (minDistance<=0.0) return; } } } void DistanceOp::computeMinDistancePoints(vector<Geometry*> *points0,vector<Geometry*> *points1,vector<GeometryLocation*> *locGeom){ for (int i=0;i<(int)points0->size();i++) { //Point *pt0=(Point*) (*points0)[i]; Geometry *pt0=(*points0)[i]; for (int j=0;j<(int)points1->size();j++) { //Point *pt1=(Point*) (*points1)[j]; Geometry *pt1=(*points1)[j]; double dist=pt0->getCoordinate()->distance(*(pt1->getCoordinate())); if (dist < minDistance) { minDistance = dist; // this is wrong - need to determine closest points on both segments!!! (*locGeom)[0] = new GeometryLocation(pt0, 0, *(pt0->getCoordinate())); (*locGeom)[1] = new GeometryLocation(pt1, 0, *(pt1->getCoordinate())); } if (minDistance<=0.0) return; } } } void DistanceOp::computeMinDistanceLinesPoints(vector<Geometry*> *lines,vector<Geometry*> *points,vector<GeometryLocation*> *locGeom){ for (int i=0;i<(int)lines->size();i++) { LineString *line=(LineString*) (*lines)[i]; for (int j=0;j<(int)points->size();j++) { Point *pt=(Point*) (*points)[j]; computeMinDistance(line,pt,locGeom); if (minDistance<=0.0) return; } } } void DistanceOp::computeMinDistance(LineString *line0, LineString *line1,vector<GeometryLocation*> *locGeom) { Envelope *env0=line0->getEnvelopeInternal(); Envelope *env1=line1->getEnvelopeInternal(); if (env0->distance(env1)>minDistance) { delete env0; delete env1; return; } delete env0; delete env1; CoordinateList *coord0=line0->getCoordinates(); CoordinateList *coord1=line1->getCoordinates(); // brute force approach! for(int i=0;i<coord0->getSize()-1;i++) { for(int j=0;j<coord1->getSize()-1;j++) { double dist=CGAlgorithms::distanceLineLine(coord0->getAt(i),coord0->getAt(i+1), coord1->getAt(j),coord1->getAt(j+1)); if (dist < minDistance) { minDistance = dist; LineSegment *seg0 = new LineSegment(coord0->getAt(i), coord0->getAt(i + 1)); LineSegment *seg1 = new LineSegment(coord1->getAt(j), coord1->getAt(j + 1)); CoordinateList* closestPt = seg0->closestPoints(seg1); (*locGeom)[0] = new GeometryLocation(line0, i, (Coordinate)closestPt->getAt(0)); (*locGeom)[1] = new GeometryLocation(line1, j, (Coordinate)closestPt->getAt(1)); } if (minDistance<=0.0) return; } } } void DistanceOp::computeMinDistance(LineString *line,Point *pt,vector<GeometryLocation*> *locGeom){ Envelope *env0=line->getEnvelopeInternal(); Envelope *env1=pt->getEnvelopeInternal(); if (env0->distance(env1)>minDistance) { delete env0; delete env1; return; } delete env0; delete env1; CoordinateList *coord0=line->getCoordinates(); const Coordinate *coord=pt->getCoordinate(); // brute force approach! for(int i=0;i<coord0->getSize()-1;i++) { double dist=CGAlgorithms::distancePointLine(*coord,coord0->getAt(i),coord0->getAt(i+1)); if (dist < minDistance) { minDistance = dist; LineSegment *seg = new LineSegment(coord0->getAt(i), coord0->getAt(i + 1)); const Coordinate *segClosestPoint = seg->closestPoint(*coord); (*locGeom)[0] = new GeometryLocation(line, i, (Coordinate)*segClosestPoint); (*locGeom)[1] = new GeometryLocation(pt, 0, (Coordinate)*coord); } if (minDistance<=0.0) return; } } } <|endoftext|>
<commit_before>#include <sltypes.h> #include <slntuapi.h> #include <slc.h> #include <stdio.h> #include <pushbase.h> #include <hwinfo.h> #include <sladl.h> #include "AmdGpu.h" #define R6XX_CONFIG_MEMSIZE 0x5428 SlAdl RdnAdl; extern "C" UINT8 GetRadeonTemp() { UINT32 temp; temp = ReadGpuRegister(0x730); //printf("Tremp %x\n", temp); return temp; } /*extern "C" UINT8 GetRadeonUsage() { //ADL_Usages(0, &ADLactinfo); //return ADLactinfo.iActivityPercent; DWORD usage, reg6do; FLOAT f1; usage = ReadGpuRegister(0x668); reg6do = ReadGpuRegister(0x6D0); reg6do = (reg6do & 0x0000ffff); usage = (usage & 0x0000ffff); f1 = usage; f1 = f1 * 200.0f; f1 = f1 / (float) reg6do; return f1; }*/ extern "C" UINT16 GetRadeonMemorySize() { return ReadGpuRegister(R6XX_CONFIG_MEMSIZE); } extern "C" UINT16 RdnGetEngineClock() { return RdnAdl.GetEngineClock(); } extern "C" UINT16 RdnGetMemoryClock() { return RdnAdl.GetMemoryClock(); } extern "C" UINT16 RdnGetEngineClockMax() { return RdnAdl.GetEngineClockMax(); } extern "C" UINT16 RdnGetMemoryClockMax() { return RdnAdl.GetMemoryClockMax(); } extern "C" VOID RdnSetMaxClocks() { RdnAdl.SetMaxClocks(); } UINT16 AmdGpu::GetEngineClock() { return 0; } UINT16 AmdGpu::GetMemoryClock() { return 0; } UINT64 AmdGpu::GetTotalMemory() { return 0; } UINT64 AmdGpu::GetFreeMemory() { return 0; } UINT8 AmdGpu::GetTemperature() { return 0; } UINT8 AmdGpu::GetLoad() { DWORD usage, reg6do; FLOAT f1; usage = ReadGpuRegister(0x668); reg6do = ReadGpuRegister(0x6D0); reg6do = (reg6do & 0x0000ffff); usage = (usage & 0x0000ffff); f1 = usage; f1 = f1 * 200.0f; f1 = f1 / (float) reg6do; return f1; } UINT16 AmdGpu::GetMaximumEngineClock() { return 0; } UINT16 AmdGpu::GetMaximumMemoryClock() { return 0; } VOID AmdGpu::ForceMaximumClocks() { }<commit_msg>fixed amd gpu temperature<commit_after>#include <sltypes.h> #include <slntuapi.h> #include <slc.h> #include <stdio.h> #include <pushbase.h> #include <hwinfo.h> #include <sladl.h> #include "AmdGpu.h" #define R6XX_CONFIG_MEMSIZE 0x5428 SlAdl RdnAdl; /*extern "C" UINT8 GetRadeonTemp() { UINT32 temp; temp = ReadGpuRegister(0x730); //printf("Tremp %x\n", temp); return temp; }*/ extern "C" UINT16 GetRadeonMemorySize() { return ReadGpuRegister(R6XX_CONFIG_MEMSIZE); } extern "C" UINT16 RdnGetEngineClock() { return RdnAdl.GetEngineClock(); } extern "C" UINT16 RdnGetMemoryClock() { return RdnAdl.GetMemoryClock(); } extern "C" UINT16 RdnGetEngineClockMax() { return RdnAdl.GetEngineClockMax(); } extern "C" UINT16 RdnGetMemoryClockMax() { return RdnAdl.GetMemoryClockMax(); } extern "C" VOID RdnSetMaxClocks() { RdnAdl.SetMaxClocks(); } UINT16 AmdGpu::GetEngineClock() { return 0; } UINT16 AmdGpu::GetMemoryClock() { return 0; } UINT64 AmdGpu::GetTotalMemory() { return 0; } UINT64 AmdGpu::GetFreeMemory() { return 0; } UINT8 AmdGpu::GetTemperature() { UINT32 temp; temp = ReadGpuRegister(0x730); return temp; } UINT8 AmdGpu::GetLoad() { DWORD usage, reg6do; FLOAT f1; usage = ReadGpuRegister(0x668); reg6do = ReadGpuRegister(0x6D0); reg6do = (reg6do & 0x0000ffff); usage = (usage & 0x0000ffff); f1 = usage; f1 = f1 * 200.0f; f1 = f1 / (float) reg6do; return f1; } UINT16 AmdGpu::GetMaximumEngineClock() { return 0; } UINT16 AmdGpu::GetMaximumMemoryClock() { return 0; } VOID AmdGpu::ForceMaximumClocks() { }<|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/views/options/content_settings_window_view.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/views/options/advanced_page_view.h" #include "chrome/browser/views/options/content_filter_page_view.h" #include "chrome/browser/views/options/cookie_filter_page_view.h" #include "chrome/browser/views/options/general_page_view.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "views/controls/tabbed_pane/tabbed_pane.h" #include "views/widget/root_view.h" #include "views/window/dialog_delegate.h" #include "views/window/window.h" static ContentSettingsWindowView* instance_ = NULL; // Content setting dialog bounds padding. static const int kDialogPadding = 7; /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, public: // static void ContentSettingsWindowView::Show(ContentSettingsType page, Profile* profile) { DCHECK(profile); // If there's already an existing options window, activate it and switch to // the specified page. // TODO(beng): note this is not multi-simultaneous-profile-safe. When we care // about this case this will have to be fixed. if (!instance_) { instance_ = new ContentSettingsWindowView(profile); views::Window::CreateChromeWindow(NULL, gfx::Rect(), instance_); // The window is alive by itself now... } instance_->ShowContentSettingsTab(page); } // static void ContentSettingsWindowView::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterIntegerPref(prefs::kContentSettingsWindowLastTabIndex, 0); } ContentSettingsWindowView::ContentSettingsWindowView(Profile* profile) // Always show preferences for the original profile. Most state when off // the record comes from the original profile, but we explicitly use // the original profile to avoid potential problems. : tabs_(NULL), profile_(profile->GetOriginalProfile()) { // We don't need to observe changes in this value. last_selected_page_.Init(prefs::kContentSettingsWindowLastTabIndex, g_browser_process->local_state(), NULL); } ContentSettingsWindowView::~ContentSettingsWindowView() { } /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, views::DialogDelegate implementation: std::wstring ContentSettingsWindowView::GetWindowTitle() const { return l10n_util::GetString(IDS_CONTENT_SETTINGS_TITLE); } void ContentSettingsWindowView::WindowClosing() { instance_ = NULL; } bool ContentSettingsWindowView::Cancel() { return GetCurrentContentSettingsTabView()->CanClose(); } views::View* ContentSettingsWindowView::GetContentsView() { return this; } /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, views::TabbedPane::Listener implementation: void ContentSettingsWindowView::TabSelectedAt(int index) { } /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, views::View overrides: void ContentSettingsWindowView::Layout() { tabs_->SetBounds(kDialogPadding, kDialogPadding, width() - (2 * kDialogPadding), height() - (2 * kDialogPadding)); } gfx::Size ContentSettingsWindowView::GetPreferredSize() { return gfx::Size(views::Window::GetLocalizedContentsSize( IDS_CONTENT_SETTINGS_DIALOG_WIDTH_CHARS, IDS_CONTENT_SETTINGS_DIALOG_HEIGHT_LINES)); } void ContentSettingsWindowView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { // Can't init before we're inserted into a Container, because we require a // HWND to parent native child controls to. if (is_add && child == this) Init(); } /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, private: void ContentSettingsWindowView::Init() { // Make sure we don't leak memory by calling this twice. DCHECK(!tabs_); tabs_ = new views::TabbedPane; tabs_->SetListener(this); AddChildView(tabs_); int tab_index = 0; CookieFilterPageView* cookie_page = new CookieFilterPageView(profile_); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_COOKIES_TAB_LABEL), cookie_page, false); ContentFilterPageView* image_page = new ContentFilterPageView(profile_, IDS_IMAGES_SETTING_LABEL, IDS_IMAGES_LOAD_RADIO, IDS_IMAGES_NOLOAD_RADIO); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_IMAGES_TAB_LABEL), image_page, false); ContentFilterPageView* javascript_page = new ContentFilterPageView(profile_, IDS_JS_SETTING_LABEL, IDS_JS_ALLOW_RADIO, IDS_JS_DONOTALLOW_RADIO); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_JAVASCRIPT_TAB_LABEL), javascript_page, false); ContentFilterPageView* plugin_page = new ContentFilterPageView(profile_, IDS_PLUGIN_SETTING_LABEL, IDS_PLUGIN_LOAD_RADIO, IDS_PLUGIN_NOLOAD_RADIO); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_PLUGIN_TAB_LABEL), plugin_page, false); ContentFilterPageView* popup_page = new ContentFilterPageView(profile_, IDS_POPUP_SETTING_LABEL, IDS_POPUP_ALLOW_RADIO, IDS_POPUP_BLOCK_RADIO); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_POPUP_TAB_LABEL), popup_page, false); DCHECK(tabs_->GetTabCount() == CONTENT_SETTINGS_NUM_TYPES); } void ContentSettingsWindowView::ShowContentSettingsTab( ContentSettingsType page) { // If the window is not yet visible, we need to show it (it will become // active), otherwise just bring it to the front. if (!window()->IsVisible()) window()->Show(); else window()->Activate(); if (page == CONTENT_SETTINGS_TYPE_DEFAULT) { // Remember the last visited page from local state. page = static_cast<ContentSettingsType>(last_selected_page_.GetValue()); if (page == CONTENT_SETTINGS_TYPE_DEFAULT) page = CONTENT_SETTINGS_FIRST_TYPE; } // If the page number is out of bounds, reset to the first tab. if (page < 0 || page >= tabs_->GetTabCount()) page = CONTENT_SETTINGS_FIRST_TYPE; tabs_->SelectTabAt(static_cast<int>(page)); } const OptionsPageView* ContentSettingsWindowView::GetCurrentContentSettingsTabView() const { return static_cast<OptionsPageView*>(tabs_->GetSelectedTab()); } <commit_msg>Fix broken pref usage; I changed the registration to a user pref but didn't change the read.<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/views/options/content_settings_window_view.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/profile.h" #include "chrome/browser/views/options/advanced_page_view.h" #include "chrome/browser/views/options/content_filter_page_view.h" #include "chrome/browser/views/options/cookie_filter_page_view.h" #include "chrome/browser/views/options/general_page_view.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "views/controls/tabbed_pane/tabbed_pane.h" #include "views/widget/root_view.h" #include "views/window/dialog_delegate.h" #include "views/window/window.h" static ContentSettingsWindowView* instance_ = NULL; // Content setting dialog bounds padding. static const int kDialogPadding = 7; /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, public: // static void ContentSettingsWindowView::Show(ContentSettingsType page, Profile* profile) { DCHECK(profile); // If there's already an existing options window, activate it and switch to // the specified page. // TODO(beng): note this is not multi-simultaneous-profile-safe. When we care // about this case this will have to be fixed. if (!instance_) { instance_ = new ContentSettingsWindowView(profile); views::Window::CreateChromeWindow(NULL, gfx::Rect(), instance_); // The window is alive by itself now... } instance_->ShowContentSettingsTab(page); } // static void ContentSettingsWindowView::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterIntegerPref(prefs::kContentSettingsWindowLastTabIndex, 0); } ContentSettingsWindowView::ContentSettingsWindowView(Profile* profile) // Always show preferences for the original profile. Most state when off // the record comes from the original profile, but we explicitly use // the original profile to avoid potential problems. : tabs_(NULL), profile_(profile->GetOriginalProfile()) { // We don't need to observe changes in this value. last_selected_page_.Init(prefs::kContentSettingsWindowLastTabIndex, profile->GetPrefs(), NULL); } ContentSettingsWindowView::~ContentSettingsWindowView() { } /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, views::DialogDelegate implementation: std::wstring ContentSettingsWindowView::GetWindowTitle() const { return l10n_util::GetString(IDS_CONTENT_SETTINGS_TITLE); } void ContentSettingsWindowView::WindowClosing() { instance_ = NULL; } bool ContentSettingsWindowView::Cancel() { return GetCurrentContentSettingsTabView()->CanClose(); } views::View* ContentSettingsWindowView::GetContentsView() { return this; } /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, views::TabbedPane::Listener implementation: void ContentSettingsWindowView::TabSelectedAt(int index) { } /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, views::View overrides: void ContentSettingsWindowView::Layout() { tabs_->SetBounds(kDialogPadding, kDialogPadding, width() - (2 * kDialogPadding), height() - (2 * kDialogPadding)); } gfx::Size ContentSettingsWindowView::GetPreferredSize() { return gfx::Size(views::Window::GetLocalizedContentsSize( IDS_CONTENT_SETTINGS_DIALOG_WIDTH_CHARS, IDS_CONTENT_SETTINGS_DIALOG_HEIGHT_LINES)); } void ContentSettingsWindowView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { // Can't init before we're inserted into a Container, because we require a // HWND to parent native child controls to. if (is_add && child == this) Init(); } /////////////////////////////////////////////////////////////////////////////// // ContentSettingsWindowView, private: void ContentSettingsWindowView::Init() { // Make sure we don't leak memory by calling this twice. DCHECK(!tabs_); tabs_ = new views::TabbedPane; tabs_->SetListener(this); AddChildView(tabs_); int tab_index = 0; CookieFilterPageView* cookie_page = new CookieFilterPageView(profile_); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_COOKIES_TAB_LABEL), cookie_page, false); ContentFilterPageView* image_page = new ContentFilterPageView(profile_, IDS_IMAGES_SETTING_LABEL, IDS_IMAGES_LOAD_RADIO, IDS_IMAGES_NOLOAD_RADIO); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_IMAGES_TAB_LABEL), image_page, false); ContentFilterPageView* javascript_page = new ContentFilterPageView(profile_, IDS_JS_SETTING_LABEL, IDS_JS_ALLOW_RADIO, IDS_JS_DONOTALLOW_RADIO); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_JAVASCRIPT_TAB_LABEL), javascript_page, false); ContentFilterPageView* plugin_page = new ContentFilterPageView(profile_, IDS_PLUGIN_SETTING_LABEL, IDS_PLUGIN_LOAD_RADIO, IDS_PLUGIN_NOLOAD_RADIO); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_PLUGIN_TAB_LABEL), plugin_page, false); ContentFilterPageView* popup_page = new ContentFilterPageView(profile_, IDS_POPUP_SETTING_LABEL, IDS_POPUP_ALLOW_RADIO, IDS_POPUP_BLOCK_RADIO); tabs_->AddTabAtIndex(tab_index++, l10n_util::GetString(IDS_POPUP_TAB_LABEL), popup_page, false); DCHECK(tabs_->GetTabCount() == CONTENT_SETTINGS_NUM_TYPES); } void ContentSettingsWindowView::ShowContentSettingsTab( ContentSettingsType page) { // If the window is not yet visible, we need to show it (it will become // active), otherwise just bring it to the front. if (!window()->IsVisible()) window()->Show(); else window()->Activate(); if (page == CONTENT_SETTINGS_TYPE_DEFAULT) { // Remember the last visited page from local state. page = static_cast<ContentSettingsType>(last_selected_page_.GetValue()); if (page == CONTENT_SETTINGS_TYPE_DEFAULT) page = CONTENT_SETTINGS_FIRST_TYPE; } // If the page number is out of bounds, reset to the first tab. if (page < 0 || page >= tabs_->GetTabCount()) page = CONTENT_SETTINGS_FIRST_TYPE; tabs_->SelectTabAt(static_cast<int>(page)); } const OptionsPageView* ContentSettingsWindowView::GetCurrentContentSettingsTabView() const { return static_cast<OptionsPageView*>(tabs_->GetSelectedTab()); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2004 by * * Jason Kivlighn ([email protected]) * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "authorlistview.h" #include <kmessagebox.h> #include <kconfig.h> #include <klocale.h> #include <kglobal.h> #include <kiconloader.h> #include <kmenu.h> #include <QList> #include "backends/recipedb.h" #include "dialogs/createelementdialog.h" #include "dialogs/dependanciesdialog.h" AuthorListView::AuthorListView( QWidget *parent, RecipeDB *db ) : DBListViewBase( parent, db, db->authorCount() ) { setAllColumnsShowFocus( true ); setDefaultRenameAction( Q3ListView::Reject ); } void AuthorListView::init() { connect( database, SIGNAL( authorCreated( const Element & ) ), SLOT( checkCreateAuthor( const Element & ) ) ); connect( database, SIGNAL( authorRemoved( int ) ), SLOT( removeAuthor( int ) ) ); } void AuthorListView::load( int limit, int offset ) { ElementList authorList; database->loadAuthors( &authorList, limit, offset ); setTotalItems(authorList.count()); for ( ElementList::const_iterator ing_it = authorList.begin(); ing_it != authorList.end(); ++ing_it ) createAuthor( *ing_it ); } void AuthorListView::checkCreateAuthor( const Element &el ) { if ( handleElement(el.name) ) { //only create this author if the base class okays it createAuthor(el); } } StdAuthorListView::StdAuthorListView( QWidget *parent, RecipeDB *db, bool editable ) : AuthorListView( parent, db ) { addColumn( i18n( "Author" ) ); KConfigGroup config = KGlobal::config()->group( "Advanced" ); bool show_id = config.readEntry( "ShowID", false ); addColumn( i18n( "Id" ), show_id ? -1 : 0 ); if ( editable ) { setRenameable( 0, true ); KIconLoader *il = KIconLoader::global(); kpop = new KMenu( this ); kpop->addAction( il->loadIcon( "document-new", KIconLoader::NoGroup, 16 ), i18n( "&Create" ), this, SLOT( createNew() ), Qt::CTRL + Qt::Key_N ); kpop->addAction( il->loadIcon( "edit-delete", KIconLoader::NoGroup, 16 ), i18n( "&Delete" ), this, SLOT( remove () ), Qt::Key_Delete ); kpop->addAction( il->loadIcon( "edit-rename", KIconLoader::NoGroup, 16 ), i18n( "&Rename" ), this, SLOT( slotRename() ), Qt::CTRL + Qt::Key_R ); kpop->ensurePolished(); connect( this, SIGNAL( contextMenu( K3ListView *, Q3ListViewItem *, const QPoint & ) ), SLOT( showPopup( K3ListView *, Q3ListViewItem *, const QPoint & ) ) ); connect( this, SIGNAL( doubleClicked( Q3ListViewItem* ) ), this, SLOT( modAuthor( Q3ListViewItem* ) ) ); connect( this, SIGNAL( itemRenamed( Q3ListViewItem* ) ), this, SLOT( saveAuthor( Q3ListViewItem* ) ) ); } } void StdAuthorListView::showPopup( K3ListView * /*l*/, Q3ListViewItem *i, const QPoint &p ) { if ( i ) kpop->exec( p ); } void StdAuthorListView::createNew() { CreateElementDialog * elementDialog = new CreateElementDialog( this, i18n( "New Author" ) ); if ( elementDialog->exec() == QDialog::Accepted ) { QString result = elementDialog->newElementName(); //check bounds first if ( checkBounds( result ) ) database->createNewAuthor( result ); // Create the new author in the database } delete elementDialog; } void StdAuthorListView::remove () { Q3ListViewItem * item = currentItem(); if ( item ) { int id = item->text( 1 ).toInt(); ElementList recipeDependancies; database->findUseOfAuthorInRecipes( &recipeDependancies, id ); if ( recipeDependancies.isEmpty() ) { switch ( KMessageBox::warningContinueCancel( this, i18n( "Are you sure you want to delete this author?" ) ) ) { case KMessageBox::Continue: database->removeAuthor( id ); break; } return; } else { // need warning! ListInfo info; info.list = recipeDependancies; info.name = i18n("Recipes"); DependanciesDialog warnDialog( this, info, false ); if ( warnDialog.exec() == QDialog::Accepted ) database->removeAuthor( id ); } } } void StdAuthorListView::slotRename() { rename( 0, 0 ); } void StdAuthorListView::rename( Q3ListViewItem* /*item*/,int /*c*/ ) { Q3ListViewItem * item = currentItem(); if ( item ) AuthorListView::rename( item, 0 ); } void StdAuthorListView::createAuthor( const Element &author ) { createElement(new Q3ListViewItem( this, author.name, QString::number( author.id ) )); } void StdAuthorListView::removeAuthor( int id ) { Q3ListViewItem * item = findItem( QString::number( id ), 1 ); removeElement(item); } void StdAuthorListView::modAuthor( Q3ListViewItem* i ) { if ( i ) AuthorListView::rename( i, 0 ); } void StdAuthorListView::saveAuthor( Q3ListViewItem* i ) { if ( !checkBounds( i->text( 0 ) ) ) { reload(ForceReload); //reset the changed text return ; } int existing_id = database->findExistingAuthorByName( i->text( 0 ) ); int author_id = i->text( 1 ).toInt(); if ( existing_id != -1 && existing_id != author_id ) //category already exists with this label... merge the two { switch ( KMessageBox::warningContinueCancel( this, i18n( "This author already exists. Continuing will merge these two authors into one. Are you sure?" ) ) ) { case KMessageBox::Continue: { database->mergeAuthors( existing_id, author_id ); break; } default: reload(ForceReload); break; } } else { database->modAuthor( ( i->text( 1 ) ).toInt(), i->text( 0 ) ); } } bool StdAuthorListView::checkBounds( const QString &name ) { if ( name.length() > int(database->maxAuthorNameLength()) ) { KMessageBox::error( this, i18np( "Author name cannot be longer than 1 character.", "Author name cannot be longer than %1 characters." , database->maxAuthorNameLength() )); return false; } return true; } AuthorCheckListItem::AuthorCheckListItem( AuthorCheckListView* qlv, const Element &author ) : Q3CheckListItem( qlv, QString::null, Q3CheckListItem::CheckBox ), authorStored(author), m_listview(qlv) { } AuthorCheckListItem::AuthorCheckListItem( AuthorCheckListView* qlv, Q3ListViewItem *after, const Element &author ) : Q3CheckListItem( qlv, after, QString::null, Q3CheckListItem::CheckBox ), authorStored(author), m_listview(qlv) { } Element AuthorCheckListItem::author() const { return authorStored; } QString AuthorCheckListItem::text( int column ) const { switch ( column ) { case 0: return ( authorStored.name ); case 1: return ( QString::number( authorStored.id ) ); default: return QString::null; } } void AuthorCheckListItem::stateChange( bool on ) { m_listview->stateChange(this,on); } AuthorCheckListView::AuthorCheckListView( QWidget *parent, RecipeDB *db ) : AuthorListView( parent, db ) { addColumn( i18n( "Author" ) ); KConfigGroup config = KGlobal::config()->group( "Advanced" ); bool show_id = config.readEntry( "ShowID", false ); addColumn( i18n( "Id" ), show_id ? -1 : 0 ); } void AuthorCheckListView::createAuthor( const Element &author ) { createElement(new AuthorCheckListItem( this, author )); } void AuthorCheckListView::removeAuthor( int id ) { Q3ListViewItem * item = findItem( QString::number( id ), 1 ); removeElement(item); } void AuthorCheckListView::load( int limit, int offset ) { AuthorListView::load(limit,offset); for ( QList<Element>::const_iterator author_it = m_selections.constBegin(); author_it != m_selections.constEnd(); ++author_it ) { Q3CheckListItem * item = ( Q3CheckListItem* ) findItem( QString::number( (*author_it).id ), 1 ); if ( item ) { item->setOn(true); } } } void AuthorCheckListView::stateChange(AuthorCheckListItem *it,bool on) { if ( !reloading() ) { if ( on ) m_selections.append(it->author()); else m_selections.removeAll(it->author()); } } #include "authorlistview.moc" <commit_msg>Fixes for krazy issues (not using QPointer when showing modal dialogs with exec() ), see: http://www.kdedevelopers.org/node/3919<commit_after>/*************************************************************************** * Copyright (C) 2004 by * * Jason Kivlighn ([email protected]) * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "authorlistview.h" #include <kmessagebox.h> #include <kconfig.h> #include <klocale.h> #include <kglobal.h> #include <kiconloader.h> #include <kmenu.h> #include <QList> #include <QPointer> #include "backends/recipedb.h" #include "dialogs/createelementdialog.h" #include "dialogs/dependanciesdialog.h" AuthorListView::AuthorListView( QWidget *parent, RecipeDB *db ) : DBListViewBase( parent, db, db->authorCount() ) { setAllColumnsShowFocus( true ); setDefaultRenameAction( Q3ListView::Reject ); } void AuthorListView::init() { connect( database, SIGNAL( authorCreated( const Element & ) ), SLOT( checkCreateAuthor( const Element & ) ) ); connect( database, SIGNAL( authorRemoved( int ) ), SLOT( removeAuthor( int ) ) ); } void AuthorListView::load( int limit, int offset ) { ElementList authorList; database->loadAuthors( &authorList, limit, offset ); setTotalItems(authorList.count()); for ( ElementList::const_iterator ing_it = authorList.begin(); ing_it != authorList.end(); ++ing_it ) createAuthor( *ing_it ); } void AuthorListView::checkCreateAuthor( const Element &el ) { if ( handleElement(el.name) ) { //only create this author if the base class okays it createAuthor(el); } } StdAuthorListView::StdAuthorListView( QWidget *parent, RecipeDB *db, bool editable ) : AuthorListView( parent, db ) { addColumn( i18n( "Author" ) ); KConfigGroup config = KGlobal::config()->group( "Advanced" ); bool show_id = config.readEntry( "ShowID", false ); addColumn( i18n( "Id" ), show_id ? -1 : 0 ); if ( editable ) { setRenameable( 0, true ); KIconLoader *il = KIconLoader::global(); kpop = new KMenu( this ); kpop->addAction( il->loadIcon( "document-new", KIconLoader::NoGroup, 16 ), i18n( "&Create" ), this, SLOT( createNew() ), Qt::CTRL + Qt::Key_N ); kpop->addAction( il->loadIcon( "edit-delete", KIconLoader::NoGroup, 16 ), i18n( "&Delete" ), this, SLOT( remove () ), Qt::Key_Delete ); kpop->addAction( il->loadIcon( "edit-rename", KIconLoader::NoGroup, 16 ), i18n( "&Rename" ), this, SLOT( slotRename() ), Qt::CTRL + Qt::Key_R ); kpop->ensurePolished(); connect( this, SIGNAL( contextMenu( K3ListView *, Q3ListViewItem *, const QPoint & ) ), SLOT( showPopup( K3ListView *, Q3ListViewItem *, const QPoint & ) ) ); connect( this, SIGNAL( doubleClicked( Q3ListViewItem* ) ), this, SLOT( modAuthor( Q3ListViewItem* ) ) ); connect( this, SIGNAL( itemRenamed( Q3ListViewItem* ) ), this, SLOT( saveAuthor( Q3ListViewItem* ) ) ); } } void StdAuthorListView::showPopup( K3ListView * /*l*/, Q3ListViewItem *i, const QPoint &p ) { if ( i ) kpop->exec( p ); } void StdAuthorListView::createNew() { QPointer<CreateElementDialog> elementDialog = new CreateElementDialog( this, i18n( "New Author" ) ); if ( elementDialog->exec() == QDialog::Accepted ) { QString result = elementDialog->newElementName(); //check bounds first if ( checkBounds( result ) ) database->createNewAuthor( result ); // Create the new author in the database } delete elementDialog; } void StdAuthorListView::remove () { Q3ListViewItem * item = currentItem(); if ( item ) { int id = item->text( 1 ).toInt(); ElementList recipeDependancies; database->findUseOfAuthorInRecipes( &recipeDependancies, id ); if ( recipeDependancies.isEmpty() ) { switch ( KMessageBox::warningContinueCancel( this, i18n( "Are you sure you want to delete this author?" ) ) ) { case KMessageBox::Continue: database->removeAuthor( id ); break; } return; } else { // need warning! ListInfo info; info.list = recipeDependancies; info.name = i18n("Recipes"); QPointer<DependanciesDialog> warnDialog = new DependanciesDialog( this, info, false ); if ( warnDialog->exec() == QDialog::Accepted ) database->removeAuthor( id ); delete warnDialog; } } } void StdAuthorListView::slotRename() { rename( 0, 0 ); } void StdAuthorListView::rename( Q3ListViewItem* /*item*/,int /*c*/ ) { Q3ListViewItem * item = currentItem(); if ( item ) AuthorListView::rename( item, 0 ); } void StdAuthorListView::createAuthor( const Element &author ) { createElement(new Q3ListViewItem( this, author.name, QString::number( author.id ) )); } void StdAuthorListView::removeAuthor( int id ) { Q3ListViewItem * item = findItem( QString::number( id ), 1 ); removeElement(item); } void StdAuthorListView::modAuthor( Q3ListViewItem* i ) { if ( i ) AuthorListView::rename( i, 0 ); } void StdAuthorListView::saveAuthor( Q3ListViewItem* i ) { if ( !checkBounds( i->text( 0 ) ) ) { reload(ForceReload); //reset the changed text return ; } int existing_id = database->findExistingAuthorByName( i->text( 0 ) ); int author_id = i->text( 1 ).toInt(); if ( existing_id != -1 && existing_id != author_id ) //category already exists with this label... merge the two { switch ( KMessageBox::warningContinueCancel( this, i18n( "This author already exists. Continuing will merge these two authors into one. Are you sure?" ) ) ) { case KMessageBox::Continue: { database->mergeAuthors( existing_id, author_id ); break; } default: reload(ForceReload); break; } } else { database->modAuthor( ( i->text( 1 ) ).toInt(), i->text( 0 ) ); } } bool StdAuthorListView::checkBounds( const QString &name ) { if ( name.length() > int(database->maxAuthorNameLength()) ) { KMessageBox::error( this, i18np( "Author name cannot be longer than 1 character.", "Author name cannot be longer than %1 characters." , database->maxAuthorNameLength() )); return false; } return true; } AuthorCheckListItem::AuthorCheckListItem( AuthorCheckListView* qlv, const Element &author ) : Q3CheckListItem( qlv, QString::null, Q3CheckListItem::CheckBox ), authorStored(author), m_listview(qlv) { } AuthorCheckListItem::AuthorCheckListItem( AuthorCheckListView* qlv, Q3ListViewItem *after, const Element &author ) : Q3CheckListItem( qlv, after, QString::null, Q3CheckListItem::CheckBox ), authorStored(author), m_listview(qlv) { } Element AuthorCheckListItem::author() const { return authorStored; } QString AuthorCheckListItem::text( int column ) const { switch ( column ) { case 0: return ( authorStored.name ); case 1: return ( QString::number( authorStored.id ) ); default: return QString::null; } } void AuthorCheckListItem::stateChange( bool on ) { m_listview->stateChange(this,on); } AuthorCheckListView::AuthorCheckListView( QWidget *parent, RecipeDB *db ) : AuthorListView( parent, db ) { addColumn( i18n( "Author" ) ); KConfigGroup config = KGlobal::config()->group( "Advanced" ); bool show_id = config.readEntry( "ShowID", false ); addColumn( i18n( "Id" ), show_id ? -1 : 0 ); } void AuthorCheckListView::createAuthor( const Element &author ) { createElement(new AuthorCheckListItem( this, author )); } void AuthorCheckListView::removeAuthor( int id ) { Q3ListViewItem * item = findItem( QString::number( id ), 1 ); removeElement(item); } void AuthorCheckListView::load( int limit, int offset ) { AuthorListView::load(limit,offset); for ( QList<Element>::const_iterator author_it = m_selections.constBegin(); author_it != m_selections.constEnd(); ++author_it ) { Q3CheckListItem * item = ( Q3CheckListItem* ) findItem( QString::number( (*author_it).id ), 1 ); if ( item ) { item->setOn(true); } } } void AuthorCheckListView::stateChange(AuthorCheckListItem *it,bool on) { if ( !reloading() ) { if ( on ) m_selections.append(it->author()); else m_selections.removeAll(it->author()); } } #include "authorlistview.moc" <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2004 by * * Jason Kivlighn ([email protected]) * * Unai Garro ([email protected]) * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "recipelistview.h" #include <qintdict.h> #include <qdatastream.h> #include <kdebug.h> #include <kconfig.h> #include <kglobal.h> #include <klocale.h> #include <kiconloader.h> #include "backends/recipedb.h" class UncategorizedItem : public QListViewItem { public: UncategorizedItem( QListView *lv ) : QListViewItem( lv, i18n("Uncategorized") ){} int rtti() const { return 1006; } }; RecipeItemDrag::RecipeItemDrag( RecipeListItem *recipeItem, QWidget *dragSource, const char *name ) : QStoredDrag( RECIPEITEMMIMETYPE, dragSource, name ) { if ( recipeItem ) { QByteArray data; QDataStream out( data, IO_WriteOnly ); out << recipeItem->recipeID(); out << recipeItem->title(); setEncodedData( data ); } } bool RecipeItemDrag::canDecode( QMimeSource* e ) { return e->provides( RECIPEITEMMIMETYPE ); } bool RecipeItemDrag::decode( const QMimeSource* e, RecipeListItem& item ) { if ( !e ) return false; QByteArray data = e->encodedData( RECIPEITEMMIMETYPE ); if ( data.isEmpty() ) return false; QString title; int recipeID; QDataStream in( data, IO_ReadOnly ); in >> recipeID; in >> title; item.setTitle( title ); item.setRecipeID( recipeID ); return true; } RecipeListView::RecipeListView( QWidget *parent, RecipeDB *db ) : StdCategoryListView( parent, db ), flat_list( false ), m_uncat_item(0) { connect( database, SIGNAL( recipeCreated( const Element &, const ElementList & ) ), SLOT( createRecipe( const Element &, const ElementList & ) ) ); connect( database, SIGNAL( recipeRemoved( int ) ), SLOT( removeRecipe( int ) ) ); connect( database, SIGNAL( recipeRemoved( int, int ) ), SLOT( removeRecipe( int, int ) ) ); connect( database, SIGNAL( recipeModified( const Element &, const ElementList & ) ), SLOT( modifyRecipe( const Element &, const ElementList & ) ) ); setColumnText( 0, i18n( "Recipe" ) ); KConfig *config = KGlobal::config(); config->setGroup( "Performance" ); curr_limit = config->readNumEntry("CategoryLimit",-1); KIconLoader il; setPixmap( il.loadIcon( "categories", KIcon::NoGroup, 16 ) ); } QDragObject *RecipeListView::dragObject() { RecipeListItem * item = dynamic_cast<RecipeListItem*>( selectedItem() ); if ( item != 0 ) { RecipeItemDrag * obj = new RecipeItemDrag( item, this, "Recipe drag item" ); /*const QPixmap *pm = item->pixmap(0); if( pm ) obj->setPixmap( *pm );*/ return obj; } return 0; } bool RecipeListView::acceptDrag( QDropEvent *event ) const { return RecipeItemDrag::canDecode( event ); } void RecipeListView::load(int limit, int offset) { m_uncat_item = 0; if ( flat_list ) { ElementList recipeList; database->loadRecipeList( &recipeList ); ElementList::const_iterator recipe_it; for ( recipe_it = recipeList.begin();recipe_it != recipeList.end();++recipe_it ) { Recipe recipe; recipe.recipeID = ( *recipe_it ).id; recipe.title = ( *recipe_it ).name; createRecipe( recipe, -1 ); } } else { StdCategoryListView::load(limit,offset); if ( offset == 0 ) { ElementList recipeList; database->loadUncategorizedRecipes( &recipeList ); ElementList::const_iterator recipe_it; for ( recipe_it = recipeList.begin();recipe_it != recipeList.end();++recipe_it ) { Recipe recipe; recipe.recipeID = ( *recipe_it ).id; recipe.title = ( *recipe_it ).name; createRecipe( recipe, -1 ); } } } } void RecipeListView::populate( QListViewItem *item ) { StdCategoryListView::populate(item); if ( !flat_list ) { for ( QListViewItem *it = item->firstChild(); it; it = it->nextSibling() ) { if ( it->rtti() == RECIPELISTITEM_RTTI ) return; } CategoryItemInfo *cat_item = dynamic_cast<CategoryItemInfo*>(item); if ( !cat_item ) return; int id = cat_item->categoryId(); // Now show the recipes ElementList recipeList; database->loadRecipeList( &recipeList, id ); ElementList::const_iterator recipe_it; for ( recipe_it = recipeList.begin(); recipe_it != recipeList.end(); ++recipe_it ) { Recipe recipe; recipe.recipeID = ( *recipe_it ).id; recipe.title = ( *recipe_it ).name; createRecipe( recipe, id ); } } } void RecipeListView::populateAll( QListViewItem *parent ) { if ( !parent ) parent = firstChild(); else { populate( parent ); parent = parent->firstChild(); } for ( QListViewItem *item = parent; item; item = item->nextSibling() ) { populateAll( item ); } } void RecipeListView::createRecipe( const Recipe &recipe, int parent_id ) { if ( parent_id == -1 ) { if ( !m_uncat_item && curr_offset == 0 ) { m_uncat_item = new UncategorizedItem(this); if ( childCount() == 1 ) //only call createElement if this is the only item in the list createElement(m_uncat_item); //otherwise, this item won't stay at the top } if ( m_uncat_item ) new RecipeListItem( m_uncat_item, recipe ); } else { CategoryListItem *parent = (CategoryListItem*)items_map[ parent_id ]; if ( parent && parent->isPopulated() ) createElement(new RecipeListItem( parent, recipe )); } } void RecipeListView::createRecipe( const Element &recipe_el, const ElementList &categories ) { Recipe recipe; recipe.recipeID = recipe_el.id; recipe.title = recipe_el.name; if ( categories.count() == 0 ) { createRecipe( recipe, -1 ); } else { for ( ElementList::const_iterator cat_it = categories.begin(); cat_it != categories.end(); ++cat_it ) { int cur_cat_id = ( *cat_it ).id; QListViewItemIterator iterator( this ); while ( iterator.current() ) { if ( iterator.current() ->rtti() == 1001 ) { CategoryListItem * cat_item = ( CategoryListItem* ) iterator.current(); if ( cat_item->categoryId() == cur_cat_id ) { createRecipe( recipe, cur_cat_id ); } } ++iterator; } } } } void RecipeListView::modifyRecipe( const Element &recipe, const ElementList &categories ) { removeRecipe( recipe.id ); createRecipe( recipe, categories ); } void RecipeListView::removeRecipe( int id ) { QListViewItemIterator iterator( this ); while ( iterator.current() ) { if ( iterator.current() ->rtti() == 1000 ) { RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current(); if ( recipe_it->recipeID() == id ) removeElement(recipe_it); } ++iterator; } } void RecipeListView::removeRecipe( int recipe_id, int cat_id ) { QListViewItem * item = items_map[ cat_id ]; //find out if this is the only category the recipe belongs to int finds = 0; QListViewItemIterator iterator( this ); while ( iterator.current() ) { if ( iterator.current() ->rtti() == 1000 ) { RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current(); if ( recipe_it->recipeID() == recipe_id ) { if ( finds > 1 ) break; finds++; } } ++iterator; } //do this to only iterate over children of 'item' QListViewItem *pEndItem = NULL; QListViewItem *pStartItem = item; do { if ( pStartItem->nextSibling() ) pEndItem = pStartItem->nextSibling(); else pStartItem = pStartItem->parent(); } while ( pStartItem && !pEndItem ); iterator = QListViewItemIterator( item ); while ( iterator.current() != pEndItem ) { if ( iterator.current() ->rtti() == 1000 ) { RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current(); if ( recipe_it->recipeID() == recipe_id ) { if ( finds == 1 ) { //the item is now uncategorized if ( !m_uncat_item && curr_offset == 0 ) m_uncat_item = new UncategorizedItem(this); if ( m_uncat_item ) { Recipe r; r.title = recipe_it->title(); r.recipeID = recipe_id; new RecipeListItem(m_uncat_item,r); } } removeElement(recipe_it); break; } } ++iterator; } } void RecipeListView::removeCategory( int id ) { QListViewItem * item = items_map[ id ]; if ( !item ) return ; //this may have been deleted already by its parent being deleted moveChildrenToRoot( item ); StdCategoryListView::removeCategory( id ); } void RecipeListView::moveChildrenToRoot( QListViewItem *item ) { QListViewItem * next_sibling; for ( QListViewItem * it = item->firstChild(); it; it = next_sibling ) { next_sibling = it->nextSibling(); if ( it->rtti() == 1000 ) { RecipeListItem *recipe_it = (RecipeListItem*) it; Recipe r; r.title = recipe_it->title(); r.recipeID = recipe_it->recipeID(); //the item is now uncategorized removeElement(it,false); it->parent() ->takeItem( it ); if ( !m_uncat_item && curr_offset == 0 ) m_uncat_item = new UncategorizedItem(this); if ( m_uncat_item ) new RecipeListItem(m_uncat_item,r); } moveChildrenToRoot( it ); delete it; } } #include "recipelistview.moc" <commit_msg>Boost performance just a bit on the search filter by performing fewer options to determine if an item has been populated. In particular, we don't have to iterate through the listview to find this out.<commit_after>/*************************************************************************** * Copyright (C) 2004 by * * Jason Kivlighn ([email protected]) * * Unai Garro ([email protected]) * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "recipelistview.h" #include <qintdict.h> #include <qdatastream.h> #include <kdebug.h> #include <kconfig.h> #include <kglobal.h> #include <klocale.h> #include <kiconloader.h> #include "backends/recipedb.h" class UncategorizedItem : public QListViewItem { public: UncategorizedItem( QListView *lv ) : QListViewItem( lv, i18n("Uncategorized") ){} int rtti() const { return 1006; } }; RecipeItemDrag::RecipeItemDrag( RecipeListItem *recipeItem, QWidget *dragSource, const char *name ) : QStoredDrag( RECIPEITEMMIMETYPE, dragSource, name ) { if ( recipeItem ) { QByteArray data; QDataStream out( data, IO_WriteOnly ); out << recipeItem->recipeID(); out << recipeItem->title(); setEncodedData( data ); } } bool RecipeItemDrag::canDecode( QMimeSource* e ) { return e->provides( RECIPEITEMMIMETYPE ); } bool RecipeItemDrag::decode( const QMimeSource* e, RecipeListItem& item ) { if ( !e ) return false; QByteArray data = e->encodedData( RECIPEITEMMIMETYPE ); if ( data.isEmpty() ) return false; QString title; int recipeID; QDataStream in( data, IO_ReadOnly ); in >> recipeID; in >> title; item.setTitle( title ); item.setRecipeID( recipeID ); return true; } RecipeListView::RecipeListView( QWidget *parent, RecipeDB *db ) : StdCategoryListView( parent, db ), flat_list( false ), m_uncat_item(0) { connect( database, SIGNAL( recipeCreated( const Element &, const ElementList & ) ), SLOT( createRecipe( const Element &, const ElementList & ) ) ); connect( database, SIGNAL( recipeRemoved( int ) ), SLOT( removeRecipe( int ) ) ); connect( database, SIGNAL( recipeRemoved( int, int ) ), SLOT( removeRecipe( int, int ) ) ); connect( database, SIGNAL( recipeModified( const Element &, const ElementList & ) ), SLOT( modifyRecipe( const Element &, const ElementList & ) ) ); setColumnText( 0, i18n( "Recipe" ) ); KConfig *config = KGlobal::config(); config->setGroup( "Performance" ); curr_limit = config->readNumEntry("CategoryLimit",-1); KIconLoader il; setPixmap( il.loadIcon( "categories", KIcon::NoGroup, 16 ) ); } QDragObject *RecipeListView::dragObject() { RecipeListItem * item = dynamic_cast<RecipeListItem*>( selectedItem() ); if ( item != 0 ) { RecipeItemDrag * obj = new RecipeItemDrag( item, this, "Recipe drag item" ); /*const QPixmap *pm = item->pixmap(0); if( pm ) obj->setPixmap( *pm );*/ return obj; } return 0; } bool RecipeListView::acceptDrag( QDropEvent *event ) const { return RecipeItemDrag::canDecode( event ); } void RecipeListView::load(int limit, int offset) { m_uncat_item = 0; if ( flat_list ) { ElementList recipeList; database->loadRecipeList( &recipeList ); ElementList::const_iterator recipe_it; for ( recipe_it = recipeList.begin();recipe_it != recipeList.end();++recipe_it ) { Recipe recipe; recipe.recipeID = ( *recipe_it ).id; recipe.title = ( *recipe_it ).name; createRecipe( recipe, -1 ); } } else { StdCategoryListView::load(limit,offset); if ( offset == 0 ) { ElementList recipeList; database->loadUncategorizedRecipes( &recipeList ); ElementList::const_iterator recipe_it; for ( recipe_it = recipeList.begin();recipe_it != recipeList.end();++recipe_it ) { Recipe recipe; recipe.recipeID = ( *recipe_it ).id; recipe.title = ( *recipe_it ).name; createRecipe( recipe, -1 ); } } } } void RecipeListView::populate( QListViewItem *item ) { CategoryItemInfo *cat_item = dynamic_cast<CategoryItemInfo*>(item); if ( !cat_item || cat_item->isPopulated() ) return; StdCategoryListView::populate(item); if ( !flat_list ) { int id = cat_item->categoryId(); // Now show the recipes ElementList recipeList; database->loadRecipeList( &recipeList, id ); ElementList::const_iterator recipe_it; for ( recipe_it = recipeList.begin(); recipe_it != recipeList.end(); ++recipe_it ) { Recipe recipe; recipe.recipeID = ( *recipe_it ).id; recipe.title = ( *recipe_it ).name; createRecipe( recipe, id ); } } } void RecipeListView::populateAll( QListViewItem *parent ) { if ( !parent ) parent = firstChild(); else { populate( parent ); parent = parent->firstChild(); } for ( QListViewItem *item = parent; item; item = item->nextSibling() ) { populateAll( item ); } } void RecipeListView::createRecipe( const Recipe &recipe, int parent_id ) { if ( parent_id == -1 ) { if ( !m_uncat_item && curr_offset == 0 ) { m_uncat_item = new UncategorizedItem(this); if ( childCount() == 1 ) //only call createElement if this is the only item in the list createElement(m_uncat_item); //otherwise, this item won't stay at the top } if ( m_uncat_item ) new RecipeListItem( m_uncat_item, recipe ); } else { CategoryListItem *parent = (CategoryListItem*)items_map[ parent_id ]; if ( parent && parent->isPopulated() ) createElement(new RecipeListItem( parent, recipe )); } } void RecipeListView::createRecipe( const Element &recipe_el, const ElementList &categories ) { Recipe recipe; recipe.recipeID = recipe_el.id; recipe.title = recipe_el.name; if ( categories.count() == 0 ) { createRecipe( recipe, -1 ); } else { for ( ElementList::const_iterator cat_it = categories.begin(); cat_it != categories.end(); ++cat_it ) { int cur_cat_id = ( *cat_it ).id; QListViewItemIterator iterator( this ); while ( iterator.current() ) { if ( iterator.current() ->rtti() == 1001 ) { CategoryListItem * cat_item = ( CategoryListItem* ) iterator.current(); if ( cat_item->categoryId() == cur_cat_id ) { createRecipe( recipe, cur_cat_id ); } } ++iterator; } } } } void RecipeListView::modifyRecipe( const Element &recipe, const ElementList &categories ) { removeRecipe( recipe.id ); createRecipe( recipe, categories ); } void RecipeListView::removeRecipe( int id ) { QListViewItemIterator iterator( this ); while ( iterator.current() ) { if ( iterator.current() ->rtti() == 1000 ) { RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current(); if ( recipe_it->recipeID() == id ) removeElement(recipe_it); } ++iterator; } } void RecipeListView::removeRecipe( int recipe_id, int cat_id ) { QListViewItem * item = items_map[ cat_id ]; //find out if this is the only category the recipe belongs to int finds = 0; QListViewItemIterator iterator( this ); while ( iterator.current() ) { if ( iterator.current() ->rtti() == 1000 ) { RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current(); if ( recipe_it->recipeID() == recipe_id ) { if ( finds > 1 ) break; finds++; } } ++iterator; } //do this to only iterate over children of 'item' QListViewItem *pEndItem = NULL; QListViewItem *pStartItem = item; do { if ( pStartItem->nextSibling() ) pEndItem = pStartItem->nextSibling(); else pStartItem = pStartItem->parent(); } while ( pStartItem && !pEndItem ); iterator = QListViewItemIterator( item ); while ( iterator.current() != pEndItem ) { if ( iterator.current() ->rtti() == 1000 ) { RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current(); if ( recipe_it->recipeID() == recipe_id ) { if ( finds == 1 ) { //the item is now uncategorized if ( !m_uncat_item && curr_offset == 0 ) m_uncat_item = new UncategorizedItem(this); if ( m_uncat_item ) { Recipe r; r.title = recipe_it->title(); r.recipeID = recipe_id; new RecipeListItem(m_uncat_item,r); } } removeElement(recipe_it); break; } } ++iterator; } } void RecipeListView::removeCategory( int id ) { QListViewItem * item = items_map[ id ]; if ( !item ) return ; //this may have been deleted already by its parent being deleted moveChildrenToRoot( item ); StdCategoryListView::removeCategory( id ); } void RecipeListView::moveChildrenToRoot( QListViewItem *item ) { QListViewItem * next_sibling; for ( QListViewItem * it = item->firstChild(); it; it = next_sibling ) { next_sibling = it->nextSibling(); if ( it->rtti() == 1000 ) { RecipeListItem *recipe_it = (RecipeListItem*) it; Recipe r; r.title = recipe_it->title(); r.recipeID = recipe_it->recipeID(); //the item is now uncategorized removeElement(it,false); it->parent() ->takeItem( it ); if ( !m_uncat_item && curr_offset == 0 ) m_uncat_item = new UncategorizedItem(this); if ( m_uncat_item ) new RecipeListItem(m_uncat_item,r); } moveChildrenToRoot( it ); delete it; } } #include "recipelistview.moc" <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: BarChartTypeTemplate.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:45:18 $ * * 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 CHART_BARCHARTTYPETEMPLATE_HXX #define CHART_BARCHARTTYPETEMPLATE_HXX #include "OPropertySet.hxx" #include "MutexContainer.hxx" #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #include "ChartTypeTemplate.hxx" #include "StackMode.hxx" namespace chart { class BarChartTypeTemplate : public MutexContainer, public ChartTypeTemplate, public ::property::OPropertySet { public: enum BarDirection { HORIZONTAL, VERTICAL }; explicit BarChartTypeTemplate( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext, const ::rtl::OUString & rServiceName, StackMode eStackMode, BarDirection eDirection, sal_Int32 nDim = 2 ); virtual ~BarChartTypeTemplate(); /// XServiceInfo declarations APPHELPER_XSERVICEINFO_DECL() /// merge XInterface implementations DECLARE_XINTERFACE() /// merge XTypeProvider implementations DECLARE_XTYPEPROVIDER() protected: // ____ OPropertySet ____ virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const throw(::com::sun::star::beans::UnknownPropertyException); virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); // ____ XPropertySet ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); // ____ XChartTypeTemplate ____ virtual sal_Bool SAL_CALL matchesTemplate( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram, sal_Bool bAdaptProperties ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > SAL_CALL getChartTypeForNewSeries( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > >& aFormerlyUsedChartTypes ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL applyStyle( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries, ::sal_Int32 nChartTypeGroupIndex, ::sal_Int32 nSeriesIndex, ::sal_Int32 nSeriesCount ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL resetStyles( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram ) throw (::com::sun::star::uno::RuntimeException); // ____ ChartTypeTemplate ____ virtual sal_Int32 getDimension() const; virtual StackMode getStackMode( sal_Int32 nChartTypeIndex ) const; virtual void createCoordinateSystems( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystemContainer > & xCooSysCnt ); private: StackMode m_eStackMode; BarDirection m_eBarDirection; sal_Int32 m_nDim; }; } // namespace chart // CHART_BARCHARTTYPETEMPLATE_HXX #endif <commit_msg>INTEGRATION: CWS chart17 (1.6.66); FILE MERGED 2007/11/05 14:04:10 iha 1.6.66.1: #i63857#, #i4039# more flexible placement of data point labels, best fit for pie labels<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: BarChartTypeTemplate.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: ihi $ $Date: 2007-11-23 12:00:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART_BARCHARTTYPETEMPLATE_HXX #define CHART_BARCHARTTYPETEMPLATE_HXX #include "OPropertySet.hxx" #include "MutexContainer.hxx" #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #include "ChartTypeTemplate.hxx" #include "StackMode.hxx" namespace chart { class BarChartTypeTemplate : public MutexContainer, public ChartTypeTemplate, public ::property::OPropertySet { public: enum BarDirection { HORIZONTAL, VERTICAL }; explicit BarChartTypeTemplate( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext, const ::rtl::OUString & rServiceName, StackMode eStackMode, BarDirection eDirection, sal_Int32 nDim = 2 ); virtual ~BarChartTypeTemplate(); /// XServiceInfo declarations APPHELPER_XSERVICEINFO_DECL() /// merge XInterface implementations DECLARE_XINTERFACE() /// merge XTypeProvider implementations DECLARE_XTYPEPROVIDER() protected: // ____ OPropertySet ____ virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const throw(::com::sun::star::beans::UnknownPropertyException); virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); // ____ XPropertySet ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); // ____ XChartTypeTemplate ____ virtual sal_Bool SAL_CALL matchesTemplate( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram, sal_Bool bAdaptProperties ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > SAL_CALL getChartTypeForNewSeries( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > >& aFormerlyUsedChartTypes ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL applyStyle( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries, ::sal_Int32 nChartTypeGroupIndex, ::sal_Int32 nSeriesIndex, ::sal_Int32 nSeriesCount ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL resetStyles( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram ) throw (::com::sun::star::uno::RuntimeException); // ____ ChartTypeTemplate ____ virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > getChartTypeForIndex( sal_Int32 nChartTypeIndex ); virtual sal_Int32 getDimension() const; virtual StackMode getStackMode( sal_Int32 nChartTypeIndex ) const; virtual bool isSwapXAndY() const; virtual void createCoordinateSystems( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystemContainer > & xCooSysCnt ); private: StackMode m_eStackMode; BarDirection m_eBarDirection; sal_Int32 m_nDim; }; } // namespace chart // CHART_BARCHARTTYPETEMPLATE_HXX #endif <|endoftext|>
<commit_before>/** @file Clculo del coste de los caminos mnimos. Algoritmo de Floyd. */ #include <iostream> using namespace std; #include <ctime> #include <cstdlib> #include <climits> #include <cassert> #include <cmath> static int const MAX_LONG = 10; /**********************************************************************/ /** @brief Reserva espacio en memoria dinmica para una matriz cuadrada. @param dim: dimensin de la matriz. dim > 0. @returns puntero a la zona de memoria reservada. */ int ** ReservaMatriz(int dim); /**********************************************************************/ /** @brief Libera el espacio asignado a una matriz cuadrada. @param M: puntero a la zona de memoria reservada. Es MODIFICADO. @param dim: dimensin de la matriz. dim > 0. Liberar la zona memoria asignada a M y lo pone a NULL. */ void LiberaMatriz(int ** & M, int dim); /**********************************************************************/ /** @brief Rellena una matriz cuadrada con valores aleaotorias. @param M: puntero a la zona de memoria reservada. Es MODIFICADO. @param dim: dimensin de la matriz. dim > 0. Asigna un valor aleatorio entero de [0, MAX_LONG - 1] a cada elemento de la matriz M, salvo los de la diagonal principal que quedan a 0.. */ void RellenaMatriz(int **M, int dim); /**********************************************************************/ /** @brief Clculo de caminos mnimos. @param M: Matriz de longitudes de los caminos. Es MODIFICADO. @param dim: dimensin de la matriz. dim > 0. Calcula la longitud del camino mnimo entre cada par de nodos (i,j), que se almacena en M[i][j]. */ void Floyd(int **M, int dim); /**********************************************************************/ /** Implementacin de las funciones **/ int ** ReservaMatriz(int dim) { int **M; if (dim <= 0) { cerr<< "\n ERROR: Dimension de la matriz debe ser mayor que 0" << endl; exit(1); } M = new int * [dim]; if (M == NULL) { cerr << "\n ERROR: No puedo reservar memoria para un matriz de " << dim << " x " << dim << "elementos" << endl; exit(1); } for (int i = 0; i < dim; i++) { M[i]= new int [dim]; if (M[i] == NULL) { cerr << "ERROR: No puedo reservar memoria para un matriz de " << dim << " x " << dim << endl; for (int j = 0; j < i; j++) delete [] M[i]; delete [] M; exit(1); } } return M; } /**********************************************************************/ void LiberaMatriz(int ** & M, int dim) { for (int i = 0; i < dim; i++) delete [] M[i]; delete [] M; M = NULL; } /**********************************************************************/ void RellenaMatriz(int **M, int dim) { for (int i = 0; i < dim; i++) for (int j = 0; j < dim; j++) if (i != j) M[i][j]= (rand() % MAX_LONG); } /**********************************************************************/ void Floyd(int **M, int dim) { for (int k = 0; k < dim; k++) for (int i = 0; i < dim;i++) for (int j = 0; j < dim;j++) { int sum = M[i][k] + M[k][j]; M[i][j] = (M[i][j] > sum) ? sum : M[i][j]; } } /**********************************************************************/ int main (int argc, char **argv) { clock_t tantes; // Valor del reloj antes de la ejecucin clock_t tdespues; // Valor del reloj despus de la ejecucin int dim; // Dimensin de la matriz //Lectura de los parametros de entrada if (argc != 2) { cout << "Parmetros de entrada: " << endl << "1.- Nmero de nodos" << endl << endl; return 1; } dim = atoi(argv[1]); int ** M = ReservaMatriz(dim); RellenaMatriz(M,dim); // Empieza el algoritmo de floyd tantes = clock(); Floyd(M,dim); tdespues = clock(); cout << dim << " " << ((double)(tdespues-tantes))/CLOCKS_PER_SEC << endl; LiberaMatriz(M,dim); return 0; } <commit_msg>Delete floyd.cpp<commit_after><|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * 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/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct SynthXilinxPass : public ScriptPass { SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_xilinx [options]\n"); log("\n"); log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n"); log("partly selected designs. At the moment this command creates netlists that are\n"); log("compatible with 7-Series Xilinx devices.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -arch {xcup|xcu|xc7|xc6s}\n"); log(" run synthesis for the specified Xilinx architecture\n"); log(" default: xc7\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log(" -nocarry\n"); log(" disable inference of carry chains\n"); log("\n"); log(" -nobram\n"); log(" disable inference of block rams\n"); log("\n"); log(" -nodram\n"); log(" disable inference of distributed rams\n"); log("\n"); log(" -nosrl\n"); log(" disable inference of shift registers\n"); log("\n"); log(" -nomux\n"); log(" disable inference of wide multiplexers\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -flatten\n"); log(" flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -abc9\n"); log(" use abc9 instead of abc\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); help_script(); log("\n"); } std::string top_opt, edif_file, blif_file, abc, arch; bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl, nomux; void clear_flags() YS_OVERRIDE { top_opt = "-auto-top"; edif_file.clear(); blif_file.clear(); abc = "abc"; flatten = false; retime = false; vpr = false; nocarry = false; nobram = false; nodram = false; nosrl = false; nomux = false; arch = "xc7"; } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { std::string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if (args[argidx] == "-arch" && argidx+1 < args.size()) { arch = args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-nodram") { nodram = true; continue; } if (args[argidx] == "-nosrl") { nosrl = true; continue; } if (args[argidx] == "-nomux") { nomux = true; continue; } if (args[argidx] == "-abc9") { abc = "abc9"; continue; } break; } extra_args(args, argidx, design); if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s") log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str()); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); log_header(design, "Executing SYNTH_XILINX pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } void script() YS_OVERRIDE { if (check_label("begin")) { if (vpr) run("read_verilog -lib -D_ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v"); else run("read_verilog -lib -D_ABC +/xilinx/cells_sim.v"); run("read_verilog -lib +/xilinx/cells_xtra.v"); if (!nobram || help_mode) run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')"); run(stringf("hierarchy -check %s", top_opt.c_str())); } if (check_label("flatten", "(with '-flatten' only)")) { if (flatten || help_mode) { run("proc"); run("flatten"); } } if (check_label("coarse")) { run("synth -run coarse"); // shregmap -tech xilinx can cope with $shiftx and $mux // cells for identifying variable-length shift registers, // so attempt to convert $pmux-es to the former // Also: wide multiplexer inference benefits from this too if (!(nosrl && nomux) || help_mode) run("pmux2shiftx", "(skip if '-nosrl' and '-nomux')"); // Run a number of peephole optimisations, including one // that optimises $mul cells driving $shiftx's B input // and that aids wide mux analysis run("peepopt"); } if (check_label("bram", "(skip if '-nobram')")) { if (!nobram || help_mode) { run("memory_bram -rules +/xilinx/brams.txt"); run("techmap -map +/xilinx/brams_map.v"); } } if (check_label("dram", "(skip if '-nodram')")) { if (!nodram || help_mode) { run("memory_bram -rules +/xilinx/drams.txt"); run("techmap -map +/xilinx/drams_map.v"); } } if (check_label("fine")) { run("opt -fast -full"); run("memory_map"); run("dffsr2dff"); run("dff2dffe"); run("opt -full"); if (!nosrl || help_mode) { // shregmap operates on bit-level flops, not word-level, // so break those down here run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')"); // shregmap with '-tech xilinx' infers variable length shift regs run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')"); } if (vpr && !nocarry && !help_mode) run("techmap -map +/techmap.v -map +/xilinx/arith_map.v -D _EXPLICIT_CARRY"); else if (abc == "abc9" && !nocarry && !help_mode) run("techmap -map +/techmap.v -map +/xilinx/arith_map.v -D _CLB_CARRY"); else if (!nocarry || help_mode) run("techmap -map +/techmap.v -map +/xilinx/arith_map.v", "(skip if '-nocarry')"); else run("techmap -map +/techmap.v"); run("opt -fast"); } if (check_label("map_cells")) { run("techmap -map +/techmap.v -map +/xilinx/cells_map.v -map +/xilinx/ff_map.v "); run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT " "-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT"); run("clean"); } if (check_label("map_luts")) { if (abc == "abc9") run(abc + " -lut +/xilinx/abc.lut -box +/xilinx/abc.box" + string(retime ? " -dff" : "")); else if (help_mode) run(abc + " -luts 2:2,3,6:5,10,20 [-dff]"); else run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : "")); run("clean"); // This shregmap call infers fixed length shift registers after abc // has performed any necessary retiming if (!nosrl || help_mode) run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')"); run("techmap -map +/xilinx/lut_map.v -map +/xilinx/cells_map.v"); run("clean"); } if (check_label("check")) { run("hierarchy -check"); run("stat -tech xilinx"); run("check -noinit"); } if (check_label("edif")) { if (!edif_file.empty() || help_mode) run(stringf("write_edif -pvector bra %s", edif_file.c_str())); } if (check_label("blif")) { if (!blif_file.empty() || help_mode) run(stringf("write_blif %s", edif_file.c_str())); } } } SynthXilinxPass; PRIVATE_NAMESPACE_END <commit_msg>Move ff_map back after ABC for shregmap<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * 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/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct SynthXilinxPass : public ScriptPass { SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_xilinx [options]\n"); log("\n"); log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n"); log("partly selected designs. At the moment this command creates netlists that are\n"); log("compatible with 7-Series Xilinx devices.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -arch {xcup|xcu|xc7|xc6s}\n"); log(" run synthesis for the specified Xilinx architecture\n"); log(" default: xc7\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified edif file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -blif <file>\n"); log(" write the design to the specified BLIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -vpr\n"); log(" generate an output netlist (and BLIF file) suitable for VPR\n"); log(" (this feature is experimental and incomplete)\n"); log("\n"); log(" -nocarry\n"); log(" disable inference of carry chains\n"); log("\n"); log(" -nobram\n"); log(" disable inference of block rams\n"); log("\n"); log(" -nodram\n"); log(" disable inference of distributed rams\n"); log("\n"); log(" -nosrl\n"); log(" disable inference of shift registers\n"); log("\n"); log(" -nomux\n"); log(" disable inference of wide multiplexers\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -flatten\n"); log(" flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with -dff option\n"); log("\n"); log(" -abc9\n"); log(" use abc9 instead of abc\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); help_script(); log("\n"); } std::string top_opt, edif_file, blif_file, abc, arch; bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl, nomux; void clear_flags() YS_OVERRIDE { top_opt = "-auto-top"; edif_file.clear(); blif_file.clear(); abc = "abc"; flatten = false; retime = false; vpr = false; nocarry = false; nobram = false; nodram = false; nosrl = false; nomux = false; arch = "xc7"; } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { std::string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if (args[argidx] == "-arch" && argidx+1 < args.size()) { arch = args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-blif" && argidx+1 < args.size()) { blif_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-flatten") { flatten = true; continue; } if (args[argidx] == "-retime") { retime = true; continue; } if (args[argidx] == "-vpr") { vpr = true; continue; } if (args[argidx] == "-nocarry") { nocarry = true; continue; } if (args[argidx] == "-nobram") { nobram = true; continue; } if (args[argidx] == "-nodram") { nodram = true; continue; } if (args[argidx] == "-nosrl") { nosrl = true; continue; } if (args[argidx] == "-nomux") { nomux = true; continue; } if (args[argidx] == "-abc9") { abc = "abc9"; continue; } break; } extra_args(args, argidx, design); if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s") log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str()); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); log_header(design, "Executing SYNTH_XILINX pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } void script() YS_OVERRIDE { if (check_label("begin")) { if (vpr) run("read_verilog -lib -D_ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v"); else run("read_verilog -lib -D_ABC +/xilinx/cells_sim.v"); run("read_verilog -lib +/xilinx/cells_xtra.v"); if (!nobram || help_mode) run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')"); run(stringf("hierarchy -check %s", top_opt.c_str())); } if (check_label("flatten", "(with '-flatten' only)")) { if (flatten || help_mode) { run("proc"); run("flatten"); } } if (check_label("coarse")) { run("synth -run coarse"); // shregmap -tech xilinx can cope with $shiftx and $mux // cells for identifying variable-length shift registers, // so attempt to convert $pmux-es to the former // Also: wide multiplexer inference benefits from this too if (!(nosrl && nomux) || help_mode) run("pmux2shiftx", "(skip if '-nosrl' and '-nomux')"); // Run a number of peephole optimisations, including one // that optimises $mul cells driving $shiftx's B input // and that aids wide mux analysis run("peepopt"); } if (check_label("bram", "(skip if '-nobram')")) { if (!nobram || help_mode) { run("memory_bram -rules +/xilinx/brams.txt"); run("techmap -map +/xilinx/brams_map.v"); } } if (check_label("dram", "(skip if '-nodram')")) { if (!nodram || help_mode) { run("memory_bram -rules +/xilinx/drams.txt"); run("techmap -map +/xilinx/drams_map.v"); } } if (check_label("fine")) { run("opt -fast -full"); run("memory_map"); run("dffsr2dff"); run("dff2dffe"); run("opt -full"); if (!nosrl || help_mode) { // shregmap operates on bit-level flops, not word-level, // so break those down here run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')"); // shregmap with '-tech xilinx' infers variable length shift regs run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')"); } if (vpr && !nocarry && !help_mode) run("techmap -map +/techmap.v -map +/xilinx/arith_map.v -D _EXPLICIT_CARRY"); else if (abc == "abc9" && !nocarry && !help_mode) run("techmap -map +/techmap.v -map +/xilinx/arith_map.v -D _CLB_CARRY"); else if (!nocarry || help_mode) run("techmap -map +/techmap.v -map +/xilinx/arith_map.v", "(skip if '-nocarry')"); else run("techmap -map +/techmap.v"); run("opt -fast"); } if (check_label("map_cells")) { run("techmap -map +/techmap.v -map +/xilinx/cells_map.v"); run("clean"); } if (check_label("map_luts")) { if (abc == "abc9") run(abc + " -lut +/xilinx/abc.lut -box +/xilinx/abc.box" + string(retime ? " -dff" : "")); else if (help_mode) run(abc + " -luts 2:2,3,6:5,10,20 [-dff]"); else run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : "")); run("clean"); // This shregmap call infers fixed length shift registers after abc // has performed any necessary retiming if (!nosrl || help_mode) run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')"); run("techmap -map +/xilinx/lut_map.v -map +/xilinx/cells_map.v -map +/xilinx/ff_map.v"); run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT " "-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT"); run("clean"); } if (check_label("check")) { run("hierarchy -check"); run("stat -tech xilinx"); run("check -noinit"); } if (check_label("edif")) { if (!edif_file.empty() || help_mode) run(stringf("write_edif -pvector bra %s", edif_file.c_str())); } if (check_label("blif")) { if (!blif_file.empty() || help_mode) run(stringf("write_blif %s", edif_file.c_str())); } } } SynthXilinxPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // Tracked vehicle model built from subsystems. // Location of subsystems hard-coded for M113 vehicle // TODO: specify this w/ JSON input data file // // ============================================================================= #include <cstdio> #include "physics/ChGlobal.h" #include "TrackVehicle.h" #include "subsys/trackSystem/TrackSystem.h" #include "subsys/driveline/TrackDriveline.h" #include "utils/ChUtilsInputOutput.h" #include "utils/ChUtilsData.h" namespace chrono { // ----------------------------------------------------------------------------- // Static variables const ChVector<> TrackVehicle::m_trackPos_Right(0.23644, -0.4780, 0.83475); // relative to chassis COG const ChVector<> TrackVehicle::m_trackPos_Left(0.23644, -0.4780, -0.83475); // relative to chassis COG const double TrackVehicle::m_mass = 5489.2; // chassis sprung mass const ChVector<> TrackVehicle::m_COM = ChVector<>(0., 0.0, 0.); // COM location, relative to body Csys REF frame const ChVector<> TrackVehicle::m_inertia(1786.9, 10449.7, 10721.2); // chassis inertia (roll,yaw,pitch) const ChCoordsys<> TrackVehicle::m_driverCsys(ChVector<>(0.0, 0.5, 1.2), ChQuaternion<>(1, 0, 0, 0)); /// constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff TrackVehicle::TrackVehicle(const std::string& name, VisualizationType chassisVis, CollisionType chassisCollide) :ChTrackVehicle(), m_num_tracks(2) { // --------------------------------------------------------------------------- // Set the base class variables m_vis = chassisVis; m_collide = chassisCollide; m_meshName = "M113_chassis"; m_meshFile = utils::GetModelDataFile("M113/Chassis_XforwardYup.obj"); m_chassisBoxSize = ChVector<>(2.0, 0.6, 0.75); // create the chassis body m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef); m_chassis->SetIdentifier(0); m_chassis->SetNameString(name); m_chassis->SetFrame_COG_to_REF(ChFrame<>(m_COM, ChQuaternion<>(1, 0, 0, 0))); // basic body info m_chassis->SetMass(m_mass); m_chassis->SetInertiaXX(m_inertia); // add visualization assets to the chassis AddVisualization(); // m_chassis->SetBodyFixed(true); // add the chassis body to the system m_system->Add(m_chassis); // resize all vectors for the number of track systems m_TrackSystems.resize(m_num_tracks); m_TrackSystem_locs.resize(m_num_tracks); // Right and Left track System relative locations, respectively m_TrackSystem_locs[0] = m_trackPos_Right; m_TrackSystem_locs[1] = m_trackPos_Left; // two drive Gears, like a 2WD driven vehicle. m_num_engines = 1; m_drivelines.resize(m_num_engines); m_ptrains.resize(m_num_engines); // create track systems for (int i = 0; i < m_num_tracks; i++) { m_TrackSystems[i] = ChSharedPtr<TrackSystem>(new TrackSystem("track chain "+std::to_string(i), i) ); } // create the powertrain and drivelines for (int j = 0; j < m_num_engines; j++) { m_drivelines[j] = ChSharedPtr<TrackDriveline>(new TrackDriveline("driveline "+std::to_string(j)) ); m_ptrains[j] = ChSharedPtr<TrackPowertrain>(new TrackPowertrain("powertrain "+std::to_string(j)) ); } // TODO: add brakes. Perhaps they are a part of the suspension subsystem? } TrackVehicle::~TrackVehicle() { if(m_ownsSystem) delete m_system; } // Set any collision geometry on the hull, then Initialize() all subsystems void TrackVehicle::Initialize(const ChCoordsys<>& chassis_Csys) { // move the chassis REF frame to the specified initial position/orientation m_chassis->SetFrame_REF_to_abs(ChFrame<>(chassis_Csys)); // add collision geometry to the chassis AddCollisionGeometry(); // initialize the subsystems with the initial c-sys and specified offsets for (int i = 0; i < m_num_tracks; i++) { m_TrackSystems[i]->Initialize(m_chassis, m_TrackSystem_locs[i]); } // initialize the powertrain, drivelines for (int j = 0; j < m_num_engines; j++) { size_t driveGear_R_idx = 2*j; size_t driveGear_L_idx = 2*j + 1; m_drivelines[j]->Initialize(m_chassis, m_TrackSystems[driveGear_R_idx]->GetDriveGear(), m_TrackSystems[driveGear_L_idx]->GetDriveGear()); m_ptrains[j]->Initialize(m_chassis, m_drivelines[j]->GetDriveshaft()); } } void TrackVehicle::Update(double time, const std::vector<double>& throttle, const std::vector<double>& braking) { assert( throttle.size() >= m_num_tracks); assert( braking.size() >= m_num_tracks ); // update left and right powertrains, with the new left and right throttle/shaftspeed for(int i = 0; i < m_num_engines; i++) { m_ptrains[i]->Update(time, throttle[i], m_drivelines[0]->GetDriveshaftSpeed() ); } } void TrackVehicle::Advance(double step) { double t = 0; double settlePhaseA = 0.5; double settlePhaseB = 0.8; while (t < step) { double h = std::min<>(m_stepsize, step - t); if( m_system->GetChTime() < settlePhaseA ) { h = 4e-4; } else if ( m_system->GetChTime() < settlePhaseB ) { h = 6e-4; } m_system->DoStepDynamics(h); t += h; } } double TrackVehicle::GetIdlerForce(size_t side) const { assert(side < m_num_tracks); ChVector<> out_force = m_TrackSystems[side]->Get_idler_spring_react(); return out_force.Length(); } double TrackVehicle::GetDriveshaftSpeed(size_t idx) const { assert(idx < m_drivelines.size() ); return m_drivelines[idx]->GetDriveshaftSpeed(); } const ChSharedPtr<TrackPowertrain> TrackVehicle::GetPowertrain(size_t idx) const { assert( idx < m_num_engines ); return m_ptrains[idx]; } } // end namespace chrono <commit_msg>use new base constructor<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // Tracked vehicle model built from subsystems. // Location of subsystems hard-coded for M113 vehicle // TODO: specify this w/ JSON input data file // // ============================================================================= #include <cstdio> #include "physics/ChGlobal.h" #include "TrackVehicle.h" #include "subsys/trackSystem/TrackSystem.h" #include "subsys/driveline/TrackDriveline.h" #include "utils/ChUtilsInputOutput.h" #include "utils/ChUtilsData.h" namespace chrono { // ----------------------------------------------------------------------------- // Static variables const ChVector<> TrackVehicle::m_trackPos_Right(0.23644, -0.4780, 0.83475); // relative to chassis COG const ChVector<> TrackVehicle::m_trackPos_Left(0.23644, -0.4780, -0.83475); // relative to chassis COG const double TrackVehicle::m_mass = 5489.2; // chassis sprung mass const ChVector<> TrackVehicle::m_COM = ChVector<>(0., 0.0, 0.); // COM location, relative to body Csys REF frame const ChVector<> TrackVehicle::m_inertia(1786.9, 10449.7, 10721.2); // chassis inertia (roll,yaw,pitch) const ChCoordsys<> TrackVehicle::m_driverCsys(ChVector<>(0.0, 0.5, 1.2), ChQuaternion<>(1, 0, 0, 0)); /// constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff TrackVehicle::TrackVehicle(const std::string& name, VisualizationType chassisVis, CollisionType chassisCollide) :ChTrackVehicle(1e-3, 1, chassisVis, chassisCollide), m_num_tracks(2) { // --------------------------------------------------------------------------- // Set the base class variables m_meshName = "M113_chassis"; m_meshFile = utils::GetModelDataFile("M113/Chassis_XforwardYup.obj"); m_chassisBoxSize = ChVector<>(2.0, 0.6, 0.75); // create the chassis body m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef); m_chassis->SetIdentifier(0); m_chassis->SetNameString(name); m_chassis->SetFrame_COG_to_REF(ChFrame<>(m_COM, ChQuaternion<>(1, 0, 0, 0))); // basic body info m_chassis->SetMass(m_mass); m_chassis->SetInertiaXX(m_inertia); // add visualization assets to the chassis AddVisualization(); // m_chassis->SetBodyFixed(true); // add the chassis body to the system m_system->Add(m_chassis); // resize all vectors for the number of track systems m_TrackSystems.resize(m_num_tracks); m_TrackSystem_locs.resize(m_num_tracks); // Right and Left track System relative locations, respectively m_TrackSystem_locs[0] = m_trackPos_Right; m_TrackSystem_locs[1] = m_trackPos_Left; // two drive Gears, like a 2WD driven vehicle. m_num_engines = 1; m_drivelines.resize(m_num_engines); m_ptrains.resize(m_num_engines); // create track systems for (int i = 0; i < m_num_tracks; i++) { m_TrackSystems[i] = ChSharedPtr<TrackSystem>(new TrackSystem("track chain "+std::to_string(i), i) ); } // create the powertrain and drivelines for (int j = 0; j < m_num_engines; j++) { m_drivelines[j] = ChSharedPtr<TrackDriveline>(new TrackDriveline("driveline "+std::to_string(j)) ); m_ptrains[j] = ChSharedPtr<TrackPowertrain>(new TrackPowertrain("powertrain "+std::to_string(j)) ); } // TODO: add brakes. Perhaps they are a part of the suspension subsystem? } TrackVehicle::~TrackVehicle() { if(m_ownsSystem) delete m_system; } // Set any collision geometry on the hull, then Initialize() all subsystems void TrackVehicle::Initialize(const ChCoordsys<>& chassis_Csys) { // move the chassis REF frame to the specified initial position/orientation m_chassis->SetFrame_REF_to_abs(ChFrame<>(chassis_Csys)); // add collision geometry to the chassis AddCollisionGeometry(); // initialize the subsystems with the initial c-sys and specified offsets for (int i = 0; i < m_num_tracks; i++) { m_TrackSystems[i]->Initialize(m_chassis, m_TrackSystem_locs[i]); } // initialize the powertrain, drivelines for (int j = 0; j < m_num_engines; j++) { size_t driveGear_R_idx = 2*j; size_t driveGear_L_idx = 2*j + 1; m_drivelines[j]->Initialize(m_chassis, m_TrackSystems[driveGear_R_idx]->GetDriveGear(), m_TrackSystems[driveGear_L_idx]->GetDriveGear()); m_ptrains[j]->Initialize(m_chassis, m_drivelines[j]->GetDriveshaft()); } } void TrackVehicle::Update(double time, const std::vector<double>& throttle, const std::vector<double>& braking) { assert( throttle.size() >= m_num_tracks); assert( braking.size() >= m_num_tracks ); // update left and right powertrains, with the new left and right throttle/shaftspeed for(int i = 0; i < m_num_engines; i++) { m_ptrains[i]->Update(time, throttle[i], m_drivelines[0]->GetDriveshaftSpeed() ); } } void TrackVehicle::Advance(double step) { double t = 0; double settlePhaseA = 0.5; double settlePhaseB = 0.8; while (t < step) { double h = std::min<>(m_stepsize, step - t); if( m_system->GetChTime() < settlePhaseA ) { h = 4e-4; } else if ( m_system->GetChTime() < settlePhaseB ) { h = 6e-4; } m_system->DoStepDynamics(h); t += h; } } double TrackVehicle::GetIdlerForce(size_t side) const { assert(side < m_num_tracks); ChVector<> out_force = m_TrackSystems[side]->Get_idler_spring_react(); return out_force.Length(); } double TrackVehicle::GetDriveshaftSpeed(size_t idx) const { assert(idx < m_drivelines.size() ); return m_drivelines[idx]->GetDriveshaftSpeed(); } const ChSharedPtr<TrackPowertrain> TrackVehicle::GetPowertrain(size_t idx) const { assert( idx < m_num_engines ); return m_ptrains[idx]; } } // end namespace chrono <|endoftext|>
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2002 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qwidget.h> #include <kaboutdata.h> #include <kapplication.h> #include <kdebug.h> #include <klocale.h> #include <kcmdlineargs.h> #include "alarmdialog.h" int main(int argc,char **argv) { KAboutData aboutData("testkabc",I18N_NOOP("TestKabc"),"0.1"); KCmdLineArgs::init(argc,argv,&aboutData); KApplication app; Event *e = new Event; e->setSummary( "This is a summary." ); e->setDtStart( QDateTime::currentDateTime() ); e->setDtEnd( QDateTime::currentDateTime().addDays( 1 ) ); Alarm *a = e->newAlarm(); // a->setProcedureAlarm( "/usr/X11R6/bin/xeyes" ); a->setAudioAlarm( "/opt/kde/share/apps/korganizer/sounds/spinout.wav" ); AlarmDialog dlg; app.setMainWidget( &dlg ); dlg.setIncidence( e ); dlg.show(); dlg.eventNotification(); app.exec(); } <commit_msg>fix make check<commit_after>/* This file is part of KOrganizer. Copyright (c) 2002 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qwidget.h> #include <kaboutdata.h> #include <kapplication.h> #include <kdebug.h> #include <klocale.h> #include <kcmdlineargs.h> #include "alarmdialog.h" int main(int argc,char **argv) { KAboutData aboutData("testkabc",I18N_NOOP("TestKabc"),"0.1"); KCmdLineArgs::init(argc,argv,&aboutData); KApplication app; Event *e = new Event; e->setSummary( "This is a summary." ); e->setDtStart( QDateTime::currentDateTime() ); e->setDtEnd( QDateTime::currentDateTime().addDays( 1 ) ); Alarm *a = e->newAlarm(); // a->setProcedureAlarm( "/usr/X11R6/bin/xeyes" ); a->setAudioAlarm( "/opt/kde/share/apps/korganizer/sounds/spinout.wav" ); AlarmDialog dlg; app.setMainWidget( &dlg ); dlg.addIncidence( e, QDateTime::currentDateTime() ); dlg.show(); dlg.eventNotification(); app.exec(); } <|endoftext|>
<commit_before>/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 — Vladimír Vondruš <[email protected]> 2013 — Jan Dupal <[email protected]> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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 <btBulletDynamicsCommon.h> #include <Corrade/Containers/Optional.h> #include <Magnum/Timeline.h> #include <Magnum/BulletIntegration/Integration.h> #include <Magnum/BulletIntegration/MotionState.h> #include <Magnum/BulletIntegration/DebugDraw.h> #include <Magnum/GL/DefaultFramebuffer.h> #include <Magnum/GL/Mesh.h> #include <Magnum/GL/Renderer.h> #include <Magnum/Math/Constants.h> #include <Magnum/MeshTools/Compile.h> #include <Magnum/MeshTools/Transform.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Primitives/UVSphere.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/MatrixTransformation3D.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Trade/MeshData3D.h> namespace Magnum { namespace Examples { using namespace Math::Literals; typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D; typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D; class BulletExample: public Platform::Application { public: explicit BulletExample(const Arguments& arguments); private: void drawEvent() override; void keyPressEvent(KeyEvent& event) override; void mousePressEvent(MouseEvent& event) override; btRigidBody* createRigidBody(Object3D& object, Float mass, btCollisionShape* bShape); GL::Mesh _box{NoCreate}, _sphere{NoCreate}; Shaders::Phong _shader{NoCreate}; BulletIntegration::DebugDraw _debugDraw{NoCreate}; Scene3D _scene; SceneGraph::Camera3D* _camera; SceneGraph::DrawableGroup3D _drawables; Timeline _timeline; Object3D *_cameraRig, *_cameraObject; btDiscreteDynamicsWorld* _bWorld; btCollisionShape *_bBoxShape, *_bSphereShape; btRigidBody* _bGround; bool _drawCubes{true}, _drawDebug{true}, _shootBox{true}; }; class ColoredDrawable: public SceneGraph::Drawable3D { public: explicit ColoredDrawable(Object3D& object, Shaders::Phong& shader, GL::Mesh& mesh, const Color4& color, const Matrix4& primitiveTransformation, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh), _color{color}, _primitiveTransformation{primitiveTransformation} {} private: void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) override { _shader.setDiffuseColor(_color) .setTransformationMatrix(transformation*_primitiveTransformation) .setProjectionMatrix(camera.projectionMatrix()) .setNormalMatrix(transformation.rotationScaling()); _mesh.draw(_shader); } Shaders::Phong& _shader; GL::Mesh& _mesh; Color4 _color; Matrix4 _primitiveTransformation; }; BulletExample::BulletExample(const Arguments& arguments): Platform::Application(arguments, NoCreate) { /* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x MSAA if we have enough DPI. */ { const Vector2 dpiScaling = this->dpiScaling({}); Configuration conf; conf.setTitle("Magnum Bullet Integration Example") .setSize(conf.size(), dpiScaling); GLConfiguration glConf; glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2); if(!tryCreate(conf, glConf)) create(conf, glConf.setSampleCount(0)); } /* Camera setup */ (*(_cameraRig = new Object3D{&_scene})) .translate(Vector3::yAxis(3.0f)) .rotateY(40.0_degf); (*(_cameraObject = new Object3D{_cameraRig})) .translate(Vector3::zAxis(20.0f)) .rotateX(-25.0_degf); (_camera = new SceneGraph::Camera3D(*_cameraObject)) ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 1.0f, 0.001f, 100.0f)) .setViewport(GL::defaultFramebuffer.viewport().size()); /* Drawing setup */ _box = MeshTools::compile(Primitives::cubeSolid()); _sphere = MeshTools::compile(Primitives::uvSphereSolid(16, 32)); _shader = Shaders::Phong{}; _shader.setAmbientColor(0x111111_rgbf) .setSpecularColor(0x330000_rgbf) .setLightPosition({10.0f, 15.0f, 5.0f}); _debugDraw = BulletIntegration::DebugDraw{}; _debugDraw.setMode(BulletIntegration::DebugDraw::Mode::DrawWireframe); /* Setup the renderer so we can draw the debug lines on top */ GL::Renderer::enable(GL::Renderer::Feature::DepthTest); GL::Renderer::enable(GL::Renderer::Feature::FaceCulling); GL::Renderer::enable(GL::Renderer::Feature::PolygonOffsetFill); GL::Renderer::setPolygonOffset(2.0f, 0.5f); /* Bullet setup */ auto* broadphase = new btDbvtBroadphase; auto* collisionConfiguration = new btDefaultCollisionConfiguration; auto* dispatcher = new btCollisionDispatcher{collisionConfiguration}; auto* solver = new btSequentialImpulseConstraintSolver; _bWorld = new btDiscreteDynamicsWorld{dispatcher, broadphase, solver, collisionConfiguration}; _bWorld->setGravity({0.0f, -10.0f, 0.0f}); _bWorld->setDebugDrawer(&_debugDraw); _bBoxShape = new btBoxShape{{0.5f, 0.5f, 0.5f}}; _bSphereShape = new btSphereShape{0.25f}; /* Create the ground */ auto* ground = new Object3D{&_scene}; _bGround = createRigidBody(*ground, 0.0f, new btBoxShape{{4.0f, 0.5f, 4.0f}}); new ColoredDrawable{*ground, _shader, _box, 0xffffff_rgbf, Matrix4::scaling({4.0f, 0.5f, 4.0f}), _drawables}; /* Create boxes with random colors */ Deg hue = 42.0_degf; for(Int i = 0; i != 5; ++i) { for(Int j = 0; j != 5; ++j) { for(Int k = 0; k != 5; ++k) { auto* o = new Object3D{&_scene}; o->translate({i - 2.0f, j + 4.0f, k - 2.0f}); new ColoredDrawable{*o, _shader, _box, Color3::fromHsv(hue += 137.5_degf, 0.75f, 0.9f), Matrix4::scaling(Vector3{0.5f}), _drawables}; createRigidBody(*o, 1.0f, _bBoxShape); } } } /* Loop at 60 Hz max */ setSwapInterval(1); setMinimalLoopPeriod(16); _timeline.start(); } btRigidBody* BulletExample::createRigidBody(Object3D& object, Float mass, btCollisionShape* bShape) { /* Calculate inertia so the object reacts as it should with rotation and everything */ btVector3 bInertia(0.0f, 0.0f, 0.0f); if(mass != 0.0f) bShape->calculateLocalInertia(mass, bInertia); /* Bullet rigid body setup */ auto* motionState = new BulletIntegration::MotionState{object}; auto* bRigidBody = new btRigidBody{btRigidBody::btRigidBodyConstructionInfo{ mass, &motionState->btMotionState(), bShape, bInertia}}; bRigidBody->forceActivationState(DISABLE_DEACTIVATION); _bWorld->addRigidBody(bRigidBody); return bRigidBody; } void BulletExample::drawEvent() { GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth); /* Step bullet simulation */ _bWorld->stepSimulation(_timeline.previousFrameDuration(), 5); /* Draw the cubes */ if(_drawCubes) _camera->draw(_drawables); /* Debug draw. If drawing on top of cubes, avoid flickering by setting depth function to <= instead of just <. */ if(_drawDebug) { if(_drawCubes) GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::LessOrEqual); _debugDraw.setTransformationProjectionMatrix( _camera->projectionMatrix()*_camera->cameraMatrix()); _bWorld->debugDrawWorld(); if(_drawCubes) GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::Less); } swapBuffers(); _timeline.nextFrame(); redraw(); } void BulletExample::keyPressEvent(KeyEvent& event) { /* Movement */ if(event.key() == KeyEvent::Key::Down) { _cameraObject->rotateX(5.0_degf); } else if(event.key() == KeyEvent::Key::Up) { _cameraObject->rotateX(-5.0_degf); } else if(event.key() == KeyEvent::Key::Left) { _cameraRig->rotateY(-5.0_degf); } else if(event.key() == KeyEvent::Key::Right) { _cameraRig->rotateY(5.0_degf); /* Toggling draw modes */ } else if(event.key() == KeyEvent::Key::D) { if(_drawCubes && _drawDebug) { _drawDebug = false; } else if(_drawCubes && !_drawDebug) { _drawCubes = false; _drawDebug = true; } else if(!_drawCubes && _drawDebug) { _drawCubes = true; _drawDebug = true; } /* What to shoot */ } else if(event.key() == KeyEvent::Key::S) { _shootBox ^= true; } else return; event.setAccepted(); } void BulletExample::mousePressEvent(MouseEvent& event) { /* Shoot an object on click */ if(event.button() == MouseEvent::Button::Left) { const Vector2 clickPoint = Vector2::yScale(-1.0f)*(Vector2{event.position()}/Vector2{GL::defaultFramebuffer.viewport().size()} - Vector2{0.5f})* _camera->projectionSize(); const Vector3 direction = (_cameraObject->absoluteTransformation().rotationScaling()*Vector3{clickPoint, -1.0f}).normalized(); Object3D* o = new Object3D(&_scene); o->translate(_cameraObject->absoluteTransformation().translation()); /* Create either a box or a sphere */ new ColoredDrawable{*o, _shader, _shootBox ? _box : _sphere, _shootBox ? 0x880000_rgbf : 0x220000_rgbf, Matrix4::scaling(Vector3{_shootBox ? 0.5f : 0.25f}), _drawables}; createRigidBody(*o, _shootBox ? 1.0f : 5.0f, _shootBox ? _bBoxShape : _bSphereShape) ->setLinearVelocity(btVector3{direction*25.f}); event.setAccepted(); } } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::BulletExample) <commit_msg>bullet: fix memory leaks related to Bullet<commit_after>/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 — Vladimír Vondruš <[email protected]> 2013 — Jan Dupal <[email protected]> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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 <btBulletDynamicsCommon.h> #include <Corrade/Containers/Optional.h> #include <Corrade/Containers/Pointer.h> #include <Magnum/Timeline.h> #include <Magnum/BulletIntegration/Integration.h> #include <Magnum/BulletIntegration/MotionState.h> #include <Magnum/BulletIntegration/DebugDraw.h> #include <Magnum/GL/DefaultFramebuffer.h> #include <Magnum/GL/Mesh.h> #include <Magnum/GL/Renderer.h> #include <Magnum/Math/Constants.h> #include <Magnum/MeshTools/Compile.h> #include <Magnum/MeshTools/Transform.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Primitives/UVSphere.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/MatrixTransformation3D.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Trade/MeshData3D.h> namespace Magnum { namespace Examples { using namespace Math::Literals; typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D; typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D; class BulletExample: public Platform::Application { public: explicit BulletExample(const Arguments& arguments); private: void drawEvent() override; void keyPressEvent(KeyEvent& event) override; void mousePressEvent(MouseEvent& event) override; GL::Mesh _box{NoCreate}, _sphere{NoCreate}; Shaders::Phong _shader{NoCreate}; BulletIntegration::DebugDraw _debugDraw{NoCreate}; btDbvtBroadphase _bBroadphase; btDefaultCollisionConfiguration _bCollisionConfig; btCollisionDispatcher _bDispatcher{&_bCollisionConfig}; btSequentialImpulseConstraintSolver _bSolver; btDiscreteDynamicsWorld _bWorld{&_bDispatcher, &_bBroadphase, &_bSolver, &_bCollisionConfig}; Scene3D _scene; SceneGraph::Camera3D* _camera; SceneGraph::DrawableGroup3D _drawables; Timeline _timeline; Object3D *_cameraRig, *_cameraObject; btBoxShape _bBoxShape{{0.5f, 0.5f, 0.5f}}; btSphereShape _bSphereShape{0.25f}; btBoxShape _bGroundShape{{4.0f, 0.5f, 4.0f}}; bool _drawCubes{true}, _drawDebug{true}, _shootBox{true}; }; class ColoredDrawable: public SceneGraph::Drawable3D { public: explicit ColoredDrawable(Object3D& object, Shaders::Phong& shader, GL::Mesh& mesh, const Color4& color, const Matrix4& primitiveTransformation, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh), _color{color}, _primitiveTransformation{primitiveTransformation} {} private: void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) override { _shader.setDiffuseColor(_color) .setTransformationMatrix(transformation*_primitiveTransformation) .setProjectionMatrix(camera.projectionMatrix()) .setNormalMatrix(transformation.rotationScaling()); _mesh.draw(_shader); } Shaders::Phong& _shader; GL::Mesh& _mesh; Color4 _color; Matrix4 _primitiveTransformation; }; class RigidBody: public Object3D { public: RigidBody(Object3D* parent, Float mass, btCollisionShape* bShape, btDynamicsWorld& bWorld): Object3D{parent}, _bWorld{bWorld} { /* Calculate inertia so the object reacts as it should with rotation and everything */ btVector3 bInertia(0.0f, 0.0f, 0.0f); if(mass != 0.0f) bShape->calculateLocalInertia(mass, bInertia); /* Bullet rigid body setup */ auto* motionState = new BulletIntegration::MotionState{*this}; _bRigidBody.emplace(btRigidBody::btRigidBodyConstructionInfo{ mass, &motionState->btMotionState(), bShape, bInertia}); _bRigidBody->forceActivationState(DISABLE_DEACTIVATION); bWorld.addRigidBody(_bRigidBody.get()); } ~RigidBody() { _bWorld.removeRigidBody(_bRigidBody.get()); } btRigidBody& rigidBody() { return *_bRigidBody; } /* needed after changing the pose from Magnum side */ void syncPose() { _bRigidBody->setWorldTransform(btTransform(transformationMatrix())); } private: btDynamicsWorld& _bWorld; Containers::Pointer<btRigidBody> _bRigidBody; }; BulletExample::BulletExample(const Arguments& arguments): Platform::Application(arguments, NoCreate) { /* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x MSAA if we have enough DPI. */ { const Vector2 dpiScaling = this->dpiScaling({}); Configuration conf; conf.setTitle("Magnum Bullet Integration Example") .setSize(conf.size(), dpiScaling); GLConfiguration glConf; glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2); if(!tryCreate(conf, glConf)) create(conf, glConf.setSampleCount(0)); } /* Camera setup */ (*(_cameraRig = new Object3D{&_scene})) .translate(Vector3::yAxis(3.0f)) .rotateY(40.0_degf); (*(_cameraObject = new Object3D{_cameraRig})) .translate(Vector3::zAxis(20.0f)) .rotateX(-25.0_degf); (_camera = new SceneGraph::Camera3D(*_cameraObject)) ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 1.0f, 0.001f, 100.0f)) .setViewport(GL::defaultFramebuffer.viewport().size()); /* Drawing setup */ _box = MeshTools::compile(Primitives::cubeSolid()); _sphere = MeshTools::compile(Primitives::uvSphereSolid(16, 32)); _shader = Shaders::Phong{}; _shader.setAmbientColor(0x111111_rgbf) .setSpecularColor(0x330000_rgbf) .setLightPosition({10.0f, 15.0f, 5.0f}); _debugDraw = BulletIntegration::DebugDraw{}; _debugDraw.setMode(BulletIntegration::DebugDraw::Mode::DrawWireframe); /* Setup the renderer so we can draw the debug lines on top */ GL::Renderer::enable(GL::Renderer::Feature::DepthTest); GL::Renderer::enable(GL::Renderer::Feature::FaceCulling); GL::Renderer::enable(GL::Renderer::Feature::PolygonOffsetFill); GL::Renderer::setPolygonOffset(2.0f, 0.5f); /* Bullet setup */ _bWorld.setGravity({0.0f, -10.0f, 0.0f}); _bWorld.setDebugDrawer(&_debugDraw); /* Create the ground */ auto* ground = new RigidBody{&_scene, 0.0f, &_bGroundShape, _bWorld}; new ColoredDrawable{*ground, _shader, _box, 0xffffff_rgbf, Matrix4::scaling({4.0f, 0.5f, 4.0f}), _drawables}; /* Create boxes with random colors */ Deg hue = 42.0_degf; for(Int i = 0; i != 5; ++i) { for(Int j = 0; j != 5; ++j) { for(Int k = 0; k != 5; ++k) { auto* o = new RigidBody{&_scene, 1.0f, &_bBoxShape, _bWorld}; o->translate({i - 2.0f, j + 4.0f, k - 2.0f}); o->syncPose(); new ColoredDrawable{*o, _shader, _box, Color3::fromHsv(hue += 137.5_degf, 0.75f, 0.9f), Matrix4::scaling(Vector3{0.5f}), _drawables}; } } } /* Loop at 60 Hz max */ setSwapInterval(1); setMinimalLoopPeriod(16); _timeline.start(); } void BulletExample::drawEvent() { GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth); /* Housekeeping: remove any objects which are far away from the origin */ for(Object3D* obj = _scene.children().first(); obj; ) { Object3D* next = obj->nextSibling(); if(obj->transformation().translation().dot() > 100*100) delete obj; obj = next; } /* Step bullet simulation */ _bWorld.stepSimulation(_timeline.previousFrameDuration(), 5); /* Draw the cubes */ if(_drawCubes) _camera->draw(_drawables); /* Debug draw. If drawing on top of cubes, avoid flickering by setting depth function to <= instead of just <. */ if(_drawDebug) { if(_drawCubes) GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::LessOrEqual); _debugDraw.setTransformationProjectionMatrix( _camera->projectionMatrix()*_camera->cameraMatrix()); _bWorld.debugDrawWorld(); if(_drawCubes) GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::Less); } swapBuffers(); _timeline.nextFrame(); redraw(); } void BulletExample::keyPressEvent(KeyEvent& event) { /* Movement */ if(event.key() == KeyEvent::Key::Down) { _cameraObject->rotateX(5.0_degf); } else if(event.key() == KeyEvent::Key::Up) { _cameraObject->rotateX(-5.0_degf); } else if(event.key() == KeyEvent::Key::Left) { _cameraRig->rotateY(-5.0_degf); } else if(event.key() == KeyEvent::Key::Right) { _cameraRig->rotateY(5.0_degf); /* Toggling draw modes */ } else if(event.key() == KeyEvent::Key::D) { if(_drawCubes && _drawDebug) { _drawDebug = false; } else if(_drawCubes && !_drawDebug) { _drawCubes = false; _drawDebug = true; } else if(!_drawCubes && _drawDebug) { _drawCubes = true; _drawDebug = true; } /* What to shoot */ } else if(event.key() == KeyEvent::Key::S) { _shootBox ^= true; } else return; event.setAccepted(); } void BulletExample::mousePressEvent(MouseEvent& event) { /* Shoot an object on click */ if(event.button() == MouseEvent::Button::Left) { const Vector2 clickPoint = Vector2::yScale(-1.0f)*(Vector2{event.position()}/Vector2{GL::defaultFramebuffer.viewport().size()} - Vector2{0.5f})* _camera->projectionSize(); const Vector3 direction = (_cameraObject->absoluteTransformation().rotationScaling()*Vector3{clickPoint, -1.0f}).normalized(); auto* object = new RigidBody{ &_scene, _shootBox ? 1.0f : 5.0f, _shootBox ? static_cast<btCollisionShape*>(&_bBoxShape) : &_bSphereShape, _bWorld}; object->translate(_cameraObject->absoluteTransformation().translation()); object->syncPose(); /* Create either a box or a sphere */ new ColoredDrawable{*object, _shader, _shootBox ? _box : _sphere, _shootBox ? 0x880000_rgbf : 0x220000_rgbf, Matrix4::scaling(Vector3{_shootBox ? 0.5f : 0.25f}), _drawables}; /* Give it an initial velocity */ object->rigidBody().setLinearVelocity(btVector3{direction*25.f}); event.setAccepted(); } } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::BulletExample) <|endoftext|>
<commit_before>/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2019 Grégory Van den Borre * * More infos available: https://engine.yildiz-games.be * * 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 <OgreArchive.h> #include <OgreString.h> #include <yz_physfs_File.hpp> namespace yz { namespace ogre { namespace vfs { /** * Ogre Archive implementation for a VFS. *@author Grégory Van den Borre */ class Archive: public Ogre::Archive { public: Archive(yz::physfs::Wrapper* vfs, const Ogre::String& name, const Ogre::String& type) : Ogre::Archive(name, type), this->vfs(vfs) { LOG_FUNCTION } /** PhysFS is case sensitive in general */ bool isCaseSensitive() const { LOG_FUNCTION return true; } /** * Loading is handled by the VFS. */ void load() { LOG_FUNCTION } /** * Unloading is handled by the VFS. */ void unload() { LOG_FUNCTION } inline time_t getModifiedTime(const Ogre::String& file) const { LOG_FUNCTION return this->vfs->getLastModTime(file); } Ogre::DataStreamPtr open(const Ogre::String& filename, bool append) const; Ogre::StringVectorPtr list(bool recursive = true, bool dirs = false) const; Ogre::FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const; Ogre::StringVectorPtr find(const Ogre::String& pattern, bool recursive = true, bool dirs = false) const; bool exists(const Ogre::String& filename) const; Ogre::FileInfoListPtr findFileInfo(const Ogre::String& pattern, bool recursive = true, bool dirs = false) const; private: void listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const; void listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const; yz::physfs::Wrapper* vfs; }; }}} <commit_msg>[WIP] Use Vfs module.<commit_after>/* * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT) * * Copyright (c) 2019 Grégory Van den Borre * * More infos available: https://engine.yildiz-games.be * * 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 <OgreArchive.h> #include <OgreString.h> #include <yz_physfs_File.hpp> namespace yz { namespace ogre { namespace vfs { /** * Ogre Archive implementation for a VFS. *@author Grégory Van den Borre */ class Archive: public Ogre::Archive { public: Archive(yz::physfs::Wrapper* vfs, const Ogre::String& name, const Ogre::String& type) : Ogre::Archive(name, type), vfs(vfs) { LOG_FUNCTION } /** PhysFS is case sensitive in general */ bool isCaseSensitive() const { LOG_FUNCTION return true; } /** * Loading is handled by the VFS. */ void load() { LOG_FUNCTION } /** * Unloading is handled by the VFS. */ void unload() { LOG_FUNCTION } inline time_t getModifiedTime(const Ogre::String& file) const { LOG_FUNCTION return this->vfs->getLastModTime(file); } Ogre::DataStreamPtr open(const Ogre::String& filename, bool append) const; Ogre::StringVectorPtr list(bool recursive = true, bool dirs = false) const; Ogre::FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const; Ogre::StringVectorPtr find(const Ogre::String& pattern, bool recursive = true, bool dirs = false) const; bool exists(const Ogre::String& filename) const; Ogre::FileInfoListPtr findFileInfo(const Ogre::String& pattern, bool recursive = true, bool dirs = false) const; private: void listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const; void listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const; yz::physfs::Wrapper* vfs; }; }}} <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * warm_start_ipopt_interface.cc */ #include "modules/planning/planner/open_space/warm_start_ipopt_interface.h" #include <math.h> #include <utility> #include "modules/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { constexpr std::size_t N = 80; WarmStartIPOPTInterface::WarmStartIPOPTInterface( int num_of_variables, int num_of_constraints, std::size_t horizon, float ts, float wheelbase_length, Eigen::MatrixXd x0, Eigen::MatrixXd xf, Eigen::MatrixXd XYbounds) : num_of_variables_(num_of_variables), num_of_constraints_(num_of_constraints), horizon_(horizon), ts_(ts), wheelbase_length_(wheelbase_length), x0_(x0), xf_(xf), XYbounds_(XYbounds) {} void WarmStartIPOPTInterface::get_optimization_results() const {} bool WarmStartIPOPTInterface::get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { // number of variables n = num_of_variables_; // number of constraints m = num_of_constraints_; // number of nonzero hessian and lagrangian. // TODO(QiL) : Update nnz_jac_g; nnz_jac_g = 0; // TOdo(QiL) : Update nnz_h_lag; nnz_h_lag = 0; index_style = IndexStyleEnum::C_STYLE; return true; } bool WarmStartIPOPTInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { // here, the n and m we gave IPOPT in get_nlp_info are passed back to us. // If desired, we could assert to make sure they are what we think they are. CHECK(n == num_of_variables_) << "num_of_variables_ mismatch, n: " << n << ", num_of_variables_: " << num_of_variables_; CHECK(m == num_of_constraints_) << "num_of_constraints_ mismatch, n: " << n << ", num_of_constraints_: " << num_of_constraints_; // Variables: includes u and sample time /* for (std::size_t i = 0; i < horizon_; ++i) { variable_index = i * 3; // steer command x_l[variable_index] = -0.6; x_u[variable_index] = 0.6; // acceleration x_l[variable_index + 1] = -1; x_u[variable_index + 1] = 1; // sampling time; x_l[variable_index + 2] = 0.5; x_u[variable_index + 2] = 2.5; } */ // 1. state variables // start point pose std::size_t variable_index = 0; for (std::size_t i = 0; i < 4; ++i) { x_l[i] = x0_(i, 0); x_u[i] = x0_(i, 0); } variable_index += 4; // During horizons for (std::size_t i = 1; i < horizon_ - 1; ++i) { // x x_l[variable_index] = XYbounds_(0, 0); x_u[variable_index] = XYbounds_(1, 0); // y x_l[variable_index + 1] = XYbounds_(2, 0); x_u[variable_index + 1] = XYbounds_(3, 0); // phi // TODO(QiL): Change this to configs x_l[variable_index + 2] = -7; x_u[variable_index + 2] = 7; // v // TODO(QiL) : Change this to configs x_l[variable_index + 3] = -1; x_u[variable_index + 3] = 2; variable_index += 4; } // end point pose for (std::size_t i = 0; i < 4; ++i) { x_l[variable_index + i] = xf_(i, 0); x_u[variable_index + i] = xf_(i, 0); } variable_index += 4; ADEBUG << "variable_index after adding state constraints : " << variable_index; // 2. input constraints for (std::size_t i = 1; i < horizon_; ++i) { // u1 x_l[variable_index] = -0.6; x_u[variable_index] = 0.6; // u2 x_l[variable_index + 1] = -1; x_u[variable_index + 1] = 1; variable_index += 2; } ADEBUG << "variable_index after adding input constraints : " << variable_index; // 3. sampling time constraints for (std::size_t i = 1; i < horizon_; ++i) { x_l[variable_index] = -0.6; x_u[variable_index] = 0.6; ++variable_index; } ADEBUG << "variable_index : " << variable_index; // Constraints // 1. state constraints // start point pose std::size_t constraint_index = 0; for (std::size_t i = 0; i < 4; ++i) { g_l[i] = x0_(i, 0); g_u[i] = x0_(i, 0); } constraint_index += 4; // During horizons for (std::size_t i = 1; i < horizon_ - 1; ++i) { // x g_l[constraint_index] = XYbounds_(0, 0); g_u[constraint_index] = XYbounds_(1, 0); // y g_l[constraint_index + 1] = XYbounds_(2, 0); g_u[constraint_index + 1] = XYbounds_(3, 0); // phi // TODO(QiL): Change this to configs g_l[constraint_index + 2] = -7; g_u[constraint_index + 2] = 7; // v // TODO(QiL) : Change this to configs g_l[constraint_index + 3] = -1; g_u[constraint_index + 3] = 2; constraint_index += 4; } // end point pose for (std::size_t i = 0; i < 4; ++i) { g_l[constraint_index + i] = xf_(i, 0); g_u[constraint_index + i] = xf_(i, 0); } constraint_index += 4; ADEBUG << "constraint_index after adding state constraints : " << constraint_index; // 2. input constraints for (std::size_t i = 1; i < horizon_; ++i) { // u1 g_l[constraint_index] = -0.6; g_u[constraint_index] = 0.6; // u2 g_l[constraint_index + 1] = -1; g_u[constraint_index + 1] = 1; constraint_index += 2; } ADEBUG << "constraint_index after adding input constraints : " << constraint_index; // 3. sampling time constraints for (std::size_t i = 1; i < horizon_; ++i) { g_l[constraint_index] = -0.6; g_u[constraint_index] = 0.6; ++constraint_index; } ADEBUG << "constraint_index after adding sampling time constraints : " << constraint_index; return true; } bool WarmStartIPOPTInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { return true; } bool WarmStartIPOPTInterface::eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { return true; } bool WarmStartIPOPTInterface::eval_h(int n, const double* x, bool new_x, double obj_factor, int m, const double* lambda, bool new_lambda, int nele_hess, int* iRow, int* jCol, double* values) { return true; } bool WarmStartIPOPTInterface::get_starting_point(int n, bool init_x, double* x, bool init_z, double* z_L, double* z_U, int m, bool init_lambda, double* lambda) { CHECK(n == num_of_variables_) << "No. of variables wrong. n : " << n; CHECK(init_x == true) << "Warm start init_x setting failed"; CHECK(init_z == false) << "Warm start init_z setting failed"; CHECK(init_lambda == false) << "Warm start init_lambda setting failed"; // 1. state variables linspace initialization std::vector<std::vector<double>> x_guess(4, std::vector<double>(horizon_)); for (std::size_t i = 0; i < 4; ++i) { ::apollo::common::util::uniform_slice(x0_(i, 0), xf_(i, 0), horizon_, &x_guess[i]); } for (std::size_t i = 0; i <= horizon_; ++i) { for (std::size_t j = 0; j < 4; ++j) { x[i * 4 + j] = x_guess[j][i]; } } // 2. input initialization for (std::size_t i = 0; i <= 2 * horizon_; ++i) { x[i] = 0.6; } // 3. sampling time constraints for (std::size_t i = 0; i <= horizon_; ++i) { x[i] = 0.5; } return true; } } // namespace planning } // namespace apollo <commit_msg>Planning : update warm start objective function<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * warm_start_ipopt_interface.cc */ #include "modules/planning/planner/open_space/warm_start_ipopt_interface.h" #include <math.h> #include <utility> #include "modules/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { constexpr std::size_t N = 80; WarmStartIPOPTInterface::WarmStartIPOPTInterface( int num_of_variables, int num_of_constraints, std::size_t horizon, float ts, float wheelbase_length, Eigen::MatrixXd x0, Eigen::MatrixXd xf, Eigen::MatrixXd XYbounds) : num_of_variables_(num_of_variables), num_of_constraints_(num_of_constraints), horizon_(horizon), ts_(ts), wheelbase_length_(wheelbase_length), x0_(x0), xf_(xf), XYbounds_(XYbounds) {} void WarmStartIPOPTInterface::get_optimization_results() const {} bool WarmStartIPOPTInterface::get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { // number of variables n = num_of_variables_; // number of constraints m = num_of_constraints_; // number of nonzero hessian and lagrangian. // TODO(QiL) : Update nnz_jac_g; nnz_jac_g = 0; // TOdo(QiL) : Update nnz_h_lag; nnz_h_lag = 0; index_style = IndexStyleEnum::C_STYLE; return true; } bool WarmStartIPOPTInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { // here, the n and m we gave IPOPT in get_nlp_info are passed back to us. // If desired, we could assert to make sure they are what we think they are. CHECK(n == num_of_variables_) << "num_of_variables_ mismatch, n: " << n << ", num_of_variables_: " << num_of_variables_; CHECK(m == num_of_constraints_) << "num_of_constraints_ mismatch, n: " << n << ", num_of_constraints_: " << num_of_constraints_; // Variables: includes u and sample time // 1. state variables // start point pose std::size_t variable_index = 0; for (std::size_t i = 0; i < 4; ++i) { x_l[i] = x0_(i, 0); x_u[i] = x0_(i, 0); } variable_index += 4; // During horizons for (std::size_t i = 1; i < horizon_ - 1; ++i) { // x x_l[variable_index] = XYbounds_(0, 0); x_u[variable_index] = XYbounds_(1, 0); // y x_l[variable_index + 1] = XYbounds_(2, 0); x_u[variable_index + 1] = XYbounds_(3, 0); // phi // TODO(QiL): Change this to configs x_l[variable_index + 2] = -7; x_u[variable_index + 2] = 7; // v // TODO(QiL) : Change this to configs x_l[variable_index + 3] = -1; x_u[variable_index + 3] = 2; variable_index += 4; } // end point pose for (std::size_t i = 0; i < 4; ++i) { x_l[variable_index + i] = xf_(i, 0); x_u[variable_index + i] = xf_(i, 0); } variable_index += 4; ADEBUG << "variable_index after adding state constraints : " << variable_index; // 2. input constraints for (std::size_t i = 1; i < horizon_; ++i) { // u1 x_l[variable_index] = -0.6; x_u[variable_index] = 0.6; // u2 x_l[variable_index + 1] = -1; x_u[variable_index + 1] = 1; variable_index += 2; } ADEBUG << "variable_index after adding input constraints : " << variable_index; // 3. sampling time constraints for (std::size_t i = 1; i < horizon_; ++i) { x_l[variable_index] = -0.6; x_u[variable_index] = 0.6; ++variable_index; } ADEBUG << "variable_index : " << variable_index; // Constraints // 1. state constraints // start point pose std::size_t constraint_index = 0; for (std::size_t i = 0; i < 4; ++i) { g_l[i] = x0_(i, 0); g_u[i] = x0_(i, 0); } constraint_index += 4; // During horizons for (std::size_t i = 1; i < horizon_ - 1; ++i) { // x g_l[constraint_index] = XYbounds_(0, 0); g_u[constraint_index] = XYbounds_(1, 0); // y g_l[constraint_index + 1] = XYbounds_(2, 0); g_u[constraint_index + 1] = XYbounds_(3, 0); // phi // TODO(QiL): Change this to configs g_l[constraint_index + 2] = -7; g_u[constraint_index + 2] = 7; // v // TODO(QiL) : Change this to configs g_l[constraint_index + 3] = -1; g_u[constraint_index + 3] = 2; constraint_index += 4; } // end point pose for (std::size_t i = 0; i < 4; ++i) { g_l[constraint_index + i] = xf_(i, 0); g_u[constraint_index + i] = xf_(i, 0); } constraint_index += 4; ADEBUG << "constraint_index after adding state constraints : " << constraint_index; // 2. input constraints for (std::size_t i = 1; i < horizon_; ++i) { // u1 g_l[constraint_index] = -0.6; g_u[constraint_index] = 0.6; // u2 g_l[constraint_index + 1] = -1; g_u[constraint_index + 1] = 1; constraint_index += 2; } ADEBUG << "constraint_index after adding input constraints : " << constraint_index; // 3. sampling time constraints for (std::size_t i = 1; i < horizon_; ++i) { g_l[constraint_index] = -0.6; g_u[constraint_index] = 0.6; ++constraint_index; } ADEBUG << "constraint_index after adding sampling time constraints : " << constraint_index; return true; } bool WarmStartIPOPTInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { return true; } bool WarmStartIPOPTInterface::eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { return true; } bool WarmStartIPOPTInterface::eval_h(int n, const double* x, bool new_x, double obj_factor, int m, const double* lambda, bool new_lambda, int nele_hess, int* iRow, int* jCol, double* values) { return true; } bool WarmStartIPOPTInterface::get_starting_point(int n, bool init_x, double* x, bool init_z, double* z_L, double* z_U, int m, bool init_lambda, double* lambda) { CHECK(n == num_of_variables_) << "No. of variables wrong. n : " << n; CHECK(init_x == true) << "Warm start init_x setting failed"; CHECK(init_z == false) << "Warm start init_z setting failed"; CHECK(init_lambda == false) << "Warm start init_lambda setting failed"; // 1. state variables linspace initialization std::vector<std::vector<double>> x_guess(4, std::vector<double>(horizon_)); for (std::size_t i = 0; i < 4; ++i) { ::apollo::common::util::uniform_slice(x0_(i, 0), xf_(i, 0), horizon_, &x_guess[i]); } for (std::size_t i = 0; i <= horizon_; ++i) { for (std::size_t j = 0; j < 4; ++j) { x[i * 4 + j] = x_guess[j][i]; } } // 2. input initialization for (std::size_t i = 0; i <= 2 * horizon_; ++i) { x[i] = 0.6; } // 3. sampling time constraints for (std::size_t i = 0; i <= horizon_; ++i) { x[i] = 0.5; } return true; } bool WarmStartIPOPTInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { // first (horizon_ + 1) * 4 is state, then next horizon_ * 2 is control input, // then last horizon_ + 1 is sampling time std::size_t start_index = (horizon_ + 1) * 4; std::size_t time_start_index = start_index + horizon_ * 2; for (std::size_t i = 0; i < horizon_; ++i) { obj_value += 0.1 * x[start_index + i] * x[start_index + i] + x[start_index + i] * x[start_index + i + 1] + 0.5 * x[time_start_index + i] + x[time_start_index + i] * x[time_start_index + i]; } obj_value += 0.5 * x[time_start_index + horizon_] + x[time_start_index + horizon_] * x[time_start_index + horizon_]; return true; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/explorer/primitives/ec_public.hpp> #include <iostream> #include <sstream> #include <string> #include <boost/program_options.hpp> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/define.hpp> #include <bitcoin/explorer/primitives/base16.hpp> using namespace po; namespace libbitcoin { namespace explorer { namespace primitives { // ec_point format is currently private to bx. static bool decode_point(ec_point& point, const std::string& encoded) { data_chunk result; if (!decode_base16(result, encoded) || result.size() != point.size()) return false; if (verify_public_key_fast(ec_point(result))) return false; point.assign(result.begin(), result.end()); return true; } static std::string encode_point(const ec_point& point) { return encode_base16(point); } ec_public::ec_public() : value_() { } ec_public::ec_public(const std::string& hexcode) { std::stringstream(hexcode) >> *this; } ec_public::ec_public(const bc::ec_point& value) : value_(value) { } ec_public::ec_public(const ec_public& other) : ec_public(other.value_) { } ec_public::ec_public(const hd_private_key& value) : ec_public(value.public_key()) { } ec_public::ec_public(const hd_public_key& value) : ec_public(value.public_key()) { } ec_point& ec_public::data() { return value_; } ec_public::operator const ec_point&() const { return value_; } ec_public::operator data_slice() const { return value_; } std::istream& operator>>(std::istream& input, ec_public& argument) { std::string hexcode; input >> hexcode; if (!decode_point(argument.value_, hexcode)) BOOST_THROW_EXCEPTION(invalid_option_value(hexcode)); return input; } std::ostream& operator<<(std::ostream& output, const ec_public& argument) { output << encode_point(argument.value_); return output; } } // namespace explorer } // namespace primitives } // namespace libbitcoin <commit_msg>Restore ec_public functionality<commit_after>/** * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/explorer/primitives/ec_public.hpp> #include <iostream> #include <sstream> #include <string> #include <boost/program_options.hpp> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/define.hpp> #include <bitcoin/explorer/primitives/base16.hpp> using namespace po; namespace libbitcoin { namespace explorer { namespace primitives { // ec_point format is currently private to bx. static bool decode_point(ec_point& point, const std::string& encoded) { data_chunk result; if (!decode_base16(result, encoded)) return false; if (!verify_public_key_fast(ec_point(result))) return false; point.assign(result.begin(), result.end()); return true; } static std::string encode_point(const ec_point& point) { return encode_base16(point); } ec_public::ec_public() : value_() { } ec_public::ec_public(const std::string& hexcode) { std::stringstream(hexcode) >> *this; } ec_public::ec_public(const bc::ec_point& value) : value_(value) { } ec_public::ec_public(const ec_public& other) : ec_public(other.value_) { } ec_public::ec_public(const hd_private_key& value) : ec_public(value.public_key()) { } ec_public::ec_public(const hd_public_key& value) : ec_public(value.public_key()) { } ec_point& ec_public::data() { return value_; } ec_public::operator const ec_point&() const { return value_; } ec_public::operator data_slice() const { return value_; } std::istream& operator>>(std::istream& input, ec_public& argument) { std::string hexcode; input >> hexcode; if (!decode_point(argument.value_, hexcode)) BOOST_THROW_EXCEPTION(invalid_option_value(hexcode)); return input; } std::ostream& operator<<(std::ostream& output, const ec_public& argument) { output << encode_point(argument.value_); return output; } } // namespace explorer } // namespace primitives } // namespace libbitcoin <|endoftext|>
<commit_before>#include "FilesDecisionModel.h" FilesDecisionModel::FilesDecisionModel(TreeRootItem* root) : m_rootItem(root) { } FilesDecisionModel::~FilesDecisionModel() { if (m_rootItem) delete m_rootItem; } void FilesDecisionModel::setFilesInfo(TreeRootItem* rootItem) { m_rootItem = rootItem; } QModelIndex FilesDecisionModel::index(int row, int column, const QModelIndex& parent) const { if (!hasIndex(row, column, parent)) { return QModelIndex(); } if (!parent.isValid()) { if (row < m_rootItem->childCount()) { return createIndex(row, column, nullptr); } else { return QModelIndex(); } } else { if (parent.internalPointer() == nullptr) { TreeInnerItem *childItem = m_rootItem->child(parent.row()); if (childItem) { return createIndex(row, column, childItem); } else { return QModelIndex(); } } } return QModelIndex(); } QModelIndex FilesDecisionModel::parent(const QModelIndex& child) const { if (!child.isValid()) { return QModelIndex(); } if (child.internalPointer() == nullptr) { return QModelIndex(); } TreeInnerItem *childItem = static_cast<TreeInnerItem*>(child.internalPointer()); return createIndex(childItem->row(), 0, nullptr); } int FilesDecisionModel::rowCount(const QModelIndex& parent) const { if (parent.column() > 0) { return 0; } if (!parent.isValid()) { return m_rootItem->dataCount(); } else { if (parent.internalPointer() == nullptr) { if (parent.row() < m_rootItem->childItems().size()) { int count = m_rootItem->child(parent.row())->dataCount(); return count; } else { return 0; } } else { return 0; } } } int FilesDecisionModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 1; } QVariant FilesDecisionModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) { return QVariant(); } if (role != Qt::DisplayRole) { return QVariant(); } if (index.internalPointer() == nullptr) { return m_rootItem->data(index.row()); } else { TreeInnerItem *item = static_cast<TreeInnerItem*>(index.internalPointer()); return item->data(index.row()); } } Qt::ItemFlags FilesDecisionModel::flags(const QModelIndex& index) const { Q_UNUSED(index); return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } <commit_msg>[*] minor model changes<commit_after>#include "FilesDecisionModel.h" FilesDecisionModel::FilesDecisionModel(TreeRootItem* root) : m_rootItem(root) { } FilesDecisionModel::~FilesDecisionModel() { if (m_rootItem) delete m_rootItem; } void FilesDecisionModel::setFilesInfo(TreeRootItem* rootItem) { m_rootItem = rootItem; } QModelIndex FilesDecisionModel::index(int row, int column, const QModelIndex& parent) const { if (!hasIndex(row, column, parent)) { return QModelIndex(); } if (!parent.isValid()) { return createIndex(row, column, nullptr); } else { if (parent.internalPointer() == nullptr) { TreeInnerItem *childItem = m_rootItem->child(parent.row()); if (childItem) { return createIndex(row, column, childItem); } } } return QModelIndex(); } QModelIndex FilesDecisionModel::parent(const QModelIndex& child) const { if (!child.isValid()) { return QModelIndex(); } if (child.internalPointer() == nullptr) { return QModelIndex(); } TreeInnerItem *childItem = static_cast<TreeInnerItem*>(child.internalPointer()); return createIndex(childItem->row(), 0, nullptr); } int FilesDecisionModel::rowCount(const QModelIndex& parent) const { if (parent.column() > 0) { return 0; } if (!parent.isValid()) { return m_rootItem->dataCount(); } else { if (parent.internalPointer() == nullptr) { if (parent.row() < m_rootItem->childItems().size()) { return m_rootItem->child(parent.row())->dataCount(); } } } return 0; } int FilesDecisionModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 1; } QVariant FilesDecisionModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) { return QVariant(); } if (role != Qt::DisplayRole) { return QVariant(); } if (index.internalPointer() == nullptr) { return m_rootItem->data(index.row()); } else { TreeInnerItem *item = static_cast<TreeInnerItem*>(index.internalPointer()); return item->data(index.row()); } } Qt::ItemFlags FilesDecisionModel::flags(const QModelIndex& index) const { Q_UNUSED(index); return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786) #endif #include "common.h" #include <algorithm> #include "AutoCompleter.h" void AutoCompleter::registerWord(const std::string& str) { words.insert(std::lower_bound(words.begin(), words.end(), str), str); } void AutoCompleter::unregisterWord(const std::string& str) { std::vector<std::string>::iterator iter = std::lower_bound(words.begin(), words.end(), str); if (iter != words.end() && *iter == str) words.erase(iter); } std::string AutoCompleter::complete(const std::string& str) { if (str.size() == 0) return str; // find the first and last word with the prefix str std::vector<std::string>::iterator first, last; first = std::lower_bound(words.begin(), words.end(), str); if (first == words.end() || first->substr(0, str.size()) != str) return str; std::string tmp = str; tmp[tmp.size() - 1]++; last = std::lower_bound(first, words.end(), tmp) - 1; // return the largest common prefix unsigned int i; for (i = 0; i < first->size() && i < last->size(); ++i) if ((*first)[i] != (*last)[i]) break; return first->substr(0, i); } DefaultCompleter::DefaultCompleter() { setDefaults(); } void DefaultCompleter::setDefaults() { words.clear(); registerWord("/ban "); registerWord("/banlist"); registerWord("/countdown"); registerWord("/clientquery"); registerWord("/date"); registerWord("/deregister"); registerWord("/flag "); registerWord("reset"); registerWord("up"); registerWord("show"); registerWord("/flaghistory"); registerWord("/gameover"); registerWord("/ghost "); registerWord("/groupperms"); registerWord("/help"); registerWord("/highlight "); registerWord("/identify "); registerWord("/idlestats"); registerWord("/kick "); registerWord("/kill "); registerWord("/lagstats"); registerWord("/lagwarn "); registerWord("/localset "); registerWord("/mute "); registerWord("/password "); registerWord("/playerlist"); registerWord("/poll "); registerWord("ban"); registerWord("kick"); registerWord("kill"); registerWord("/quit"); registerWord("/record"); registerWord("start"); registerWord("stop"); registerWord("size"); registerWord("rate"); registerWord("stats"); registerWord("file"); registerWord("save"); registerWord("/register "); registerWord("/reload"); registerWord("/masterban"); // also uses list registerWord("reload"); registerWord("flush"); registerWord("/removegroup "); registerWord("/replay "); registerWord("list"); registerWord("load"); registerWord("play"); registerWord("skip"); registerWord("/report "); registerWord("/reset"); registerWord("/retexture"); registerWord("/roampos "); registerWord("/set"); registerWord("/setgroup "); registerWord("/setpass "); registerWord("/showgroup "); registerWord("/shutdownserver"); registerWord("/superkill"); registerWord("/time"); registerWord("/unban "); registerWord("/unmute "); registerWord("/uptime"); registerWord("/veto"); registerWord("/viewreports"); registerWord("/vote"); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>added serverquery<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning( 4: 4786) #endif #include "common.h" #include <algorithm> #include "AutoCompleter.h" void AutoCompleter::registerWord(const std::string& str) { words.insert(std::lower_bound(words.begin(), words.end(), str), str); } void AutoCompleter::unregisterWord(const std::string& str) { std::vector<std::string>::iterator iter = std::lower_bound(words.begin(), words.end(), str); if (iter != words.end() && *iter == str) words.erase(iter); } std::string AutoCompleter::complete(const std::string& str) { if (str.size() == 0) return str; // find the first and last word with the prefix str std::vector<std::string>::iterator first, last; first = std::lower_bound(words.begin(), words.end(), str); if (first == words.end() || first->substr(0, str.size()) != str) return str; std::string tmp = str; tmp[tmp.size() - 1]++; last = std::lower_bound(first, words.end(), tmp) - 1; // return the largest common prefix unsigned int i; for (i = 0; i < first->size() && i < last->size(); ++i) if ((*first)[i] != (*last)[i]) break; return first->substr(0, i); } DefaultCompleter::DefaultCompleter() { setDefaults(); } void DefaultCompleter::setDefaults() { words.clear(); registerWord("/ban "); registerWord("/banlist"); registerWord("/countdown"); registerWord("/clientquery"); registerWord("/date"); registerWord("/deregister"); registerWord("/flag "); registerWord("reset"); registerWord("up"); registerWord("show"); registerWord("/flaghistory"); registerWord("/gameover"); registerWord("/ghost "); registerWord("/groupperms"); registerWord("/help"); registerWord("/highlight "); registerWord("/identify "); registerWord("/idlestats"); registerWord("/kick "); registerWord("/kill "); registerWord("/lagstats"); registerWord("/lagwarn "); registerWord("/localset "); registerWord("/mute "); registerWord("/password "); registerWord("/playerlist"); registerWord("/poll "); registerWord("ban"); registerWord("kick"); registerWord("kill"); registerWord("/quit"); registerWord("/record"); registerWord("start"); registerWord("stop"); registerWord("size"); registerWord("rate"); registerWord("stats"); registerWord("file"); registerWord("save"); registerWord("/register "); registerWord("/reload"); registerWord("/masterban"); // also uses list registerWord("reload"); registerWord("flush"); registerWord("/removegroup "); registerWord("/replay "); registerWord("list"); registerWord("load"); registerWord("play"); registerWord("skip"); registerWord("/report "); registerWord("/reset"); registerWord("/retexture"); registerWord("/roampos "); registerWord("/serverquery"); registerWord("/set"); registerWord("/setgroup "); registerWord("/setpass "); registerWord("/showgroup "); registerWord("/shutdownserver"); registerWord("/superkill"); registerWord("/time"); registerWord("/unban "); registerWord("/unmute "); registerWord("/uptime"); registerWord("/veto"); registerWord("/viewreports"); registerWord("/vote"); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include <rtcmix_types.h> #include <PField.h> #include <string.h> // for strcmp() #include <stdlib.h> // for free() Arg::~Arg() { if (_type == ArrayType) free(_val.array); } bool Arg::operator == (const char *str) const { return isType(StringType) && !strcmp(_val.string, str); } void Arg::printInline(FILE *stream) const { switch (type()) { case DoubleType: fprintf(stream, "%g ", _val.number); break; case StringType: fprintf(stream, "\"%s\" ", _val.string); break; case HandleType: fprintf(stream, "%sHndl:", _val.handle->type == PFieldType ? "PF" : _val.handle->type == InstrumentPtrType ? "Inst" : _val.handle->type == PFieldType ? "AudioStr" : "Unknown"); if (_val.handle->type == PFieldType) { // Print PField start and end values. PField *pf = (PField *) _val.handle->ptr; double start = pf->doubleValue(0); double end = pf->doubleValue(1.0); fprintf(stream, "[%g,...,%g] ", start, end); } else fprintf(stream, " "); break; case ArrayType: fprintf(stream, "[%g,...,%g] ", _val.array->data[0], _val.array->data[_val.array->len - 1]); break; default: break; } } <commit_msg>Changed arg printout from PFHndl: to PF:<commit_after>#include <rtcmix_types.h> #include <PField.h> #include <string.h> // for strcmp() #include <stdlib.h> // for free() Arg::~Arg() { if (_type == ArrayType) free(_val.array); } bool Arg::operator == (const char *str) const { return isType(StringType) && !strcmp(_val.string, str); } void Arg::printInline(FILE *stream) const { switch (type()) { case DoubleType: fprintf(stream, "%g ", _val.number); break; case StringType: fprintf(stream, "\"%s\" ", _val.string); break; case HandleType: fprintf(stream, "%s:", _val.handle->type == PFieldType ? "PF" : _val.handle->type == InstrumentPtrType ? "Inst" : _val.handle->type == PFieldType ? "AudioStr" : "Unknown"); if (_val.handle->type == PFieldType) { // Print PField start and end values. PField *pf = (PField *) _val.handle->ptr; double start = pf->doubleValue(0); double end = pf->doubleValue(1.0); fprintf(stream, "[%g,...,%g] ", start, end); } else fprintf(stream, " "); break; case ArrayType: fprintf(stream, "[%g,...,%g] ", _val.array->data[0], _val.array->data[_val.array->len - 1]); break; default: break; } } <|endoftext|>
<commit_before>#include "REPL.h" #include "ConsoleWriter.h" #include <iostream> #include <parser/Parser.h> #include <common/Errors.h> #include <semantics/SemanticAnalyzer.h> #include <semantics/ScopedNodes.h> #include <cassert> #include <ast/ast.h> #include <semantics/GlobalScope.h> #include <semantics/FunctionOverloadedSymbol.h> #include <semantics/FunctionSymbol.h> using namespace std; using namespace Swallow; REPL::REPL(const ConsoleWriterPtr& out) :out(out), canQuit(false) { initCommands(); resultId = 0; } void REPL::repl() { wstring line; int id = 1; out->printf(L"Welcome to Swallow! Type :help for assistance.\n"); program = nodeFactory.createProgram(); while(!canQuit && !wcin.eof()) { out->printf(L"%3d> ", id); getline(wcin, line); if(line.empty()) continue; if(line[0] == ':') { evalCommand(line.substr(1)); continue; } CompilerResults compilerResults; eval(compilerResults, line); dumpCompilerResults(compilerResults, line); id++; } } void REPL::eval(CompilerResults& compilerResults, const wstring& line) { Parser parser(&nodeFactory, &compilerResults); parser.setFileName(L"<file>"); //remove parsed nodes in last eval program->clearStatements(); bool successed = parser.parse(line.c_str(), program); if(!successed) return; try { SemanticAnalyzer analyzer(&registry, &compilerResults); program->accept(&analyzer); dumpProgram(); } catch(const Abort&) { //ignore this } } void REPL::dumpProgram() { SymbolScope* scope = static_pointer_cast<ScopedProgram>(program)->getScope(); assert(scope != nullptr); out->setForegroundColor(Cyan); for(const StatementPtr& st : *program) { SymbolPtr sym = nullptr; switch(st->getNodeType()) { case NodeType::Identifier: { IdentifierPtr id = static_pointer_cast<Identifier>(st); sym = scope->lookup(id->getIdentifier()); dumpSymbol(sym); break; } case NodeType::ValueBindings: { ValueBindingsPtr vars = static_pointer_cast<ValueBindings>(st); for(const ValueBindingPtr& var : *vars) { if(IdentifierPtr id = dynamic_pointer_cast<Identifier>(var->getName())) { sym = scope->lookup(id->getIdentifier()); dumpSymbol(sym); } } break; } default: { if(PatternPtr pat = dynamic_pointer_cast<Pattern>(st)) { if(pat->getType() && !Type::equals(registry.getGlobalScope()->t_Void, pat->getType())) { wstringstream s; s<<L"$R"<<(resultId++); SymbolPlaceHolderPtr sym(new SymbolPlaceHolder(s.str(), pat->getType(), SymbolPlaceHolder::R_LOCAL_VARIABLE, 0)); dumpSymbol(sym); } } break; } } } out->reset(); } void REPL::dumpSymbol(const SymbolPtr& sym) { if(sym && sym->getType()) { wstring type = sym->getType()->toString(); out->printf(L"%ls : %ls\n", sym->getName().c_str(), type.c_str()); } } void REPL::dumpCompilerResults(CompilerResults& compilerResults, const std::wstring& code) { for(auto res : compilerResults) { out->setForegroundColor(White); out->printf(L"%d:%d: ", res.line, res.column); switch(res.level) { case ErrorLevel::Fatal: out->setForegroundColor(Red); out->printf(L"fatal"); break; case ErrorLevel::Error: out->setForegroundColor(Red, Bright); out->printf(L"error"); break; case ErrorLevel::Note: out->setForegroundColor(White); out->printf(L"note"); break; case ErrorLevel::Warning: out->setForegroundColor(Yellow); out->printf(L"warning"); break; } out->setForegroundColor(White, Bright); out->printf(L": "); wstring msg = Errors::format(res.code, res.items); out->printf(L"%ls\n", msg.c_str()); out->reset(); out->printf(L"%ls\n", code.c_str()); for(int i = 1; i < res.column; i++) { out->printf(L" "); } out->setForegroundColor(Green); out->printf(L"^\n"); out->reset(); } } void REPL::evalCommand(const wstring &command) { wstring cmd = command; wstring args; wstring::size_type pos = command.find(L' '); if(pos != wstring::npos) { cmd = command.substr(0, pos); args = command.substr(pos + 1, command.size() - pos - 1); } auto iter = methods.find(cmd); if(iter == methods.end()) { out->printf(L"error: '%ls' is not a valid command.\n", cmd.c_str()); return; } (this->*iter->second)(args); } void REPL::initCommands() { methods.insert(make_pair(L"help", &REPL::commandHelp)); methods.insert(make_pair(L"quit", &REPL::commandQuit)); methods.insert(make_pair(L"exit", &REPL::commandQuit)); methods.insert(make_pair(L"symbols", &REPL::commandSymbols)); } void REPL::commandHelp(const wstring& args) { out->printf(L"The Swallow REPL (Read-Eval-Print-Loop) acts like an interpreter. Valid statements, expressions, and declarations.\n"); out->printf(L"Compiler and execution is not finished yet."); out->printf(L"\n"); out->printf(L"The complete set of commands are also available as described below. Commands must be prefixed with a colon at the REPL prompt (:quit for example.) \n\n\n"); out->printf(L"REPL commands:\n"); out->printf(L" help -- Show a list of all swallow commands, or give details about specific commands.\n"); out->printf(L" symbols -- Dump symbols\n"); out->printf(L" quit -- Quit out of the Swallow REPL.\n\n"); } void REPL::commandQuit(const wstring& args) { canQuit = true; } static void dumpSymbol(const wstring& name, const SymbolPtr& sym, const ConsoleWriterPtr& out) { const wchar_t* kind = L"?????"; if(dynamic_pointer_cast<Type>(sym)) kind = L"Type"; else if(dynamic_pointer_cast<SymbolPlaceHolder>(sym)) kind = L"Placeholder"; else if(dynamic_pointer_cast<FunctionSymbol>(sym)) kind = L"Function"; out->setForegroundColor(White , Bright); out->printf(L"%10ls\t", name.c_str()); out->setForegroundColor(Magenta , Bright); out->printf(L"%7ls\t", kind); if(sym->getType()) { wstring type = sym->getType()->toString(); out->setForegroundColor(Yellow, Bright); out->printf(L"%ls\t", type.c_str()); } out->setForegroundColor(Cyan, Bright); static const SymbolFlags flags[] = {SymbolFlagInitializing, SymbolFlagInitialized, SymbolFlagMember, SymbolFlagWritable, SymbolFlagReadable, SymbolFlagTemporary, SymbolFlagHasInitializer, SymbolFlagStatic, SymbolFlagInit}; static const wchar_t* flagNames[] = {L"initializing", L"initialized", L"member", L"writable", L"readable", L"temporary", L"has_initializer", L"static", L"init"}; for(int i = 0; i < sizeof(flags) / sizeof(flags[0]); i++) { if(sym->hasFlags(flags[i])) out->printf(L"%ls,", flagNames[i]); } out->printf(L"\n"); out->reset(); } static void dumpSymbols(SymbolScope* scope, const ConsoleWriterPtr& out) { for(auto entry : scope->getSymbols()) { if(FunctionOverloadedSymbolPtr funcs = dynamic_pointer_cast<FunctionOverloadedSymbol>(entry.second)) { for(const FunctionSymbolPtr& func : *funcs) { dumpSymbol(entry.first, func, out); } } else { dumpSymbol(entry.first, entry.second, out); } } } void REPL::commandSymbols(const wstring& args) { SymbolScope* scope = nullptr; ScopedProgramPtr p = static_pointer_cast<ScopedProgram>(program); if(args == L"global") scope = this->registry.getGlobalScope(); else scope = p->getScope(); dumpSymbols(scope, out); }<commit_msg>Refactored the type's naming in GlobalScope.h<commit_after>#include "REPL.h" #include "ConsoleWriter.h" #include <iostream> #include <parser/Parser.h> #include <common/Errors.h> #include <semantics/SemanticAnalyzer.h> #include <semantics/ScopedNodes.h> #include <cassert> #include <ast/ast.h> #include <semantics/GlobalScope.h> #include <semantics/FunctionOverloadedSymbol.h> #include <semantics/FunctionSymbol.h> using namespace std; using namespace Swallow; REPL::REPL(const ConsoleWriterPtr& out) :out(out), canQuit(false) { initCommands(); resultId = 0; } void REPL::repl() { wstring line; int id = 1; out->printf(L"Welcome to Swallow! Type :help for assistance.\n"); program = nodeFactory.createProgram(); while(!canQuit && !wcin.eof()) { out->printf(L"%3d> ", id); getline(wcin, line); if(line.empty()) continue; if(line[0] == ':') { evalCommand(line.substr(1)); continue; } CompilerResults compilerResults; eval(compilerResults, line); dumpCompilerResults(compilerResults, line); id++; } } void REPL::eval(CompilerResults& compilerResults, const wstring& line) { Parser parser(&nodeFactory, &compilerResults); parser.setFileName(L"<file>"); //remove parsed nodes in last eval program->clearStatements(); bool successed = parser.parse(line.c_str(), program); if(!successed) return; try { SemanticAnalyzer analyzer(&registry, &compilerResults); program->accept(&analyzer); dumpProgram(); } catch(const Abort&) { //ignore this } } void REPL::dumpProgram() { SymbolScope* scope = static_pointer_cast<ScopedProgram>(program)->getScope(); assert(scope != nullptr); out->setForegroundColor(Cyan); for(const StatementPtr& st : *program) { SymbolPtr sym = nullptr; switch(st->getNodeType()) { case NodeType::Identifier: { IdentifierPtr id = static_pointer_cast<Identifier>(st); sym = scope->lookup(id->getIdentifier()); dumpSymbol(sym); break; } case NodeType::ValueBindings: { ValueBindingsPtr vars = static_pointer_cast<ValueBindings>(st); for(const ValueBindingPtr& var : *vars) { if(IdentifierPtr id = dynamic_pointer_cast<Identifier>(var->getName())) { sym = scope->lookup(id->getIdentifier()); dumpSymbol(sym); } } break; } default: { if(PatternPtr pat = dynamic_pointer_cast<Pattern>(st)) { if(pat->getType() && !Type::equals(registry.getGlobalScope()->Void, pat->getType())) { wstringstream s; s<<L"$R"<<(resultId++); SymbolPlaceHolderPtr sym(new SymbolPlaceHolder(s.str(), pat->getType(), SymbolPlaceHolder::R_LOCAL_VARIABLE, 0)); dumpSymbol(sym); } } break; } } } out->reset(); } void REPL::dumpSymbol(const SymbolPtr& sym) { if(sym && sym->getType()) { wstring type = sym->getType()->toString(); out->printf(L"%ls : %ls\n", sym->getName().c_str(), type.c_str()); } } void REPL::dumpCompilerResults(CompilerResults& compilerResults, const std::wstring& code) { for(auto res : compilerResults) { out->setForegroundColor(White); out->printf(L"%d:%d: ", res.line, res.column); switch(res.level) { case ErrorLevel::Fatal: out->setForegroundColor(Red); out->printf(L"fatal"); break; case ErrorLevel::Error: out->setForegroundColor(Red, Bright); out->printf(L"error"); break; case ErrorLevel::Note: out->setForegroundColor(White); out->printf(L"note"); break; case ErrorLevel::Warning: out->setForegroundColor(Yellow); out->printf(L"warning"); break; } out->setForegroundColor(White, Bright); out->printf(L": "); wstring msg = Errors::format(res.code, res.items); out->printf(L"%ls\n", msg.c_str()); out->reset(); out->printf(L"%ls\n", code.c_str()); for(int i = 1; i < res.column; i++) { out->printf(L" "); } out->setForegroundColor(Green); out->printf(L"^\n"); out->reset(); } } void REPL::evalCommand(const wstring &command) { wstring cmd = command; wstring args; wstring::size_type pos = command.find(L' '); if(pos != wstring::npos) { cmd = command.substr(0, pos); args = command.substr(pos + 1, command.size() - pos - 1); } auto iter = methods.find(cmd); if(iter == methods.end()) { out->printf(L"error: '%ls' is not a valid command.\n", cmd.c_str()); return; } (this->*iter->second)(args); } void REPL::initCommands() { methods.insert(make_pair(L"help", &REPL::commandHelp)); methods.insert(make_pair(L"quit", &REPL::commandQuit)); methods.insert(make_pair(L"exit", &REPL::commandQuit)); methods.insert(make_pair(L"symbols", &REPL::commandSymbols)); } void REPL::commandHelp(const wstring& args) { out->printf(L"The Swallow REPL (Read-Eval-Print-Loop) acts like an interpreter. Valid statements, expressions, and declarations.\n"); out->printf(L"Compiler and execution is not finished yet."); out->printf(L"\n"); out->printf(L"The complete set of commands are also available as described below. Commands must be prefixed with a colon at the REPL prompt (:quit for example.) \n\n\n"); out->printf(L"REPL commands:\n"); out->printf(L" help -- Show a list of all swallow commands, or give details about specific commands.\n"); out->printf(L" symbols -- Dump symbols\n"); out->printf(L" quit -- Quit out of the Swallow REPL.\n\n"); } void REPL::commandQuit(const wstring& args) { canQuit = true; } static void dumpSymbol(const wstring& name, const SymbolPtr& sym, const ConsoleWriterPtr& out) { const wchar_t* kind = L"?????"; if(dynamic_pointer_cast<Type>(sym)) kind = L"Type"; else if(dynamic_pointer_cast<SymbolPlaceHolder>(sym)) kind = L"Placeholder"; else if(dynamic_pointer_cast<FunctionSymbol>(sym)) kind = L"Function"; out->setForegroundColor(White , Bright); out->printf(L"%10ls\t", name.c_str()); out->setForegroundColor(Magenta , Bright); out->printf(L"%7ls\t", kind); if(sym->getType()) { wstring type = sym->getType()->toString(); out->setForegroundColor(Yellow, Bright); out->printf(L"%ls\t", type.c_str()); } out->setForegroundColor(Cyan, Bright); static const SymbolFlags flags[] = {SymbolFlagInitializing, SymbolFlagInitialized, SymbolFlagMember, SymbolFlagWritable, SymbolFlagReadable, SymbolFlagTemporary, SymbolFlagHasInitializer, SymbolFlagStatic, SymbolFlagInit}; static const wchar_t* flagNames[] = {L"initializing", L"initialized", L"member", L"writable", L"readable", L"temporary", L"has_initializer", L"static", L"init"}; for(int i = 0; i < sizeof(flags) / sizeof(flags[0]); i++) { if(sym->hasFlags(flags[i])) out->printf(L"%ls,", flagNames[i]); } out->printf(L"\n"); out->reset(); } static void dumpSymbols(SymbolScope* scope, const ConsoleWriterPtr& out) { for(auto entry : scope->getSymbols()) { if(FunctionOverloadedSymbolPtr funcs = dynamic_pointer_cast<FunctionOverloadedSymbol>(entry.second)) { for(const FunctionSymbolPtr& func : *funcs) { dumpSymbol(entry.first, func, out); } } else { dumpSymbol(entry.first, entry.second, out); } } } void REPL::commandSymbols(const wstring& args) { SymbolScope* scope = nullptr; ScopedProgramPtr p = static_pointer_cast<ScopedProgram>(program); if(args == L"global") scope = this->registry.getGlobalScope(); else scope = p->getScope(); dumpSymbols(scope, out); }<|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_draminit.C /// @brief Initialize dram /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <p9_mss_draminit.H> #include <lib/utils/count_dimm.H> #include <lib/fir/training_fir.H> #include <lib/utils/conversions.H> #include <lib/dimm/bcw_load.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; extern "C" { /// /// @brief Initialize dram /// @param[in] i_target, the McBIST of the ports of the dram you're initializing /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { fapi2::buffer<uint64_t> l_data; mss::ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst; mss::ccs::instruction_t<TARGET_TYPE_MCBIST> l_des = mss::ccs::des_command<TARGET_TYPE_MCBIST>(); mss::ccs::program<TARGET_TYPE_MCBIST> l_program; // Up, down P down, up N. Somewhat magic numbers - came from Centaur and proven to be the // same on Nimbus. Why these are what they are might be lost to time ... constexpr uint64_t PCLK_INITIAL_VALUE = 0b10; constexpr uint64_t NCLK_INITIAL_VALUE = 0b01; const auto l_mca = mss::find_targets<TARGET_TYPE_MCA>(i_target); FAPI_INF("Start draminit: %s", mss::c_str(i_target)); // If we don't have any ports, lets go. if (l_mca.size() == 0) { FAPI_INF("++++ No ports? %s ++++", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } // If we don't have any DIMM, lets go. if (mss::count_dimm(i_target) == 0) { FAPI_INF("++++ NO DIMM on %s ++++", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } // Configure the CCS engine. Since this is a chunk of MCBIST logic, we don't want // to do it for every port. If we ever break this code out so f/w can call draminit // per-port (separate threads) we'll need to provide them a way to set this up before // sapwning per-port threads. { fapi2::buffer<uint64_t> l_ccs_config; FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) ); // It's unclear if we want to run with this true or false. Right now (10/15) this // has to be false. Shelton was unclear if this should be on or off in general BRS mss::ccs::stop_on_err(i_target, l_ccs_config, mss::LOW); mss::ccs::ue_disable(i_target, l_ccs_config, mss::LOW); mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, mss::HIGH); mss::ccs::parity_after_cmd(i_target, l_ccs_config, mss::HIGH); FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) ); } // We initialize dram by iterating over the (ungarded) ports. We could allow the caller // to initialize each port's dram on a separate thread if we could synchronize access // to the MCBIST (CCS engine.) Right now we can't, so we'll do it this way. // // We expect to come in to draminit with the following setup: // 1. ENABLE_RESET_N (FARB5Q(6)) 0 // 2. RESET_N (FARB5Q(4)) 0 - driving reset // 3. CCS_ADDR_MUX_SEL (FARB5Q(5)) - 1 // 4. CKE out of high impedence // for (const auto& p : l_mca) { FAPI_TRY( mss::draminit_entry_invariant(p) ); FAPI_TRY( mss::ddr_resetn(p, mss::HIGH) ); // Begin driving mem clks, and wait 10ns (we'll do this outside the loop) FAPI_TRY( mss::drive_mem_clks(p, PCLK_INITIAL_VALUE, NCLK_INITIAL_VALUE) ); } // From the DDR4 JEDEC Spec (79-A): Power-up Initialization Sequence // Lets find our max delay in ns { // Clocks (CK_t,CK_c) need to be started and stable for 10ns or 5tCK // (whichever is greater) before CKE goes active. constexpr uint64_t DELAY_5TCK = 5; uint64_t l_delay_in_ns = std::max( static_cast<uint64_t>(mss::DELAY_10NS), mss::cycles_to_ns(i_target, DELAY_5TCK) ); uint64_t l_delay_in_cycles = mss::ns_to_cycles(i_target, l_delay_in_ns); // Set our delay (for HW and SIM) FAPI_TRY( fapi2::delay(l_delay_in_ns, mss::cycles_to_simcycles(l_delay_in_cycles)) ); } // Also a Deselect command must be registered as required from the Spec. // Register DES instruction, which pulls CKE high. Idle 400 cycles, and then begin RCD loading // Note: This only is sent to one of the MCA as we still have the mux_addr_sel bit set, meaning // we'll PDE/DES all DIMM at the same time. l_des.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES, MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(400); l_program.iv_instructions.push_back(l_des); FAPI_TRY( mss::ccs::execute(i_target, l_program, l_mca[0]) ); // Per conversation with Shelton and Steve 10/9/15, turn off addr_mux_sel after the CKE CCS but // before the RCD/MRS CCSs for (const auto& p : l_mca) { FAPI_TRY( change_addr_mux_sel(p, mss::LOW) ); } // Load RCD control words FAPI_TRY( mss::rcd_load(i_target) ); // Load data buffer control words (BCW) FAPI_TRY( mss::bcw_load(i_target) ); // Register has been configured, so we can unmask 'training' errors which includes parity // which we want to see during MRS load FAPI_TRY( mss::unmask_training_errors(i_target) ); // Load MRS FAPI_TRY( mss::mrs_load(i_target) ); fapi_try_exit: FAPI_INF("End draminit: %s (0x%lx)", mss::c_str(i_target), uint64_t(fapi2::current_err)); return fapi2::current_err; } } <commit_msg>Add Memory Subsystem FIR support<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_draminit.C /// @brief Initialize dram /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <mss.H> #include <p9_mss_draminit.H> #include <lib/utils/count_dimm.H> #include <lib/utils/conversions.H> #include <lib/dimm/bcw_load.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; using fapi2::FAPI2_RC_SUCCESS; extern "C" { /// /// @brief Initialize dram /// @param[in] i_target, the McBIST of the ports of the dram you're initializing /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_draminit( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { fapi2::buffer<uint64_t> l_data; mss::ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst; mss::ccs::instruction_t<TARGET_TYPE_MCBIST> l_des = mss::ccs::des_command<TARGET_TYPE_MCBIST>(); mss::ccs::program<TARGET_TYPE_MCBIST> l_program; // Up, down P down, up N. Somewhat magic numbers - came from Centaur and proven to be the // same on Nimbus. Why these are what they are might be lost to time ... constexpr uint64_t PCLK_INITIAL_VALUE = 0b10; constexpr uint64_t NCLK_INITIAL_VALUE = 0b01; const auto l_mca = mss::find_targets<TARGET_TYPE_MCA>(i_target); FAPI_INF("Start draminit: %s", mss::c_str(i_target)); // If we don't have any ports, lets go. if (l_mca.size() == 0) { FAPI_INF("++++ No ports? %s ++++", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } // If we don't have any DIMM, lets go. if (mss::count_dimm(i_target) == 0) { FAPI_INF("++++ NO DIMM on %s ++++", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } // Configure the CCS engine. Since this is a chunk of MCBIST logic, we don't want // to do it for every port. If we ever break this code out so f/w can call draminit // per-port (separate threads) we'll need to provide them a way to set this up before // sapwning per-port threads. { fapi2::buffer<uint64_t> l_ccs_config; FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) ); // It's unclear if we want to run with this true or false. Right now (10/15) this // has to be false. Shelton was unclear if this should be on or off in general BRS mss::ccs::stop_on_err(i_target, l_ccs_config, mss::LOW); mss::ccs::ue_disable(i_target, l_ccs_config, mss::LOW); mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, mss::HIGH); mss::ccs::parity_after_cmd(i_target, l_ccs_config, mss::HIGH); FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) ); } // We initialize dram by iterating over the (ungarded) ports. We could allow the caller // to initialize each port's dram on a separate thread if we could synchronize access // to the MCBIST (CCS engine.) Right now we can't, so we'll do it this way. // // We expect to come in to draminit with the following setup: // 1. ENABLE_RESET_N (FARB5Q(6)) 0 // 2. RESET_N (FARB5Q(4)) 0 - driving reset // 3. CCS_ADDR_MUX_SEL (FARB5Q(5)) - 1 // 4. CKE out of high impedence // for (const auto& p : l_mca) { FAPI_TRY( mss::draminit_entry_invariant(p) ); FAPI_TRY( mss::ddr_resetn(p, mss::HIGH) ); // Begin driving mem clks, and wait 10ns (we'll do this outside the loop) FAPI_TRY( mss::drive_mem_clks(p, PCLK_INITIAL_VALUE, NCLK_INITIAL_VALUE) ); } // From the DDR4 JEDEC Spec (79-A): Power-up Initialization Sequence // Lets find our max delay in ns { // Clocks (CK_t,CK_c) need to be started and stable for 10ns or 5tCK // (whichever is greater) before CKE goes active. constexpr uint64_t DELAY_5TCK = 5; const uint64_t l_delay_in_ns = std::max( static_cast<uint64_t>(mss::DELAY_10NS), mss::cycles_to_ns(i_target, DELAY_5TCK) ); const uint64_t l_delay_in_cycles = mss::ns_to_cycles(i_target, l_delay_in_ns); // Set our delay (for HW and SIM) FAPI_TRY( fapi2::delay(l_delay_in_ns, mss::cycles_to_simcycles(l_delay_in_cycles)) ); } // Also a Deselect command must be registered as required from the Spec. // Register DES instruction, which pulls CKE high. Idle 400 cycles, and then begin RCD loading // Note: This only is sent to one of the MCA as we still have the mux_addr_sel bit set, meaning // we'll PDE/DES all DIMM at the same time. l_des.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES, MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(400); l_program.iv_instructions.push_back(l_des); FAPI_TRY( mss::ccs::execute(i_target, l_program, l_mca[0]) ); // Per conversation with Shelton and Steve 10/9/15, turn off addr_mux_sel after the CKE CCS but // before the RCD/MRS CCSs for (const auto& p : l_mca) { FAPI_TRY( change_addr_mux_sel(p, mss::LOW) ); } // Load RCD control words FAPI_TRY( mss::rcd_load(i_target) ); // Load data buffer control words (BCW) FAPI_TRY( mss::bcw_load(i_target) ); // Load MRS FAPI_TRY( mss::mrs_load(i_target) ); fapi_try_exit: FAPI_INF("End draminit: %s (0x%lx)", mss::c_str(i_target), uint64_t(fapi2::current_err)); return fapi2::current_err; } } <|endoftext|>
<commit_before>/* Copyright (C) 2007 <SWGEmu> This File is part of Core3. This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking Engine3 statically or dynamically with other modules is making a combined work based on Engine3. Thus, the terms and conditions of the GNU Lesser General Public License cover the whole combination. In addition, as a special exception, the copyright holders of Engine3 give you permission to combine Engine3 program with free software programs or libraries that are released under the GNU LGPL and with code included in the standard release of Core3 under the GNU LGPL license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU LGPL for Engine3 and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU LGPL requires distribution of source code. Note that people who make modified versions of Engine3 are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. */ #include "LairSpawnArea.h" #include "server/zone/objects/scene/SceneObject.h" #include "server/zone/managers/creature/LairSpawnGroup.h" #include "server/zone/managers/creature/CreatureManager.h" #include "server/zone/managers/creature/CreatureTemplateManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "SpawnObserver.h" #include "server/zone/managers/terrain/TerrainManager.h" #include "server/zone/managers/collision/CollisionManager.h" #include "events/RemoveNoSpawnAreaTask.h" #include "server/ServerCore.h" #include "server/zone/templates/mobile/LairTemplate.h" void LairSpawnAreaImplementation::notifyEnter(SceneObject* object) { if (!object->isPlayerCreature()) return; ManagedReference<SceneObject*> parent = object->getParent(); if (parent != NULL && parent->isCellObject()) return; if (object->getCityRegion() != NULL) return; trySpawnLair(object); } int LairSpawnAreaImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { if (eventType != ObserverEventType::OBJECTREMOVEDFROMZONE) return 1; TangibleObject* tano = dynamic_cast<TangibleObject*>(observable); if (tano == NULL) return 1; Locker locker(_this.get()); uint32 lairTemplate = lairTypes.remove(tano->getObjectID()); if (lairTemplate != 0) { int currentSpawnCount = spawnedGroupsCount.get(lairTemplate) - 1; if (currentSpawnCount < 1) spawnedGroupsCount.remove(lairTemplate); else spawnedGroupsCount.put(lairTemplate, currentSpawnCount); --currentlySpawnedLairs; locker.release(); ManagedReference<ActiveArea*> area = cast<ActiveArea*>(ServerCore::getZoneServer()->createObject(String("object/active_area.iff").hashCode(), 0)); area->setRadius(64); area->setNoSpawnArea(true); zone->transferObject(area, -1, true); Reference<Task*> task = new RemoveNoSpawnAreaTask(area); task->schedule(300000); } //info("removing spawned lair from here", true); return 1; } LairSpawnGroup* LairSpawnAreaImplementation::getSpawnGroup() { if (spawnGroup == NULL && spawnCreatureTemplates.size() != 0) { uint32 templateGroupCRC = spawnCreatureTemplates.get(0); spawnGroup = CreatureTemplateManager::instance()->getLairGroup(templateGroupCRC); } return spawnGroup; } int LairSpawnAreaImplementation::trySpawnLair(SceneObject* object) { if (spawnGroup == NULL && spawnCreatureTemplates.size() != 0) { uint32 templateGroupCRC = spawnCreatureTemplates.get(0); spawnGroup = CreatureTemplateManager::instance()->getLairGroup(templateGroupCRC); } if (spawnGroup == NULL) { error("spawnGroup is NULL"); return 1; } Vector<Reference<LairSpawn*> >* lairs = spawnGroup->getLairList(); int totalSize = lairs->size(); if (totalSize == 0) { error("totalSize is NULL"); return 2; } Zone* zone = getZone(); if (zone == NULL) { error("zone is NULL"); return 3; } if (currentlySpawnedLairs >= spawnGroup->getMaxSpawnLimit()) return 4; if (lastSpawn.miliDifference() < MINSPAWNINTERVAL) return 5; ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager(); Vector3 randomPosition = getRandomPosition(object); if (randomPosition.getX() == 0 && randomPosition.getY() == 0) { return 6; } float spawnZ = zone->getHeight(randomPosition.getX(), randomPosition.getY()); randomPosition.setZ(spawnZ); //lets check if we intersect with some object (buildings, etc..) if (CollisionManager::checkSphereCollision(randomPosition, 64, zone)) return 7; //dont spawn in cities SortedVector<ManagedReference<ActiveArea* > > activeAreas; zone->getInRangeActiveAreas(randomPosition.getX(), randomPosition.getY(), &activeAreas, true); for (int i = 0; i < activeAreas.size(); ++i) { ActiveArea* area = activeAreas.get(i); if (area->isRegion() || area->isMunicipalZone() || area->isNoSpawnArea()) return 8; } //check in range objects for no build radi if (!planetManager->isBuildingPermittedAt(randomPosition.getX(), randomPosition.getY(), object)) { return 9; } //Lets choose 3 random spawns; LairSpawn* firstSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* secondSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* thirdSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* finalSpawn = NULL; int totalWeights = firstSpawn->getWeighting() + secondSpawn->getWeighting() + thirdSpawn->getWeighting(); int finalChoice = System::random(totalWeights); if (finalChoice <= firstSpawn->getWeighting()) { finalSpawn = firstSpawn; } else if (finalChoice <= firstSpawn->getWeighting() + secondSpawn->getWeighting()) { finalSpawn = secondSpawn; } else { finalSpawn = thirdSpawn; } int spawnLimit = finalSpawn->getSpawnLimit(); Locker _locker(_this.get()); lastSpawn.updateToCurrentTime(); String lairTemplate = finalSpawn->getLairTemplateName(); uint32 lairHashCode = lairTemplate.hashCode(); int currentSpawnCount = spawnedGroupsCount.get(lairHashCode); if (spawnLimit != -1) { if (currentSpawnCount >= spawnLimit) return 10; } CreatureManager* creatureManager = zone->getCreatureManager(); int difficulty = System::random(finalSpawn->getMaxDifficulty() - finalSpawn->getMinDifficulty()) + finalSpawn->getMinDifficulty(); LairTemplate* lair = CreatureTemplateManager::instance()->getLairTemplate(lairHashCode); if (lair == NULL) return 12; unsigned int faction = lair->getFaction(); ManagedReference<SceneObject*> obj = creatureManager->spawnLair(lairHashCode, difficulty, randomPosition.getX(), spawnZ, randomPosition.getY(), faction); if (obj != NULL) { StringBuffer msg; msg << "lair spawned at " << obj->getPositionX() << " " << obj->getPositionY(); obj->info(msg.toString()); } else { error("could not spawn lair " + lairTemplate); return 11; } if (exitObserver == NULL) { exitObserver = new SpawnObserver(_this.get()); exitObserver->deploy(); } lairTypes.put(obj->getObjectID(), lairHashCode); Locker objLocker(obj); obj->registerObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, exitObserver); ++currentlySpawnedLairs; spawnedGroupsCount.put(lairTemplate.hashCode(), currentSpawnCount); return 0; } void LairSpawnAreaImplementation::notifyPositionUpdate(QuadTreeEntry* obj) { CreatureObject* creature = dynamic_cast<CreatureObject*>(obj); if (creature == NULL) return; if (!creature->isPlayerCreature()) return; ManagedReference<SceneObject*> parent = creature->getParent(); if (parent != NULL && parent->isCellObject()) return; if (System::random(25) == 1) trySpawnLair(creature); } void LairSpawnAreaImplementation::notifyExit(SceneObject* object) { } <commit_msg>(unstable) [fixed] temp no spawn lair areas position<commit_after>/* Copyright (C) 2007 <SWGEmu> This File is part of Core3. This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking Engine3 statically or dynamically with other modules is making a combined work based on Engine3. Thus, the terms and conditions of the GNU Lesser General Public License cover the whole combination. In addition, as a special exception, the copyright holders of Engine3 give you permission to combine Engine3 program with free software programs or libraries that are released under the GNU LGPL and with code included in the standard release of Core3 under the GNU LGPL license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU LGPL for Engine3 and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU LGPL requires distribution of source code. Note that people who make modified versions of Engine3 are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. */ #include "LairSpawnArea.h" #include "server/zone/objects/scene/SceneObject.h" #include "server/zone/managers/creature/LairSpawnGroup.h" #include "server/zone/managers/creature/CreatureManager.h" #include "server/zone/managers/creature/CreatureTemplateManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "SpawnObserver.h" #include "server/zone/managers/terrain/TerrainManager.h" #include "server/zone/managers/collision/CollisionManager.h" #include "events/RemoveNoSpawnAreaTask.h" #include "server/ServerCore.h" #include "server/zone/templates/mobile/LairTemplate.h" void LairSpawnAreaImplementation::notifyEnter(SceneObject* object) { if (!object->isPlayerCreature()) return; ManagedReference<SceneObject*> parent = object->getParent(); if (parent != NULL && parent->isCellObject()) return; if (object->getCityRegion() != NULL) return; trySpawnLair(object); } int LairSpawnAreaImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { if (eventType != ObserverEventType::OBJECTREMOVEDFROMZONE) return 1; TangibleObject* tano = dynamic_cast<TangibleObject*>(observable); if (tano == NULL) return 1; Locker locker(_this.get()); uint32 lairTemplate = lairTypes.remove(tano->getObjectID()); if (lairTemplate != 0) { int currentSpawnCount = spawnedGroupsCount.get(lairTemplate) - 1; if (currentSpawnCount < 1) spawnedGroupsCount.remove(lairTemplate); else spawnedGroupsCount.put(lairTemplate, currentSpawnCount); --currentlySpawnedLairs; locker.release(); ManagedReference<ActiveArea*> area = cast<ActiveArea*>(ServerCore::getZoneServer()->createObject(String("object/active_area.iff").hashCode(), 0)); area->setRadius(64); area->setNoSpawnArea(true); area->initializePosition(tano->getPositionX(), tano->getPositionZ(), tano->getPositionZ()); zone->transferObject(area, -1, true); Reference<Task*> task = new RemoveNoSpawnAreaTask(area); task->schedule(300000); } //info("removing spawned lair from here", true); return 1; } LairSpawnGroup* LairSpawnAreaImplementation::getSpawnGroup() { if (spawnGroup == NULL && spawnCreatureTemplates.size() != 0) { uint32 templateGroupCRC = spawnCreatureTemplates.get(0); spawnGroup = CreatureTemplateManager::instance()->getLairGroup(templateGroupCRC); } return spawnGroup; } int LairSpawnAreaImplementation::trySpawnLair(SceneObject* object) { if (spawnGroup == NULL && spawnCreatureTemplates.size() != 0) { uint32 templateGroupCRC = spawnCreatureTemplates.get(0); spawnGroup = CreatureTemplateManager::instance()->getLairGroup(templateGroupCRC); } if (spawnGroup == NULL) { error("spawnGroup is NULL"); return 1; } Vector<Reference<LairSpawn*> >* lairs = spawnGroup->getLairList(); int totalSize = lairs->size(); if (totalSize == 0) { error("totalSize is NULL"); return 2; } Zone* zone = getZone(); if (zone == NULL) { error("zone is NULL"); return 3; } if (currentlySpawnedLairs >= spawnGroup->getMaxSpawnLimit()) return 4; if (lastSpawn.miliDifference() < MINSPAWNINTERVAL) return 5; ManagedReference<PlanetManager*> planetManager = zone->getPlanetManager(); Vector3 randomPosition = getRandomPosition(object); if (randomPosition.getX() == 0 && randomPosition.getY() == 0) { return 6; } float spawnZ = zone->getHeight(randomPosition.getX(), randomPosition.getY()); randomPosition.setZ(spawnZ); //lets check if we intersect with some object (buildings, etc..) if (CollisionManager::checkSphereCollision(randomPosition, 64, zone)) return 7; //dont spawn in cities SortedVector<ManagedReference<ActiveArea* > > activeAreas; zone->getInRangeActiveAreas(randomPosition.getX(), randomPosition.getY(), &activeAreas, true); for (int i = 0; i < activeAreas.size(); ++i) { ActiveArea* area = activeAreas.get(i); if (area->isRegion() || area->isMunicipalZone() || area->isNoSpawnArea()) return 8; } //check in range objects for no build radi if (!planetManager->isBuildingPermittedAt(randomPosition.getX(), randomPosition.getY(), object)) { return 9; } //Lets choose 3 random spawns; LairSpawn* firstSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* secondSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* thirdSpawn = lairs->get(System::random(totalSize - 1)); LairSpawn* finalSpawn = NULL; int totalWeights = firstSpawn->getWeighting() + secondSpawn->getWeighting() + thirdSpawn->getWeighting(); int finalChoice = System::random(totalWeights); if (finalChoice <= firstSpawn->getWeighting()) { finalSpawn = firstSpawn; } else if (finalChoice <= firstSpawn->getWeighting() + secondSpawn->getWeighting()) { finalSpawn = secondSpawn; } else { finalSpawn = thirdSpawn; } int spawnLimit = finalSpawn->getSpawnLimit(); Locker _locker(_this.get()); lastSpawn.updateToCurrentTime(); String lairTemplate = finalSpawn->getLairTemplateName(); uint32 lairHashCode = lairTemplate.hashCode(); int currentSpawnCount = spawnedGroupsCount.get(lairHashCode); if (spawnLimit != -1) { if (currentSpawnCount >= spawnLimit) return 10; } CreatureManager* creatureManager = zone->getCreatureManager(); int difficulty = System::random(finalSpawn->getMaxDifficulty() - finalSpawn->getMinDifficulty()) + finalSpawn->getMinDifficulty(); LairTemplate* lair = CreatureTemplateManager::instance()->getLairTemplate(lairHashCode); if (lair == NULL) return 12; unsigned int faction = lair->getFaction(); ManagedReference<SceneObject*> obj = creatureManager->spawnLair(lairHashCode, difficulty, randomPosition.getX(), spawnZ, randomPosition.getY(), faction); if (obj != NULL) { StringBuffer msg; msg << "lair spawned at " << obj->getPositionX() << " " << obj->getPositionY(); obj->info(msg.toString()); } else { error("could not spawn lair " + lairTemplate); return 11; } if (exitObserver == NULL) { exitObserver = new SpawnObserver(_this.get()); exitObserver->deploy(); } lairTypes.put(obj->getObjectID(), lairHashCode); Locker objLocker(obj); obj->registerObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, exitObserver); ++currentlySpawnedLairs; spawnedGroupsCount.put(lairTemplate.hashCode(), currentSpawnCount); return 0; } void LairSpawnAreaImplementation::notifyPositionUpdate(QuadTreeEntry* obj) { CreatureObject* creature = dynamic_cast<CreatureObject*>(obj); if (creature == NULL) return; if (!creature->isPlayerCreature()) return; ManagedReference<SceneObject*> parent = creature->getParent(); if (parent != NULL && parent->isCellObject()) return; if (System::random(25) == 1) trySpawnLair(creature); } void LairSpawnAreaImplementation::notifyExit(SceneObject* object) { } <|endoftext|>
<commit_before>/** * @file Cosa/Cipher/RC4.hh * @version 1.0 * * @section License * Copyright (C) 2013, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * This file is part of the Arduino Che Cosa project. */ #ifndef __COSA_CIPHER_RC4_HH__ #define __COSA_CIPHER_RC4_HH__ #include "Cosa/Types.h" /** * RC4 cipher. * @section See Also * 1. http://en.wikipedia.org/wiki/RC4 * 2. http://cypherpunks.venona.com/archive/1994/09/msg00304.html */ class RC4 { private: uint8_t m_state[256]; uint8_t m_x; uint8_t m_y; public: /** * Construct RC4 cipher for given key and length. * @param[in] key pointer to key. * @param[in] len length of key in bytes. */ RC4(const void* key, size_t len) { restart(key, len); } /** * Restart the given key and length. * @param[in] key pointer to key. * @param[in] len length of key in bytes. */ void restart(const void* key, size_t len); /** * Encrypt the given character. * @param[in] c character to encode. * @return encoded character. */ char encrypt(char c) { m_y = m_y + m_state[++m_x]; uint8_t tmp = m_state[m_x]; m_state[m_x] = m_state[m_y]; m_state[m_y] = tmp; uint8_t ix = m_state[m_x] + m_state[m_y]; return (c ^ m_state[ix]); } /** * Encrypt the given buffer. * @param[in] buf buffer pointer. * @param[in] n number of bytes. */ void encrypt(void* buf, size_t n) { for (char* bp = (char*) buf; n--; bp++) *bp = encrypt(*bp); } /** * Encrypt the given src buffer to the dest buffer. * @param[in] dest buffer pointer. * @param[in] src buffer pointer. * @param[in] n number of bytes. */ void encrypt(void* dest, const void* src, size_t n) { char* dp = (char*) dest; const char* sp = (const char*) src; while (n--) *dp++ = encrypt(*sp++); } /** * Decrypt the given character. * @param[in] c character to decode. * @return decoded character. */ char decrypt(char c) { return (encrypt(c)); } /** * Decrypt the given buffer. * @param[in] buf buffer pointer. * @param[in] n number of bytes. */ void decrypt(void* buf, size_t n) { for (char* bp = (char*) buf; n--; bp++) *bp = decrypt(*bp); } /** * Decrypt the given src buffer to the dest buffer. * @param[in] dest buffer pointer. * @param[in] src buffer pointer. * @param[in] n number of bytes. */ void decrypt(void* dest, const void* src, size_t n) { char* dp = (char*) dest; const char* sp = (const char*) src; while (n--) *dp++ = decrypt(*sp++); } }; #endif <commit_msg>Remove a few instructions in RC4::encrypt(). Down to 2,1 us per byte.<commit_after>/** * @file Cosa/Cipher/RC4.hh * @version 1.0 * * @section License * Copyright (C) 2013, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * This file is part of the Arduino Che Cosa project. */ #ifndef __COSA_CIPHER_RC4_HH__ #define __COSA_CIPHER_RC4_HH__ #include "Cosa/Types.h" /** * RC4 cipher. * @section See Also * 1. http://en.wikipedia.org/wiki/RC4 * 2. http://cypherpunks.venona.com/archive/1994/09/msg00304.html */ class RC4 { private: uint8_t m_state[256]; uint8_t m_x; uint8_t m_y; public: /** * Construct RC4 cipher for given key and length. * @param[in] key pointer to key. * @param[in] len length of key in bytes. */ RC4(const void* key, size_t len) { restart(key, len); } /** * Restart the given key and length. * @param[in] key pointer to key. * @param[in] len length of key in bytes. */ void restart(const void* key, size_t len); /** * Encrypt the given character. * @param[in] c character to encode. * @return encoded character. */ char encrypt(char c) { m_x += 1; uint8_t sx = m_state[m_x]; m_y += sx; uint8_t sy = m_state[m_y]; m_state[m_x] = sy; m_state[m_y] = sx; uint8_t ix = sx + sy; return (c ^ m_state[ix]); } /** * Encrypt the given buffer. * @param[in] buf buffer pointer. * @param[in] n number of bytes. */ void encrypt(void* buf, size_t n) { for (char* bp = (char*) buf; n--; bp++) *bp = encrypt(*bp); } /** * Encrypt the given src buffer to the dest buffer. * @param[in] dest buffer pointer. * @param[in] src buffer pointer. * @param[in] n number of bytes. */ void encrypt(void* dest, const void* src, size_t n) { char* dp = (char*) dest; const char* sp = (const char*) src; while (n--) *dp++ = encrypt(*sp++); } /** * Decrypt the given character. * @param[in] c character to decode. * @return decoded character. */ char decrypt(char c) { return (encrypt(c)); } /** * Decrypt the given buffer. * @param[in] buf buffer pointer. * @param[in] n number of bytes. */ void decrypt(void* buf, size_t n) { for (char* bp = (char*) buf; n--; bp++) *bp = decrypt(*bp); } /** * Decrypt the given src buffer to the dest buffer. * @param[in] dest buffer pointer. * @param[in] src buffer pointer. * @param[in] n number of bytes. */ void decrypt(void* dest, const void* src, size_t n) { char* dp = (char*) dest; const char* sp = (const char*) src; while (n--) *dp++ = decrypt(*sp++); } }; #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 <stdio.h> #include <dlfcn.h> #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 #include <cxxabi.h> #else #include <typeinfo> #endif #include <boost/unordered_map.hpp> #include <rtl/instance.hxx> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <com/sun/star/uno/genfunc.hxx> #include "com/sun/star/uno/RuntimeException.hpp" #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 using namespace ::__cxxabiv1; #endif namespace CPPU_CURRENT_NAMESPACE { #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 // MacOSX10.4u.sdk/usr/include/c++/4.0.0/cxxabi.h defined // __cxxabiv1::__class_type_info and __cxxabiv1::__si_class_type_info but // MacOSX10.7.sdk/usr/include/cxxabi.h no longer does, so instances of those // classes need to be created manually: // std::type_info defined in <typeinfo> offers a protected ctor: struct FAKE_type_info: public std::type_info { FAKE_type_info(char const * name): type_info(name) {} }; // Modeled after __cxxabiv1::__si_class_type_info defined in // MacOSX10.4u.sdk/usr/include/c++/4.0.0/cxxabi.h (i.e., // abi::__si_class_type_info documented at // <http://www.codesourcery.com/public/cxx-abi/abi.html#rtti>): struct FAKE_si_class_type_info: public FAKE_type_info { FAKE_si_class_type_info(char const * name, std::type_info const * theBase): FAKE_type_info(name), base(theBase) {} std::type_info const * base; // actually a __cxxabiv1::__class_type_info pointer }; struct Base {}; struct Derived: Base {}; std::type_info * create_FAKE_class_type_info(char const * name) { std::type_info * p = new FAKE_type_info(name); // cxxabiv1::__class_type_info has no data members in addition to // std::type_info *reinterpret_cast< void ** >(p) = *reinterpret_cast< void * const * >( &typeid(Base)); // copy correct __cxxabiv1::__class_type_info vtable into place return p; } std::type_info * create_FAKE_si_class_type_info( char const * name, std::type_info const * base) { std::type_info * p = new FAKE_si_class_type_info(name, base); *reinterpret_cast< void ** >(p) = *reinterpret_cast< void * const * >( &typeid(Derived)); // copy correct __cxxabiv1::__si_class_type_info vtable into place return p; } #endif void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW(()) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef boost::unordered_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW(()); ~RTTI() SAL_THROW(()); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW(()); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW(()) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW(()) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW(()) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind2( m_generatedRttis.find( unoName ) ); if (iFind2 == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI char const * rttiName = symName.getStr() +4; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); #else rtti = create_FAKE_si_class_type_info( strdup( rttiName ), base_rtti ); #endif } else { // this class has no base class #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 rtti = new __class_type_info( strdup( rttiName ) ); #else rtti = create_FAKE_class_type_info( strdup( rttiName ) ); #endif } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" ); } else // taking already generated rtti { rtti = iFind2->second; } } } else { rtti = iFind->second; } return rtti; } struct RTTISingleton: public rtl::Static< RTTI, RTTISingleton > {}; //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { #if OSL_DEBUG_LEVEL > 1 OString cstr( OUStringToOString( *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> uno exception occurred: %s\n", cstr.getStr() ); #endif void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); rtti = (type_info *)RTTISingleton::get().getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno ) { if (! header) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ), Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_FAIL( cstr.getStr() ); #endif return; } typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); #if OSL_DEBUG_LEVEL > 1 OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> c++ exception occurred: %s\n", cstr_unoName.getStr() ); #endif typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); if (0 == pExcTypeDescr) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName, Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_FAIL( cstr.getStr() ); #endif } else { // construct uno exception any uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); typelib_typedescription_release( pExcTypeDescr ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>WaE: unused variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 <stdio.h> #include <dlfcn.h> #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 #include <cxxabi.h> #else #include <typeinfo> #endif #include <boost/unordered_map.hpp> #include <rtl/instance.hxx> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <com/sun/star/uno/genfunc.hxx> #include "com/sun/star/uno/RuntimeException.hpp" #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 using namespace ::__cxxabiv1; #endif namespace CPPU_CURRENT_NAMESPACE { #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 // MacOSX10.4u.sdk/usr/include/c++/4.0.0/cxxabi.h defined // __cxxabiv1::__class_type_info and __cxxabiv1::__si_class_type_info but // MacOSX10.7.sdk/usr/include/cxxabi.h no longer does, so instances of those // classes need to be created manually: // std::type_info defined in <typeinfo> offers a protected ctor: struct FAKE_type_info: public std::type_info { FAKE_type_info(char const * name): type_info(name) {} }; // Modeled after __cxxabiv1::__si_class_type_info defined in // MacOSX10.4u.sdk/usr/include/c++/4.0.0/cxxabi.h (i.e., // abi::__si_class_type_info documented at // <http://www.codesourcery.com/public/cxx-abi/abi.html#rtti>): struct FAKE_si_class_type_info: public FAKE_type_info { FAKE_si_class_type_info(char const * name, std::type_info const * theBase): FAKE_type_info(name), base(theBase) {} std::type_info const * base; // actually a __cxxabiv1::__class_type_info pointer }; struct Base {}; struct Derived: Base {}; std::type_info * create_FAKE_class_type_info(char const * name) { std::type_info * p = new FAKE_type_info(name); // cxxabiv1::__class_type_info has no data members in addition to // std::type_info *reinterpret_cast< void ** >(p) = *reinterpret_cast< void * const * >( &typeid(Base)); // copy correct __cxxabiv1::__class_type_info vtable into place return p; } std::type_info * create_FAKE_si_class_type_info( char const * name, std::type_info const * base) { std::type_info * p = new FAKE_si_class_type_info(name, base); *reinterpret_cast< void ** >(p) = *reinterpret_cast< void * const * >( &typeid(Derived)); // copy correct __cxxabiv1::__si_class_type_info vtable into place return p; } #endif void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW(()) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef boost::unordered_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW(()); ~RTTI() SAL_THROW(()); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW(()); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW(()) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW(()) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW(()) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); SAL_WARN_IF( !insertion.second, "bridges", "inserting new rtti failed" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind2( m_generatedRttis.find( unoName ) ); if (iFind2 == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI char const * rttiName = symName.getStr() +4; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); #else rtti = create_FAKE_si_class_type_info( strdup( rttiName ), base_rtti ); #endif } else { // this class has no base class #if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 rtti = new __class_type_info( strdup( rttiName ) ); #else rtti = create_FAKE_class_type_info( strdup( rttiName ) ); #endif } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); SAL_WARN_IF( !insertion.second, "bridges", "inserting new generated rtti failed" ); } else // taking already generated rtti { rtti = iFind2->second; } } } else { rtti = iFind->second; } return rtti; } struct RTTISingleton: public rtl::Static< RTTI, RTTISingleton > {}; //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { #if OSL_DEBUG_LEVEL > 1 OString cstr( OUStringToOString( *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> uno exception occurred: %s\n", cstr.getStr() ); #endif void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); rtti = (type_info *)RTTISingleton::get().getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) { throw RuntimeException( OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) + *reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ), Reference< XInterface >() ); } } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno ) { if (! header) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ), Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_FAIL( cstr.getStr() ); #endif return; } typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); #if OSL_DEBUG_LEVEL > 1 OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> c++ exception occurred: %s\n", cstr_unoName.getStr() ); #endif typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); if (0 == pExcTypeDescr) { RuntimeException aRE( OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName, Reference< XInterface >() ); Type const & rType = ::getCppuType( &aRE ); uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno ); #if OSL_DEBUG_LEVEL > 0 OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_FAIL( cstr.getStr() ); #endif } else { // construct uno exception any uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); typelib_typedescription_release( pExcTypeDescr ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "libs/catch/catch.hpp" #include "libs/exceptionpp/exception.h" #include <iostream> #include "src/file.h" TEST_CASE("giga|config-probe") { giga::Config c = giga::Config(100, 200); std::shared_ptr<giga::Page> p (new giga::Page(1, "", 0, 100, false)); REQUIRE(c.probe(p, 0, 1000) == 200); REQUIRE(c.probe(p, 0, 10) == 10); REQUIRE(c.probe(p, 10, 10) == 10); REQUIRE(c.probe(p, 10, 90) == 90); REQUIRE(c.probe(p, 10, 1000) == 190); REQUIRE(c.probe(p, 100, 1000) == 100); REQUIRE(c.probe(p, 100, 10) == 10); REQUIRE(c.probe(p, 100, 0) == 0); } TEST_CASE("giga|file") { REQUIRE_THROWS_AS(giga::File("tests/files/nonexistent", "r"), exceptionpp::InvalidOperation); giga::File f = giga::File("tests/files/foo", "r", giga::Config(3, 4)); REQUIRE(f.get_filename().compare("tests/files/foo") == 0); REQUIRE(f.get_mode().compare("r") == 0); } TEST_CASE("giga|file-open") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r")); std::shared_ptr<giga::Client> c = f->open(); REQUIRE(c->get_pos() == 0); c->close(); } TEST_CASE("giga|file-seek") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 2))); std::shared_ptr<giga::Client> c = f->open(); REQUIRE(f->get_size() == 13); REQUIRE(c->seek(2, true) == 2); REQUIRE(c->seek(1, false) == 1); REQUIRE(c->seek(1, false) == 0); REQUIRE(c->seek(9, true) == 9); REQUIRE(c->seek(3, false) == 6); REQUIRE(c->seek(100, true) == 13); REQUIRE(c->seek(100, false) == 0); REQUIRE(c->seek(100, true) == 13); c->close(); } TEST_CASE("giga|file-read") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 2))); std::shared_ptr<giga::Client> c = f->open(); REQUIRE(c->read(0).compare("") == 0); REQUIRE(c->read(1).compare("h") == 0); REQUIRE(c->read(2).compare("el") == 0); REQUIRE(c->read(100).compare("lo world!\n") == 0); c->close(); } TEST_CASE("giga|file-erase") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 5))); std::shared_ptr<giga::Client> c_1 = f->open(); std::shared_ptr<giga::Client> c_2 = f->open(); REQUIRE(c_2->seek(1, true) == 1); REQUIRE(c_2->erase(1) == 1); REQUIRE(f->get_size() == 12); REQUIRE(c_1->get_pos() == 0); REQUIRE(c_2->get_pos() == 1); REQUIRE(c_1->read(100).compare("hllo world!\n") == 0); REQUIRE(c_2->read(100).compare("llo world!\n") == 0); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_1->seek(1, true) == 1); REQUIRE(c_2->seek(2, true) == 2); REQUIRE(c_1->get_pos() == 1); REQUIRE(c_2->get_pos() == 2); REQUIRE(c_1->erase(1) == 1); REQUIRE(f->get_size() == 11); REQUIRE(c_1->get_pos() == 1); REQUIRE(c_2->get_pos() == 1); REQUIRE(c_1->read(100).compare("lo world!\n") == 0); REQUIRE(c_2->read(100).compare("lo world!\n") == 0); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_2->read(100).compare("hlo world!\n") == 0); REQUIRE(c_1->read(100).compare("hlo world!\n") == 0); c_1->close(); c_2->close(); f.reset(); f = std::shared_ptr<giga::File> (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 5))); c_1 = f->open(); c_2 = f->open(); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_2->seek(2, true) == 2); REQUIRE(c_1->erase(2) == 2); REQUIRE(c_1->get_pos() == 0); REQUIRE(c_2->get_pos() == 0); REQUIRE(c_1->read(100).compare("llo world!\n") == 0); REQUIRE(c_2->read(100).compare("llo world!\n") == 0); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_2->seek(3, true) == 3); REQUIRE(c_1->erase(2) == 2); REQUIRE(c_1->get_pos() == 0); REQUIRE(c_2->get_pos() == 1); REQUIRE(c_1->read(100).compare("o world!\n") == 0); REQUIRE(c_2->read(100).compare(" world!\n") == 0); REQUIRE(c_1->erase(100) == 0); REQUIRE(c_1->seek(100, false) == 0); std::cout << "REQUIRE(c_1->erase(100))" << std::endl; REQUIRE(c_1->erase(100) == 8); REQUIRE(c_1->read(100).compare("") == 0); REQUIRE(c_2->read(100).compare("") == 0); // REQUIRE(f->get_size() == 0); // REQUIRE(c_1->get_pos() == 0); // REQUIRE(c_2->get_pos() == 0); c_1->close(); c_2->close(); } TEST_CASE("giga|file-insert") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 3))); std::shared_ptr<giga::Client> c_1 = f->open(); std::shared_ptr<giga::Client> c_2 = f->open(); REQUIRE(c_1->seek(1, true) == 1); REQUIRE(f->get_size() == 13); REQUIRE(c_2->write("foo", true) == 3); REQUIRE(f->get_size() == 16); REQUIRE(c_2->get_pos() == 3); REQUIRE(c_1->get_pos() == 4); REQUIRE(c_1->read(100).compare("ello world!\n") == 0); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_1->seek(1, true) == 1); REQUIRE(c_1->write("foo", true) == 3); REQUIRE(f->get_size() == 19); REQUIRE(c_2->get_pos() == 0); REQUIRE(c_2->read(100).compare("ffoooohello world!\n") == 0); REQUIRE(c_2->write("addendum") == 8); REQUIRE(f->get_size() == 27); REQUIRE(c_1->read(100).compare("oohello world!\naddendum") == 0); c_1->close(); c_2->close(); } TEST_CASE("giga|file-write") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 3))); std::shared_ptr<giga::Client> c = f->open(); REQUIRE(c->write("") == 0); REQUIRE(c->get_pos() == 0); REQUIRE(c->write("abcde") == 5); REQUIRE(c->get_pos() == 5); REQUIRE(c->write("|world!\nEXTRAEXTRA") == 18); REQUIRE(f->get_size() == 23); REQUIRE(c->get_pos() == 23); REQUIRE(c->seek(100, false) == 0); REQUIRE(c->read(100).compare("abcde|world!\nEXTRAEXTRA") == 0); c->close(); } <commit_msg>added more tests<commit_after>#include "libs/catch/catch.hpp" #include "libs/exceptionpp/exception.h" #include <iostream> #include "src/file.h" TEST_CASE("giga|config-probe") { giga::Config c = giga::Config(100, 200); std::shared_ptr<giga::Page> p (new giga::Page(1, "", 0, 100, false)); REQUIRE(c.probe(p, 0, 1000) == 200); REQUIRE(c.probe(p, 0, 10) == 10); REQUIRE(c.probe(p, 10, 10) == 10); REQUIRE(c.probe(p, 10, 90) == 90); REQUIRE(c.probe(p, 10, 1000) == 190); REQUIRE(c.probe(p, 100, 1000) == 100); REQUIRE(c.probe(p, 100, 10) == 10); REQUIRE(c.probe(p, 100, 0) == 0); } TEST_CASE("giga|file") { REQUIRE_THROWS_AS(giga::File("tests/files/nonexistent", "r"), exceptionpp::InvalidOperation); giga::File f = giga::File("tests/files/foo", "r", giga::Config(3, 4)); REQUIRE(f.get_filename().compare("tests/files/foo") == 0); REQUIRE(f.get_mode().compare("r") == 0); } TEST_CASE("giga|file-open") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r")); std::shared_ptr<giga::Client> c = f->open(); REQUIRE(c->get_pos() == 0); c->close(); } TEST_CASE("giga|file-seek") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 2))); std::shared_ptr<giga::Client> c = f->open(); REQUIRE(f->get_size() == 13); REQUIRE(c->seek(2, true) == 2); REQUIRE(c->seek(1, false) == 1); REQUIRE(c->seek(1, false) == 0); REQUIRE(c->seek(9, true) == 9); REQUIRE(c->seek(3, false) == 6); REQUIRE(c->seek(100, true) == 13); REQUIRE(c->seek(100, false) == 0); REQUIRE(c->seek(100, true) == 13); c->close(); } TEST_CASE("giga|file-read") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 2))); std::shared_ptr<giga::Client> c = f->open(); REQUIRE(c->read(0).compare("") == 0); REQUIRE(c->read(1).compare("h") == 0); REQUIRE(c->read(2).compare("el") == 0); REQUIRE(c->read(100).compare("lo world!\n") == 0); c->close(); } TEST_CASE("giga|file-erase") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 5))); std::shared_ptr<giga::Client> c_1 = f->open(); std::shared_ptr<giga::Client> c_2 = f->open(); REQUIRE(c_2->seek(1, true) == 1); REQUIRE(c_2->erase(1) == 1); REQUIRE(f->get_size() == 12); REQUIRE(c_1->get_pos() == 0); REQUIRE(c_2->get_pos() == 1); REQUIRE(c_1->read(100).compare("hllo world!\n") == 0); REQUIRE(c_2->read(100).compare("llo world!\n") == 0); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_1->seek(1, true) == 1); REQUIRE(c_2->seek(2, true) == 2); REQUIRE(c_1->get_pos() == 1); REQUIRE(c_2->get_pos() == 2); REQUIRE(c_1->erase(1) == 1); REQUIRE(f->get_size() == 11); REQUIRE(c_1->get_pos() == 1); REQUIRE(c_2->get_pos() == 1); REQUIRE(c_1->read(100).compare("lo world!\n") == 0); REQUIRE(c_2->read(100).compare("lo world!\n") == 0); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_2->read(100).compare("hlo world!\n") == 0); REQUIRE(c_1->read(100).compare("hlo world!\n") == 0); c_1->close(); c_2->close(); f.reset(); f = std::shared_ptr<giga::File> (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 5))); c_1 = f->open(); c_2 = f->open(); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_2->seek(2, true) == 2); REQUIRE(c_1->erase(2) == 2); REQUIRE(c_1->get_pos() == 0); REQUIRE(c_2->get_pos() == 0); REQUIRE(c_1->read(100).compare("llo world!\n") == 0); REQUIRE(c_2->read(100).compare("llo world!\n") == 0); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_2->seek(3, true) == 3); REQUIRE(c_1->erase(2) == 2); REQUIRE(c_1->get_pos() == 0); REQUIRE(c_2->get_pos() == 1); REQUIRE(c_1->read(100).compare("o world!\n") == 0); REQUIRE(c_2->read(100).compare(" world!\n") == 0); REQUIRE(c_1->erase(100) == 0); REQUIRE(c_1->seek(100, false) == 0); std::cout << "REQUIRE(c_1->erase(100))" << std::endl; REQUIRE(c_1->erase(100) == 8); REQUIRE(c_1->read(100).compare("") == 0); REQUIRE(c_2->read(100).compare("") == 0); REQUIRE(f->get_size() == 0); REQUIRE(c_1->get_pos() == 0); REQUIRE(c_2->get_pos() == 0); c_1->close(); c_2->close(); } TEST_CASE("giga|file-insert") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 3))); std::shared_ptr<giga::Client> c_1 = f->open(); std::shared_ptr<giga::Client> c_2 = f->open(); REQUIRE(c_1->seek(1, true) == 1); REQUIRE(f->get_size() == 13); REQUIRE(c_2->write("foo", true) == 3); REQUIRE(f->get_size() == 16); REQUIRE(c_2->get_pos() == 3); REQUIRE(c_1->get_pos() == 4); REQUIRE(c_1->read(100).compare("ello world!\n") == 0); REQUIRE(c_1->seek(100, false) == 0); REQUIRE(c_2->seek(100, false) == 0); REQUIRE(c_1->seek(1, true) == 1); REQUIRE(c_1->write("foo", true) == 3); REQUIRE(f->get_size() == 19); REQUIRE(c_2->get_pos() == 0); REQUIRE(c_2->read(100).compare("ffoooohello world!\n") == 0); REQUIRE(c_2->write("addendum") == 8); REQUIRE(f->get_size() == 27); REQUIRE(c_1->read(100).compare("oohello world!\naddendum") == 0); c_1->close(); c_2->close(); } TEST_CASE("giga|file-write") { std::shared_ptr<giga::File> f (new giga::File("tests/files/giga-file-read", "r", giga::Config(2, 3))); std::shared_ptr<giga::Client> c = f->open(); REQUIRE(c->write("") == 0); REQUIRE(c->get_pos() == 0); REQUIRE(c->write("abcde") == 5); REQUIRE(c->get_pos() == 5); REQUIRE(c->write("|world!\nEXTRAEXTRA") == 18); REQUIRE(f->get_size() == 23); REQUIRE(c->get_pos() == 23); REQUIRE(c->seek(100, false) == 0); REQUIRE(c->read(100).compare("abcde|world!\nEXTRAEXTRA") == 0); c->close(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <iostream> #include <map> #include <rtl/string.hxx> #include "po.hxx" // Translated style names must be unique static void checkStyleNames(OString aLanguage) { std::map<OString,sal_uInt16> aLocalizedStyleNames; std::map<OString,sal_uInt16> aLocalizedNumStyleNames; OString aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/sw/source/ui/utlui.po"; PoIfstream aPoInput; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getSourceFile() == "poolfmt.src" && aPoEntry.getGroupId().startsWith("STR_POOLCOLL") ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedStyleNames.find(aMsgStr) == aLocalizedStyleNames.end() ) aLocalizedStyleNames[aMsgStr] = 1; else aLocalizedStyleNames[aMsgStr]++; } if( !aPoEntry.isFuzzy() && aPoEntry.getSourceFile() == "poolfmt.src" && aPoEntry.getGroupId().startsWith("STR_POOLNUMRULE") ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedNumStyleNames.find(aMsgStr) == aLocalizedNumStyleNames.end() ) aLocalizedNumStyleNames[aMsgStr] = 1; else aLocalizedNumStyleNames[aMsgStr]++; } } aPoInput.close(); for( std::map<OString,sal_uInt16>::iterator it=aLocalizedStyleNames.begin(); it!=aLocalizedStyleNames.end(); ++it) { if( it->second > 1 ) { std::cout << "ERROR: Style name translations must be unique in:\n" << aPoPath << "\nLanguage: " << aLanguage << "\nDuplicated translation is: " << it->first << "\nSee STR_POOLCOLL_*\n\n"; } } for( std::map<OString,sal_uInt16>::iterator it=aLocalizedNumStyleNames.begin(); it!=aLocalizedNumStyleNames.end(); ++it) { if( it->second > 1 ) { std::cout << "ERROR: Style name translations must be unique in:\n" << aPoPath << "\nLanguage: " << aLanguage << "\nDuplicated translation is: " << it->first << "\nSee STR_POOLNUMRULE_*\n\n"; } } } // Translated spreadsheet function names must be unique static void checkFunctionNames(OString aLanguage) { std::map<OString,sal_uInt16> aLocalizedFunctionNames; std::map<OString,sal_uInt16> aLocalizedCoreFunctionNames; OString aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/formula/source/core/resource.po"; PoIfstream aPoInput; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_STRLIST_FUNCTION_NAMES" ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedCoreFunctionNames.find(aMsgStr) == aLocalizedCoreFunctionNames.end() ) aLocalizedCoreFunctionNames[aMsgStr] = 1; if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) aLocalizedFunctionNames[aMsgStr] = 1; else aLocalizedFunctionNames[aMsgStr]++; } } aPoInput.close(); aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/scaddins/source/analysis.po"; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_ANALYSIS_FUNCTION_NAMES" ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() ) aMsgStr += "_ADD"; if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) aLocalizedFunctionNames[aMsgStr] = 1; else aLocalizedFunctionNames[aMsgStr]++; } } aPoInput.close(); aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/scaddins/source/datefunc.po"; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_DATE_FUNCTION_NAMES" ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() ) aMsgStr += "_ADD"; if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) aLocalizedFunctionNames[aMsgStr] = 1; else aLocalizedFunctionNames[aMsgStr]++; } } aPoInput.close(); aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/scaddins/source/pricing.po"; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_PRICING_FUNCTION_NAMES" ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() ) aMsgStr += "_ADD"; if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) aLocalizedFunctionNames[aMsgStr] = 1; else aLocalizedFunctionNames[aMsgStr]++; } } aPoInput.close(); for( std::map<OString,sal_uInt16>::iterator it=aLocalizedFunctionNames.begin(); it!=aLocalizedFunctionNames.end(); ++it) { if( it->second > 1 ) { std::cout << "ERROR: Spreadsheet function name translations must be unique.\n" << "Language: " << aLanguage << "\nDuplicated translation is: " << it->first << "\n\n"; } } } // In instsetoo_native/inc_openoffice/windows/msi_languages.po // where an en-US string ends with '|', translation must end // with '|', too. static void checkVerticalBar(OString aLanguage) { OString aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/instsetoo_native/inc_openoffice/windows/msi_languages.po"; PoIfstream aPoInput; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getMsgId().endsWith("|") && !aPoEntry.getMsgStr().isEmpty() && !aPoEntry.getMsgStr().endsWith("|") ) { std::cout << "ERROR: Missing '|' character at the end of translated string.\n" << "It causes runtime error in installer.\n" << "File: " << aPoPath << std::endl << "Language: " << aLanguage << std::endl << "English: " << aPoEntry.getMsgId() << std::endl << "Localized: " << aPoEntry.getMsgStr() << std::endl << std::endl; } } aPoInput.close(); } int main() { OString aLanguages(getenv("ALL_LANGS")); if( aLanguages.isEmpty() ) { std::cerr << "Usage: make cmd cmd=solver/*/bin/pocheck\n"; return 1; } for(sal_Int32 i = 1;;++i) // skip en-US { OString aLanguage = aLanguages.getToken(i,' '); if( aLanguage.isEmpty() ) break; if( aLanguage == "qtz" ) continue; checkStyleNames(aLanguage); checkFunctionNames(aLanguage); checkVerticalBar(aLanguage); } return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>pocheck: Math symbol names (from symbol.src) must not contain spaces<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <iostream> #include <map> #include <rtl/string.hxx> #include "po.hxx" // Translated style names must be unique static void checkStyleNames(OString aLanguage) { std::map<OString,sal_uInt16> aLocalizedStyleNames; std::map<OString,sal_uInt16> aLocalizedNumStyleNames; OString aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/sw/source/ui/utlui.po"; PoIfstream aPoInput; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getSourceFile() == "poolfmt.src" && aPoEntry.getGroupId().startsWith("STR_POOLCOLL") ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedStyleNames.find(aMsgStr) == aLocalizedStyleNames.end() ) aLocalizedStyleNames[aMsgStr] = 1; else aLocalizedStyleNames[aMsgStr]++; } if( !aPoEntry.isFuzzy() && aPoEntry.getSourceFile() == "poolfmt.src" && aPoEntry.getGroupId().startsWith("STR_POOLNUMRULE") ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedNumStyleNames.find(aMsgStr) == aLocalizedNumStyleNames.end() ) aLocalizedNumStyleNames[aMsgStr] = 1; else aLocalizedNumStyleNames[aMsgStr]++; } } aPoInput.close(); for( std::map<OString,sal_uInt16>::iterator it=aLocalizedStyleNames.begin(); it!=aLocalizedStyleNames.end(); ++it) { if( it->second > 1 ) { std::cout << "ERROR: Style name translations must be unique in:\n" << aPoPath << "\nLanguage: " << aLanguage << "\nDuplicated translation is: " << it->first << "\nSee STR_POOLCOLL_*\n\n"; } } for( std::map<OString,sal_uInt16>::iterator it=aLocalizedNumStyleNames.begin(); it!=aLocalizedNumStyleNames.end(); ++it) { if( it->second > 1 ) { std::cout << "ERROR: Style name translations must be unique in:\n" << aPoPath << "\nLanguage: " << aLanguage << "\nDuplicated translation is: " << it->first << "\nSee STR_POOLNUMRULE_*\n\n"; } } } // Translated spreadsheet function names must be unique static void checkFunctionNames(OString aLanguage) { std::map<OString,sal_uInt16> aLocalizedFunctionNames; std::map<OString,sal_uInt16> aLocalizedCoreFunctionNames; OString aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/formula/source/core/resource.po"; PoIfstream aPoInput; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_STRLIST_FUNCTION_NAMES" ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedCoreFunctionNames.find(aMsgStr) == aLocalizedCoreFunctionNames.end() ) aLocalizedCoreFunctionNames[aMsgStr] = 1; if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) aLocalizedFunctionNames[aMsgStr] = 1; else aLocalizedFunctionNames[aMsgStr]++; } } aPoInput.close(); aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/scaddins/source/analysis.po"; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_ANALYSIS_FUNCTION_NAMES" ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() ) aMsgStr += "_ADD"; if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) aLocalizedFunctionNames[aMsgStr] = 1; else aLocalizedFunctionNames[aMsgStr]++; } } aPoInput.close(); aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/scaddins/source/datefunc.po"; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_DATE_FUNCTION_NAMES" ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() ) aMsgStr += "_ADD"; if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) aLocalizedFunctionNames[aMsgStr] = 1; else aLocalizedFunctionNames[aMsgStr]++; } } aPoInput.close(); aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/scaddins/source/pricing.po"; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_PRICING_FUNCTION_NAMES" ) { OString aMsgStr = aPoEntry.getMsgStr(); if( aMsgStr.isEmpty() ) continue; if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() ) aMsgStr += "_ADD"; if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) aLocalizedFunctionNames[aMsgStr] = 1; else aLocalizedFunctionNames[aMsgStr]++; } } aPoInput.close(); for( std::map<OString,sal_uInt16>::iterator it=aLocalizedFunctionNames.begin(); it!=aLocalizedFunctionNames.end(); ++it) { if( it->second > 1 ) { std::cout << "ERROR: Spreadsheet function name translations must be unique.\n" << "Language: " << aLanguage << "\nDuplicated translation is: " << it->first << "\n\n"; } } } // In instsetoo_native/inc_openoffice/windows/msi_languages.po // where an en-US string ends with '|', translation must end // with '|', too. static void checkVerticalBar(OString aLanguage) { OString aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/instsetoo_native/inc_openoffice/windows/msi_languages.po"; PoIfstream aPoInput; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getMsgId().endsWith("|") && !aPoEntry.getMsgStr().isEmpty() && !aPoEntry.getMsgStr().endsWith("|") ) { std::cout << "ERROR: Missing '|' character at the end of translated string.\n" << "It causes runtime error in installer.\n" << "File: " << aPoPath << std::endl << "Language: " << aLanguage << std::endl << "English: " << aPoEntry.getMsgId() << std::endl << "Localized: " << aPoEntry.getMsgStr() << std::endl << std::endl; } } aPoInput.close(); } // In starmath/source.po Math symbol names (from symbol.src) // must not contain spaces static void checkMathSymbolNames(OString aLanguage) { OString aPoPath = OString(getenv("SRC_ROOT")) + "/translations/source/" + aLanguage + "/starmath/source.po"; PoIfstream aPoInput; aPoInput.open(aPoPath); if( !aPoInput.isOpen() ) std::cerr << "Warning: Cannot open " << aPoPath << std::endl; for(;;) { PoEntry aPoEntry; aPoInput.readEntry(aPoEntry); if( aPoInput.eof() ) break; if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == "RID_UI_SYMBOL_NAMES" && !aPoEntry.getMsgStr().isEmpty() && (aPoEntry.getMsgStr().indexOf(" ") != -1) ) { std::cout << "ERROR: Math symbol names must not contain spaces.\n" << "File: " << aPoPath << std::endl << "Language: " << aLanguage << std::endl << "English: " << aPoEntry.getMsgId() << std::endl << "Localized: " << aPoEntry.getMsgStr() << std::endl << std::endl; } } aPoInput.close(); } int main() { OString aLanguages(getenv("ALL_LANGS")); if( aLanguages.isEmpty() ) { std::cerr << "Usage: make cmd cmd=solver/*/bin/pocheck\n"; return 1; } for(sal_Int32 i = 1;;++i) // skip en-US { OString aLanguage = aLanguages.getToken(i,' '); if( aLanguage.isEmpty() ) break; if( aLanguage == "qtz" ) continue; checkStyleNames(aLanguage); checkFunctionNames(aLanguage); checkVerticalBar(aLanguage); checkMathSymbolNames(aLanguage); } return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/** \file system_monitor.cc * \brief Collect a few basic system metrics * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <csignal> #include <cstring> #include <unistd.h> #include "Compiler.h" #include "FileUtil.h" #include "IniFile.h" #include "SignalUtil.h" #include "StringUtil.h" #include "TimeUtil.h" #include "UBTools.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("[--foreground] output_filename\n" " When --foreground has been specified the program does not daemonise.\n" " The config file path is \"" + UBTools::GetTuelibPath() + FileUtil::GetBasename(::progname) + ".conf\"."); } volatile sig_atomic_t sigterm_seen = false; void SigTermHandler(int /* signum */) { sigterm_seen = true; } void CheckForSigTermAndExitIfSeen() { if (sigterm_seen) { LOG_WARNING("caught SIGTERM, exiting..."); std::exit(EXIT_SUCCESS); } } // Returns local time using an ISO 8601 format w/o time zone. inline std::string GetLocalTime() { return TimeUtil::GetCurrentDateAndTime(TimeUtil::ISO_8601_FORMAT); } void CollectCPUStats(File * const log) { static auto proc_meminfo(FileUtil::OpenInputFileOrDie("/proc/stat")); const auto current_date_and_time(GetLocalTime()); static uint64_t last_total, last_idle; std::string line; while (proc_meminfo->getline(&line) > 0) { if (StringUtil::StartsWith(line, "cpu ")) { std::vector<std::string> parts; StringUtil::Split(line, ' ', &parts, /* suppress_empty_components = */true); uint64_t total(0), idle(StringUtil::ToUInt64T(parts[4])); for (unsigned i(1); i < parts.size(); ++i) total += StringUtil::ToUInt64T(parts[i]); const uint64_t diff_idle(idle - last_idle); const uint64_t diff_total(total - last_total); const uint64_t diff_usage((1000ull * (diff_total - diff_idle) / diff_total + 5) / 10ull); (*log) << "CPU " << diff_usage << ' ' << current_date_and_time << '\n'; log->flush(); last_total = total; last_idle = idle; return; } } } void CollectMemoryStats(File * const log) { static const auto proc_meminfo(FileUtil::OpenInputFileOrDie("/proc/meminfo")); static const std::vector<std::string> COLLECTED_LABELS{ "MemAvailable", "SwapFree", "Unevictable" }; const auto current_date_and_time(GetLocalTime()); std::string line; while (proc_meminfo->getline(&line) > 0) { const auto first_colon_pos(line.find(':')); if (unlikely(first_colon_pos == std::string::npos)) LOG_ERROR("missing colon in \"" + line + "\"!"); const auto label(line.substr(0, first_colon_pos)); if (std::find(COLLECTED_LABELS.cbegin(), COLLECTED_LABELS.cend(), label) == COLLECTED_LABELS.cend()) continue; const auto rest(StringUtil::LeftTrim(line.substr(first_colon_pos + 1))); const auto first_space_pos(rest.find(' ')); if (first_space_pos == std::string::npos) (*log) << label << ' ' << rest << ' ' << current_date_and_time << '\n'; else (*log) << label << ' ' << rest.substr(0, first_space_pos) << ' ' << current_date_and_time << '\n'; } log->flush(); proc_meminfo->rewind(); } void CollectDiscStats(File * const log) { const auto current_date_and_time(GetLocalTime()); FileUtil::Directory directory("/sys/block", "sd?"); for (const auto &entry : directory) { const auto block_device_path("/sys/block/" + entry.getName() + "/size"); const auto proc_entry(FileUtil::OpenInputFileOrDie(block_device_path)); std::string line; proc_entry->getline(&line); (*log) << block_device_path << ' ' << StringUtil::ToUnsignedLong(line) * 512 << ' ' << current_date_and_time << '\n'; } log->flush(); } const std::string PID_FILE("/usr/local/run/system_monitor.pid"); bool IsAlreadyRunning(std::string * const pid_as_string) { if (not FileUtil::Exists(PID_FILE)) return false; FileUtil::ReadString(PID_FILE, pid_as_string); pid_t pid; if (not StringUtil::ToNumber(*pid_as_string, &pid)) LOG_ERROR("\"" + *pid_as_string + "\" is not a valid PID!"); return ::getpgid(pid) >= 0; } void CheckStats(const uint64_t ticks, const unsigned stats_interval, void (*stats_func)(File * const log), File * const log) { if ((ticks % stats_interval) == 0) { SignalUtil::SignalBlocker sighup_blocker(SIGHUP); stats_func(log); } CheckForSigTermAndExitIfSeen(); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 2) Usage(); bool foreground(false); if (std::strcmp(argv[1], "--foreground") == 0) { foreground = true; --argc, ++argv; } if (argc != 2) Usage(); std::string pid; if (IsAlreadyRunning(&pid)) { std::cerr << "system_monitor: This service may already be running! (PID: "<< pid << ")\n"; return EXIT_FAILURE; } const IniFile ini_file(UBTools::GetTuelibPath() + FileUtil::GetBasename(::progname) + ".conf"); const unsigned memory_stats_interval(ini_file.getUnsigned("", "memory_stats_interval")); const unsigned disc_stats_interval(ini_file.getUnsigned("", "disc_stats_interval")); const unsigned cpu_stats_interval(ini_file.getUnsigned("", "cpu_stats_interval")); if (not foreground) { SignalUtil::InstallHandler(SIGTERM, SigTermHandler); if (::daemon(0, 1 /* do not close file descriptors and redirect to /dev/null */) != 0) LOG_ERROR("we failed to deamonize our process!"); } if (not FileUtil::WriteString(PID_FILE, StringUtil::ToString(::getpid()))) LOG_ERROR("failed to write our PID to " + PID_FILE + "!"); const auto log(FileUtil::OpenForAppendingOrDie(argv[1])); uint64_t ticks(0); for (;;) { CheckStats(ticks, memory_stats_interval, CollectMemoryStats, log.get()); CheckStats(ticks, disc_stats_interval, CollectDiscStats, log.get()); CheckStats(ticks, cpu_stats_interval, CollectCPUStats, log.get()); ::sleep(1); ++ticks; } } <commit_msg>Fixed a typo.<commit_after>/** \file system_monitor.cc * \brief Collect a few basic system metrics * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <csignal> #include <cstring> #include <unistd.h> #include "Compiler.h" #include "FileUtil.h" #include "IniFile.h" #include "SignalUtil.h" #include "StringUtil.h" #include "TimeUtil.h" #include "UBTools.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("[--foreground] output_filename\n" " When --foreground has been specified the program does not daemonise.\n" " The config file path is \"" + UBTools::GetTuelibPath() + FileUtil::GetBasename(::progname) + ".conf\"."); } volatile sig_atomic_t sigterm_seen = false; void SigTermHandler(int /* signum */) { sigterm_seen = true; } void CheckForSigTermAndExitIfSeen() { if (sigterm_seen) { LOG_WARNING("caught SIGTERM, exiting..."); std::exit(EXIT_SUCCESS); } } // Returns local time using an ISO 8601 format w/o time zone. inline std::string GetLocalTime() { return TimeUtil::GetCurrentDateAndTime(TimeUtil::ISO_8601_FORMAT); } void CollectCPUStats(File * const log) { static auto proc_meminfo(FileUtil::OpenInputFileOrDie("/proc/stat")); const auto current_date_and_time(GetLocalTime()); static uint64_t last_total, last_idle; std::string line; while (proc_meminfo->getline(&line) > 0) { if (StringUtil::StartsWith(line, "cpu ")) { std::vector<std::string> parts; StringUtil::Split(line, ' ', &parts, /* suppress_empty_components = */true); uint64_t total(0), idle(StringUtil::ToUInt64T(parts[4])); for (unsigned i(1); i < parts.size(); ++i) total += StringUtil::ToUInt64T(parts[i]); const uint64_t diff_idle(idle - last_idle); const uint64_t diff_total(total - last_total); const uint64_t diff_usage((1000ull * (diff_total - diff_idle) / diff_total + 5) / 10ull); (*log) << "CPU " << diff_usage << ' ' << current_date_and_time << '\n'; log->flush(); last_total = total; last_idle = idle; return; } } } void CollectMemoryStats(File * const log) { static const auto proc_meminfo(FileUtil::OpenInputFileOrDie("/proc/meminfo")); static const std::vector<std::string> COLLECTED_LABELS{ "MemAvailable", "SwapFree", "Unevictable" }; const auto current_date_and_time(GetLocalTime()); std::string line; while (proc_meminfo->getline(&line) > 0) { const auto first_colon_pos(line.find(':')); if (unlikely(first_colon_pos == std::string::npos)) LOG_ERROR("missing colon in \"" + line + "\"!"); const auto label(line.substr(0, first_colon_pos)); if (std::find(COLLECTED_LABELS.cbegin(), COLLECTED_LABELS.cend(), label) == COLLECTED_LABELS.cend()) continue; const auto rest(StringUtil::LeftTrim(line.substr(first_colon_pos + 1))); const auto first_space_pos(rest.find(' ')); if (first_space_pos == std::string::npos) (*log) << label << ' ' << rest << ' ' << current_date_and_time << '\n'; else (*log) << label << ' ' << rest.substr(0, first_space_pos) << ' ' << current_date_and_time << '\n'; } log->flush(); proc_meminfo->rewind(); } void CollectDiscStats(File * const log) { const auto current_date_and_time(GetLocalTime()); FileUtil::Directory directory("/sys/block", "sd?"); for (const auto &entry : directory) { const auto block_device_path("/sys/block/" + entry.getName() + "/size"); const auto proc_entry(FileUtil::OpenInputFileOrDie(block_device_path)); std::string line; proc_entry->getline(&line); (*log) << block_device_path << ' ' << StringUtil::ToUnsignedLong(line) * 512 << ' ' << current_date_and_time << '\n'; } log->flush(); } const std::string PID_FILE("/usr/local/run/system_monitor.pid"); bool IsAlreadyRunning(std::string * const pid_as_string) { if (not FileUtil::Exists(PID_FILE)) return false; FileUtil::ReadString(PID_FILE, pid_as_string); pid_t pid; if (not StringUtil::ToNumber(*pid_as_string, &pid)) LOG_ERROR("\"" + *pid_as_string + "\" is not a valid PID!"); return ::getpgid(pid) >= 0; } void CheckStats(const uint64_t ticks, const unsigned stats_interval, void (*stats_func)(File * const log), File * const log) { if ((ticks % stats_interval) == 0) { SignalUtil::SignalBlocker sighup_blocker(SIGHUP); stats_func(log); } CheckForSigTermAndExitIfSeen(); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 2) Usage(); bool foreground(false); if (std::strcmp(argv[1], "--foreground") == 0) { foreground = true; --argc, ++argv; } if (argc != 2) Usage(); std::string pid; if (IsAlreadyRunning(&pid)) { std::cerr << "system_monitor: This service may already be running! (PID: "<< pid << ")\n"; return EXIT_FAILURE; } const IniFile ini_file(UBTools::GetTuelibPath() + FileUtil::GetBasename(::progname) + ".conf"); const unsigned memory_stats_interval(ini_file.getUnsigned("", "memory_stats_interval")); const unsigned disc_stats_interval(ini_file.getUnsigned("", "disc_stats_interval")); const unsigned cpu_stats_interval(ini_file.getUnsigned("", "cpu_stats_interval")); if (not foreground) { SignalUtil::InstallHandler(SIGTERM, SigTermHandler); if (::daemon(0, 1 /* do not close file descriptors and redirect to /dev/null */) != 0) LOG_ERROR("we failed to daemonize our process!"); } if (not FileUtil::WriteString(PID_FILE, StringUtil::ToString(::getpid()))) LOG_ERROR("failed to write our PID to " + PID_FILE + "!"); const auto log(FileUtil::OpenForAppendingOrDie(argv[1])); uint64_t ticks(0); for (;;) { CheckStats(ticks, memory_stats_interval, CollectMemoryStats, log.get()); CheckStats(ticks, disc_stats_interval, CollectDiscStats, log.get()); CheckStats(ticks, cpu_stats_interval, CollectCPUStats, log.get()); ::sleep(1); ++ticks; } } <|endoftext|>
<commit_before>#include "Exception.h" using namespace CppUnit; const std::string CppUnit::Exception::UNKNOWNFILENAME = "<unknown>"; const int CppUnit::Exception::UNKNOWNLINENUMBER = -1; /// Construct the exception CppUnit::Exception::Exception (const Exception& other) : exception (other) { m_message = other.m_message; m_lineNumber = other.m_lineNumber; m_fileName = other.m_fileName; } CppUnit::Exception::Exception (std::string message, long lineNumber, std::string fileName) : m_message (message), m_lineNumber (lineNumber), m_fileName (fileName) {} /// Destruct the exception CppUnit::Exception::~Exception () {} /// Perform an assignment Exception& CppUnit::Exception::operator= (const Exception& other) { exception::operator= (other); if (&other != this) { m_message = other.m_message; m_lineNumber = other.m_lineNumber; m_fileName = other.m_fileName; } return *this; } /// Return descriptive message const char* CppUnit::Exception::what() const throw () { return m_message.c_str (); } /// The line on which the error occurred long CppUnit::Exception::lineNumber () { return m_lineNumber; } /// The file in which the error occurred std::string CppUnit::Exception::fileName () { return m_fileName; } <commit_msg>code beautification.<commit_after>#include "Exception.h" using namespace CppUnit; const std::string CppUnit::Exception::UNKNOWNFILENAME = "<unknown>"; const int CppUnit::Exception::UNKNOWNLINENUMBER = -1; /// Construct the exception CppUnit::Exception::Exception (const Exception& other) : exception (other) { m_message = other.m_message; m_lineNumber = other.m_lineNumber; m_fileName = other.m_fileName; } CppUnit::Exception::Exception (std::string message, long lineNumber, std::string fileName) : m_message (message), m_lineNumber (lineNumber), m_fileName (fileName) { } /// Destruct the exception CppUnit::Exception::~Exception () {} /// Perform an assignment Exception& CppUnit::Exception::operator= (const Exception& other) { exception::operator= (other); if (&other != this) { m_message = other.m_message; m_lineNumber = other.m_lineNumber; m_fileName = other.m_fileName; } return *this; } /// Return descriptive message const char* CppUnit::Exception::what() const throw () { return m_message.c_str (); } /// The line on which the error occurred long CppUnit::Exception::lineNumber () { return m_lineNumber; } /// The file in which the error occurred std::string CppUnit::Exception::fileName () { return m_fileName; } <|endoftext|>
<commit_before>#include <qt/mintingtablemodel.h> #include <qt/mintingfilterproxy.h> #include <kernelrecord.h> #include <qt/transactiondesc.h> //#include <qt/guiutil.h> #include <qt/walletmodel.h> #include <qt/guiconstants.h> #include <qt/bitcoinunits.h> #include <qt/optionsmodel.h> #include <qt/addresstablemodel.h> #include <util.h> #include <wallet/wallet.h> #include <validation.h> #include <ui_interface.h> #include <QColor> #include <QTimer> // Amount column is right-aligned it contains numbers static int column_alignments[] = { Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter }; // Comparison operator for sort/binary search of model tx list struct TxLessThan { bool operator()(const KernelRecord &a, const KernelRecord &b) const { return a.hash < b.hash; } bool operator()(const KernelRecord &a, const uint256 &b) const { return a.hash < b; } bool operator()(const uint256 &a, const KernelRecord &b) const { return a < b.hash; } }; // Private implementation class MintingTablePriv { public: MintingTablePriv(CWallet *wallet, MintingTableModel *parent): wallet(wallet), parent(parent) { } CWallet *wallet; MintingTableModel *parent; /* Local cache of wallet. * As it is in the same order as the CWallet, by definition * this is sorted by sha256. */ QList<KernelRecord> cachedWallet; /* Query entire wallet anew from core. */ void refreshWallet() { LogPrintf("refreshWallet\n"); cachedWallet.clear(); { LOCK(wallet->cs_wallet); for(std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it) { std::vector<KernelRecord> txList = KernelRecord::decomposeOutput(wallet, it->second); if(KernelRecord::showTransaction(it->second)) for(const KernelRecord& kr : txList) { if(!kr.spent) { cachedWallet.append(kr); } } } } } /* Update our model of the wallet incrementally, to synchronize our model of the wallet with that of the core. Call with transaction that was added, removed or changed. */ void updateWallet(const uint256 &hash, int status) { LogPrintf("minting updateWallet %s %i\n", hash.ToString(), status); { LOCK(wallet->cs_wallet); // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); bool inWallet = mi != wallet->mapWallet.end(); // Find bounds of this transaction in model QList<KernelRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<KernelRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); // Determine whether to show transaction or not bool showTransaction = (inWallet && KernelRecord::showTransaction(mi->second)); if(status == CT_UPDATED) { if(showTransaction && !inModel) status = CT_NEW; /* Not in model, but want to show, treat as new */ if(!showTransaction && inModel) status = CT_DELETED; /* In model, but want to hide, treat as deleted */ } LogPrintf(" inWallet=%i inModel=%i Index=%i-%i showTransaction=%i derivedStatus=%i\n", inWallet, inModel, lowerIndex, upperIndex, showTransaction, status); switch(status) { case CT_NEW: if(inModel) { LogPrintf("Warning: updateWallet: Got CT_NEW, but transaction is already in model\n"); break; } if(!inWallet) { LogPrintf("Warning: updateWallet: Got CT_NEW, but transaction is not in wallet\n"); break; } if(showTransaction) { // Added -- insert at the right position std::vector<KernelRecord> toInsert = KernelRecord::decomposeOutput(wallet, mi->second); if(toInsert.size() != 0) /* only if something to insert */ { parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1); int insert_idx = lowerIndex; for (const KernelRecord &rec : toInsert) { if(!rec.spent) { cachedWallet.insert(insert_idx, rec); insert_idx += 1; } } parent->endInsertRows(); } } break; case CT_DELETED: if(!inModel) { LogPrintf("Warning: updateWallet: Got CT_DELETED, but transaction is not in model\n"); break; } // Removed -- remove entire transaction from table parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedWallet.erase(lower, upper); parent->endRemoveRows(); break; case CT_UPDATED: // Updated -- remove spent coins from table std::vector<KernelRecord> toCheck = KernelRecord::decomposeOutput(wallet, mi->second); if(!toCheck.empty()) { for(const KernelRecord &rec : toCheck) { if(rec.spent) { for(int i = lowerIndex; i < upperIndex; i++) { KernelRecord cachedRec = cachedWallet.at(i); if((rec.address == cachedRec.address) && (rec.nValue == cachedRec.nValue) && (rec.idx == cachedRec.idx)) { parent->beginRemoveRows(QModelIndex(), i, i); cachedWallet.removeAt(i); parent->endRemoveRows(); break; } } } } } break; } } } int size() { return cachedWallet.size(); } KernelRecord *index(int idx) { if(idx >= 0 && idx < cachedWallet.size()) { KernelRecord *rec = &cachedWallet[idx]; return rec; } else { return 0; } } QString describe(KernelRecord *rec) { { LOCK(wallet->cs_wallet); std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if(mi != wallet->mapWallet.end()) { return TransactionDesc::toHTML(wallet, mi->second, nullptr, 0); //ppcTODO - fix the last 2 parameters } } return QString(""); } }; MintingTableModel::MintingTableModel(CWallet* wallet, WalletModel *parent) : QAbstractTableModel(parent), wallet(wallet), walletModel(parent), mintingInterval(10), priv(new MintingTablePriv(wallet, this)), cachedNumBlocks(0) { columns << tr("Transaction") << tr("Address") << tr("Age") << tr("Balance") << tr("CoinDay") << tr("MintProbability"); priv->refreshWallet(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateAge())); timer->start(MODEL_UPDATE_DELAY); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } MintingTableModel::~MintingTableModel() { delete priv; } void MintingTableModel::updateTransaction(const QString &hash, int status) { uint256 updated; updated.SetHex(hash.toStdString()); priv->updateWallet(updated, status); mintingProxyModel->invalidate(); // Force deletion of empty rows } void MintingTableModel::updateAge() { Q_EMIT dataChanged(index(0, Age), index(priv->size()-1, Age)); Q_EMIT dataChanged(index(0, CoinDay), index(priv->size()-1, CoinDay)); Q_EMIT dataChanged(index(0, MintProbability), index(priv->size()-1, MintProbability)); } void MintingTableModel::setMintingProxyModel(MintingFilterProxy *mintingProxy) { mintingProxyModel = mintingProxy; } int MintingTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int MintingTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant MintingTableModel::data(const QModelIndex &index, int role) const { const Consensus::Params& params = Params().GetConsensus(); if(!index.isValid()) return QVariant(); KernelRecord *rec = static_cast<KernelRecord*>(index.internalPointer()); switch(role) { case Qt::DisplayRole: switch(index.column()) { case Address: return formatTxAddress(rec, false); case TxHash: return formatTxHash(rec); case Age: return formatTxAge(rec); case Balance: return formatTxBalance(rec); case CoinDay: return formatTxCoinDay(rec); case MintProbability: return formatDayToMint(rec); } break; case Qt::TextAlignmentRole: return column_alignments[index.column()]; break; case Qt::ToolTipRole: switch(index.column()) { case MintProbability: int interval = this->mintingInterval; QString unit = tr("minutes"); int hours = interval / 60; int days = hours / 24; if(hours > 1) { interval = hours; unit = tr("hours"); } if(days > 1) { interval = days; unit = tr("days"); } QString str = QString(tr("You have %1 chance to find a POS block if you mint %2 %3 at current difficulty.")); return str.arg(index.data().toString().toUtf8().constData()).arg(interval).arg(unit); } break; case Qt::EditRole: switch(index.column()) { case Address: return formatTxAddress(rec, false); case TxHash: return formatTxHash(rec); case Age: return qint64(rec->getAge()); case CoinDay: return qint64(rec->coinAge); case Balance: return qint64(rec->nValue); case MintProbability: return getDayToMint(rec); } break; case Qt::BackgroundColorRole: int minAge = params.nStakeMinAge / 60 / 60 / 24; int maxAge = params.nStakeMaxAge / 60 / 60 / 24; if(rec->getAge() < minAge) { return COLOR_MINT_YOUNG; } else if (rec->getAge() >= minAge && rec->getAge() < maxAge) { return COLOR_MINT_MATURE; } else { return COLOR_MINT_OLD; } break; } return QVariant(); } void MintingTableModel::setMintingInterval(int interval) { mintingInterval = interval; } QString MintingTableModel::lookupAddress(const std::string &address, bool tooltip) const { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address)); QString description; if(!label.isEmpty()) { description += label + QString(" "); } if(label.isEmpty() || tooltip) { description += QString(" (") + QString::fromStdString(address) + QString(")"); } return description; } double MintingTableModel::getDayToMint(KernelRecord *wtx) const { const CBlockIndex *p = GetLastBlockIndex(chainActive.Tip(), true); double difficulty = p->GetBlockDifficulty(); double prob = wtx->getProbToMintWithinNMinutes(difficulty, mintingInterval); prob = prob * 100; return prob; } QString MintingTableModel::formatDayToMint(KernelRecord *wtx) const { double prob = getDayToMint(wtx); return QString::number(prob, 'f', 6) + "%"; } QString MintingTableModel::formatTxAddress(const KernelRecord *wtx, bool tooltip) const { return QString::fromStdString(wtx->address); } QString MintingTableModel::formatTxHash(const KernelRecord *wtx) const { return QString::fromStdString(wtx->hash.ToString()); } QString MintingTableModel::formatTxCoinDay(const KernelRecord *wtx) const { return QString::number(wtx->coinAge); } QString MintingTableModel::formatTxAge(const KernelRecord *wtx) const { int64_t nAge = wtx->getAge(); return QString::number(nAge); } QString MintingTableModel::formatTxBalance(const KernelRecord *wtx) const { return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->nValue); } QVariant MintingTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch(section) { case Address: return tr("Destination address of the output."); case TxHash: return tr("Original transaction id."); case Age: return tr("Age of the transaction in days."); case Balance: return tr("Balance of the output."); case CoinDay: return tr("Coin age in the output."); case MintProbability: return tr("Chance to mint a block within given time interval."); } } } return QVariant(); } QModelIndex MintingTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); KernelRecord *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void MintingTableModel::updateDisplayUnit() { // emit dataChanged to update Balance column with the current unit Q_EMIT dataChanged(index(0, Balance), index(priv->size()-1, Balance)); } <commit_msg>fix loading wallet<commit_after>#include <qt/mintingtablemodel.h> #include <qt/mintingfilterproxy.h> #include <kernelrecord.h> #include <qt/transactiondesc.h> //#include <qt/guiutil.h> #include <qt/walletmodel.h> #include <qt/guiconstants.h> #include <qt/bitcoinunits.h> #include <qt/optionsmodel.h> #include <qt/addresstablemodel.h> #include <util.h> #include <wallet/wallet.h> #include <validation.h> #include <ui_interface.h> #include <QColor> #include <QTimer> // Amount column is right-aligned it contains numbers static int column_alignments[] = { Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter }; // Comparison operator for sort/binary search of model tx list struct TxLessThan { bool operator()(const KernelRecord &a, const KernelRecord &b) const { return a.hash < b.hash; } bool operator()(const KernelRecord &a, const uint256 &b) const { return a.hash < b; } bool operator()(const uint256 &a, const KernelRecord &b) const { return a < b.hash; } }; // Private implementation class MintingTablePriv { public: MintingTablePriv(CWallet *wallet, MintingTableModel *parent): wallet(wallet), parent(parent) { } CWallet *wallet; MintingTableModel *parent; /* Local cache of wallet. * As it is in the same order as the CWallet, by definition * this is sorted by sha256. */ QList<KernelRecord> cachedWallet; /* Query entire wallet anew from core. */ void refreshWallet() { LogPrintf("refreshWallet\n"); cachedWallet.clear(); { // cs_main lock was added because GetDepthInMainChain requires it LOCK2(cs_main, wallet->cs_wallet); for(std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it) { std::vector<KernelRecord> txList = KernelRecord::decomposeOutput(wallet, it->second); if(KernelRecord::showTransaction(it->second)) for(const KernelRecord& kr : txList) { if(!kr.spent) { cachedWallet.append(kr); } } } } } /* Update our model of the wallet incrementally, to synchronize our model of the wallet with that of the core. Call with transaction that was added, removed or changed. */ void updateWallet(const uint256 &hash, int status) { LogPrintf("minting updateWallet %s %i\n", hash.ToString(), status); { LOCK(wallet->cs_wallet); // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); bool inWallet = mi != wallet->mapWallet.end(); // Find bounds of this transaction in model QList<KernelRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<KernelRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); // Determine whether to show transaction or not bool showTransaction = (inWallet && KernelRecord::showTransaction(mi->second)); if(status == CT_UPDATED) { if(showTransaction && !inModel) status = CT_NEW; /* Not in model, but want to show, treat as new */ if(!showTransaction && inModel) status = CT_DELETED; /* In model, but want to hide, treat as deleted */ } LogPrintf(" inWallet=%i inModel=%i Index=%i-%i showTransaction=%i derivedStatus=%i\n", inWallet, inModel, lowerIndex, upperIndex, showTransaction, status); switch(status) { case CT_NEW: if(inModel) { LogPrintf("Warning: updateWallet: Got CT_NEW, but transaction is already in model\n"); break; } if(!inWallet) { LogPrintf("Warning: updateWallet: Got CT_NEW, but transaction is not in wallet\n"); break; } if(showTransaction) { // Added -- insert at the right position std::vector<KernelRecord> toInsert = KernelRecord::decomposeOutput(wallet, mi->second); if(toInsert.size() != 0) /* only if something to insert */ { parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1); int insert_idx = lowerIndex; for (const KernelRecord &rec : toInsert) { if(!rec.spent) { cachedWallet.insert(insert_idx, rec); insert_idx += 1; } } parent->endInsertRows(); } } break; case CT_DELETED: if(!inModel) { LogPrintf("Warning: updateWallet: Got CT_DELETED, but transaction is not in model\n"); break; } // Removed -- remove entire transaction from table parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedWallet.erase(lower, upper); parent->endRemoveRows(); break; case CT_UPDATED: // Updated -- remove spent coins from table std::vector<KernelRecord> toCheck = KernelRecord::decomposeOutput(wallet, mi->second); if(!toCheck.empty()) { for(const KernelRecord &rec : toCheck) { if(rec.spent) { for(int i = lowerIndex; i < upperIndex; i++) { KernelRecord cachedRec = cachedWallet.at(i); if((rec.address == cachedRec.address) && (rec.nValue == cachedRec.nValue) && (rec.idx == cachedRec.idx)) { parent->beginRemoveRows(QModelIndex(), i, i); cachedWallet.removeAt(i); parent->endRemoveRows(); break; } } } } } break; } } } int size() { return cachedWallet.size(); } KernelRecord *index(int idx) { if(idx >= 0 && idx < cachedWallet.size()) { KernelRecord *rec = &cachedWallet[idx]; return rec; } else { return 0; } } QString describe(KernelRecord *rec) { { LOCK(wallet->cs_wallet); std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if(mi != wallet->mapWallet.end()) { return TransactionDesc::toHTML(wallet, mi->second, nullptr, 0); //ppcTODO - fix the last 2 parameters } } return QString(""); } }; MintingTableModel::MintingTableModel(CWallet* wallet, WalletModel *parent) : QAbstractTableModel(parent), wallet(wallet), walletModel(parent), mintingInterval(10), priv(new MintingTablePriv(wallet, this)), cachedNumBlocks(0) { columns << tr("Transaction") << tr("Address") << tr("Age") << tr("Balance") << tr("CoinDay") << tr("MintProbability"); priv->refreshWallet(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateAge())); timer->start(MODEL_UPDATE_DELAY); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } MintingTableModel::~MintingTableModel() { delete priv; } void MintingTableModel::updateTransaction(const QString &hash, int status) { uint256 updated; updated.SetHex(hash.toStdString()); priv->updateWallet(updated, status); mintingProxyModel->invalidate(); // Force deletion of empty rows } void MintingTableModel::updateAge() { Q_EMIT dataChanged(index(0, Age), index(priv->size()-1, Age)); Q_EMIT dataChanged(index(0, CoinDay), index(priv->size()-1, CoinDay)); Q_EMIT dataChanged(index(0, MintProbability), index(priv->size()-1, MintProbability)); } void MintingTableModel::setMintingProxyModel(MintingFilterProxy *mintingProxy) { mintingProxyModel = mintingProxy; } int MintingTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int MintingTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant MintingTableModel::data(const QModelIndex &index, int role) const { const Consensus::Params& params = Params().GetConsensus(); if(!index.isValid()) return QVariant(); KernelRecord *rec = static_cast<KernelRecord*>(index.internalPointer()); switch(role) { case Qt::DisplayRole: switch(index.column()) { case Address: return formatTxAddress(rec, false); case TxHash: return formatTxHash(rec); case Age: return formatTxAge(rec); case Balance: return formatTxBalance(rec); case CoinDay: return formatTxCoinDay(rec); case MintProbability: return formatDayToMint(rec); } break; case Qt::TextAlignmentRole: return column_alignments[index.column()]; break; case Qt::ToolTipRole: switch(index.column()) { case MintProbability: int interval = this->mintingInterval; QString unit = tr("minutes"); int hours = interval / 60; int days = hours / 24; if(hours > 1) { interval = hours; unit = tr("hours"); } if(days > 1) { interval = days; unit = tr("days"); } QString str = QString(tr("You have %1 chance to find a POS block if you mint %2 %3 at current difficulty.")); return str.arg(index.data().toString().toUtf8().constData()).arg(interval).arg(unit); } break; case Qt::EditRole: switch(index.column()) { case Address: return formatTxAddress(rec, false); case TxHash: return formatTxHash(rec); case Age: return qint64(rec->getAge()); case CoinDay: return qint64(rec->coinAge); case Balance: return qint64(rec->nValue); case MintProbability: return getDayToMint(rec); } break; case Qt::BackgroundColorRole: int minAge = params.nStakeMinAge / 60 / 60 / 24; int maxAge = params.nStakeMaxAge / 60 / 60 / 24; if(rec->getAge() < minAge) { return COLOR_MINT_YOUNG; } else if (rec->getAge() >= minAge && rec->getAge() < maxAge) { return COLOR_MINT_MATURE; } else { return COLOR_MINT_OLD; } break; } return QVariant(); } void MintingTableModel::setMintingInterval(int interval) { mintingInterval = interval; } QString MintingTableModel::lookupAddress(const std::string &address, bool tooltip) const { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address)); QString description; if(!label.isEmpty()) { description += label + QString(" "); } if(label.isEmpty() || tooltip) { description += QString(" (") + QString::fromStdString(address) + QString(")"); } return description; } double MintingTableModel::getDayToMint(KernelRecord *wtx) const { const CBlockIndex *p = GetLastBlockIndex(chainActive.Tip(), true); double difficulty = p->GetBlockDifficulty(); double prob = wtx->getProbToMintWithinNMinutes(difficulty, mintingInterval); prob = prob * 100; return prob; } QString MintingTableModel::formatDayToMint(KernelRecord *wtx) const { double prob = getDayToMint(wtx); return QString::number(prob, 'f', 6) + "%"; } QString MintingTableModel::formatTxAddress(const KernelRecord *wtx, bool tooltip) const { return QString::fromStdString(wtx->address); } QString MintingTableModel::formatTxHash(const KernelRecord *wtx) const { return QString::fromStdString(wtx->hash.ToString()); } QString MintingTableModel::formatTxCoinDay(const KernelRecord *wtx) const { return QString::number(wtx->coinAge); } QString MintingTableModel::formatTxAge(const KernelRecord *wtx) const { int64_t nAge = wtx->getAge(); return QString::number(nAge); } QString MintingTableModel::formatTxBalance(const KernelRecord *wtx) const { return BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->nValue); } QVariant MintingTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch(section) { case Address: return tr("Destination address of the output."); case TxHash: return tr("Original transaction id."); case Age: return tr("Age of the transaction in days."); case Balance: return tr("Balance of the output."); case CoinDay: return tr("Coin age in the output."); case MintProbability: return tr("Chance to mint a block within given time interval."); } } } return QVariant(); } QModelIndex MintingTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); KernelRecord *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void MintingTableModel::updateDisplayUnit() { // emit dataChanged to update Balance column with the current unit Q_EMIT dataChanged(index(0, Balance), index(priv->size()-1, Balance)); } <|endoftext|>
<commit_before>#include <osgAnimation/RigGeometry> #include <osgDB/ObjectWrapper> #include <osgDB/InputStream> #include <osgDB/OutputStream> static bool checkInfluenceMap( const osgAnimation::RigGeometry& geom ) { return geom.getInfluenceMap()->size()>0; } static bool readInfluenceMap( osgDB::InputStream& is, osgAnimation::RigGeometry& geom ) { osgAnimation::VertexInfluenceMap* map = new osgAnimation::VertexInfluenceMap; unsigned int size = is.readSize(); is >> is.BEGIN_BRACKET; for ( unsigned int i=0; i<size; ++i ) { std::string name; unsigned int viSize = 0; is >> is.PROPERTY("VertexInfluence") >> name; viSize = is.readSize(); is >> is.BEGIN_BRACKET; osgAnimation::VertexInfluence vi; vi.setName( name ); vi.reserve( viSize ); for ( unsigned int j=0; j<viSize; ++j ) { int index = 0; float weight = 0.0f; is >> index >> weight; vi.push_back( osgAnimation::VertexIndexWeight(index, weight) ); } (*map)[name] = vi; is >> is.END_BRACKET; } is >> is.END_BRACKET; if ( !map->empty() ) geom.setInfluenceMap( map ); return true; } static bool writeInfluenceMap( osgDB::OutputStream& os, const osgAnimation::RigGeometry& geom ) { const osgAnimation::VertexInfluenceMap* map = geom.getInfluenceMap(); os.writeSize(map->size()); os << os.BEGIN_BRACKET << std::endl; for ( osgAnimation::VertexInfluenceMap::const_iterator itr=map->begin(); itr!=map->end(); ++itr ) { std::string name = itr->first; const osgAnimation::VertexInfluence& vi = itr->second; if ( name.empty() ) name = "Empty"; os << os.PROPERTY("VertexInfluence") << name; os.writeSize(vi.size()) ; os << os.BEGIN_BRACKET << std::endl; for ( osgAnimation::VertexInfluence::const_iterator vitr=vi.begin(); vitr != vi.end(); ++vitr ) { os << vitr->first << vitr->second << std::endl; } os << os.END_BRACKET << std::endl; } os << os.END_BRACKET << std::endl; return true; } REGISTER_OBJECT_WRAPPER( osgAnimation_RigGeometry, new osgAnimation::RigGeometry, osgAnimation::RigGeometry, "osg::Object osg::Drawable osg::Geometry osgAnimation::RigGeometry" ) { ADD_USER_SERIALIZER( InfluenceMap ); // _vertexInfluenceMap ADD_OBJECT_SERIALIZER( SourceGeometry, osg::Geometry, NULL ); // _geometry } <commit_msg>From Jan Ciger, "Here is a little patch to fix a bug in the InfluenceMap serialization. The names of the maps weren't quoted properly and therefore it was breaking loading of rigged models exported from e.g. Blender. Also names that contained spaces wouldn't have been parsed properly. "<commit_after>#include <osgAnimation/RigGeometry> #include <osgDB/ObjectWrapper> #include <osgDB/InputStream> #include <osgDB/OutputStream> static bool checkInfluenceMap( const osgAnimation::RigGeometry& geom ) { return geom.getInfluenceMap()->size()>0; } static bool readInfluenceMap( osgDB::InputStream& is, osgAnimation::RigGeometry& geom ) { osgAnimation::VertexInfluenceMap* map = new osgAnimation::VertexInfluenceMap; unsigned int size = is.readSize(); is >> is.BEGIN_BRACKET; for ( unsigned int i=0; i<size; ++i ) { std::string name; unsigned int viSize = 0; is >> is.PROPERTY("VertexInfluence"); is.readWrappedString(name); viSize = is.readSize(); is >> is.BEGIN_BRACKET; osgAnimation::VertexInfluence vi; vi.setName( name ); vi.reserve( viSize ); for ( unsigned int j=0; j<viSize; ++j ) { int index = 0; float weight = 0.0f; is >> index >> weight; vi.push_back( osgAnimation::VertexIndexWeight(index, weight) ); } (*map)[name] = vi; is >> is.END_BRACKET; } is >> is.END_BRACKET; if ( !map->empty() ) geom.setInfluenceMap( map ); return true; } static bool writeInfluenceMap( osgDB::OutputStream& os, const osgAnimation::RigGeometry& geom ) { const osgAnimation::VertexInfluenceMap* map = geom.getInfluenceMap(); os.writeSize(map->size()); os << os.BEGIN_BRACKET << std::endl; for ( osgAnimation::VertexInfluenceMap::const_iterator itr=map->begin(); itr!=map->end(); ++itr ) { std::string name = itr->first; const osgAnimation::VertexInfluence& vi = itr->second; if ( name.empty() ) name = "Empty"; os << os.PROPERTY("VertexInfluence"); os.writeWrappedString(name); os.writeSize(vi.size()) ; os << os.BEGIN_BRACKET << std::endl; for ( osgAnimation::VertexInfluence::const_iterator vitr=vi.begin(); vitr != vi.end(); ++vitr ) { os << vitr->first << vitr->second << std::endl; } os << os.END_BRACKET << std::endl; } os << os.END_BRACKET << std::endl; return true; } REGISTER_OBJECT_WRAPPER( osgAnimation_RigGeometry, new osgAnimation::RigGeometry, osgAnimation::RigGeometry, "osg::Object osg::Drawable osg::Geometry osgAnimation::RigGeometry" ) { ADD_USER_SERIALIZER( InfluenceMap ); // _vertexInfluenceMap ADD_OBJECT_SERIALIZER( SourceGeometry, osg::Geometry, NULL ); // _geometry } <|endoftext|>
<commit_before>#include "transactionrecord.h" #include "headers.h" /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction(const CWalletTx &wtx) { if (wtx.IsCoinBase()) { // Don't show generated coin until confirmed by at least one block after it // so we don't get the user's hopes up until it looks like it's probably accepted. // // It is not an error when generated blocks are not accepted. By design, // some percentage of blocks, like 10% or more, will end up not accepted. // This is the normal mechanism by which the network copes with latency. // // We display regular transactions right away before any confirmation // because they can always get into some block eventually. Generated coins // are special because if their block is not accepted, they are not valid. // if (wtx.GetDepthInMainChain() < 2) { return false; } } return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) { QList<TransactionRecord> parts; int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime(); int64 nCredit = wtx.GetCredit(true); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; if (showTransaction(wtx)) { if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // TransactionRecord sub(hash, nTime); sub.credit = nNet; if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; if (nCredit == 0) { int64 nUnmatured = 0; BOOST_FOREACH(const CTxOut& txout, wtx.vout) nUnmatured += wallet->GetCredit(txout); sub.credit = nUnmatured; } } else { bool foundAddress = false; // Received by Bitcoin Address BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if(wallet->IsMine(txout)) { CBitcoinAddress address; if (ExtractAddress(txout.scriptPubKey, address) && wallet->HaveKey(address)) { sub.type = TransactionRecord::RecvWithAddress; sub.address = address.ToString(); foundAddress = true; break; } } } if(!foundAddress) { // Received by IP connection, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } } parts.append(sub); } else { bool fAllFromMe = true; BOOST_FOREACH(const CTxIn& txin, wtx.vin) fAllFromMe = fAllFromMe && wallet->IsMine(txin); bool fAllToMe = true; BOOST_FOREACH(const CTxOut& txout, wtx.vout) fAllToMe = fAllToMe && wallet->IsMine(txout); if (fAllFromMe && fAllToMe) { // Payment to self int64 nChange = wtx.GetChange(); parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", -(nDebit - nChange), nCredit - nChange)); } else if (fAllFromMe) { // // Debit // int64 nTxFee = nDebit - wtx.GetValueOut(); for (int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); if(wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CBitcoinAddress address; if (ExtractAddress(txout.scriptPubKey, address)) { // Sent to Bitcoin Address sub.type = TransactionRecord::SendToAddress; sub.address = address.ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } int64 nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // bool fAllMine = true; BOOST_FOREACH(const CTxOut& txout, wtx.vout) fAllMine = fAllMine && wallet->IsMine(txout); BOOST_FOREACH(const CTxIn& txin, wtx.vin) fAllMine = fAllMine && wallet->IsMine(txin); parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); } } } return parts; } void TransactionRecord::updateStatus(const CWalletTx &wtx) { // Determine transaction status // Find the block the tx is in CBlockIndex* pindex = NULL; std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock); if (mi != mapBlockIndex.end()) pindex = (*mi).second; // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx); status.confirmed = wtx.IsConfirmed(); status.depth = wtx.GetDepthInMainChain(); status.cur_num_blocks = nBestHeight; if (!wtx.IsFinal()) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = nBestHeight - wtx.nLockTime; } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.nLockTime; } } else { if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) { status.status = TransactionStatus::Offline; } else if (status.depth < NumConfirmations) { status.status = TransactionStatus::Unconfirmed; } else { status.status = TransactionStatus::HaveConfirmations; } } // For generated transactions, determine maturity if(type == TransactionRecord::Generated) { int64 nCredit = wtx.GetCredit(true); if (nCredit == 0) { status.maturity = TransactionStatus::Immature; if (wtx.IsInMainChain()) { status.matures_in = wtx.GetBlocksToMaturity(); // Check if the block was requested by anyone if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) status.maturity = TransactionStatus::MaturesWarning; } else { status.maturity = TransactionStatus::NotAccepted; } } else { status.maturity = TransactionStatus::Mature; } } } bool TransactionRecord::statusUpdateNeeded() { return status.cur_num_blocks != nBestHeight; } std::string TransactionRecord::getTxID() { return hash.ToString() + strprintf("-%03d", idx); } <commit_msg>Restructure credit transaction decomposition (solves issue #689)<commit_after>#include "transactionrecord.h" #include "headers.h" /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction(const CWalletTx &wtx) { if (wtx.IsCoinBase()) { // Don't show generated coin until confirmed by at least one block after it // so we don't get the user's hopes up until it looks like it's probably accepted. // // It is not an error when generated blocks are not accepted. By design, // some percentage of blocks, like 10% or more, will end up not accepted. // This is the normal mechanism by which the network copes with latency. // // We display regular transactions right away before any confirmation // because they can always get into some block eventually. Generated coins // are special because if their block is not accepted, they are not valid. // if (wtx.GetDepthInMainChain() < 2) { return false; } } return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) { QList<TransactionRecord> parts; int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime(); int64 nCredit = wtx.GetCredit(true); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; if (showTransaction(wtx)) { if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if(wallet->IsMine(txout)) { TransactionRecord sub(hash, nTime); CBitcoinAddress address; sub.idx = parts.size(); // sequence number sub.credit = txout.nValue; if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; } else if (ExtractAddress(txout.scriptPubKey, address) && wallet->HaveKey(address)) { // Received by Bitcoin Address sub.type = TransactionRecord::RecvWithAddress; sub.address = address.ToString(); } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } parts.append(sub); } } } else { bool fAllFromMe = true; BOOST_FOREACH(const CTxIn& txin, wtx.vin) fAllFromMe = fAllFromMe && wallet->IsMine(txin); bool fAllToMe = true; BOOST_FOREACH(const CTxOut& txout, wtx.vout) fAllToMe = fAllToMe && wallet->IsMine(txout); if (fAllFromMe && fAllToMe) { // Payment to self int64 nChange = wtx.GetChange(); parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", -(nDebit - nChange), nCredit - nChange)); } else if (fAllFromMe) { // // Debit // int64 nTxFee = nDebit - wtx.GetValueOut(); for (int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); if(wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CBitcoinAddress address; if (ExtractAddress(txout.scriptPubKey, address)) { // Sent to Bitcoin Address sub.type = TransactionRecord::SendToAddress; sub.address = address.ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } int64 nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // bool fAllMine = true; BOOST_FOREACH(const CTxOut& txout, wtx.vout) fAllMine = fAllMine && wallet->IsMine(txout); BOOST_FOREACH(const CTxIn& txin, wtx.vin) fAllMine = fAllMine && wallet->IsMine(txin); parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); } } } return parts; } void TransactionRecord::updateStatus(const CWalletTx &wtx) { // Determine transaction status // Find the block the tx is in CBlockIndex* pindex = NULL; std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock); if (mi != mapBlockIndex.end()) pindex = (*mi).second; // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx); status.confirmed = wtx.IsConfirmed(); status.depth = wtx.GetDepthInMainChain(); status.cur_num_blocks = nBestHeight; if (!wtx.IsFinal()) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = nBestHeight - wtx.nLockTime; } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.nLockTime; } } else { if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) { status.status = TransactionStatus::Offline; } else if (status.depth < NumConfirmations) { status.status = TransactionStatus::Unconfirmed; } else { status.status = TransactionStatus::HaveConfirmations; } } // For generated transactions, determine maturity if(type == TransactionRecord::Generated) { int64 nCredit = wtx.GetCredit(true); if (nCredit == 0) { status.maturity = TransactionStatus::Immature; if (wtx.IsInMainChain()) { status.matures_in = wtx.GetBlocksToMaturity(); // Check if the block was requested by anyone if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) status.maturity = TransactionStatus::MaturesWarning; } else { status.maturity = TransactionStatus::NotAccepted; } } else { status.maturity = TransactionStatus::Mature; } } } bool TransactionRecord::statusUpdateNeeded() { return status.cur_num_blocks != nBestHeight; } std::string TransactionRecord::getTxID() { return hash.ToString() + strprintf("-%03d", idx); } <|endoftext|>
<commit_before>#include "utils.h" #include "crypto/sha2.h" #include "flaggedarrayset.h" #include "relayprocess.h" #include <stdio.h> #include <sys/time.h> #include <algorithm> #include <random> #include <string.h> #include <unistd.h> void fill_txv(std::vector<unsigned char>& block, std::vector<std::shared_ptr<std::vector<unsigned char> > >& txVectors, float includeP) { std::vector<unsigned char>::const_iterator readit = block.begin(); move_forward(readit, sizeof(struct bitcoin_msg_header), block.end()); move_forward(readit, 80, block.end()); uint32_t txcount = read_varint(readit, block.end()); std::default_random_engine engine; std::uniform_real_distribution<double> distribution(0.0, 1.0); for (uint32_t i = 0; i < txcount; i++) { std::vector<unsigned char>::const_iterator txstart = readit; move_forward(readit, 4, block.end()); uint32_t txins = read_varint(readit, block.end()); for (uint32_t j = 0; j < txins; j++) { move_forward(readit, 36, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen + 4, block.end()); } uint32_t txouts = read_varint(readit, block.end()); for (uint32_t j = 0; j < txouts; j++) { move_forward(readit, 8, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen, block.end()); } move_forward(readit, 4, block.end()); if (distribution(engine) < includeP) txVectors.push_back(std::make_shared<std::vector<unsigned char> >(txstart, readit)); } std::shuffle(txVectors.begin(), txVectors.end(), std::default_random_engine()); } int pipefd[2]; uint32_t block_tx_count; std::shared_ptr<std::vector<unsigned char> > decompressed_block; RelayNodeCompressor receiver; void recv_block() { auto res = receiver.decompress_relay_block(pipefd[0], block_tx_count); if (std::get<2>(res)) { printf("ERROR Decompressing block %s\n", std::get<2>(res)); exit(2); } decompressed_block = std::get<1>(res); } void compress_block(std::vector<unsigned char>& data, std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors) { std::vector<unsigned char> fullhash(32); getblockhash(fullhash, data, sizeof(struct bitcoin_msg_header)); RelayNodeCompressor sender; receiver.reset(); for (auto& v : txVectors) if (sender.get_relay_transaction(v).use_count()) receiver.recv_tx(v); struct timeval start, compressed; gettimeofday(&start, NULL); auto res = sender.maybe_compress_block(fullhash, data, true); gettimeofday(&compressed, NULL); printf("Compressed from %lu to %lu in %ld ms with %lu txn pre-relayed\n", data.size(), std::get<0>(res)->size(), int64_t(compressed.tv_sec - start.tv_sec)*1000 + (int64_t(compressed.tv_usec) - start.tv_usec)/1000, txVectors.size()); struct relay_msg_header header; memcpy(&header, &(*std::get<0>(res))[0], sizeof(header)); block_tx_count = ntohl(header.length); if (pipe(pipefd)) { printf("Failed to create pipe?\n"); exit(3); } std::thread recv(recv_block); write(pipefd[1], &(*std::get<0>(res))[sizeof(header)], std::get<0>(res)->size() - sizeof(header)); recv.join(); if (*decompressed_block != data) { printf("Re-constructed block did not match!\n"); exit(4); } } void run_test(std::vector<unsigned char>& data) { std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors; compress_block(data, txVectors); fill_txv(data, txVectors, 1.0); compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.5); compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.9); compress_block(data, txVectors); } int main() { std::vector<unsigned char> data(sizeof(struct bitcoin_msg_header)); std::vector<unsigned char> lastBlock; std::vector<std::shared_ptr<std::vector<unsigned char> > > allTxn; FILE* f = fopen("block.txt", "r"); while (true) { char hex[2]; if (fread(hex, 1, 1, f) != 1) break; else if (hex[0] == '\n') { if (data.size()) { run_test(data); fill_txv(data, allTxn, 0.9); lastBlock = data; } data = std::vector<unsigned char>(sizeof(struct bitcoin_msg_header)); } else if (fread(hex + 1, 1, 1, f) != 1) break; else { if (hex[0] >= 'a') hex[0] -= 'a' - '9' - 1; if (hex[1] >= 'a') hex[1] -= 'a' - '9' - 1; data.push_back((hex[0] - '0') << 4 | (hex[1] - '0')); } } compress_block(lastBlock, allTxn); return 0; } <commit_msg>Time decompress in test as well<commit_after>#include "utils.h" #include "crypto/sha2.h" #include "flaggedarrayset.h" #include "relayprocess.h" #include <stdio.h> #include <sys/time.h> #include <algorithm> #include <random> #include <string.h> #include <unistd.h> void fill_txv(std::vector<unsigned char>& block, std::vector<std::shared_ptr<std::vector<unsigned char> > >& txVectors, float includeP) { std::vector<unsigned char>::const_iterator readit = block.begin(); move_forward(readit, sizeof(struct bitcoin_msg_header), block.end()); move_forward(readit, 80, block.end()); uint32_t txcount = read_varint(readit, block.end()); std::default_random_engine engine; std::uniform_real_distribution<double> distribution(0.0, 1.0); for (uint32_t i = 0; i < txcount; i++) { std::vector<unsigned char>::const_iterator txstart = readit; move_forward(readit, 4, block.end()); uint32_t txins = read_varint(readit, block.end()); for (uint32_t j = 0; j < txins; j++) { move_forward(readit, 36, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen + 4, block.end()); } uint32_t txouts = read_varint(readit, block.end()); for (uint32_t j = 0; j < txouts; j++) { move_forward(readit, 8, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen, block.end()); } move_forward(readit, 4, block.end()); if (distribution(engine) < includeP) txVectors.push_back(std::make_shared<std::vector<unsigned char> >(txstart, readit)); } std::shuffle(txVectors.begin(), txVectors.end(), std::default_random_engine()); } int pipefd[2]; uint32_t block_tx_count; std::shared_ptr<std::vector<unsigned char> > decompressed_block; RelayNodeCompressor receiver; void recv_block() { struct timeval start, decompressed; gettimeofday(&start, NULL); auto res = receiver.decompress_relay_block(pipefd[0], block_tx_count); gettimeofday(&decompressed, NULL); if (std::get<2>(res)) { printf("ERROR Decompressing block %s\n", std::get<2>(res)); exit(2); } else printf("Decompressed block in %lu ms\n", int64_t(decompressed.tv_sec - start.tv_sec)*1000 + (int64_t(decompressed.tv_usec) - start.tv_usec)/1000); decompressed_block = std::get<1>(res); } void compress_block(std::vector<unsigned char>& data, std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors) { std::vector<unsigned char> fullhash(32); getblockhash(fullhash, data, sizeof(struct bitcoin_msg_header)); RelayNodeCompressor sender; receiver.reset(); for (auto& v : txVectors) if (sender.get_relay_transaction(v).use_count()) receiver.recv_tx(v); struct timeval start, compressed; gettimeofday(&start, NULL); auto res = sender.maybe_compress_block(fullhash, data, true); gettimeofday(&compressed, NULL); printf("Compressed from %lu to %lu in %ld ms with %lu txn pre-relayed\n", data.size(), std::get<0>(res)->size(), int64_t(compressed.tv_sec - start.tv_sec)*1000 + (int64_t(compressed.tv_usec) - start.tv_usec)/1000, txVectors.size()); struct relay_msg_header header; memcpy(&header, &(*std::get<0>(res))[0], sizeof(header)); block_tx_count = ntohl(header.length); if (pipe(pipefd)) { printf("Failed to create pipe?\n"); exit(3); } std::thread recv(recv_block); write(pipefd[1], &(*std::get<0>(res))[sizeof(header)], std::get<0>(res)->size() - sizeof(header)); recv.join(); if (*decompressed_block != data) { printf("Re-constructed block did not match!\n"); exit(4); } } void run_test(std::vector<unsigned char>& data) { std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors; compress_block(data, txVectors); fill_txv(data, txVectors, 1.0); compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.5); compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.9); compress_block(data, txVectors); } int main() { std::vector<unsigned char> data(sizeof(struct bitcoin_msg_header)); std::vector<unsigned char> lastBlock; std::vector<std::shared_ptr<std::vector<unsigned char> > > allTxn; FILE* f = fopen("block.txt", "r"); while (true) { char hex[2]; if (fread(hex, 1, 1, f) != 1) break; else if (hex[0] == '\n') { if (data.size()) { run_test(data); fill_txv(data, allTxn, 0.9); lastBlock = data; } data = std::vector<unsigned char>(sizeof(struct bitcoin_msg_header)); } else if (fread(hex + 1, 1, 1, f) != 1) break; else { if (hex[0] >= 'a') hex[0] -= 'a' - '9' - 1; if (hex[1] >= 'a') hex[1] -= 'a' - '9' - 1; data.push_back((hex[0] - '0') << 4 | (hex[1] - '0')); } } compress_block(lastBlock, allTxn); return 0; } <|endoftext|>
<commit_before>#include "CUDADenseGraphBFSearcher.h" #include <sqaodc/common/internal/ShapeChecker.h> #include <sqaodc/cpu/SharedFormulas.h> #include "Device.h" #include <cmath> #include <float.h> #include <algorithm> #include <limits> namespace sqint = sqaod_internal; namespace sqcpu = sqaod_cpu; using namespace sqaod_cuda; template<class real> CUDADenseGraphBFSearcher<real>::CUDADenseGraphBFSearcher() { tileSize_ = 1u << 18; /* FIXME: give a correct size */ deviceAssigned_ = false; } template<class real> CUDADenseGraphBFSearcher<real>::CUDADenseGraphBFSearcher(Device &device) { tileSize_ = 1u << 18; /* FIXME: give a correct size */ deviceAssigned_ = false; assignDevice(device); } template<class real> CUDADenseGraphBFSearcher<real>::~CUDADenseGraphBFSearcher() { } template<class real> void CUDADenseGraphBFSearcher<real>::deallocate() { if (h_packedXmin_.d_data != NULL) HostObjectAllocator().deallocate(h_packedXmin_); batchSearch_.deallocate(); } template<class real> void CUDADenseGraphBFSearcher<real>::assignDevice(sqaod::cuda::Device &device) { assignDevice(static_cast<Device&>(device)); } template<class real> void CUDADenseGraphBFSearcher<real>::assignDevice(Device &device) { throwErrorIf(deviceAssigned_, "Device already assigned."); batchSearch_.assignDevice(device); devCopy_.assignDevice(device); deviceAssigned_ = true; } template<class real> void CUDADenseGraphBFSearcher<real>::setQUBO(const Matrix &W, sq::OptimizeMethod om) { throwErrorIf(!deviceAssigned_, "Device not set."); sqint::matrixCheckIfSymmetric(W, __func__); throwErrorIf(63 < W.rows, "N must be smaller than 64, N=%d.", W.rows); N_ = W.rows; W_ = sqcpu::symmetrize(W); om_ = om; if (om_ == sq::optMaximize) W_ *= real(-1.); setState(solProblemSet); } template<class real> sq::Preferences CUDADenseGraphBFSearcher<real>::getPreferences() const { sq::Preferences prefs = Base::getPreferences(); prefs.pushBack(sq::Preference(sq::pnDevice, "cuda")); return prefs; } template<class real> const sq::BitSetArray &CUDADenseGraphBFSearcher<real>::get_x() const { if (!isSolutionAvailable()) const_cast<This*>(this)->makeSolution(); /* synchronized there */ return xList_; } template<class real> const sq::VectorType<real> &CUDADenseGraphBFSearcher<real>::get_E() const { if (!isEAvailable()) const_cast<This*>(this)->calculate_E(); return E_; } template<class real> void CUDADenseGraphBFSearcher<real>::prepare() { throwErrorIfProblemNotSet(); deallocate(); x_ = 0; sq::PackedBitSet maxTileSize = 1ull << N_; if (maxTileSize < (sq::PackedBitSet)tileSize_) { tileSize_ = maxTileSize; sq::log("Tile size is adjusted to %d for N=%d", maxTileSize, N_); } batchSearch_.setQUBO(W_, tileSize_); HostObjectAllocator().allocate(&h_packedXmin_, tileSize_ * 2); Emin_ = std::numeric_limits<real>::max(); xList_.clear(); xMax_ = 1ull << N_; setState(solPrepared); #ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST rangeMap_.clear(); #endif } template<class real> void CUDADenseGraphBFSearcher<real>::calculate_E() { throwErrorIfNotPrepared(); if (xList_.empty()) E_.resize(1); else E_.resize(xList_.size()); E_ = Emin_; if (om_ == sq::optMaximize) E_ *= real(-1.); setState(solEAvailable); } template<class real> void CUDADenseGraphBFSearcher<real>::makeSolution() { throwErrorIfNotPrepared(); batchSearch_.synchronize(); const DevicePackedBitSetArray &dPackedXmin = batchSearch_.get_xMins(); sq::SizeType nXMin = std::min(tileSize_, dPackedXmin.size); devCopy_(&h_packedXmin_, dPackedXmin); devCopy_.synchronize(); xList_.clear(); for (sq::IdxType idx = 0; idx < (sq::IdxType)nXMin; ++idx) { sq::BitSet bits; unpackBitSet(&bits, h_packedXmin_[idx], N_); xList_.pushBack(bits); // FIXME: apply move } setState(solSolutionAvailable); calculate_E(); #ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST assert(rangeMap_.size() == 1); sq::PackedBitSetPair pair = rangeMap_[0]; assert((pair.bits0 == 0) && (pair.bits1 == xMax_)); #endif } template<class real> bool CUDADenseGraphBFSearcher<real>::searchRange(sq::PackedBitSet *curXEnd) { throwErrorIfNotPrepared(); clearState(solSolutionAvailable); /* FIXME: Use multiple searchers, multi GPU */ sq::PackedBitSet xBegin = x_; sq::PackedBitSet xEnd = std::min(x_ + tileSize_, xMax_); if (xBegin < xEnd) { batchSearch_.calculate_E(xBegin, xEnd); batchSearch_.synchronize(); real newEmin = batchSearch_.get_Emin(); if (newEmin < Emin_) { batchSearch_.partition_xMins(false); Emin_ = newEmin; } else if (newEmin == Emin_) { batchSearch_.partition_xMins(true); } } #ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST if (xBegin < xEnd) rangeMap_.insert(xBegin, xEnd); #endif x_ = xEnd; if (curXEnd != NULL) *curXEnd = x_; return x_ == xMax_; } template class sqaod_cuda::CUDADenseGraphBFSearcher<float>; template class sqaod_cuda::CUDADenseGraphBFSearcher<double>; <commit_msg>Suppress warning on VS.<commit_after>#include "CUDADenseGraphBFSearcher.h" #include <sqaodc/common/internal/ShapeChecker.h> #include <sqaodc/cpu/SharedFormulas.h> #include "Device.h" #include <cmath> #include <float.h> #include <algorithm> #include <limits> namespace sqint = sqaod_internal; namespace sqcpu = sqaod_cpu; using namespace sqaod_cuda; template<class real> CUDADenseGraphBFSearcher<real>::CUDADenseGraphBFSearcher() { tileSize_ = 1u << 18; /* FIXME: give a correct size */ deviceAssigned_ = false; } template<class real> CUDADenseGraphBFSearcher<real>::CUDADenseGraphBFSearcher(Device &device) { tileSize_ = 1u << 18; /* FIXME: give a correct size */ deviceAssigned_ = false; assignDevice(device); } template<class real> CUDADenseGraphBFSearcher<real>::~CUDADenseGraphBFSearcher() { } template<class real> void CUDADenseGraphBFSearcher<real>::deallocate() { if (h_packedXmin_.d_data != NULL) HostObjectAllocator().deallocate(h_packedXmin_); batchSearch_.deallocate(); } template<class real> void CUDADenseGraphBFSearcher<real>::assignDevice(sqaod::cuda::Device &device) { assignDevice(static_cast<Device&>(device)); } template<class real> void CUDADenseGraphBFSearcher<real>::assignDevice(Device &device) { throwErrorIf(deviceAssigned_, "Device already assigned."); batchSearch_.assignDevice(device); devCopy_.assignDevice(device); deviceAssigned_ = true; } template<class real> void CUDADenseGraphBFSearcher<real>::setQUBO(const Matrix &W, sq::OptimizeMethod om) { throwErrorIf(!deviceAssigned_, "Device not set."); sqint::matrixCheckIfSymmetric(W, __func__); throwErrorIf(63 < W.rows, "N must be smaller than 64, N=%d.", W.rows); N_ = W.rows; W_ = sqcpu::symmetrize(W); om_ = om; if (om_ == sq::optMaximize) W_ *= real(-1.); setState(solProblemSet); } template<class real> sq::Preferences CUDADenseGraphBFSearcher<real>::getPreferences() const { sq::Preferences prefs = Base::getPreferences(); prefs.pushBack(sq::Preference(sq::pnDevice, "cuda")); return prefs; } template<class real> const sq::BitSetArray &CUDADenseGraphBFSearcher<real>::get_x() const { if (!isSolutionAvailable()) const_cast<This*>(this)->makeSolution(); /* synchronized there */ return xList_; } template<class real> const sq::VectorType<real> &CUDADenseGraphBFSearcher<real>::get_E() const { if (!isEAvailable()) const_cast<This*>(this)->calculate_E(); return E_; } template<class real> void CUDADenseGraphBFSearcher<real>::prepare() { throwErrorIfProblemNotSet(); deallocate(); x_ = 0; sq::PackedBitSet maxTileSize = 1ull << N_; if (maxTileSize < (sq::PackedBitSet)tileSize_) { tileSize_ = (sq::SizeType)maxTileSize; sq::log("Tile size is adjusted to %d for N=%d", maxTileSize, N_); } batchSearch_.setQUBO(W_, tileSize_); HostObjectAllocator().allocate(&h_packedXmin_, tileSize_ * 2); Emin_ = std::numeric_limits<real>::max(); xList_.clear(); xMax_ = 1ull << N_; setState(solPrepared); #ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST rangeMap_.clear(); #endif } template<class real> void CUDADenseGraphBFSearcher<real>::calculate_E() { throwErrorIfNotPrepared(); if (xList_.empty()) E_.resize(1); else E_.resize(xList_.size()); E_ = Emin_; if (om_ == sq::optMaximize) E_ *= real(-1.); setState(solEAvailable); } template<class real> void CUDADenseGraphBFSearcher<real>::makeSolution() { throwErrorIfNotPrepared(); batchSearch_.synchronize(); const DevicePackedBitSetArray &dPackedXmin = batchSearch_.get_xMins(); sq::SizeType nXMin = std::min(tileSize_, dPackedXmin.size); devCopy_(&h_packedXmin_, dPackedXmin); devCopy_.synchronize(); xList_.clear(); for (sq::IdxType idx = 0; idx < (sq::IdxType)nXMin; ++idx) { sq::BitSet bits; unpackBitSet(&bits, h_packedXmin_[idx], N_); xList_.pushBack(bits); // FIXME: apply move } setState(solSolutionAvailable); calculate_E(); #ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST assert(rangeMap_.size() == 1); sq::PackedBitSetPair pair = rangeMap_[0]; assert((pair.bits0 == 0) && (pair.bits1 == xMax_)); #endif } template<class real> bool CUDADenseGraphBFSearcher<real>::searchRange(sq::PackedBitSet *curXEnd) { throwErrorIfNotPrepared(); clearState(solSolutionAvailable); /* FIXME: Use multiple searchers, multi GPU */ sq::PackedBitSet xBegin = x_; sq::PackedBitSet xEnd = std::min(x_ + tileSize_, xMax_); if (xBegin < xEnd) { batchSearch_.calculate_E(xBegin, xEnd); batchSearch_.synchronize(); real newEmin = batchSearch_.get_Emin(); if (newEmin < Emin_) { batchSearch_.partition_xMins(false); Emin_ = newEmin; } else if (newEmin == Emin_) { batchSearch_.partition_xMins(true); } } #ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST if (xBegin < xEnd) rangeMap_.insert(xBegin, xEnd); #endif x_ = xEnd; if (curXEnd != NULL) *curXEnd = x_; return x_ == xMax_; } template class sqaod_cuda::CUDADenseGraphBFSearcher<float>; template class sqaod_cuda::CUDADenseGraphBFSearcher<double>; <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // User message widget //============================================================================== #include "usermessagewidget.h" //============================================================================== #include <Qt> //============================================================================== #include <QFont> #include <QSizePolicy> #include <QWidget> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== void UserMessageWidget::constructor(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage) { // Some initialisations mIcon = QString(); mMessage = QString(); mExtraMessage = QString(); // Customise our background setAutoFillBackground(true); setBackgroundRole(QPalette::Base); // Increase the size of our font QFont newFont = font(); newFont.setPointSizeF(1.35*newFont.pointSize()); setFont(newFont); // Some other customisations setContextMenuPolicy(Qt::NoContextMenu); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setWordWrap(true); // 'Initialise' our message setIconMessage(pIcon, pMessage, pExtraMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon, pMessage, pExtraMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, const QString &pMessage, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon, pMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon); } //============================================================================== UserMessageWidget::UserMessageWidget(QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(); } //============================================================================== void UserMessageWidget::setIconMessage(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage) { // Set our message, if needed if ( pIcon.compare(mIcon) || pMessage.compare(mMessage) || pExtraMessage.compare(mExtraMessage)) { mIcon = pIcon; mMessage = pMessage; mExtraMessage = pExtraMessage; if (mExtraMessage.isEmpty()) setText(QString("<table align=center>" " <tr valign=middle>" " <td>" " <img src=\"%1\"/>" " </td>" " <td align=center>" " <p style=\"margin: 0px;\">" " %2" " </p>" " </td>" " </tr>" "</table>").arg(mIcon, mMessage)); else setText(QString("<table align=center>" " <tr valign=middle>" " <td>" " <img src=\"%1\"/>" " </td>" " <td align=center>" " <p style=\"margin: 0px;\">" " %2" " </p>" " <p style=\"margin: 0px;\">" " <small><em>(%3)</em></small>" " </p>" " </td>" " </tr>" "</table>").arg(mIcon, mMessage, mExtraMessage)); } } //============================================================================== void UserMessageWidget::setMessage(const QString &pMessage, const QString &pExtraMessage) { // Set our message setIconMessage(mIcon, pMessage, pExtraMessage); } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up of Core::UserMessageWidget.<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team 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. *******************************************************************************/ //============================================================================== // User message widget //============================================================================== #include "usermessagewidget.h" //============================================================================== #include <Qt> //============================================================================== #include <QFont> #include <QSizePolicy> #include <QWidget> //============================================================================== namespace OpenCOR { namespace Core { //============================================================================== void UserMessageWidget::constructor(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage) { // Some initialisations mIcon = QString(); mMessage = QString(); mExtraMessage = QString(); // Customise our background setAutoFillBackground(true); setBackgroundRole(QPalette::Base); // Increase the size of our font QFont newFont = font(); newFont.setPointSizeF(1.35*newFont.pointSize()); setFont(newFont); // Some other customisations setContextMenuPolicy(Qt::NoContextMenu); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setWordWrap(true); // 'Initialise' our message setIconMessage(pIcon, pMessage, pExtraMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon, pMessage, pExtraMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, const QString &pMessage, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon, pMessage); } //============================================================================== UserMessageWidget::UserMessageWidget(const QString &pIcon, QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(pIcon); } //============================================================================== UserMessageWidget::UserMessageWidget(QWidget *pParent) : QLabel(pParent) { // Construct our object constructor(); } //============================================================================== void UserMessageWidget::setIconMessage(const QString &pIcon, const QString &pMessage, const QString &pExtraMessage) { // Set our message, if needed if ( pIcon.compare(mIcon) || pMessage.compare(mMessage) || pExtraMessage.compare(mExtraMessage)) { mIcon = pIcon; mMessage = pMessage; mExtraMessage = pExtraMessage; if (mExtraMessage.isEmpty()) setText(QString("<table align=center>" " <tbody>" " <tr valign=middle>" " <td>" " <img src=\"%1\"/>" " </td>" " <td align=center>" " <p style=\"margin: 0px;\">" " %2" " </p>" " </td>" " </tr>" " </tbody>" "</table>").arg(mIcon, mMessage)); else setText(QString("<table align=center>" " <tbody>" " <tr valign=middle>" " <td>" " <img src=\"%1\"/>" " </td>" " <td align=center>" " <p style=\"margin: 0px;\">" " %2" " </p>" " <p style=\"margin: 0px;\">" " <small><em>(%3)</em></small>" " </p>" " </td>" " </tr>" " </tbody>" "</table>").arg(mIcon, mMessage, mExtraMessage)); } } //============================================================================== void UserMessageWidget::setMessage(const QString &pMessage, const QString &pExtraMessage) { // Set our message setIconMessage(mIcon, pMessage, pExtraMessage); } //============================================================================== } // namespace Core } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> in_all_people, int in_dim ) { all_people = in_all_people; dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); field <std::string> parallel_names(n_peo*n_actions,4); int sc = total_scenes; //Solo estoy usando 1 int k =0; for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; load_folder << path <<"./kth-features_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; parallel_names(k,0) = load_feat_video_i.str(); parallel_names(k,1) = load_labels_video_i.str(); parallel_names(k,2) = std::to_string(pe); parallel_names(k,3) = std::to_string(act); k++; } } //Aca podria hacer el paparelo for (int k = 0; k< parallel_names.n_rows; ++k) { std::string load_feat_video_i = parallel_names(k,0); std::string load_labels_video_i = parallel_names(k,1); int pe = atoi( parallel_names(k,2).c_str() ); int act = atoi( parallel_names(k,3).c_str() ); cov_mat_kth::one_video(load_feat_video_i, load_labels_video_i, sc, pe, act ); } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act ) { cout << load_feat_video_i << endl; mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, hdf5_binary ); lab_video_i.load( load_labels_video_i, hdf5_binary ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); //cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; //cout << " " << l; for (int j=l; j< l + segment_length; ++j) { //k++; //cout << " " << j; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } //cout << endl; //cout << " " << stat_seg.count(); if (stat_seg.count()>100) // Cuando en el segmento hay mas de 100 vectores { std::stringstream save_cov_seg; save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; std::stringstream save_LogMcov_seg; save_LogMcov_seg << save_folder.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; double THRESH = 0.000001; mat cov_seg_i = stat_seg.cov(); //Following Mehrtash suggestions as per email dated June26th 2014 cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t()); vec D; mat V; eig_sym(D, V, cov_seg_i); uvec q1 = find(D < THRESH); if (q1.n_elem>0) { for (uword pos = 0; pos < q1.n_elem; ++pos) { D( q1(pos) ) = THRESH; } cov_seg_i = V*diagmat(D)*V.t(); } //end suggestion eig_sym(D, V, cov_seg_i); mat log_M = V*diagmat( log(D) )*V.t(); cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); log_M.save( save_LogMcov_seg.str(), hdf5_binary ); s++; } else { //cout << " " << stat_seg.count(); //getchar(); } } std::stringstream save_seg; vec total_seg; total_seg.zeros(1); total_seg( 0 ) = s; save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str(), raw_ascii ); cout << "Total # of segments " << s << endl; //cout << "press a key " ; //getchar(); } <commit_msg>Changing code to make it easy tu run in parallel<commit_after>inline cov_mat_kth::cov_mat_kth( const std::string in_path, const std::string in_actionNames, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length ) :path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length) { actions.load( actionNames ); } inline void cov_mat_kth::calculate( field<string> in_all_people, int in_dim ) { all_people = in_all_people; dim = in_dim; int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); field <std::string> parallel_names(n_peo*n_actions,4); int sc = total_scenes; //Solo estoy usando 1 int k =0; for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream load_folder; std::stringstream load_feat_video_i; std::stringstream load_labels_video_i; load_folder << path <<"./kth-features_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; parallel_names(k,0) = load_feat_video_i.str(); parallel_names(k,1) = load_labels_video_i.str(); parallel_names(k,2) = std::stoi(pe); parallel_names(k,3) = std::stoi(act); k++; } } //Aca podria hacer el paparelo for (int k = 0; k< parallel_names.n_rows; ++k) { std::string load_feat_video_i = parallel_names(k,0); std::string load_labels_video_i = parallel_names(k,1); int pe = atoi( parallel_names(k,2).c_str() ); int act = atoi( parallel_names(k,3).c_str() ); cov_mat_kth::one_video(load_feat_video_i, load_labels_video_i, sc, pe, act ); } } inline void cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act ) { cout << load_feat_video_i << endl; mat mat_features_video_i; vec lab_video_i; mat_features_video_i.load( load_feat_video_i, hdf5_binary ); lab_video_i.load( load_labels_video_i, hdf5_binary ); int n_vec = lab_video_i.n_elem; int last = lab_video_i( n_vec - 1 ); //cout << last << endl; int s = 0; std::stringstream save_folder; save_folder << "./kth-cov-mat_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; for (int l=2; l<last-segment_length; l = l+4 ) { running_stat_vec<rowvec> stat_seg(true); //int k =0; //cout << " " << l; for (int j=l; j< l + segment_length; ++j) { //k++; //cout << " " << j; uvec indices = find(lab_video_i == j); mat tmp_feat = mat_features_video_i.cols(indices); //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl; for (int v=0; v < tmp_feat.n_cols; ++v) { vec sample = tmp_feat.col(v); stat_seg (sample); } } //cout << endl; //cout << " " << stat_seg.count(); if (stat_seg.count()>100) // Cuando en el segmento hay mas de 100 vectores { std::stringstream save_cov_seg; save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; std::stringstream save_LogMcov_seg; save_LogMcov_seg << save_folder.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; double THRESH = 0.000001; mat cov_seg_i = stat_seg.cov(); //Following Mehrtash suggestions as per email dated June26th 2014 cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t()); vec D; mat V; eig_sym(D, V, cov_seg_i); uvec q1 = find(D < THRESH); if (q1.n_elem>0) { for (uword pos = 0; pos < q1.n_elem; ++pos) { D( q1(pos) ) = THRESH; } cov_seg_i = V*diagmat(D)*V.t(); } //end suggestion eig_sym(D, V, cov_seg_i); mat log_M = V*diagmat( log(D) )*V.t(); cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); log_M.save( save_LogMcov_seg.str(), hdf5_binary ); s++; } else { //cout << " " << stat_seg.count(); //getchar(); } } std::stringstream save_seg; vec total_seg; total_seg.zeros(1); total_seg( 0 ) = s; save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.save( save_seg.str(), raw_ascii ); cout << "Total # of segments " << s << endl; //cout << "press a key " ; //getchar(); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmakeprojectimporter.h" #include "qmakebuildinfo.h" #include "qmakekitinformation.h" #include "qmakebuildconfiguration.h" #include "qmakeproject.h" #include <coreplugin/icore.h> #include <coreplugin/idocument.h> #include <projectexplorer/kitmanager.h> #include <projectexplorer/target.h> #include <qtsupport/qtkitinformation.h> #include <qtsupport/qtsupportconstants.h> #include <qtsupport/qtversionfactory.h> #include <qtsupport/qtversionmanager.h> #include <utils/qtcprocess.h> #include <QDir> #include <QFileInfo> #include <QStringList> #include <QMessageBox> static const Core::Id QT_IS_TEMPORARY("Qmake.TempQt"); namespace QmakeProjectManager { namespace Internal { QmakeProjectImporter::QmakeProjectImporter(const QString &path) : ProjectExplorer::ProjectImporter(path) { } QList<ProjectExplorer::BuildInfo *> QmakeProjectImporter::import(const Utils::FileName &importPath, bool silent) { QList<ProjectExplorer::BuildInfo *> result; QFileInfo fi = importPath.toFileInfo(); if (!fi.exists() && !fi.isDir()) return result; QStringList makefiles = QDir(importPath.toString()).entryList(QStringList(QLatin1String("Makefile*"))); QtSupport::BaseQtVersion *version = 0; bool temporaryVersion = false; foreach (const QString &file, makefiles) { // find interesting makefiles QString makefile = importPath.toString() + QLatin1Char('/') + file; Utils::FileName qmakeBinary = QtSupport::QtVersionManager::findQMakeBinaryFromMakefile(makefile); QFileInfo qmakeFi = qmakeBinary.toFileInfo(); Utils::FileName canonicalQmakeBinary = Utils::FileName::fromString(qmakeFi.canonicalFilePath()); if (canonicalQmakeBinary.isEmpty()) continue; if (QtSupport::QtVersionManager::makefileIsFor(makefile, projectFilePath()) != QtSupport::QtVersionManager::SameProject) continue; // Find version: foreach (QtSupport::BaseQtVersion *v, QtSupport::QtVersionManager::versions()) { QFileInfo vfi = v->qmakeCommand().toFileInfo(); Utils::FileName current = Utils::FileName::fromString(vfi.canonicalFilePath()); if (current == canonicalQmakeBinary) { version = v; break; } } // Create a new version if not found: if (!version) { // Do not use the canonical path here... version = QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmakeBinary); if (!version) continue; setIsUpdating(true); QtSupport::QtVersionManager::addVersion(version); setIsUpdating(false); temporaryVersion = true; } // find qmake arguments and mkspec QPair<QtSupport::BaseQtVersion::QmakeBuildConfigs, QString> makefileBuildConfig = QtSupport::QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig()); QString additionalArguments = makefileBuildConfig.second; Utils::FileName parsedSpec = QmakeBuildConfiguration::extractSpecFromArguments(&additionalArguments, importPath.toString(), version); Utils::FileName versionSpec = version->mkspec(); if (parsedSpec.isEmpty() || parsedSpec == Utils::FileName::fromLatin1("default")) parsedSpec = versionSpec; QString specArgument; // Compare mkspecs and add to additional arguments if (parsedSpec != versionSpec) specArgument = QLatin1String("-spec ") + Utils::QtcProcess::quoteArg(parsedSpec.toUserOutput()); Utils::QtcProcess::addArgs(&specArgument, additionalArguments); // Find kits (can be more than one, e.g. (Linux-)Desktop and embedded linux): QList<ProjectExplorer::Kit *> kitList; foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits()) { QtSupport::BaseQtVersion *kitVersion = QtSupport::QtKitInformation::qtVersion(k); Utils::FileName kitSpec = QmakeKitInformation::mkspec(k); ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k); if (kitSpec.isEmpty() && kitVersion) kitSpec = kitVersion->mkspecFor(tc); if (kitVersion == version && kitSpec == parsedSpec) kitList.append(k); } if (kitList.isEmpty()) kitList.append(createTemporaryKit(version, temporaryVersion, parsedSpec)); foreach (ProjectExplorer::Kit *k, kitList) { addProject(k); QmakeBuildConfigurationFactory *factory = qobject_cast<QmakeBuildConfigurationFactory *>( ProjectExplorer::IBuildConfigurationFactory::find(k, projectFilePath())); if (!factory) continue; // create info: QmakeBuildInfo *info = new QmakeBuildInfo(factory); if (makefileBuildConfig.first & QtSupport::BaseQtVersion::DebugBuild) { info->type = ProjectExplorer::BuildConfiguration::Debug; info->displayName = QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "Debug"); } else { info->type = ProjectExplorer::BuildConfiguration::Release; info->displayName = QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "Release"); } info->kitId = k->id(); info->buildDirectory = Utils::FileName::fromString(fi.absoluteFilePath()); info->additionalArguments = additionalArguments; info->makefile = makefile; bool found = false; foreach (ProjectExplorer::BuildInfo *bInfo, result) { if (*static_cast<QmakeBuildInfo *>(bInfo) == *info) { found = true; break; } } if (found) delete info; else result << info; } } if (result.isEmpty() && !silent) QMessageBox::critical(Core::ICore::mainWindow(), QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "No Build Found"), QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "No build found in %1 matching project %2.") .arg(importPath.toUserOutput()).arg(projectFilePath())); return result; } QStringList QmakeProjectImporter::importCandidates(const Utils::FileName &projectPath) { QStringList candidates; QFileInfo pfi = projectPath.toFileInfo(); const QString prefix = pfi.baseName(); candidates << pfi.absolutePath(); QList<ProjectExplorer::Kit *> kitList = ProjectExplorer::KitManager::kits(); foreach (ProjectExplorer::Kit *k, kitList) { QFileInfo fi(QmakeProject::shadowBuildDirectory(projectPath.toString(), k, QString())); const QString baseDir = fi.absolutePath(); foreach (const QString &dir, QDir(baseDir).entryList()) { const QString path = baseDir + QLatin1Char('/') + dir; if (dir.startsWith(prefix) && !candidates.contains(path)) candidates << path; } } return candidates; } ProjectExplorer::Target *QmakeProjectImporter::preferredTarget(const QList<ProjectExplorer::Target *> &possibleTargets) { // Select active target // a) The default target // b) Simulator target // c) Desktop target // d) the first target ProjectExplorer::Target *activeTarget = possibleTargets.isEmpty() ? 0 : possibleTargets.at(0); int activeTargetPriority = 0; foreach (ProjectExplorer::Target *t, possibleTargets) { QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(t->kit()); if (t->kit() == ProjectExplorer::KitManager::defaultKit()) { activeTarget = t; activeTargetPriority = 3; } else if (activeTargetPriority < 2 && version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)) { activeTarget = t; activeTargetPriority = 2; } else if (activeTargetPriority < 1 && version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)) { activeTarget = t; activeTargetPriority = 1; } } return activeTarget; } void QmakeProjectImporter::cleanupKit(ProjectExplorer::Kit *k) { QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::version(k->value(QT_IS_TEMPORARY, -1).toInt()); if (version) QtSupport::QtVersionManager::removeVersion(version); } ProjectExplorer::Kit *QmakeProjectImporter::createTemporaryKit(QtSupport::BaseQtVersion *version, bool temporaryVersion, const Utils::FileName &parsedSpec) { ProjectExplorer::Kit *k = new ProjectExplorer::Kit; QtSupport::QtKitInformation::setQtVersion(k, version); ProjectExplorer::ToolChainKitInformation::setToolChain(k, version->preferredToolChain(parsedSpec)); QmakeKitInformation::setMkspec(k, parsedSpec); markTemporary(k); if (temporaryVersion) k->setValue(QT_IS_TEMPORARY, version->uniqueId()); k->setDisplayName(version->displayName()); setIsUpdating(true); ProjectExplorer::KitManager::registerKit(k); setIsUpdating(false); return k; } } // namespace Internal } // namespace QmakeProjectManager <commit_msg>qmakeprojectmanager: Native separators in import() error message<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmakeprojectimporter.h" #include "qmakebuildinfo.h" #include "qmakekitinformation.h" #include "qmakebuildconfiguration.h" #include "qmakeproject.h" #include <coreplugin/icore.h> #include <coreplugin/idocument.h> #include <projectexplorer/kitmanager.h> #include <projectexplorer/target.h> #include <qtsupport/qtkitinformation.h> #include <qtsupport/qtsupportconstants.h> #include <qtsupport/qtversionfactory.h> #include <qtsupport/qtversionmanager.h> #include <utils/qtcprocess.h> #include <QDir> #include <QFileInfo> #include <QStringList> #include <QMessageBox> static const Core::Id QT_IS_TEMPORARY("Qmake.TempQt"); namespace QmakeProjectManager { namespace Internal { QmakeProjectImporter::QmakeProjectImporter(const QString &path) : ProjectExplorer::ProjectImporter(path) { } QList<ProjectExplorer::BuildInfo *> QmakeProjectImporter::import(const Utils::FileName &importPath, bool silent) { QList<ProjectExplorer::BuildInfo *> result; QFileInfo fi = importPath.toFileInfo(); if (!fi.exists() && !fi.isDir()) return result; QStringList makefiles = QDir(importPath.toString()).entryList(QStringList(QLatin1String("Makefile*"))); QtSupport::BaseQtVersion *version = 0; bool temporaryVersion = false; foreach (const QString &file, makefiles) { // find interesting makefiles QString makefile = importPath.toString() + QLatin1Char('/') + file; Utils::FileName qmakeBinary = QtSupport::QtVersionManager::findQMakeBinaryFromMakefile(makefile); QFileInfo qmakeFi = qmakeBinary.toFileInfo(); Utils::FileName canonicalQmakeBinary = Utils::FileName::fromString(qmakeFi.canonicalFilePath()); if (canonicalQmakeBinary.isEmpty()) continue; if (QtSupport::QtVersionManager::makefileIsFor(makefile, projectFilePath()) != QtSupport::QtVersionManager::SameProject) continue; // Find version: foreach (QtSupport::BaseQtVersion *v, QtSupport::QtVersionManager::versions()) { QFileInfo vfi = v->qmakeCommand().toFileInfo(); Utils::FileName current = Utils::FileName::fromString(vfi.canonicalFilePath()); if (current == canonicalQmakeBinary) { version = v; break; } } // Create a new version if not found: if (!version) { // Do not use the canonical path here... version = QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmakeBinary); if (!version) continue; setIsUpdating(true); QtSupport::QtVersionManager::addVersion(version); setIsUpdating(false); temporaryVersion = true; } // find qmake arguments and mkspec QPair<QtSupport::BaseQtVersion::QmakeBuildConfigs, QString> makefileBuildConfig = QtSupport::QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig()); QString additionalArguments = makefileBuildConfig.second; Utils::FileName parsedSpec = QmakeBuildConfiguration::extractSpecFromArguments(&additionalArguments, importPath.toString(), version); Utils::FileName versionSpec = version->mkspec(); if (parsedSpec.isEmpty() || parsedSpec == Utils::FileName::fromLatin1("default")) parsedSpec = versionSpec; QString specArgument; // Compare mkspecs and add to additional arguments if (parsedSpec != versionSpec) specArgument = QLatin1String("-spec ") + Utils::QtcProcess::quoteArg(parsedSpec.toUserOutput()); Utils::QtcProcess::addArgs(&specArgument, additionalArguments); // Find kits (can be more than one, e.g. (Linux-)Desktop and embedded linux): QList<ProjectExplorer::Kit *> kitList; foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits()) { QtSupport::BaseQtVersion *kitVersion = QtSupport::QtKitInformation::qtVersion(k); Utils::FileName kitSpec = QmakeKitInformation::mkspec(k); ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k); if (kitSpec.isEmpty() && kitVersion) kitSpec = kitVersion->mkspecFor(tc); if (kitVersion == version && kitSpec == parsedSpec) kitList.append(k); } if (kitList.isEmpty()) kitList.append(createTemporaryKit(version, temporaryVersion, parsedSpec)); foreach (ProjectExplorer::Kit *k, kitList) { addProject(k); QmakeBuildConfigurationFactory *factory = qobject_cast<QmakeBuildConfigurationFactory *>( ProjectExplorer::IBuildConfigurationFactory::find(k, projectFilePath())); if (!factory) continue; // create info: QmakeBuildInfo *info = new QmakeBuildInfo(factory); if (makefileBuildConfig.first & QtSupport::BaseQtVersion::DebugBuild) { info->type = ProjectExplorer::BuildConfiguration::Debug; info->displayName = QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "Debug"); } else { info->type = ProjectExplorer::BuildConfiguration::Release; info->displayName = QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "Release"); } info->kitId = k->id(); info->buildDirectory = Utils::FileName::fromString(fi.absoluteFilePath()); info->additionalArguments = additionalArguments; info->makefile = makefile; bool found = false; foreach (ProjectExplorer::BuildInfo *bInfo, result) { if (*static_cast<QmakeBuildInfo *>(bInfo) == *info) { found = true; break; } } if (found) delete info; else result << info; } } if (result.isEmpty() && !silent) QMessageBox::critical(Core::ICore::mainWindow(), QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "No Build Found"), QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "No build found in %1 matching project %2.") .arg(importPath.toUserOutput()).arg(QDir::toNativeSeparators(projectFilePath()))); return result; } QStringList QmakeProjectImporter::importCandidates(const Utils::FileName &projectPath) { QStringList candidates; QFileInfo pfi = projectPath.toFileInfo(); const QString prefix = pfi.baseName(); candidates << pfi.absolutePath(); QList<ProjectExplorer::Kit *> kitList = ProjectExplorer::KitManager::kits(); foreach (ProjectExplorer::Kit *k, kitList) { QFileInfo fi(QmakeProject::shadowBuildDirectory(projectPath.toString(), k, QString())); const QString baseDir = fi.absolutePath(); foreach (const QString &dir, QDir(baseDir).entryList()) { const QString path = baseDir + QLatin1Char('/') + dir; if (dir.startsWith(prefix) && !candidates.contains(path)) candidates << path; } } return candidates; } ProjectExplorer::Target *QmakeProjectImporter::preferredTarget(const QList<ProjectExplorer::Target *> &possibleTargets) { // Select active target // a) The default target // b) Simulator target // c) Desktop target // d) the first target ProjectExplorer::Target *activeTarget = possibleTargets.isEmpty() ? 0 : possibleTargets.at(0); int activeTargetPriority = 0; foreach (ProjectExplorer::Target *t, possibleTargets) { QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(t->kit()); if (t->kit() == ProjectExplorer::KitManager::defaultKit()) { activeTarget = t; activeTargetPriority = 3; } else if (activeTargetPriority < 2 && version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)) { activeTarget = t; activeTargetPriority = 2; } else if (activeTargetPriority < 1 && version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)) { activeTarget = t; activeTargetPriority = 1; } } return activeTarget; } void QmakeProjectImporter::cleanupKit(ProjectExplorer::Kit *k) { QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::version(k->value(QT_IS_TEMPORARY, -1).toInt()); if (version) QtSupport::QtVersionManager::removeVersion(version); } ProjectExplorer::Kit *QmakeProjectImporter::createTemporaryKit(QtSupport::BaseQtVersion *version, bool temporaryVersion, const Utils::FileName &parsedSpec) { ProjectExplorer::Kit *k = new ProjectExplorer::Kit; QtSupport::QtKitInformation::setQtVersion(k, version); ProjectExplorer::ToolChainKitInformation::setToolChain(k, version->preferredToolChain(parsedSpec)); QmakeKitInformation::setMkspec(k, parsedSpec); markTemporary(k); if (temporaryVersion) k->setValue(QT_IS_TEMPORARY, version->uniqueId()); k->setDisplayName(version->displayName()); setIsUpdating(true); ProjectExplorer::KitManager::registerKit(k); setIsUpdating(false); return k; } } // namespace Internal } // namespace QmakeProjectManager <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.commontk.org/LICENSE Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QColor> #include <QDebug> #include <QEvent> #include <QPainter> #include <QSize> // CTK includes #include "ctkCrosshairLabel.h" #include "ctkLogger.h" // STD includes #include <math.h> //-------------------------------------------------------------------------- static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkCrosshairLabel"); //-------------------------------------------------------------------------- //----------------------------------------------------------------------------- class ctkCrosshairLabelPrivate { Q_DECLARE_PUBLIC(ctkCrosshairLabel); protected: ctkCrosshairLabel* const q_ptr; public: ctkCrosshairLabelPrivate(ctkCrosshairLabel& object); void init(); void drawCrosshair(); void drawSimpleCrosshair(QPainter& painter); void drawBullsEyeCrosshair(QPainter& painter); bool ShowCrosshair; QPen CrosshairPen; ctkCrosshairLabel::CrosshairTypes CrosshairType; int BullsEyeWidth; static const double BULLS_EYE_BLANK_FRACTION = 0.1; }; // -------------------------------------------------------------------------- // ctkCrosshairLabelPrivate methods // -------------------------------------------------------------------------- ctkCrosshairLabelPrivate::ctkCrosshairLabelPrivate(ctkCrosshairLabel& object) :q_ptr(&object) { this->ShowCrosshair = true; this->CrosshairType = ctkCrosshairLabel::SimpleCrosshair; this->BullsEyeWidth = 15; } //--------------------------------------------------------------------------- void ctkCrosshairLabelPrivate::init() { Q_Q(ctkCrosshairLabel); q->setAutoFillBackground(true); q->setAlignment(Qt::AlignCenter); this->CrosshairPen.setColor(q->palette().color(QPalette::Highlight)); this->CrosshairPen.setWidth(0); this->CrosshairPen.setJoinStyle(Qt::MiterJoin); } //--------------------------------------------------------------------------- void ctkCrosshairLabelPrivate::drawCrosshair() { // Abort if we are not to draw the crosshair if (!this->ShowCrosshair) { return; } // Setup the painter object to paint on the label Q_Q(ctkCrosshairLabel); QPainter painter(q); painter.setPen(this->CrosshairPen); // Draw crosshair (based on current parameters) onto the label switch (this->CrosshairType) { case ctkCrosshairLabel::SimpleCrosshair: this->drawSimpleCrosshair(painter); break; case ctkCrosshairLabel::BullsEyeCrosshair: this->drawBullsEyeCrosshair(painter); break; default: qDebug() << "Unsupported crosshair type" << this->CrosshairType; break; } } //--------------------------------------------------------------------------- void ctkCrosshairLabelPrivate::drawSimpleCrosshair(QPainter& painter) { Q_Q(ctkCrosshairLabel); QSize size = q->size(); double halfWidth = (size.width()-1.0) / 2.0; double halfHeight = (size.height()-1.0) / 2.0; painter.drawLine(QPointF(0, halfHeight), QPointF(size.width(), halfHeight)); painter.drawLine(QPointF(halfWidth, 0), QPointF(halfWidth, size.height())); } // -------------------------------------------------------------------------- void ctkCrosshairLabelPrivate::drawBullsEyeCrosshair(QPainter& painter) { Q_Q(ctkCrosshairLabel); QSize size = q->size(); // Draw rectangle double bullsEye = this->BullsEyeWidth; double lineWidth = painter.pen().width(); lineWidth = std::max(lineWidth, 1.0); double halfLineWidth = (lineWidth-1.0) / 2.0; double x = (size.width()-bullsEye) / 2.0; double y = (size.height()-bullsEye) / 2.0; double rectWidth = bullsEye; if (bullsEye != 1) { rectWidth = rectWidth - lineWidth; } rectWidth = std::max(rectWidth, 0.0); painter.drawRect( QRectF(x+halfLineWidth, y+halfLineWidth, rectWidth, rectWidth)); // Draw the lines double halfWidth = (size.width()-1.0) / 2.0; double halfHeight = (size.height()-1.0) / 2.0; double blank = round(std::min(halfWidth, halfHeight) * this->BULLS_EYE_BLANK_FRACTION); painter.drawLine(QPointF(0, halfHeight), QPointF(x-blank-1.0, halfHeight)); painter.drawLine(QPointF(x+bullsEye+blank, halfHeight), QPointF(size.width(), halfHeight)); painter.drawLine(QPointF(halfWidth, 0), QPointF(halfWidth, y-blank-1.0)); painter.drawLine(QPointF(halfWidth, y+bullsEye+blank), QPointF(halfWidth, size.height())); } //--------------------------------------------------------------------------- // ctkCrosshairLabel methods // -------------------------------------------------------------------------- ctkCrosshairLabel::ctkCrosshairLabel(QWidget* parent) : Superclass(parent) , d_ptr(new ctkCrosshairLabelPrivate(*this)) { Q_D(ctkCrosshairLabel); d->init(); } // -------------------------------------------------------------------------- ctkCrosshairLabel::~ctkCrosshairLabel() { } // -------------------------------------------------------------------------- CTK_GET_CPP(ctkCrosshairLabel, bool, showCrosshair, ShowCrosshair); // -------------------------------------------------------------------------- void ctkCrosshairLabel::setShowCrosshair(bool newShow) { Q_D(ctkCrosshairLabel); if (newShow == d->ShowCrosshair) { return; } d->ShowCrosshair = newShow; this->update(); } // -------------------------------------------------------------------------- CTK_GET_CPP(ctkCrosshairLabel, QPen, crosshairPen, CrosshairPen); // -------------------------------------------------------------------------- void ctkCrosshairLabel::setCrosshairPen(const QPen& newPen) { Q_D(ctkCrosshairLabel); if (newPen == d->CrosshairPen) { return; } d->CrosshairPen = newPen; this->update(); } // -------------------------------------------------------------------------- QColor ctkCrosshairLabel::crosshairColor() const { Q_D(const ctkCrosshairLabel); return d->CrosshairPen.color(); } // -------------------------------------------------------------------------- void ctkCrosshairLabel::setCrosshairColor(const QColor& newColor) { Q_D(ctkCrosshairLabel); if (d->CrosshairPen.color() == newColor) { return; } d->CrosshairPen.setColor(newColor); this->update(); } // -------------------------------------------------------------------------- int ctkCrosshairLabel::lineWidth() const { Q_D(const ctkCrosshairLabel); return d->CrosshairPen.width(); } // -------------------------------------------------------------------------- void ctkCrosshairLabel::setLineWidth(int newWidth) { Q_D(ctkCrosshairLabel); if (d->CrosshairPen.width() == newWidth || newWidth < 0) { return; } d->CrosshairPen.setWidth(newWidth); this->update(); } // -------------------------------------------------------------------------- CTK_GET_CPP(ctkCrosshairLabel, ctkCrosshairLabel::CrosshairTypes, crosshairType, CrosshairType); // -------------------------------------------------------------------------- void ctkCrosshairLabel::setCrosshairType(const CrosshairTypes& newType) { Q_D(ctkCrosshairLabel); if (newType == d->CrosshairType) { return; } d->CrosshairType = newType; this->update(); } // -------------------------------------------------------------------------- QColor ctkCrosshairLabel::marginColor() const { return this->palette().color(QPalette::Window); } // -------------------------------------------------------------------------- void ctkCrosshairLabel::setMarginColor(const QColor& newColor) { if (!newColor.isValid()) { return; } QPalette palette(this->palette()); QColor solidColor(newColor.rgb()); if (solidColor != palette.color(QPalette::Window)) { // Ignore alpha channel palette.setColor(QPalette::Window, solidColor); this->setPalette(palette); this->update(); } } // -------------------------------------------------------------------------- CTK_GET_CPP(ctkCrosshairLabel, int, bullsEyeWidth, BullsEyeWidth); // -------------------------------------------------------------------------- void ctkCrosshairLabel::setBullsEyeWidth(int newWidth) { Q_D(ctkCrosshairLabel); if (newWidth == d->BullsEyeWidth || newWidth < 0) { return; } d->BullsEyeWidth = newWidth; this->update(); } // -------------------------------------------------------------------------- void ctkCrosshairLabel::paintEvent(QPaintEvent * event) { Superclass::paintEvent(event); Q_D(ctkCrosshairLabel); d->drawCrosshair(); } // -------------------------------------------------------------------------- QSize ctkCrosshairLabel::minimumSizeHint()const { // Pretty arbitrary size (matches ctkVTKAbstractView) return QSize(50, 50); } // -------------------------------------------------------------------------- QSize ctkCrosshairLabel::sizeHint()const { // Pretty arbitrary size (matches ctkVTKAbstractView) return QSize(300, 300); } //---------------------------------------------------------------------------- bool ctkCrosshairLabel::hasHeightForWidth()const { return true; } //---------------------------------------------------------------------------- int ctkCrosshairLabel::heightForWidth(int width)const { // Tends to be square return width; } <commit_msg>BUG: Initializing class constants of type double is illegal C++.<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.commontk.org/LICENSE Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QColor> #include <QDebug> #include <QEvent> #include <QPainter> #include <QSize> // CTK includes #include "ctkCrosshairLabel.h" #include "ctkLogger.h" // STD includes #include <math.h> //-------------------------------------------------------------------------- static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkCrosshairLabel"); //-------------------------------------------------------------------------- //----------------------------------------------------------------------------- class ctkCrosshairLabelPrivate { Q_DECLARE_PUBLIC(ctkCrosshairLabel); protected: ctkCrosshairLabel* const q_ptr; public: ctkCrosshairLabelPrivate(ctkCrosshairLabel& object); void init(); void drawCrosshair(); void drawSimpleCrosshair(QPainter& painter); void drawBullsEyeCrosshair(QPainter& painter); bool ShowCrosshair; QPen CrosshairPen; ctkCrosshairLabel::CrosshairTypes CrosshairType; int BullsEyeWidth; static const double BULLS_EYE_BLANK_FRACTION; }; const double ctkCrosshairLabelPrivate::BULLS_EYE_BLANK_FRACTION = 0.1; // -------------------------------------------------------------------------- // ctkCrosshairLabelPrivate methods // -------------------------------------------------------------------------- ctkCrosshairLabelPrivate::ctkCrosshairLabelPrivate(ctkCrosshairLabel& object) :q_ptr(&object) { this->ShowCrosshair = true; this->CrosshairType = ctkCrosshairLabel::SimpleCrosshair; this->BullsEyeWidth = 15; } //--------------------------------------------------------------------------- void ctkCrosshairLabelPrivate::init() { Q_Q(ctkCrosshairLabel); q->setAutoFillBackground(true); q->setAlignment(Qt::AlignCenter); this->CrosshairPen.setColor(q->palette().color(QPalette::Highlight)); this->CrosshairPen.setWidth(0); this->CrosshairPen.setJoinStyle(Qt::MiterJoin); } //--------------------------------------------------------------------------- void ctkCrosshairLabelPrivate::drawCrosshair() { // Abort if we are not to draw the crosshair if (!this->ShowCrosshair) { return; } // Setup the painter object to paint on the label Q_Q(ctkCrosshairLabel); QPainter painter(q); painter.setPen(this->CrosshairPen); // Draw crosshair (based on current parameters) onto the label switch (this->CrosshairType) { case ctkCrosshairLabel::SimpleCrosshair: this->drawSimpleCrosshair(painter); break; case ctkCrosshairLabel::BullsEyeCrosshair: this->drawBullsEyeCrosshair(painter); break; default: qDebug() << "Unsupported crosshair type" << this->CrosshairType; break; } } //--------------------------------------------------------------------------- void ctkCrosshairLabelPrivate::drawSimpleCrosshair(QPainter& painter) { Q_Q(ctkCrosshairLabel); QSize size = q->size(); double halfWidth = (size.width()-1.0) / 2.0; double halfHeight = (size.height()-1.0) / 2.0; painter.drawLine(QPointF(0, halfHeight), QPointF(size.width(), halfHeight)); painter.drawLine(QPointF(halfWidth, 0), QPointF(halfWidth, size.height())); } // -------------------------------------------------------------------------- void ctkCrosshairLabelPrivate::drawBullsEyeCrosshair(QPainter& painter) { Q_Q(ctkCrosshairLabel); QSize size = q->size(); // Draw rectangle double bullsEye = this->BullsEyeWidth; double lineWidth = painter.pen().width(); lineWidth = std::max(lineWidth, 1.0); double halfLineWidth = (lineWidth-1.0) / 2.0; double x = (size.width()-bullsEye) / 2.0; double y = (size.height()-bullsEye) / 2.0; double rectWidth = bullsEye; if (bullsEye != 1) { rectWidth = rectWidth - lineWidth; } rectWidth = std::max(rectWidth, 0.0); painter.drawRect( QRectF(x+halfLineWidth, y+halfLineWidth, rectWidth, rectWidth)); // Draw the lines double halfWidth = (size.width()-1.0) / 2.0; double halfHeight = (size.height()-1.0) / 2.0; double blank = round(std::min(halfWidth, halfHeight) * this->BULLS_EYE_BLANK_FRACTION); painter.drawLine(QPointF(0, halfHeight), QPointF(x-blank-1.0, halfHeight)); painter.drawLine(QPointF(x+bullsEye+blank, halfHeight), QPointF(size.width(), halfHeight)); painter.drawLine(QPointF(halfWidth, 0), QPointF(halfWidth, y-blank-1.0)); painter.drawLine(QPointF(halfWidth, y+bullsEye+blank), QPointF(halfWidth, size.height())); } //--------------------------------------------------------------------------- // ctkCrosshairLabel methods // -------------------------------------------------------------------------- ctkCrosshairLabel::ctkCrosshairLabel(QWidget* parent) : Superclass(parent) , d_ptr(new ctkCrosshairLabelPrivate(*this)) { Q_D(ctkCrosshairLabel); d->init(); } // -------------------------------------------------------------------------- ctkCrosshairLabel::~ctkCrosshairLabel() { } // -------------------------------------------------------------------------- CTK_GET_CPP(ctkCrosshairLabel, bool, showCrosshair, ShowCrosshair); // -------------------------------------------------------------------------- void ctkCrosshairLabel::setShowCrosshair(bool newShow) { Q_D(ctkCrosshairLabel); if (newShow == d->ShowCrosshair) { return; } d->ShowCrosshair = newShow; this->update(); } // -------------------------------------------------------------------------- CTK_GET_CPP(ctkCrosshairLabel, QPen, crosshairPen, CrosshairPen); // -------------------------------------------------------------------------- void ctkCrosshairLabel::setCrosshairPen(const QPen& newPen) { Q_D(ctkCrosshairLabel); if (newPen == d->CrosshairPen) { return; } d->CrosshairPen = newPen; this->update(); } // -------------------------------------------------------------------------- QColor ctkCrosshairLabel::crosshairColor() const { Q_D(const ctkCrosshairLabel); return d->CrosshairPen.color(); } // -------------------------------------------------------------------------- void ctkCrosshairLabel::setCrosshairColor(const QColor& newColor) { Q_D(ctkCrosshairLabel); if (d->CrosshairPen.color() == newColor) { return; } d->CrosshairPen.setColor(newColor); this->update(); } // -------------------------------------------------------------------------- int ctkCrosshairLabel::lineWidth() const { Q_D(const ctkCrosshairLabel); return d->CrosshairPen.width(); } // -------------------------------------------------------------------------- void ctkCrosshairLabel::setLineWidth(int newWidth) { Q_D(ctkCrosshairLabel); if (d->CrosshairPen.width() == newWidth || newWidth < 0) { return; } d->CrosshairPen.setWidth(newWidth); this->update(); } // -------------------------------------------------------------------------- CTK_GET_CPP(ctkCrosshairLabel, ctkCrosshairLabel::CrosshairTypes, crosshairType, CrosshairType); // -------------------------------------------------------------------------- void ctkCrosshairLabel::setCrosshairType(const CrosshairTypes& newType) { Q_D(ctkCrosshairLabel); if (newType == d->CrosshairType) { return; } d->CrosshairType = newType; this->update(); } // -------------------------------------------------------------------------- QColor ctkCrosshairLabel::marginColor() const { return this->palette().color(QPalette::Window); } // -------------------------------------------------------------------------- void ctkCrosshairLabel::setMarginColor(const QColor& newColor) { if (!newColor.isValid()) { return; } QPalette palette(this->palette()); QColor solidColor(newColor.rgb()); if (solidColor != palette.color(QPalette::Window)) { // Ignore alpha channel palette.setColor(QPalette::Window, solidColor); this->setPalette(palette); this->update(); } } // -------------------------------------------------------------------------- CTK_GET_CPP(ctkCrosshairLabel, int, bullsEyeWidth, BullsEyeWidth); // -------------------------------------------------------------------------- void ctkCrosshairLabel::setBullsEyeWidth(int newWidth) { Q_D(ctkCrosshairLabel); if (newWidth == d->BullsEyeWidth || newWidth < 0) { return; } d->BullsEyeWidth = newWidth; this->update(); } // -------------------------------------------------------------------------- void ctkCrosshairLabel::paintEvent(QPaintEvent * event) { Superclass::paintEvent(event); Q_D(ctkCrosshairLabel); d->drawCrosshair(); } // -------------------------------------------------------------------------- QSize ctkCrosshairLabel::minimumSizeHint()const { // Pretty arbitrary size (matches ctkVTKAbstractView) return QSize(50, 50); } // -------------------------------------------------------------------------- QSize ctkCrosshairLabel::sizeHint()const { // Pretty arbitrary size (matches ctkVTKAbstractView) return QSize(300, 300); } //---------------------------------------------------------------------------- bool ctkCrosshairLabel::hasHeightForWidth()const { return true; } //---------------------------------------------------------------------------- int ctkCrosshairLabel::heightForWidth(int width)const { // Tends to be square return width; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ // // -------------------------------------- // Class AliMUONGeometryDetElement // -------------------------------------- // The class defines the detection element. // Author: Ivana Hrivnacova, IPN Orsay #include "AliMUONGeometryDetElement.h" #include "AliLog.h" #include <TGeoMatrix.h> #include <Riostream.h> #include <sstream> /// \cond CLASSIMP ClassImp(AliMUONGeometryDetElement) /// \endcond const TString AliMUONGeometryDetElement::fgkDENamePrefix = "DE"; //______________________________________________________________________________ AliMUONGeometryDetElement::AliMUONGeometryDetElement( Int_t detElemId, const TString& volumePath) : TObject(), fDEName(), fVolumePath(volumePath), fLocalTransformation(0), fGlobalTransformation(0) { /// Standard constructor SetUniqueID(detElemId); fDEName = fgkDENamePrefix; fDEName += detElemId; } //______________________________________________________________________________ AliMUONGeometryDetElement::AliMUONGeometryDetElement() : TObject(), fVolumePath(), fLocalTransformation(0), fGlobalTransformation(0) { /// Default constructor } //______________________________________________________________________________ AliMUONGeometryDetElement::~AliMUONGeometryDetElement() { /// Destructor delete fLocalTransformation; delete fGlobalTransformation; } // // private methods // //______________________________________________________________________________ void AliMUONGeometryDetElement::PrintTransform( const TGeoHMatrix* transform) const { /// Print the detection element transformation cout << "DetElemId: " << GetUniqueID(); cout << " name: " << fVolumePath << endl; if ( !transform ) { cout << " Transformation not defined." << endl; return; } const double* translation = transform->GetTranslation(); cout << " translation: " #if defined (__DECCXX) << translation[0] << ", " << translation[1] << ", " << translation[2] << endl; #else << std::fixed << std::setw(7) << std::setprecision(4) << translation[0] << ", " << std::setw(7) << std::setprecision(4) << translation[1] << ", " << std::setw(7) << std::setprecision(4) << translation[2] << endl; #endif const double* rotation = transform->GetRotationMatrix(); cout << " rotation matrix: " #if defined (__DECCXX) << rotation[0] << ", " << rotation[1] << ", " << rotation[2] << endl << " " << rotation[3] << ", " << rotation[4] << ", " << rotation[5] << endl << " " << rotation[6] << ", " << rotation[7] << ", " << rotation[8] << endl; #else << std::fixed << std::setw(7) << std::setprecision(4) << rotation[0] << ", " << rotation[1] << ", " << rotation[2] << endl << " " << rotation[3] << ", " << rotation[4] << ", " << rotation[5] << endl << " " << rotation[6] << ", " << rotation[7] << ", " << rotation[8] << endl; #endif } // // public methods // //______________________________________________________________________________ void AliMUONGeometryDetElement::Global2Local( Float_t xg, Float_t yg, Float_t zg, Float_t& xl, Float_t& yl, Float_t& zl) const { /// Transform point from the global reference frame (ALIC) /// to the local reference frame of this detection element. Double_t dxg = xg; Double_t dyg = yg; Double_t dzg = zg; Double_t dxl, dyl, dzl; Global2Local(dxg, dyg, dzg, dxl, dyl, dzl); xl = dxl; yl = dyl; zl = dzl; } //______________________________________________________________________________ void AliMUONGeometryDetElement::Global2Local( Double_t xg, Double_t yg, Double_t zg, Double_t& xl, Double_t& yl, Double_t& zl) const { /// Transform point from the global reference frame (ALIC) /// to the local reference frame of this detection element // Check transformation if (!fGlobalTransformation) { AliError(Form("Global transformation for detection element %d not defined.", GetUniqueID())); return; } // Transform point Double_t pg[3] = { xg, yg, zg }; Double_t pl[3] = { 0., 0., 0. }; fGlobalTransformation->MasterToLocal(pg, pl); // Return transformed point xl = pl[0]; yl = pl[1]; zl = pl[2]; } //______________________________________________________________________________ void AliMUONGeometryDetElement::Local2Global( Float_t xl, Float_t yl, Float_t zl, Float_t& xg, Float_t& yg, Float_t& zg) const { /// Transform point from the local reference frame of this detection element /// to the global reference frame (ALIC). Double_t dxl = xl; Double_t dyl = yl; Double_t dzl = zl; Double_t dxg, dyg, dzg; Local2Global(dxl, dyl, dzl, dxg, dyg, dzg); xg = dxg; yg = dyg; zg = dzg; } //______________________________________________________________________________ void AliMUONGeometryDetElement::Local2Global( Double_t xl, Double_t yl, Double_t zl, Double_t& xg, Double_t& yg, Double_t& zg) const { /// Transform point from the local reference frame of this detection element /// to the global reference frame (ALIC). // Check transformation if (!fGlobalTransformation) { AliError(Form("Global transformation for detection element %d not defined.", GetUniqueID())); return; } // Transform point Double_t pl[3] = { xl, yl, zl }; Double_t pg[3] = { 0., 0., 0. }; fGlobalTransformation->LocalToMaster(pl, pg); // Return transformed point xg = pg[0]; yg = pg[1]; zg = pg[2]; } //______________________________________________________________________________ void AliMUONGeometryDetElement::SetLocalTransformation( const TGeoHMatrix& transform) { /// Set local transformation; /// give warning if the global transformation is already defined. if (fLocalTransformation) { delete fLocalTransformation; AliWarning("Local transformation already defined was deleted."); } fLocalTransformation = new TGeoHMatrix(transform); } //______________________________________________________________________________ void AliMUONGeometryDetElement::SetGlobalTransformation( const TGeoHMatrix& transform) { /// Set global transformation; /// give warning if the global transformation is already defined. if (fGlobalTransformation) { delete fGlobalTransformation; AliWarning("Global transformation already defined was deleted."); } fGlobalTransformation = new TGeoHMatrix(transform); } //______________________________________________________________________________ void AliMUONGeometryDetElement::PrintLocalTransform() const { /// Print detection element relative transformation /// (the transformation wrt module frame) PrintTransform(fLocalTransformation); } //______________________________________________________________________________ void AliMUONGeometryDetElement::PrintGlobalTransform() const { /// Print detection element global transformation /// (the transformation wrt global frame) PrintTransform(fGlobalTransformation); } //______________________________________________________________________________ TString AliMUONGeometryDetElement::GetVolumeName() const { /// Extract volume name from the path std::string volPath = fVolumePath.Data(); std::string::size_type first = volPath.rfind('/')+1; std::string::size_type last = volPath.rfind('_'); return volPath.substr(first, last-first ); } //______________________________________________________________________________ Int_t AliMUONGeometryDetElement::GetVolumeCopyNo() const { /// Extract volume copyNo from the path string volPath = fVolumePath.Data(); std::string::size_type first = volPath.rfind('_'); std::string copyNoStr = volPath.substr(first+1, volPath.length()); std::istringstream in(copyNoStr); Int_t copyNo; in >> copyNo; return copyNo; } <commit_msg>Corrested data members initialization in ctor<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ // // -------------------------------------- // Class AliMUONGeometryDetElement // -------------------------------------- // The class defines the detection element. // Author: Ivana Hrivnacova, IPN Orsay #include "AliMUONGeometryDetElement.h" #include "AliLog.h" #include <TGeoMatrix.h> #include <Riostream.h> #include <sstream> /// \cond CLASSIMP ClassImp(AliMUONGeometryDetElement) /// \endcond const TString AliMUONGeometryDetElement::fgkDENamePrefix = "DE"; //______________________________________________________________________________ AliMUONGeometryDetElement::AliMUONGeometryDetElement( Int_t detElemId, const TString& volumePath) : TObject(), fDEName(), fVolumePath(volumePath), fLocalTransformation(0), fGlobalTransformation(0) { /// Standard constructor SetUniqueID(detElemId); fDEName = fgkDENamePrefix; fDEName += detElemId; } //______________________________________________________________________________ AliMUONGeometryDetElement::AliMUONGeometryDetElement() : TObject(), fDEName(), fVolumePath(), fLocalTransformation(0), fGlobalTransformation(0) { /// Default constructor } //______________________________________________________________________________ AliMUONGeometryDetElement::~AliMUONGeometryDetElement() { /// Destructor delete fLocalTransformation; delete fGlobalTransformation; } // // private methods // //______________________________________________________________________________ void AliMUONGeometryDetElement::PrintTransform( const TGeoHMatrix* transform) const { /// Print the detection element transformation cout << "DetElemId: " << GetUniqueID(); cout << " name: " << fVolumePath << endl; if ( !transform ) { cout << " Transformation not defined." << endl; return; } const double* translation = transform->GetTranslation(); cout << " translation: " #if defined (__DECCXX) << translation[0] << ", " << translation[1] << ", " << translation[2] << endl; #else << std::fixed << std::setw(7) << std::setprecision(4) << translation[0] << ", " << std::setw(7) << std::setprecision(4) << translation[1] << ", " << std::setw(7) << std::setprecision(4) << translation[2] << endl; #endif const double* rotation = transform->GetRotationMatrix(); cout << " rotation matrix: " #if defined (__DECCXX) << rotation[0] << ", " << rotation[1] << ", " << rotation[2] << endl << " " << rotation[3] << ", " << rotation[4] << ", " << rotation[5] << endl << " " << rotation[6] << ", " << rotation[7] << ", " << rotation[8] << endl; #else << std::fixed << std::setw(7) << std::setprecision(4) << rotation[0] << ", " << rotation[1] << ", " << rotation[2] << endl << " " << rotation[3] << ", " << rotation[4] << ", " << rotation[5] << endl << " " << rotation[6] << ", " << rotation[7] << ", " << rotation[8] << endl; #endif } // // public methods // //______________________________________________________________________________ void AliMUONGeometryDetElement::Global2Local( Float_t xg, Float_t yg, Float_t zg, Float_t& xl, Float_t& yl, Float_t& zl) const { /// Transform point from the global reference frame (ALIC) /// to the local reference frame of this detection element. Double_t dxg = xg; Double_t dyg = yg; Double_t dzg = zg; Double_t dxl, dyl, dzl; Global2Local(dxg, dyg, dzg, dxl, dyl, dzl); xl = dxl; yl = dyl; zl = dzl; } //______________________________________________________________________________ void AliMUONGeometryDetElement::Global2Local( Double_t xg, Double_t yg, Double_t zg, Double_t& xl, Double_t& yl, Double_t& zl) const { /// Transform point from the global reference frame (ALIC) /// to the local reference frame of this detection element // Check transformation if (!fGlobalTransformation) { AliError(Form("Global transformation for detection element %d not defined.", GetUniqueID())); return; } // Transform point Double_t pg[3] = { xg, yg, zg }; Double_t pl[3] = { 0., 0., 0. }; fGlobalTransformation->MasterToLocal(pg, pl); // Return transformed point xl = pl[0]; yl = pl[1]; zl = pl[2]; } //______________________________________________________________________________ void AliMUONGeometryDetElement::Local2Global( Float_t xl, Float_t yl, Float_t zl, Float_t& xg, Float_t& yg, Float_t& zg) const { /// Transform point from the local reference frame of this detection element /// to the global reference frame (ALIC). Double_t dxl = xl; Double_t dyl = yl; Double_t dzl = zl; Double_t dxg, dyg, dzg; Local2Global(dxl, dyl, dzl, dxg, dyg, dzg); xg = dxg; yg = dyg; zg = dzg; } //______________________________________________________________________________ void AliMUONGeometryDetElement::Local2Global( Double_t xl, Double_t yl, Double_t zl, Double_t& xg, Double_t& yg, Double_t& zg) const { /// Transform point from the local reference frame of this detection element /// to the global reference frame (ALIC). // Check transformation if (!fGlobalTransformation) { AliError(Form("Global transformation for detection element %d not defined.", GetUniqueID())); return; } // Transform point Double_t pl[3] = { xl, yl, zl }; Double_t pg[3] = { 0., 0., 0. }; fGlobalTransformation->LocalToMaster(pl, pg); // Return transformed point xg = pg[0]; yg = pg[1]; zg = pg[2]; } //______________________________________________________________________________ void AliMUONGeometryDetElement::SetLocalTransformation( const TGeoHMatrix& transform) { /// Set local transformation; /// give warning if the global transformation is already defined. if (fLocalTransformation) { delete fLocalTransformation; AliWarning("Local transformation already defined was deleted."); } fLocalTransformation = new TGeoHMatrix(transform); } //______________________________________________________________________________ void AliMUONGeometryDetElement::SetGlobalTransformation( const TGeoHMatrix& transform) { /// Set global transformation; /// give warning if the global transformation is already defined. if (fGlobalTransformation) { delete fGlobalTransformation; AliWarning("Global transformation already defined was deleted."); } fGlobalTransformation = new TGeoHMatrix(transform); } //______________________________________________________________________________ void AliMUONGeometryDetElement::PrintLocalTransform() const { /// Print detection element relative transformation /// (the transformation wrt module frame) PrintTransform(fLocalTransformation); } //______________________________________________________________________________ void AliMUONGeometryDetElement::PrintGlobalTransform() const { /// Print detection element global transformation /// (the transformation wrt global frame) PrintTransform(fGlobalTransformation); } //______________________________________________________________________________ TString AliMUONGeometryDetElement::GetVolumeName() const { /// Extract volume name from the path std::string volPath = fVolumePath.Data(); std::string::size_type first = volPath.rfind('/')+1; std::string::size_type last = volPath.rfind('_'); return volPath.substr(first, last-first ); } //______________________________________________________________________________ Int_t AliMUONGeometryDetElement::GetVolumeCopyNo() const { /// Extract volume copyNo from the path string volPath = fVolumePath.Data(); std::string::size_type first = volPath.rfind('_'); std::string copyNoStr = volPath.substr(first+1, volPath.length()); std::istringstream in(copyNoStr); Int_t copyNo; in >> copyNo; return copyNo; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "plugin.h" #include "pluginmanager.h" #include "pluginswindow.h" #include "ui_pluginswindow.h" #include <QDesktopServices> #include <QUrl> namespace OpenCOR { PluginDelegate::PluginDelegate(QStandardItemModel *pDataModel, QObject *pParent) : QStyledItemDelegate(pParent), mDataModel(pDataModel) { } void PluginDelegate::paint(QPainter *pPainter, const QStyleOptionViewItem &pOption, const QModelIndex &pIndex) const { // Paint the item as normal, except for the items which are not checkable // (i.e. plugins which the user cannot decide whether to load) in which case // we paint them as if they were disabled QStandardItem *pluginItem = mDataModel->itemFromIndex(pIndex); QStyleOptionViewItemV4 option(pOption); initStyleOption(&option, pIndex); if (!pluginItem->isCheckable()) option.state &= ~QStyle::State_Enabled; QStyledItemDelegate::paint(pPainter, option, pIndex); } PluginsWindow::PluginsWindow(PluginManager *pPluginManager, QWidget *pParent) : QDialog(pParent), mUi(new Ui::PluginsWindow), mPluginManager(pPluginManager) { // Set up the UI mUi->setupUi(this); // Update the note label mUi->noteLabel->setText(mUi->noteLabel->text().arg(qApp->applicationName())); // Set up the tree view with a delegate, so that we can select plugins that // are shown as 'disabled' (to reflect the fact that users cannot decide // whether they should be loaded) mDataModel = new QStandardItemModel; mPluginDelegate = new PluginDelegate(mDataModel); mUi->listView->setModel(mDataModel); mUi->listView->setItemDelegate(mPluginDelegate); // Populate the data model foreach (Plugin *plugin, mPluginManager->plugins()) { QStandardItem *pluginItem = new QStandardItem(plugin->name()); if (plugin->info().manageable()) { // Only manageable plugins are checkable pluginItem->setCheckable(true); // Retrieve the loading state of the plugin pluginItem->setCheckState((Plugin::load(mPluginManager->settings(), plugin->name()))? Qt::Checked: Qt::Unchecked); // We are dealing with a manageable plugin, so add it to our list of // manageable plugins mManageablePlugins << pluginItem; } else { // We are dealing with an unmanageable plugin, so add it to our list // of unmanageable plugins mUnmanageablePlugins << pluginItem; } // Add the plugin to our data model mDataModel->invisibleRootItem()->appendRow(pluginItem); } // Make sure that the loading state of all the plugins is right, including // that of the plugins which the user cannot manage updatePluginsLoadingState(); // Select the first plugin mUi->listView->selectionModel()->select(mDataModel->index(0, 0), QItemSelectionModel::Select); // Make sure that the list view only takes as much width as necessary // Note: for some reasons (maybe because we have check boxes?), the // retrieved column size gives us a width that is slightly too small // and therefore requires a horizontal scroll bar, hence we add 15% to // it (the extra 15% seems to be enough to even account for a big // number of plugins which would then require a vertical scroll bar) mUi->listView->setMinimumWidth(1.15*mUi->listView->sizeHintForColumn(0)); mUi->listView->setMaximumWidth(mUi->listView->minimumWidth()); // Make, through the note label, sure that the window has a minimum width mUi->noteLabel->setMinimumWidth(2.75*mUi->listView->minimumWidth()); // Connection to handle a plugin's information connect(mUi->listView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updatePluginInfo(const QModelIndex &, const QModelIndex &))); // Connection to handle the activation of a link in the description connect(mUi->descriptionValue, SIGNAL(linkActivated(const QString &)), this, SLOT(openLink(const QString &))); // Make sure that the window has a reasonable starting size mUi->verticalLayout->setSizeConstraint(QLayout::SetMinimumSize); } PluginsWindow::~PluginsWindow() { // Delete some internal objects delete mDataModel; delete mPluginDelegate; delete mUi; } void PluginsWindow::retranslateUi() { // Retranslate the whole window mUi->retranslateUi(this); } void PluginsWindow::updatePluginInfo(const QModelIndex &pNewIndex, const QModelIndex &) const { // Update the information view with the plugin's information QString pluginName = mDataModel->itemFromIndex(pNewIndex)->text(); Plugin *plugin = mPluginManager->plugin(pluginName); PluginInfo pluginInfo = plugin->info(); // The plugin's name mUi->nameValue->setText(pluginName); // The plugin's type switch (pluginInfo.type()) { case PluginInfo::General: mUi->typeValue->setText(tr("General")); break; case PluginInfo::Console: mUi->typeValue->setText(tr("Console")); break; case PluginInfo::Gui: mUi->typeValue->setText(tr("GUI")); break; default: mUi->typeValue->setText(tr("Undefined")); break; } // The plugin's dependencies QStringList dependencies = pluginInfo.dependencies(); if (dependencies.isEmpty()) dependencies << tr("None"); if (dependencies.count() > 1) mUi->dependenciesValue->setText("- "+dependencies.join("\n- ")); else mUi->dependenciesValue->setText(dependencies.first()); // The plugin's description QString description = pluginInfo.description(qobject_cast<MainWindow *>(parent())->locale()); mUi->descriptionValue->setText(description.isEmpty()? tr("None"): description); // The plugin's status mUi->statusValue->setText(plugin->statusDescription()); } void PluginsWindow::updatePluginsLoadingState(QStandardItem *pChangedPluginItem) const { // Disable the connection that handles a change in a plugin's loading state disconnect(mDataModel, SIGNAL(itemChanged(QStandardItem *)), this, SLOT(updatePluginsLoadingState(QStandardItem *))); // Prevent the list view from being updated, since we may change a few // things mUi->listView->setUpdatesEnabled(false); // Check whether we came here as a result of checking a plugin and, if so, // then make sure that all of that plugin's dependencies are also checked if ( pChangedPluginItem && (pChangedPluginItem->checkState() == Qt::Checked)) foreach (const QString &requiredPlugin, mPluginManager->plugin(pChangedPluginItem->text())->info().fullDependencies()) foreach (QStandardItem *pluginItem, mManageablePlugins) if (!pluginItem->text().compare(requiredPlugin)) // We are dealing with one of the plugin's dependencies, so // make sure it's checked pluginItem->setCheckState(Qt::Checked); // At this stage, all the plugins which should be checked are checked, so // now we must update the manageable plugins that are currently checked to // make sure that their loading state is consistent with that of the others. // This means going through each of the plugins and have them checked only // if all of their dependencies are checked. Note that it is fine to do it // this way since all we need is for one of a plugin's dependencies to be // unchecked for the plugin to also be unchecked, so... foreach (QStandardItem *pluginItem, mManageablePlugins) if (pluginItem->checkState() == Qt::Checked) foreach (const QString &requiredPlugin, mPluginManager->plugin(pluginItem->text())->info().fullDependencies()) foreach (QStandardItem *otherPluginItem, mManageablePlugins) if (!otherPluginItem->text().compare(requiredPlugin)) { // We have found the plugin's dependency if (otherPluginItem->checkState() == Qt::Unchecked) // The plugin's dependency is unchecked, meaning the // plugin must also be unchecked pluginItem->setCheckState(Qt::Unchecked); break; } // Finally, we need to see whether any of the unmanageable plugins should be // checked foreach (QStandardItem *pluginItem, mUnmanageablePlugins) { // First, reset the loading state of the unamangeable plugin pluginItem->setCheckState(Qt::Unchecked); // Next, go through the manageable plugins' dependencies foreach (QStandardItem *otherPluginItem, mManageablePlugins) if (otherPluginItem->checkState() == Qt::Checked) // The manageable plugin is checked, so carry on... foreach (const QString &requiredPlugin, mPluginManager->plugin(otherPluginItem->text())->info().fullDependencies()) if (!requiredPlugin.compare(pluginItem->text())) { // The manageable plugin does require the unamanageable // plugin, so... pluginItem->setCheckState(Qt::Checked); break; } } // Re-enable the the list view from being updated mUi->listView->setUpdatesEnabled(true); // Re-enable the connection that handles a change in a plugin's loading // state connect(mDataModel, SIGNAL(itemChanged(QStandardItem *)), this, SLOT(updatePluginsLoadingState(QStandardItem *))); } void PluginsWindow::openLink(const QString &pLink) const { // Open the link in the user's browser QDesktopServices::openUrl(QUrl(pLink)); } void PluginsWindow::on_buttonBox_accepted() { // Keep track of the loading state of the various plugins over which the // user has control (i.e. the ones that are checkable) foreach (QStandardItem *pluginItem, mManageablePlugins) if (pluginItem->isCheckable()) Plugin::setLoad(mPluginManager->settings(), pluginItem->text(), pluginItem->checkState() == Qt::Checked); // Confirm that we accepted the changes accept(); } void PluginsWindow::on_buttonBox_rejected() { // Simple cancel whatever was done here reject(); } } <commit_msg>Minor editing.<commit_after>#include "mainwindow.h" #include "plugin.h" #include "pluginmanager.h" #include "pluginswindow.h" #include "ui_pluginswindow.h" #include <QDesktopServices> #include <QUrl> namespace OpenCOR { PluginDelegate::PluginDelegate(QStandardItemModel *pDataModel, QObject *pParent) : QStyledItemDelegate(pParent), mDataModel(pDataModel) { } void PluginDelegate::paint(QPainter *pPainter, const QStyleOptionViewItem &pOption, const QModelIndex &pIndex) const { // Paint the item as normal, except for the items which are not checkable // (i.e. plugins which the user cannot decide whether to load) in which case // we paint them as if they were disabled QStandardItem *pluginItem = mDataModel->itemFromIndex(pIndex); QStyleOptionViewItemV4 option(pOption); initStyleOption(&option, pIndex); if (!pluginItem->isCheckable()) option.state &= ~QStyle::State_Enabled; QStyledItemDelegate::paint(pPainter, option, pIndex); } PluginsWindow::PluginsWindow(PluginManager *pPluginManager, QWidget *pParent) : QDialog(pParent), mUi(new Ui::PluginsWindow), mPluginManager(pPluginManager) { // Set up the UI mUi->setupUi(this); // Update the note label mUi->noteLabel->setText(mUi->noteLabel->text().arg(qApp->applicationName())); // Set up the tree view with a delegate, so that we can select plugins that // are shown as 'disabled' (to reflect the fact that users cannot decide // whether they should be loaded) mDataModel = new QStandardItemModel; mPluginDelegate = new PluginDelegate(mDataModel); mUi->listView->setModel(mDataModel); mUi->listView->setItemDelegate(mPluginDelegate); // Populate the data model foreach (Plugin *plugin, mPluginManager->plugins()) { QStandardItem *pluginItem = new QStandardItem(plugin->name()); if (plugin->info().manageable()) { // Only manageable plugins are checkable pluginItem->setCheckable(true); // Retrieve the loading state of the plugin pluginItem->setCheckState((Plugin::load(mPluginManager->settings(), plugin->name()))? Qt::Checked: Qt::Unchecked); // We are dealing with a manageable plugin, so add it to our list of // manageable plugins mManageablePlugins << pluginItem; } else { // We are dealing with an unmanageable plugin, so add it to our list // of unmanageable plugins mUnmanageablePlugins << pluginItem; } // Add the plugin to our data model mDataModel->invisibleRootItem()->appendRow(pluginItem); } // Make sure that the loading state of all the plugins is right, including // that of the plugins which the user cannot manage updatePluginsLoadingState(); // Select the first plugin mUi->listView->selectionModel()->select(mDataModel->index(0, 0), QItemSelectionModel::Select); // Make sure that the list view only takes as much width as necessary // Note: for some reasons (maybe because we have check boxes?), the // retrieved column size gives us a width that is slightly too small // and therefore requires a horizontal scroll bar, hence we add 15% to // it (the extra 15% seems to be enough to even account for a big // number of plugins which would then require a vertical scroll bar) mUi->listView->setMinimumWidth(1.15*mUi->listView->sizeHintForColumn(0)); mUi->listView->setMaximumWidth(mUi->listView->minimumWidth()); // Make, through the note label, sure that the window has a minimum width mUi->noteLabel->setMinimumWidth(2.75*mUi->listView->minimumWidth()); // Connection to handle a plugin's information connect(mUi->listView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(updatePluginInfo(const QModelIndex &, const QModelIndex &))); // Connection to handle the activation of a link in the description connect(mUi->descriptionValue, SIGNAL(linkActivated(const QString &)), this, SLOT(openLink(const QString &))); // Make sure that the window has a reasonable starting size mUi->verticalLayout->setSizeConstraint(QLayout::SetMinimumSize); } PluginsWindow::~PluginsWindow() { // Delete some internal objects delete mDataModel; delete mPluginDelegate; delete mUi; } void PluginsWindow::retranslateUi() { // Retranslate the whole window mUi->retranslateUi(this); } void PluginsWindow::updatePluginInfo(const QModelIndex &pNewIndex, const QModelIndex &) const { // Update the information view with the plugin's information QString pluginName = mDataModel->itemFromIndex(pNewIndex)->text(); Plugin *plugin = mPluginManager->plugin(pluginName); PluginInfo pluginInfo = plugin->info(); // The plugin's name mUi->nameValue->setText(pluginName); // The plugin's type switch (pluginInfo.type()) { case PluginInfo::General: mUi->typeValue->setText(tr("General")); break; case PluginInfo::Console: mUi->typeValue->setText(tr("Console")); break; case PluginInfo::Gui: mUi->typeValue->setText(tr("GUI")); break; default: mUi->typeValue->setText(tr("Undefined")); break; } // The plugin's dependencies QStringList dependencies = pluginInfo.dependencies(); if (dependencies.isEmpty()) dependencies << tr("None"); if (dependencies.count() > 1) mUi->dependenciesValue->setText("- "+dependencies.join("\n- ")); else mUi->dependenciesValue->setText(dependencies.first()); // The plugin's description QString description = pluginInfo.description(qobject_cast<MainWindow *>(parent())->locale()); mUi->descriptionValue->setText(description.isEmpty()? tr("None"): description); // The plugin's status mUi->statusValue->setText(plugin->statusDescription()); } void PluginsWindow::updatePluginsLoadingState(QStandardItem *pChangedPluginItem) const { // Disable the connection that handles a change in a plugin's loading state // (otherwise what we are doing here is going to be completely uneffective) disconnect(mDataModel, SIGNAL(itemChanged(QStandardItem *)), this, SLOT(updatePluginsLoadingState(QStandardItem *))); // Prevent the list view from being updated, since we may end up changing // quite a bit of its visual contents mUi->listView->setUpdatesEnabled(false); // Check whether we came here as a result of checking a plugin and, if so, // then make sure that all of that plugin's dependencies are also checked if ( pChangedPluginItem && (pChangedPluginItem->checkState() == Qt::Checked)) foreach (const QString &requiredPlugin, mPluginManager->plugin(pChangedPluginItem->text())->info().fullDependencies()) foreach (QStandardItem *pluginItem, mManageablePlugins) if (!pluginItem->text().compare(requiredPlugin)) // We are dealing with one of the plugin's dependencies, so // make sure it's checked pluginItem->setCheckState(Qt::Checked); // At this stage, all the plugins which should be checked are checked, so // now we must update the manageable plugins that are currently checked to // make sure that they should still be checked indeed. This means going // through each of the plugins and keep them checked only if all of their // dependencies are checked. Note that it is fine to do it this way since // all we need is one plugin's dependency to be unchecked for the plugin // itself to also be unchecked, so... foreach (QStandardItem *pluginItem, mManageablePlugins) if (pluginItem->checkState() == Qt::Checked) foreach (const QString &requiredPlugin, mPluginManager->plugin(pluginItem->text())->info().fullDependencies()) foreach (QStandardItem *otherPluginItem, mManageablePlugins) if (!otherPluginItem->text().compare(requiredPlugin)) { // We have found the plugin's dependency if (otherPluginItem->checkState() == Qt::Unchecked) // The plugin's dependency is unchecked which means // that the plugin cannot be checked, so... pluginItem->setCheckState(Qt::Unchecked); break; } // Finally, we need to see whether our unmanageable plugins should be // checked or unchecked foreach (QStandardItem *pluginItem, mUnmanageablePlugins) { // First, reset the loading state of the unamanageable plugin pluginItem->setCheckState(Qt::Unchecked); // Next, go through the checked manageable plugins' dependencies foreach (QStandardItem *otherPluginItem, mManageablePlugins) if (otherPluginItem->checkState() == Qt::Checked) // The manageable plugin is checked, so carry on... foreach (const QString &requiredPlugin, mPluginManager->plugin(otherPluginItem->text())->info().fullDependencies()) if (!requiredPlugin.compare(pluginItem->text())) { // The manageable plugin does require the unamanageable // plugin, so... pluginItem->setCheckState(Qt::Checked); break; } } // Re-enable the updating of the list view mUi->listView->setUpdatesEnabled(true); // Re-enable the connection that handles a change in a plugin's loading // state connect(mDataModel, SIGNAL(itemChanged(QStandardItem *)), this, SLOT(updatePluginsLoadingState(QStandardItem *))); } void PluginsWindow::openLink(const QString &pLink) const { // Open the link in the user's browser QDesktopServices::openUrl(QUrl(pLink)); } void PluginsWindow::on_buttonBox_accepted() { // Keep track of the loading state of the various plugins over which the // user has control (i.e. the ones that are checkable) foreach (QStandardItem *pluginItem, mManageablePlugins) if (pluginItem->isCheckable()) Plugin::setLoad(mPluginManager->settings(), pluginItem->text(), pluginItem->checkState() == Qt::Checked); // Confirm that we accepted the changes accept(); } void PluginsWindow::on_buttonBox_rejected() { // Simple cancel whatever was done here reject(); } } <|endoftext|>
<commit_before>/* * Copyright 2014-2015 CyberVision, 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. */ #ifndef KAATIMER_HPP_ #define KAATIMER_HPP_ #include <chrono> #include <mutex> #include <thread> #include <functional> #include <condition_variable> #include "kaa/KaaThread.hpp" #include "kaa/logging/Log.hpp" namespace kaa { template<class Signature, class Function = std::function<Signature>> class KaaTimer { typedef std::chrono::system_clock TimerClock; public: KaaTimer(const std::string& timerName) : timerName_(timerName), isThreadRun_(false), isTimerRun_(false), callback_([]{}) { } ~KaaTimer() { //KAA_LOG_TRACE(boost::format("Timer[%1%] destroying ...") % timerName_); if (isThreadRun_ && timerThread_.joinable()) { //KAA_MUTEX_LOCKING("timerGuard_"); KAA_MUTEX_UNIQUE_DECLARE(timerLock, timerGuard_); //KAA_MUTEX_LOCKED("timerGuard_"); isThreadRun_ = false; condition_.notify_one(); //KAA_MUTEX_UNLOCKING("timerGuard_"); KAA_UNLOCK(timerLock); //KAA_MUTEX_UNLOCKED("timerGuard_"); timerThread_.join(); } } void start(std::size_t seconds, const Function& callback) { KAA_LOG_TRACE(boost::format("Timer[%1%] scheduling for %2% sec ...") % timerName_ % seconds ); KAA_MUTEX_LOCKING("timerGuard_"); KAA_MUTEX_UNIQUE_DECLARE(timerLock, timerGuard_); KAA_MUTEX_LOCKED("timerGuard_"); if (!isThreadRun_) { isThreadRun_ = true; timerThread_ = std::thread([&] { run(); }); } if (!isTimerRun_) { endTS_ = TimerClock::now() + std::chrono::seconds(seconds); isTimerRun_ = true; callback_ = callback; condition_.notify_one(); } } void stop() { KAA_LOG_TRACE(boost::format("Timer[%1%] stopping ...") % timerName_); KAA_MUTEX_LOCKING("timerGuard_"); KAA_MUTEX_UNIQUE_DECLARE(timerLock, timerGuard_); KAA_MUTEX_LOCKED("timerGuard_"); if (isTimerRun_) { isTimerRun_ = false; condition_.notify_one(); } } private: void run() { KAA_LOG_TRACE(boost::format("Timer[%1%] starting thread ...") % timerName_); KAA_MUTEX_LOCKING("timerGuard_"); KAA_MUTEX_UNIQUE_DECLARE(timerLock, timerGuard_); KAA_MUTEX_LOCKED("timerGuard_"); while (isThreadRun_) { if (isTimerRun_) { auto now = TimerClock::now(); if (now >= endTS_) { KAA_LOG_TRACE(boost::format("Timer[%1%] executing callback ...") % timerName_); isTimerRun_ = false; auto currentCallback = callback_; KAA_MUTEX_UNLOCKING("timerGuard_"); KAA_UNLOCK(timerLock); KAA_MUTEX_UNLOCKED("timerGuard_"); currentCallback(); KAA_MUTEX_LOCKING("timer_mutex_"); KAA_LOCK(timerLock); KAA_MUTEX_LOCKED("timer_mutex_"); } else { KAA_MUTEX_UNLOCKING("timerGuard_"); condition_.wait_for(timerLock, (endTS_ - now)); KAA_MUTEX_UNLOCKED("timerGuard_"); } } else { KAA_MUTEX_UNLOCKING("timerGuard_"); condition_.wait(timerLock); KAA_MUTEX_UNLOCKED("timerGuard_"); } } } private: const std::string timerName_; bool isThreadRun_; bool isTimerRun_; std::thread timerThread_; std::condition_variable condition_; KAA_MUTEX_DECLARE(timerGuard_); std::chrono::time_point<TimerClock> endTS_; Function callback_; }; } /* namespace kaa */ #endif /* KAATIMER_HPP_ */ <commit_msg>KAA-565: Get rid off thread-macros in the timer class.<commit_after>/* * Copyright 2014-2015 CyberVision, 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. */ #ifndef KAATIMER_HPP_ #define KAATIMER_HPP_ #include <chrono> #include <mutex> #include <thread> #include <functional> #include <condition_variable> #include "kaa/KaaThread.hpp" #include "kaa/logging/Log.hpp" namespace kaa { template<class Signature, class Function = std::function<Signature>> class KaaTimer { typedef std::chrono::system_clock TimerClock; public: KaaTimer(const std::string& timerName) : timerName_(timerName), isThreadRun_(false), isTimerRun_(false), callback_([]{}) { } ~KaaTimer() { /* * Do not add the mutex logging it may cause crashes. */ if (isThreadRun_ && timerThread_.joinable()) { std::unique_lock<std::mutex> timerLock(timerGuard_); isThreadRun_ = false; condition_.notify_one(); timerLock.unlock(); timerThread_.join(); } } void start(std::size_t seconds, const Function& callback) { KAA_LOG_TRACE(boost::format("Timer[%1%] scheduling for %2% sec ...") % timerName_ % seconds ); KAA_MUTEX_LOCKING("timerGuard_"); std::unique_lock<std::mutex> timerLock(timerGuard_); KAA_MUTEX_LOCKED("timerGuard_"); if (!isThreadRun_) { isThreadRun_ = true; timerThread_ = std::thread([&] { run(); }); } if (!isTimerRun_) { endTS_ = TimerClock::now() + std::chrono::seconds(seconds); isTimerRun_ = true; callback_ = callback; condition_.notify_one(); } } void stop() { KAA_LOG_TRACE(boost::format("Timer[%1%] stopping ...") % timerName_); KAA_MUTEX_LOCKING("timerGuard_"); std::unique_lock<std::mutex> timerLock(timerGuard_); KAA_MUTEX_LOCKED("timerGuard_"); if (isTimerRun_) { isTimerRun_ = false; condition_.notify_one(); } } private: void run() { KAA_LOG_TRACE(boost::format("Timer[%1%] starting thread ...") % timerName_); KAA_MUTEX_LOCKING("timerGuard_"); std::unique_lock<std::mutex> timerLock(timerGuard_); KAA_MUTEX_LOCKED("timerGuard_"); while (isThreadRun_) { if (isTimerRun_) { auto now = TimerClock::now(); if (now >= endTS_) { KAA_LOG_TRACE(boost::format("Timer[%1%] executing callback ...") % timerName_); isTimerRun_ = false; auto currentCallback = callback_; KAA_MUTEX_UNLOCKING("timerGuard_"); timerLock.unlock(); KAA_MUTEX_UNLOCKED("timerGuard_"); currentCallback(); KAA_MUTEX_LOCKING("timer_mutex_"); timerLock.lock(); KAA_MUTEX_LOCKED("timer_mutex_"); } else { KAA_MUTEX_UNLOCKING("timerGuard_"); condition_.wait_for(timerLock, (endTS_ - now)); KAA_MUTEX_UNLOCKED("timerGuard_"); } } else { KAA_MUTEX_UNLOCKING("timerGuard_"); condition_.wait(timerLock); KAA_MUTEX_UNLOCKED("timerGuard_"); } } } private: const std::string timerName_; bool isThreadRun_; bool isTimerRun_; std::thread timerThread_; std::condition_variable condition_; std::mutex timerGuard_; std::chrono::time_point<TimerClock> endTS_; Function callback_; }; } /* namespace kaa */ #endif /* KAATIMER_HPP_ */ <|endoftext|>
<commit_before>#include <QSettings> #include "QGCSettingsWidget.h" #include "MainWindow.h" #include "ui_QGCSettingsWidget.h" #include "LinkManager.h" #include "MAVLinkProtocol.h" #include "MAVLinkSettingsWidget.h" #include "GAudioOutput.h" //, Qt::WindowFlags flags QGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags), ui(new Ui::QGCSettingsWidget) { m_init = false; ui->setupUi(this); // Add all protocols QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols(); foreach (ProtocolInterface* protocol, protocols) { MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol); if (mavlink) { MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this); ui->tabWidget->addTab(msettings, "MAVLink"); } } this->window()->setWindowTitle(tr("APM Planner 2 Settings")); } void QGCSettingsWidget::showEvent(QShowEvent *evt) { if (!m_init) { m_init = true; // Audio preferences ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted()); connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool))); connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool))); // Reconnect ui->reconnectCheckBox->setChecked(MainWindow::instance()->autoReconnectEnabled()); connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableAutoReconnect(bool))); // Low power mode ui->lowPowerCheckBox->setChecked(MainWindow::instance()->lowPowerModeEnabled()); connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableLowPowerMode(bool))); //Dock widget title bars ui->titleBarCheckBox->setChecked(MainWindow::instance()->dockWidgetTitleBarsEnabled()); connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),MainWindow::instance(),SLOT(enableDockWidgetTitleBars(bool))); ui->logDirEdit->setText(QGC::logDirectory()); ui->appDataDirEdit->setText((QGC::appDataDirectory())); ui->paramDirEdit->setText(QGC::parameterDirectory()); ui->mavlinkLogDirEdit->setText((QGC::MAVLinkLogDirectory())); connect(ui->logDirSetButton, SIGNAL(clicked()), this, SLOT(setLogDir())); connect(ui->appDirSetButton, SIGNAL(clicked()), this, SLOT(setAppDataDir())); connect(ui->paramDirSetButton, SIGNAL(clicked()), this, SLOT(setParamDir())); connect(ui->mavlinkDirSetButton, SIGNAL(clicked()), this, SLOT(setMAVLinkLogDir())); // Style MainWindow::QGC_MAINWINDOW_STYLE style = (MainWindow::QGC_MAINWINDOW_STYLE)MainWindow::instance()->getStyle(); switch (style) { case MainWindow::QGC_MAINWINDOW_STYLE_NATIVE: ui->nativeStyle->setChecked(true); break; case MainWindow::QGC_MAINWINDOW_STYLE_INDOOR: ui->indoorStyle->setChecked(true); break; case MainWindow::QGC_MAINWINDOW_STYLE_OUTDOOR: ui->outdoorStyle->setChecked(true); break; } connect(ui->nativeStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadNativeStyle())); connect(ui->indoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadIndoorStyle())); connect(ui->outdoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadOutdoorStyle())); // Close / destroy //connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(deleteLater())); // Set layout options // ui->generoalPaneGridLayout->setAlignment(Qt::AlignTop); } } QGCSettingsWidget::~QGCSettingsWidget() { delete ui; } void QGCSettingsWidget::setLogDir() { QFileDialog dlg(this); dlg.setFileMode(QFileDialog::Directory); dlg.setDirectory(QGC::logDirectory()); if(dlg.exec() == QDialog::Accepted) { QDir dir = dlg.directory(); QString name = dir.absolutePath(); QGC::setLogDirectory(name); ui->logDirEdit->setText(name); } } void QGCSettingsWidget::setMAVLinkLogDir() { QFileDialog dlg(this); dlg.setFileMode(QFileDialog::Directory); dlg.setDirectory(QGC::MAVLinkLogDirectory()); if(dlg.exec() == QDialog::Accepted) { QDir dir = dlg.directory(); QString name = dir.absolutePath(); QGC::setMAVLinkLogDirectory(name); ui->mavlinkLogDirEdit->setText(name); } } void QGCSettingsWidget::setParamDir() { QFileDialog dlg(this); dlg.setFileMode(QFileDialog::Directory); dlg.setDirectory(QGC::parameterDirectory()); if(dlg.exec() == QDialog::Accepted) { QDir dir = dlg.directory(); QString name = dir.absolutePath(); QGC::setParameterDirectory(name); ui->paramDirEdit->setText(name); } } void QGCSettingsWidget::setAppDataDir() { QFileDialog dlg(this); dlg.setFileMode(QFileDialog::Directory); dlg.setDirectory(QGC::appDataDirectory()); if(dlg.exec() == QDialog::Accepted) { QDir dir = dlg.directory(); QString name = dir.absolutePath(); QGC::setAppDataDirectory(name); ui->appDataDirEdit->setText(name); } } <commit_msg>Clean up some old commented out code<commit_after>#include <QSettings> #include "QGCSettingsWidget.h" #include "MainWindow.h" #include "ui_QGCSettingsWidget.h" #include "LinkManager.h" #include "MAVLinkProtocol.h" #include "MAVLinkSettingsWidget.h" #include "GAudioOutput.h" //, Qt::WindowFlags flags QGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) : QDialog(parent, flags), ui(new Ui::QGCSettingsWidget) { m_init = false; ui->setupUi(this); // Add all protocols QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols(); foreach (ProtocolInterface* protocol, protocols) { MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol); if (mavlink) { MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this); ui->tabWidget->addTab(msettings, "MAVLink"); } } this->window()->setWindowTitle(tr("APM Planner 2 Settings")); } void QGCSettingsWidget::showEvent(QShowEvent *evt) { if (!m_init) { m_init = true; // Audio preferences ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted()); connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool))); connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool))); // Reconnect ui->reconnectCheckBox->setChecked(MainWindow::instance()->autoReconnectEnabled()); connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableAutoReconnect(bool))); // Low power mode ui->lowPowerCheckBox->setChecked(MainWindow::instance()->lowPowerModeEnabled()); connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), MainWindow::instance(), SLOT(enableLowPowerMode(bool))); //Dock widget title bars ui->titleBarCheckBox->setChecked(MainWindow::instance()->dockWidgetTitleBarsEnabled()); connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),MainWindow::instance(),SLOT(enableDockWidgetTitleBars(bool))); ui->logDirEdit->setText(QGC::logDirectory()); ui->appDataDirEdit->setText((QGC::appDataDirectory())); ui->paramDirEdit->setText(QGC::parameterDirectory()); ui->mavlinkLogDirEdit->setText((QGC::MAVLinkLogDirectory())); connect(ui->logDirSetButton, SIGNAL(clicked()), this, SLOT(setLogDir())); connect(ui->appDirSetButton, SIGNAL(clicked()), this, SLOT(setAppDataDir())); connect(ui->paramDirSetButton, SIGNAL(clicked()), this, SLOT(setParamDir())); connect(ui->mavlinkDirSetButton, SIGNAL(clicked()), this, SLOT(setMAVLinkLogDir())); // Style MainWindow::QGC_MAINWINDOW_STYLE style = (MainWindow::QGC_MAINWINDOW_STYLE)MainWindow::instance()->getStyle(); switch (style) { case MainWindow::QGC_MAINWINDOW_STYLE_NATIVE: ui->nativeStyle->setChecked(true); break; case MainWindow::QGC_MAINWINDOW_STYLE_INDOOR: ui->indoorStyle->setChecked(true); break; case MainWindow::QGC_MAINWINDOW_STYLE_OUTDOOR: ui->outdoorStyle->setChecked(true); break; } connect(ui->nativeStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadNativeStyle())); connect(ui->indoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadIndoorStyle())); connect(ui->outdoorStyle, SIGNAL(clicked()), MainWindow::instance(), SLOT(loadOutdoorStyle())); } } QGCSettingsWidget::~QGCSettingsWidget() { delete ui; } void QGCSettingsWidget::setLogDir() { QFileDialog dlg(this); dlg.setFileMode(QFileDialog::Directory); dlg.setDirectory(QGC::logDirectory()); if(dlg.exec() == QDialog::Accepted) { QDir dir = dlg.directory(); QString name = dir.absolutePath(); QGC::setLogDirectory(name); ui->logDirEdit->setText(name); } } void QGCSettingsWidget::setMAVLinkLogDir() { QFileDialog dlg(this); dlg.setFileMode(QFileDialog::Directory); dlg.setDirectory(QGC::MAVLinkLogDirectory()); if(dlg.exec() == QDialog::Accepted) { QDir dir = dlg.directory(); QString name = dir.absolutePath(); QGC::setMAVLinkLogDirectory(name); ui->mavlinkLogDirEdit->setText(name); } } void QGCSettingsWidget::setParamDir() { QFileDialog dlg(this); dlg.setFileMode(QFileDialog::Directory); dlg.setDirectory(QGC::parameterDirectory()); if(dlg.exec() == QDialog::Accepted) { QDir dir = dlg.directory(); QString name = dir.absolutePath(); QGC::setParameterDirectory(name); ui->paramDirEdit->setText(name); } } void QGCSettingsWidget::setAppDataDir() { QFileDialog dlg(this); dlg.setFileMode(QFileDialog::Directory); dlg.setDirectory(QGC::appDataDirectory()); if(dlg.exec() == QDialog::Accepted) { QDir dir = dlg.directory(); QString name = dir.absolutePath(); QGC::setAppDataDirectory(name); ui->appDataDirEdit->setText(name); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "element_iterator.h" namespace game { namespace ui { D_F_Elem_Iter::D_F_Elem_Iter(Shared_Element e) noexcept { path_.emplace_back(e); } D_F_Elem_Iter::D_F_Elem_Iter() noexcept { path_.emplace_back(nullptr); } D_F_Elem_Iter::D_F_Elem_Iter(D_F_Elem_Iter const& rhs) noexcept : path_(rhs.path_) {} D_F_Elem_Iter::D_F_Elem_Iter(D_F_Elem_Iter&& rhs) noexcept : path_(std::move(rhs.path_)) {} D_F_Elem_Iter& D_F_Elem_Iter::operator=(D_F_Elem_Iter const& rhs) noexcept { path_ = rhs.path_; return *this; } D_F_Elem_Iter& D_F_Elem_Iter::operator=(D_F_Elem_Iter&& rhs) noexcept { path_ = std::move(rhs.path_); return *this; } D_F_Elem_Iter::reference D_F_Elem_Iter::operator*() const noexcept { // Get active element pointer and just dereference it. return *operator->(); } D_F_Elem_Iter::pointer D_F_Elem_Iter::operator->() const noexcept { // Return a nullptr in the end-iterator case. if(is_end()) return nullptr; return path_.back().elem.get(); } D_F_Elem_Iter& D_F_Elem_Iter::operator++() noexcept { // Get our path. auto& cur = path_.back(); // If we still have children for this element that need exploring. if(cur.cur_child + 1 < cur.elem->child_count()) { // Mark the first child as being explored. ++cur.cur_child; // Add it to our path and note that it hasn't been explored. path_.emplace_back(cur.elem->child_at(cur.cur_child), -1); } // If we are done exploring our current element's children, we can go up else if(cur.cur_child + 1 == cur.elem->child_count()) { // Get rid of this one. path_.erase(path_.end() - 1); // Increment ourselves. This will result in us going to the current // elements sibling, or if not that the one above its sibling etc. operator++(); } return *this; } D_F_Elem_Iter D_F_Elem_Iter::operator++(int) noexcept { auto it = *this; ++(*this); return it; } bool D_F_Elem_Iter::operator==(D_F_Elem_Iter const& rhs) const noexcept { return operator->() == rhs.operator->(); } bool operator!=(D_F_Elem_Iter const& lhs, D_F_Elem_Iter const& rhs) noexcept { return !(lhs == rhs); } } } <commit_msg>Fixed up the operator++ to work even if we are a end iter/nullptr.<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "element_iterator.h" namespace game { namespace ui { D_F_Elem_Iter::D_F_Elem_Iter(Shared_Element e) noexcept { path_.emplace_back(e); } D_F_Elem_Iter::D_F_Elem_Iter() noexcept { path_.emplace_back(nullptr); } D_F_Elem_Iter::D_F_Elem_Iter(D_F_Elem_Iter const& rhs) noexcept : path_(rhs.path_) {} D_F_Elem_Iter::D_F_Elem_Iter(D_F_Elem_Iter&& rhs) noexcept : path_(std::move(rhs.path_)) {} D_F_Elem_Iter& D_F_Elem_Iter::operator=(D_F_Elem_Iter const& rhs) noexcept { path_ = rhs.path_; return *this; } D_F_Elem_Iter& D_F_Elem_Iter::operator=(D_F_Elem_Iter&& rhs) noexcept { path_ = std::move(rhs.path_); return *this; } D_F_Elem_Iter::reference D_F_Elem_Iter::operator*() const noexcept { // Get active element pointer and just dereference it. return *operator->(); } D_F_Elem_Iter::pointer D_F_Elem_Iter::operator->() const noexcept { // Return a nullptr in the end-iterator case. if(is_end()) return nullptr; return path_.back().elem.get(); } D_F_Elem_Iter& D_F_Elem_Iter::operator++() noexcept { // Get our path. auto& cur = path_.back(); // If we are currently dealing with a nullptr bail out, the logic of this // function should prevent this in general unless we are an end iterator // or we become an end iterator. if(cur.elem == nullptr) return *this; // If we still have children for this element that need exploring. if(cur.cur_child + 1 < cur.elem->child_count()) { // Mark the first child as being explored. ++cur.cur_child; // Add it to our path and note that it hasn't been explored. path_.emplace_back(cur.elem->child_at(cur.cur_child), -1); } // If we are done exploring our current element's children, we can go up else if(cur.cur_child + 1 == cur.elem->child_count()) { // If we are the root node, we can't go up, just mark ourselves as done // by becoming an end iterator. if(path_.size() == 1) { path_.back().elem = nullptr; return *this; } // Get rid of this one. path_.erase(path_.end() - 1); // Increment ourselves. This will result in us going to the current // elements sibling, or if not that the one above its sibling etc. operator++(); } return *this; } D_F_Elem_Iter D_F_Elem_Iter::operator++(int) noexcept { auto it = *this; ++(*this); return it; } bool D_F_Elem_Iter::operator==(D_F_Elem_Iter const& rhs) const noexcept { return operator->() == rhs.operator->(); } bool operator!=(D_F_Elem_Iter const& lhs, D_F_Elem_Iter const& rhs) noexcept { return !(lhs == rhs); } } } <|endoftext|>
<commit_before>#include "mapQGraphicsView.h" #include <QPointF> #include <QReadLocker> #include "poiQGraphicsEllipseItem.h" #include "wallQGraphicsLineItem.h" #include "atcQGraphicsRectItem.h" #include "fleetManager.h" #include <iostream> #include "mainwindow.h" #include <cmath> #include <QDebug> #include <QMessageBox> #include "flogger.h" MapQGraphicsView::MapQGraphicsView(FleetManager* fleetManager, QWidget* parent) : QGraphicsView(parent), wallToBeAddedStartPoint_(NULL), atcToBeAddedStartPoint_(NULL), mapScale_(1), traceShown_(true), fleetManager_(fleetManager), wallToBeAddedStartPointText_(NULL), wallToBeAddedEndPointText_(NULL), atcToBeAddedStartPointText_(NULL), atcToBeAddedEndPointText_(NULL) { setRenderHints(QPainter::Antialiasing); } void MapQGraphicsView::mousePressEvent(QMouseEvent *event) { if (event->button()==Qt::LeftButton) { QPointF p = mapToScene(event->pos()); if (selectedPaintTool_ == Util::SelectedPaintTool::CURSOR) { scene()->clearSelection(); if ( QGraphicsItem* item = itemAt(event->pos()) ) { item->setSelected(true); } setDragMode(QGraphicsView::NoDrag); emit roombaSelected(); qDebug() << "Draw a cursor!"; (*flog.ts) << "Draw a cursor!" << endl; } else if (selectedPaintTool_ == Util::SelectedPaintTool::WALL) { setDragMode(QGraphicsView::NoDrag); qDebug() << "Start a wall!"; wallToBeAdded_ = new WallQGraphicsLineItem (fleetManager_, p.x(), p.y(), p.x(), p.y()); wallToBeAddedStartPoint_ = new QPointF(p.x(), p.y()); scene()->addItem(wallToBeAdded_); // Add textual coordinates to the beginning of the wall line wallToBeAddedStartPointText_ = new QGraphicsSimpleTextItem ("X: " + QString::number(p.x()*Util::COORDCORRECTION, 'f', 0) + " Y: " + QString::number(p.y()*Util::COORDCORRECTION, 'f', 0)); wallToBeAddedStartPointText_->setPos(p); wallToBeAddedStartPointText_->setZValue(5); QBrush wallToBeAddedStartPointBrush(Qt::GlobalColor::blue); wallToBeAddedStartPointText_->setBrush(wallToBeAddedStartPointBrush); scene()->addItem(wallToBeAddedStartPointText_); qDebug() << "Pos: " << p.x() << "y: "<< p.y(); (*flog.ts)<< QString("Start a wall @ x: %1 y: %2").arg(p.x()).arg(p.y()) <<endl; } else if (selectedPaintTool_ == Util::SelectedPaintTool::ATC) { setDragMode(QGraphicsView::NoDrag); qDebug() << "Draw a atc!"; atcToBeAdded_ = new AtcQGraphicsRectItem (fleetManager_, p.x(), p.y(), 0, 0); // (0,0,0,0); atcToBeAddedStartPoint_ = new QPointF(p.x(), p.y()); scene()->addItem(atcToBeAdded_); // Add textual coordinates to the Top Left corner point of the Rectangle atcToBeAddedStartPointText_ = new QGraphicsSimpleTextItem("X: " + QString::number(p.x()*Util::COORDCORRECTION) + " Y: " + QString::number(p.y()*Util::COORDCORRECTION)); atcToBeAddedStartPointText_->setPos(p); atcToBeAddedStartPointText_->setZValue(5); QBrush atcToBeAddedStartPointBrush(Qt::GlobalColor::blue); atcToBeAddedStartPointText_->setBrush(atcToBeAddedStartPointBrush); scene()->addItem(atcToBeAddedStartPointText_); qDebug() << "Square corner X: " + QString::number(p.x()) + " Y: " + QString::number(p.y()); // AtcQGraphicsRectItem* atc = new AtcQGraphicsRectItem // (0.0-POIWIDTH/5.0-TRACEWIDTH/2.0, 0.0-POIWIDTH/5.0-TRACEWIDTH/2.0, 5*POIWIDTH, 5*POIWIDTH); // (0.0-5*POIWIDTH/2.0, 0.0-5*POIWIDTH/2.0, 5*POIWIDTH, 5*POIWIDTH); // (0.0, 0.0, 5*POIWIDTH, 5*POIWIDTH); // atc->setPos(p); // fleetManager_->pushATC(p); // qDebug() << "pushATC(p) p.x(): " << p.x() << "p.y(): "<< p.y(); // atc->setFlag(QGraphicsItem::ItemIsSelectable,true); // atc->setFlag(QGraphicsItem::ItemIsMovable,false); // Disabled so that the mapChanged signal works as expected // scene()->addItem(atc); // fleetManager_->addAtc(atcToBeAdded_); // qDebug() << "Adding scenePos().x(): " << atc->scenePos().x() // << " ,scenePos().y(): " << atc->scenePos().y(); qDebug() << "squP.x(): " << p.x() << "P.y(): "<< p.y(); (*flog.ts)<< QString("Draw a ATC, Adding ATC with x: %1 y: %2").arg(p.x()).arg(p.y()) <<endl; emit mapChanged(); } else if (selectedPaintTool_ == Util::SelectedPaintTool::POI) { if(fleetManager_->isBlocked(&p)) { QMessageBox::warning (parentWidget(), "", tr("POI must be inserted further away from wall!")); } else { qDebug() << "Draw a poi!"; setDragMode(QGraphicsView::NoDrag); PoiQGraphicsEllipseItem* poi = new PoiQGraphicsEllipseItem (fleetManager_, 0.0-Util::POIWIDTH/2.0, 0.0-Util::POIWIDTH/2.0, Util::POIWIDTH, Util::POIWIDTH); poi->setPos(p); poi->setFlag(QGraphicsItem::ItemIsSelectable,false); poi->setFlag(QGraphicsItem::ItemIsMovable,false); // Disabled so that the mapChanged signal works as expected scene()->addItem(poi); fleetManager_->addPoi(poi); qDebug() << "Adding POI with x: " << poi->scenePos().x() << " , y: " << poi->scenePos().y(); emit mapChanged(); (*flog.ts)<< QString("Draw a POI, Adding POI with x: %1 y: %2").arg(p.x()).arg(p.y()) <<endl; } } else if (selectedPaintTool_ == Util::SelectedPaintTool::START || selectedPaintTool_ == Util::SelectedPaintTool::STARTVIRTUAL) { qDebug() << "Draw a start!"; (*flog.ts) << "Draw a start" << endl; setDragMode(QGraphicsView::NoDrag); PoiQGraphicsEllipseItem *startPoint = new PoiQGraphicsEllipseItem (fleetManager_, 0.0-Util::POIWIDTH*2.0/3.0, 0.0-Util::POIWIDTH*2.0/3.0, Util::POIWIDTH*4.0/3.0, Util::POIWIDTH*4.0/3.0); startPoint->setPos(p); QBrush brush(Qt::GlobalColor::green); startPoint->setBrush(brush); startPoint->setFlag(QGraphicsItem::ItemIsSelectable,false); //movable needs additional logic before allowing startPoint->setFlag(QGraphicsItem::ItemIsMovable,false); //TODO: Add deleleting of startPoint when moving it scene()->addItem(startPoint); if(selectedPaintTool_ == Util::SelectedPaintTool::START) { fleetManager_->createRoomba(startPoint, false); //real roomba } else { fleetManager_->createRoomba(startPoint, true); //virtual roomba } } } // Call the base class implementation to deliver the event for QGraphicsScene QGraphicsView::mousePressEvent(event); } void MapQGraphicsView::mouseMoveEvent(QMouseEvent *event) { // event->button() returns always Qt::NoButton for mouse move events, so button check is not needed if (wallToBeAddedStartPoint_ != NULL) { QPointF p = mapToScene(event->pos()); if (selectedPaintTool_ == Util::SelectedPaintTool::WALL) { wallToBeAdded_->setLine(wallToBeAddedStartPoint_->x(), wallToBeAddedStartPoint_->y(), p.x(), p.y()); } // Add textual coordinates to the end of the wall line if (wallToBeAddedEndPointText_ == NULL) { wallToBeAddedEndPointText_ = new QGraphicsSimpleTextItem("X: " + QString::number(p.x()) + " Y: " + QString::number(p.y())); wallToBeAddedEndPointText_->setPos(p); QBrush wallToBeAddedEndPointTextBrush(Qt::GlobalColor::blue); wallToBeAddedEndPointText_->setBrush(wallToBeAddedEndPointTextBrush); scene()->addItem(wallToBeAddedEndPointText_); wallToBeAddedEndPointText_->setZValue(5); } // Update textual coordinates in the end of the wall line else { // Calculate the current wall length float deltaX = wallToBeAdded_->line().x2() - wallToBeAdded_->line().x1(); float deltaY = wallToBeAdded_->line().y1() - wallToBeAdded_->line().y2(); // TODO: Add pythagoras from here and iRoomba to some utility function float distance = sqrt(pow(deltaX,2)+pow(deltaY,2) )*Util::COORDCORRECTION; // Use offset to avoid colliding with cursor QPointF pointToDrawLength = p; pointToDrawLength.setY(pointToDrawLength.y()+Util::WALLLENGTHINDICATOROFFSET); wallToBeAddedEndPointText_->setPos(pointToDrawLength); wallToBeAddedEndPointText_->setText(QString::number(distance, 'f', 0) + "cm"); // Ignore decimals in wall length } } if (atcToBeAddedStartPoint_ != NULL) { QPointF p = mapToScene(event->pos()); if (selectedPaintTool_ == Util::SelectedPaintTool::ATC) { atcToBeAdded_->setRect(atcToBeAddedStartPoint_->x(), atcToBeAddedStartPoint_->y(), p.x()-atcToBeAddedStartPoint_->x(), p.y()-atcToBeAddedStartPoint_->y()); scene()->update(); } // Add textual coordinates to the end of the rectangle if (atcToBeAddedEndPointText_ == NULL) { atcToBeAddedEndPointText_ = new QGraphicsSimpleTextItem("X: " + QString::number(p.x()) + " Y: " + QString::number(p.y())); atcToBeAddedEndPointText_->setPos(p); QBrush atcToBeAddedEndPointTextBrush(Qt::GlobalColor::blue); atcToBeAddedEndPointText_->setBrush(atcToBeAddedEndPointTextBrush); scene()->addItem(atcToBeAddedEndPointText_); atcToBeAddedEndPointText_->setZValue(5); } // Update textual coordinates in the end of the rectangle // line width is 3, we have to add 3 for p.x() and p.y() else { atcToBeAddedEndPointText_->setPos(p); atcToBeAddedEndPointText_->setText("X: " + QString::number(p.x()*Util::COORDCORRECTION) + " Y: " + QString::number(p.y()*Util::COORDCORRECTION) + "\nW " + QString::number((abs(atcToBeAdded_->rect().width())+3)*Util::COORDCORRECTION) + " H " + QString::number((abs(atcToBeAdded_->rect().height())+3)*Util::COORDCORRECTION) ); } } // Call the base class implementation to deliver the event for QGraphicsScene QGraphicsView::mouseMoveEvent(event); } void MapQGraphicsView::mouseReleaseEvent(QMouseEvent *event) { if (event->button()==Qt::LeftButton) { if (selectedPaintTool_ == Util::SelectedPaintTool::WALL) { wallToBeAdded_->setFlag(QGraphicsItem::ItemIsSelectable,false); wallToBeAdded_->setFlag(QGraphicsItem::ItemIsMovable,false); // Disabled so that the mapChanged signal works as expected fleetManager_->addWall(wallToBeAdded_); if(fleetManager_->removeBlockedPois()) //POIs blocked by the wall are removed { QMessageBox::warning (parentWidget(), "", tr("POIs too close to the wall were removed")); } wallToBeAdded_ = NULL; delete wallToBeAddedStartPoint_; wallToBeAddedStartPoint_ = NULL; delete wallToBeAddedStartPointText_; wallToBeAddedStartPointText_ = NULL; delete wallToBeAddedEndPointText_; wallToBeAddedEndPointText_ = NULL; emit mapChanged(); } else if (selectedPaintTool_ == Util::SelectedPaintTool::ATC) { atcToBeAdded_->setFlag(QGraphicsItem::ItemIsSelectable,false); atcToBeAdded_->setFlag(QGraphicsItem::ItemIsMovable,false); // Disabled so that the mapChanged signal works as expected fleetManager_->addAtc(atcToBeAdded_); delete atcToBeAddedStartPoint_; atcToBeAddedStartPoint_ = NULL; delete atcToBeAddedStartPointText_; atcToBeAddedStartPointText_ = NULL; delete atcToBeAddedEndPointText_; atcToBeAddedEndPointText_ = NULL; emit mapChanged(); } } // Call the base class implementation to deliver the event for QGraphicsScene QGraphicsView::mouseReleaseEvent(event); } void MapQGraphicsView::setSelectedPaintTool(Util::SelectedPaintTool tool) { selectedPaintTool_ = tool; } //gives map's width in mm unsigned int MapQGraphicsView::getmapScale() { return mapScale_; } //give new width in mm. void MapQGraphicsView::setmapScale(double scaleFactor) { mapScale_ = scaleFactor; resetTransform(); //MAP'S WIDTH IN PIXELS IS FIXED ATM scale(scaleFactor, scaleFactor); } MapQGraphicsView::~MapQGraphicsView() { } <commit_msg>MAP: Adjusted precision of ATC's informative texts<commit_after>#include "mapQGraphicsView.h" #include <QPointF> #include <QReadLocker> #include "poiQGraphicsEllipseItem.h" #include "wallQGraphicsLineItem.h" #include "atcQGraphicsRectItem.h" #include "fleetManager.h" #include <iostream> #include "mainwindow.h" #include <cmath> #include <QDebug> #include <QMessageBox> #include "flogger.h" MapQGraphicsView::MapQGraphicsView(FleetManager* fleetManager, QWidget* parent) : QGraphicsView(parent), wallToBeAddedStartPoint_(NULL), atcToBeAddedStartPoint_(NULL), mapScale_(1), traceShown_(true), fleetManager_(fleetManager), wallToBeAddedStartPointText_(NULL), wallToBeAddedEndPointText_(NULL), atcToBeAddedStartPointText_(NULL), atcToBeAddedEndPointText_(NULL) { setRenderHints(QPainter::Antialiasing); } void MapQGraphicsView::mousePressEvent(QMouseEvent *event) { if (event->button()==Qt::LeftButton) { QPointF p = mapToScene(event->pos()); if (selectedPaintTool_ == Util::SelectedPaintTool::CURSOR) { scene()->clearSelection(); if ( QGraphicsItem* item = itemAt(event->pos()) ) { item->setSelected(true); } setDragMode(QGraphicsView::NoDrag); emit roombaSelected(); qDebug() << "Draw a cursor!"; (*flog.ts) << "Draw a cursor!" << endl; } else if (selectedPaintTool_ == Util::SelectedPaintTool::WALL) { setDragMode(QGraphicsView::NoDrag); qDebug() << "Start a wall!"; wallToBeAdded_ = new WallQGraphicsLineItem (fleetManager_, p.x(), p.y(), p.x(), p.y()); wallToBeAddedStartPoint_ = new QPointF(p.x(), p.y()); scene()->addItem(wallToBeAdded_); // Add textual coordinates to the beginning of the wall line wallToBeAddedStartPointText_ = new QGraphicsSimpleTextItem ("X: " + QString::number(p.x()*Util::COORDCORRECTION, 'f', 0) + " Y: " + QString::number(p.y()*Util::COORDCORRECTION, 'f', 0)); wallToBeAddedStartPointText_->setPos(p); wallToBeAddedStartPointText_->setZValue(5); QBrush wallToBeAddedStartPointBrush(Qt::GlobalColor::blue); wallToBeAddedStartPointText_->setBrush(wallToBeAddedStartPointBrush); scene()->addItem(wallToBeAddedStartPointText_); qDebug() << "Pos: " << p.x() << "y: "<< p.y(); (*flog.ts)<< QString("Start a wall @ x: %1 y: %2").arg(p.x()).arg(p.y()) <<endl; } else if (selectedPaintTool_ == Util::SelectedPaintTool::ATC) { setDragMode(QGraphicsView::NoDrag); qDebug() << "Draw a atc!"; atcToBeAdded_ = new AtcQGraphicsRectItem (fleetManager_, p.x(), p.y(), 0, 0); // (0,0,0,0); atcToBeAddedStartPoint_ = new QPointF(p.x(), p.y()); scene()->addItem(atcToBeAdded_); // Add textual coordinates to the Top Left corner point of the Rectangle atcToBeAddedStartPointText_ = new QGraphicsSimpleTextItem("X: " + QString::number(p.x()*Util::COORDCORRECTION, 'f', 0) + " Y: " + QString::number(p.y()*Util::COORDCORRECTION, 'f', 0)); atcToBeAddedStartPointText_->setPos(p); atcToBeAddedStartPointText_->setZValue(5); QBrush atcToBeAddedStartPointBrush(Qt::GlobalColor::blue); atcToBeAddedStartPointText_->setBrush(atcToBeAddedStartPointBrush); scene()->addItem(atcToBeAddedStartPointText_); (*flog.ts)<< QString("Draw a ATC, Adding ATC with x: %1 y: %2").arg(p.x()).arg(p.y()) <<endl; emit mapChanged(); } else if (selectedPaintTool_ == Util::SelectedPaintTool::POI) { if(fleetManager_->isBlocked(&p)) { QMessageBox::warning (parentWidget(), "", tr("POI must be inserted further away from wall!")); } else { qDebug() << "Draw a poi!"; setDragMode(QGraphicsView::NoDrag); PoiQGraphicsEllipseItem* poi = new PoiQGraphicsEllipseItem (fleetManager_, 0.0-Util::POIWIDTH/2.0, 0.0-Util::POIWIDTH/2.0, Util::POIWIDTH, Util::POIWIDTH); poi->setPos(p); poi->setFlag(QGraphicsItem::ItemIsSelectable,false); poi->setFlag(QGraphicsItem::ItemIsMovable,false); // Disabled so that the mapChanged signal works as expected scene()->addItem(poi); fleetManager_->addPoi(poi); qDebug() << "Adding POI with x: " << poi->scenePos().x() << " , y: " << poi->scenePos().y(); emit mapChanged(); (*flog.ts)<< QString("Draw a POI, Adding POI with x: %1 y: %2").arg(p.x()).arg(p.y()) <<endl; } } else if (selectedPaintTool_ == Util::SelectedPaintTool::START || selectedPaintTool_ == Util::SelectedPaintTool::STARTVIRTUAL) { qDebug() << "Draw a start!"; (*flog.ts) << "Draw a start" << endl; setDragMode(QGraphicsView::NoDrag); PoiQGraphicsEllipseItem *startPoint = new PoiQGraphicsEllipseItem (fleetManager_, 0.0-Util::POIWIDTH*2.0/3.0, 0.0-Util::POIWIDTH*2.0/3.0, Util::POIWIDTH*4.0/3.0, Util::POIWIDTH*4.0/3.0); startPoint->setPos(p); QBrush brush(Qt::GlobalColor::green); startPoint->setBrush(brush); startPoint->setFlag(QGraphicsItem::ItemIsSelectable,false); //movable needs additional logic before allowing startPoint->setFlag(QGraphicsItem::ItemIsMovable,false); //TODO: Add deleleting of startPoint when moving it scene()->addItem(startPoint); if(selectedPaintTool_ == Util::SelectedPaintTool::START) { fleetManager_->createRoomba(startPoint, false); //real roomba } else { fleetManager_->createRoomba(startPoint, true); //virtual roomba } } } // Call the base class implementation to deliver the event for QGraphicsScene QGraphicsView::mousePressEvent(event); } void MapQGraphicsView::mouseMoveEvent(QMouseEvent *event) { // event->button() returns always Qt::NoButton for mouse move events, so button check is not needed if (wallToBeAddedStartPoint_ != NULL) { QPointF p = mapToScene(event->pos()); if (selectedPaintTool_ == Util::SelectedPaintTool::WALL) { wallToBeAdded_->setLine(wallToBeAddedStartPoint_->x(), wallToBeAddedStartPoint_->y(), p.x(), p.y()); } // Add textual coordinates to the end of the wall line if (wallToBeAddedEndPointText_ == NULL) { wallToBeAddedEndPointText_ = new QGraphicsSimpleTextItem("X: " + QString::number(p.x()) + " Y: " + QString::number(p.y())); wallToBeAddedEndPointText_->setPos(p); QBrush wallToBeAddedEndPointTextBrush(Qt::GlobalColor::blue); wallToBeAddedEndPointText_->setBrush(wallToBeAddedEndPointTextBrush); scene()->addItem(wallToBeAddedEndPointText_); wallToBeAddedEndPointText_->setZValue(5); } // Update textual coordinates in the end of the wall line else { // Calculate the current wall length float deltaX = wallToBeAdded_->line().x2() - wallToBeAdded_->line().x1(); float deltaY = wallToBeAdded_->line().y1() - wallToBeAdded_->line().y2(); // TODO: Add pythagoras from here and iRoomba to some utility function float distance = sqrt(pow(deltaX,2)+pow(deltaY,2) )*Util::COORDCORRECTION; // Use offset to avoid colliding with cursor QPointF pointToDrawLength = p; pointToDrawLength.setY(pointToDrawLength.y()+Util::WALLLENGTHINDICATOROFFSET); wallToBeAddedEndPointText_->setPos(pointToDrawLength); wallToBeAddedEndPointText_->setText(QString::number(distance, 'f', 0) + "cm"); // Ignore decimals in wall length } } if (atcToBeAddedStartPoint_ != NULL) { QPointF p = mapToScene(event->pos()); if (selectedPaintTool_ == Util::SelectedPaintTool::ATC) { atcToBeAdded_->setRect(atcToBeAddedStartPoint_->x(), atcToBeAddedStartPoint_->y(), p.x()-atcToBeAddedStartPoint_->x(), p.y()-atcToBeAddedStartPoint_->y()); scene()->update(); } // Add textual coordinates to the end of the rectangle if (atcToBeAddedEndPointText_ == NULL) { atcToBeAddedEndPointText_ = new QGraphicsSimpleTextItem("X: " + QString::number(p.x(), 'f', 0) + " Y: " + QString::number(p.y(), 'f', 0)); atcToBeAddedEndPointText_->setPos(p); QBrush atcToBeAddedEndPointTextBrush(Qt::GlobalColor::blue); atcToBeAddedEndPointText_->setBrush(atcToBeAddedEndPointTextBrush); scene()->addItem(atcToBeAddedEndPointText_); atcToBeAddedEndPointText_->setZValue(5); } // Update textual coordinates in the end of the rectangle // line width is 3, we have to add 3 for p.x() and p.y() else { atcToBeAddedEndPointText_->setPos(p); atcToBeAddedEndPointText_->setText("X: " + QString::number(p.x()*Util::COORDCORRECTION, 'f', 0) + " Y: " + QString::number(p.y()*Util::COORDCORRECTION, 'f', 0) + "\nW " + QString::number((abs(atcToBeAdded_->rect().width())+3)*Util::COORDCORRECTION, 'f', 0) + " H " + QString::number((abs(atcToBeAdded_->rect().height())+3)*Util::COORDCORRECTION, 'f', 0) ); } } // Call the base class implementation to deliver the event for QGraphicsScene QGraphicsView::mouseMoveEvent(event); } void MapQGraphicsView::mouseReleaseEvent(QMouseEvent *event) { if (event->button()==Qt::LeftButton) { if (selectedPaintTool_ == Util::SelectedPaintTool::WALL) { wallToBeAdded_->setFlag(QGraphicsItem::ItemIsSelectable,false); wallToBeAdded_->setFlag(QGraphicsItem::ItemIsMovable,false); // Disabled so that the mapChanged signal works as expected fleetManager_->addWall(wallToBeAdded_); if(fleetManager_->removeBlockedPois()) //POIs blocked by the wall are removed { QMessageBox::warning (parentWidget(), "", tr("POIs too close to the wall were removed")); } wallToBeAdded_ = NULL; delete wallToBeAddedStartPoint_; wallToBeAddedStartPoint_ = NULL; delete wallToBeAddedStartPointText_; wallToBeAddedStartPointText_ = NULL; delete wallToBeAddedEndPointText_; wallToBeAddedEndPointText_ = NULL; emit mapChanged(); } else if (selectedPaintTool_ == Util::SelectedPaintTool::ATC) { atcToBeAdded_->setFlag(QGraphicsItem::ItemIsSelectable,false); atcToBeAdded_->setFlag(QGraphicsItem::ItemIsMovable,false); // Disabled so that the mapChanged signal works as expected fleetManager_->addAtc(atcToBeAdded_); delete atcToBeAddedStartPoint_; atcToBeAddedStartPoint_ = NULL; delete atcToBeAddedStartPointText_; atcToBeAddedStartPointText_ = NULL; delete atcToBeAddedEndPointText_; atcToBeAddedEndPointText_ = NULL; emit mapChanged(); } } // Call the base class implementation to deliver the event for QGraphicsScene QGraphicsView::mouseReleaseEvent(event); } void MapQGraphicsView::setSelectedPaintTool(Util::SelectedPaintTool tool) { selectedPaintTool_ = tool; } //gives map's width in mm unsigned int MapQGraphicsView::getmapScale() { return mapScale_; } //give new width in mm. void MapQGraphicsView::setmapScale(double scaleFactor) { mapScale_ = scaleFactor; resetTransform(); //MAP'S WIDTH IN PIXELS IS FIXED ATM scale(scaleFactor, scaleFactor); } MapQGraphicsView::~MapQGraphicsView() { } <|endoftext|>
<commit_before>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ #include <iomanip> #include "Log.h" #include "GradientTester.h" #include "NetGraphNode.h" namespace Conv { void GradientTester::TestGradient ( NetGraph& graph, unsigned int skip_weights, bool fatal_fail ) { const double epsilon = 0.005; LOGDEBUG << "Testing gradient. FeedForward..."; graph.FeedForward(); LOGDEBUG << "Testing gradient. BackPropagate..."; graph.BackPropagate(); const datum initial_loss = graph.AggregateLoss(); unsigned int global_okay = 0; unsigned int global_tolerable = 0; unsigned int global_failed = 0; unsigned int global_weights = 0; LOGDEBUG << "Initial loss: " << initial_loss; LOGDEBUG << "Using epsilon: " << epsilon; for(unsigned int l = 0; l < graph.GetNodes().size(); l++) { NetGraphNode* node = graph.GetNodes()[l]; Layer* layer = node->layer; for(unsigned int p = 0; p < layer->parameters().size(); p++) { CombinedTensor* const param = layer->parameters()[p]; LOGDEBUG << "Testing layer " << l << " (" << layer->GetLayerDescription() << "), parameter set " << p; LOGDEBUG << param->data; bool passed = true; unsigned int okay = 0; unsigned int tolerable = 0; unsigned int failed = 0; unsigned int total = 0; for(unsigned int e = 0; e < param->data.elements(); e+=(skip_weights + 1)) { total++; #ifdef BUILD_OPENCL param->data.MoveToCPU(); param->delta.MoveToCPU(); #endif const datum old_param = param->data(e); param->data[e] = old_param + epsilon; graph.FeedForward(); const double plus_loss = graph.AggregateLoss(); #ifdef BUILD_OPENCL param->data.MoveToCPU(); #endif param->data[e] = old_param - epsilon; graph.FeedForward(); const double minus_loss = graph.AggregateLoss(); const double delta = param->delta[e]; const double actual_delta = (plus_loss - minus_loss) / (2.0 * epsilon); const double ratio = actual_delta / delta; if(ratio > 1.02 || ratio < 0.98) { if(ratio > 1.2 || ratio < 0.8) { if(passed) { LOGWARN << "delta analytic: " << delta << ", numeric: " << actual_delta << ", ratio: " << ratio; } passed = false; // std::cout << "!" << std::flush; failed++; } else { // std::cout << "#" << std::flush; tolerable++; } } else { // std::cout << "." << std::flush; okay++; } #ifdef BUILD_OPENCL param->data.MoveToCPU(); #endif param->data[e] = old_param; } // std::cout << "\n"; if(passed) { LOGDEBUG << "Okay!"; } else { LOGERROR << "Failed!"; } LOGDEBUG << okay << " of " << total << " gradients okay (delta < 2%)"; LOGDEBUG << tolerable << " of " << total << " gradients tolerable (delta < 20%)"; LOGDEBUG << failed << " of " << total << " gradients failed (delta >= 20%)"; global_okay += okay; global_tolerable += tolerable; global_failed += failed; global_weights += total; } } LOGRESULT << global_okay << " of " << global_weights << " tested gradients okay (delta < 2%)" << LOGRESULTEND; LOGRESULT << global_tolerable << " of " << global_weights << " tested gradients tolerable (delta < 20%)" << LOGRESULTEND; LOGRESULT << global_failed << " of " << global_weights << " tested gradients failed (delta >= 20%)" << LOGRESULTEND; if (global_failed > 0 && fatal_fail) { FATAL("Failed gradient check!"); } } bool GradientTester::DoGradientTest(Conv::Layer* layer, Conv::Tensor& data, Conv::Tensor& delta, std::vector<Conv::CombinedTensor*>& outputs, Conv::datum epsilon, void (*WriteLossDeltas)(const std::vector<CombinedTensor*>&), datum (*CalculateLoss)(const std::vector<CombinedTensor*>&)) { layer->FeedForward(); WriteLossDeltas(outputs); layer->BackPropagate(); unsigned int elements = data.elements(); unsigned int okay = 0; // Weight gradient test for (unsigned int w = 0; w < data.elements(); w++) { #ifdef BUILD_OPENCL data.MoveToCPU(); delta.MoveToCPU(); #endif const Conv::datum weight = data.data_ptr_const()[w]; const Conv::datum gradient = delta.data_ptr_const()[w]; // Using central diff data.data_ptr()[w] = weight + epsilon; layer->FeedForward(); const Conv::datum forward_loss = CalculateLoss(outputs); #ifdef BUILD_OPENCL data.MoveToCPU(); #endif data.data_ptr()[w] = weight - epsilon; layer->FeedForward(); const Conv::datum backward_loss = CalculateLoss(outputs); const Conv::datum fd_gradient = (forward_loss - backward_loss) / (2.0 * epsilon); #ifdef BUILD_OPENCL data.MoveToCPU(); #endif data.data_ptr()[w] = weight; const Conv::datum ratio = fd_gradient / gradient; if(ratio > 1.2 || ratio < 0.8) { LOGDEBUG << "BP Grad : " << gradient; LOGDEBUG << "FD Grad : " << fd_gradient; LOGDEBUG << "Ratio : " << ratio; LOGDEBUG << "Diff : " << gradient - fd_gradient; } else { okay++; } } if(okay != elements) { double success_rate = (double)okay/(double)elements; if(success_rate > 0.85) return true; else { LOGERROR << okay << " of " << elements << " gradients okay - " << std::setprecision(3) << 100.0 * (double)okay/(double)elements << "%"; return false; } } else { return true; } } } <commit_msg>GradientTest: Skip layers that are not gradient safe<commit_after>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ #include <iomanip> #include "Log.h" #include "GradientTester.h" #include "NetGraphNode.h" namespace Conv { void GradientTester::TestGradient ( NetGraph& graph, unsigned int skip_weights, bool fatal_fail ) { const double epsilon = 0.005; LOGDEBUG << "Testing gradient. FeedForward..."; graph.FeedForward(); LOGDEBUG << "Testing gradient. BackPropagate..."; graph.BackPropagate(); const datum initial_loss = graph.AggregateLoss(); unsigned int global_okay = 0; unsigned int global_tolerable = 0; unsigned int global_failed = 0; unsigned int global_weights = 0; LOGDEBUG << "Initial loss: " << initial_loss; LOGDEBUG << "Using epsilon: " << epsilon; for(unsigned int l = 0; l < graph.GetNodes().size(); l++) { NetGraphNode* node = graph.GetNodes()[l]; Layer* layer = node->layer; if(layer->IsNotGradientSafe()) continue; for(unsigned int p = 0; p < layer->parameters().size(); p++) { CombinedTensor* const param = layer->parameters()[p]; LOGDEBUG << "Testing layer " << l << " (" << layer->GetLayerDescription() << "), parameter set " << p; LOGDEBUG << param->data; bool passed = true; unsigned int okay = 0; unsigned int tolerable = 0; unsigned int failed = 0; unsigned int total = 0; for(unsigned int e = 0; e < param->data.elements(); e+=(skip_weights + 1)) { total++; #ifdef BUILD_OPENCL param->data.MoveToCPU(); param->delta.MoveToCPU(); #endif const datum old_param = param->data(e); param->data[e] = old_param + epsilon; graph.FeedForward(); const double plus_loss = graph.AggregateLoss(); #ifdef BUILD_OPENCL param->data.MoveToCPU(); #endif param->data[e] = old_param - epsilon; graph.FeedForward(); const double minus_loss = graph.AggregateLoss(); const double delta = param->delta[e]; const double actual_delta = (plus_loss - minus_loss) / (2.0 * epsilon); const double ratio = actual_delta / delta; if(ratio > 1.02 || ratio < 0.98) { if(ratio > 1.2 || ratio < 0.8) { if(passed) { LOGWARN << "delta analytic: " << delta << ", numeric: " << actual_delta << ", ratio: " << ratio; } passed = false; // std::cout << "!" << std::flush; failed++; } else { // std::cout << "#" << std::flush; tolerable++; } } else { // std::cout << "." << std::flush; okay++; } #ifdef BUILD_OPENCL param->data.MoveToCPU(); #endif param->data[e] = old_param; } // std::cout << "\n"; if(passed) { LOGDEBUG << "Okay!"; } else { LOGERROR << "Failed!"; } LOGDEBUG << okay << " of " << total << " gradients okay (delta < 2%)"; LOGDEBUG << tolerable << " of " << total << " gradients tolerable (delta < 20%)"; LOGDEBUG << failed << " of " << total << " gradients failed (delta >= 20%)"; global_okay += okay; global_tolerable += tolerable; global_failed += failed; global_weights += total; } } LOGRESULT << global_okay << " of " << global_weights << " tested gradients okay (delta < 2%)" << LOGRESULTEND; LOGRESULT << global_tolerable << " of " << global_weights << " tested gradients tolerable (delta < 20%)" << LOGRESULTEND; LOGRESULT << global_failed << " of " << global_weights << " tested gradients failed (delta >= 20%)" << LOGRESULTEND; if (global_failed > 0 && fatal_fail) { FATAL("Failed gradient check!"); } } bool GradientTester::DoGradientTest(Conv::Layer* layer, Conv::Tensor& data, Conv::Tensor& delta, std::vector<Conv::CombinedTensor*>& outputs, Conv::datum epsilon, void (*WriteLossDeltas)(const std::vector<CombinedTensor*>&), datum (*CalculateLoss)(const std::vector<CombinedTensor*>&)) { layer->FeedForward(); WriteLossDeltas(outputs); layer->BackPropagate(); unsigned int elements = data.elements(); unsigned int okay = 0; // Weight gradient test for (unsigned int w = 0; w < data.elements(); w++) { #ifdef BUILD_OPENCL data.MoveToCPU(); delta.MoveToCPU(); #endif const Conv::datum weight = data.data_ptr_const()[w]; const Conv::datum gradient = delta.data_ptr_const()[w]; // Using central diff data.data_ptr()[w] = weight + epsilon; layer->FeedForward(); const Conv::datum forward_loss = CalculateLoss(outputs); #ifdef BUILD_OPENCL data.MoveToCPU(); #endif data.data_ptr()[w] = weight - epsilon; layer->FeedForward(); const Conv::datum backward_loss = CalculateLoss(outputs); const Conv::datum fd_gradient = (forward_loss - backward_loss) / (2.0 * epsilon); #ifdef BUILD_OPENCL data.MoveToCPU(); #endif data.data_ptr()[w] = weight; const Conv::datum ratio = fd_gradient / gradient; if(ratio > 1.2 || ratio < 0.8) { LOGDEBUG << "BP Grad : " << gradient; LOGDEBUG << "FD Grad : " << fd_gradient; LOGDEBUG << "Ratio : " << ratio; LOGDEBUG << "Diff : " << gradient - fd_gradient; } else { okay++; } } if(okay != elements) { double success_rate = (double)okay/(double)elements; if(success_rate > 0.85) return true; else { LOGERROR << okay << " of " << elements << " gradients okay - " << std::setprecision(3) << 100.0 * (double)okay/(double)elements << "%"; return false; } } else { return true; } } } <|endoftext|>
<commit_before>#pragma once #include <vector> #include <distributions/clustering.hpp> #include <distributions/models/dd.hpp> #include <distributions/models/dpd.hpp> #include <distributions/models/nich.hpp> #include <distributions/models/gp.hpp> #include <distributions/mixture.hpp> #include <distributions/io/protobuf.hpp> #include "common.hpp" #include "protobuf.hpp" namespace loom { using distributions::rng_t; using distributions::VectorFloat; enum { DD_DIM = 256 }; struct ProductModel { typedef protobuf::ProductModel::SparseValue Value; typedef distributions::Clustering<int>::PitmanYor Clustering; struct Mixture; protobuf::SparseValueSchema schema; Clustering clustering; std::vector<distributions::dirichlet_discrete::Model<DD_DIM>> dd; std::vector<distributions::dirichlet_process_discrete::Model> dpd; std::vector<distributions::gamma_poisson::Model> gp; std::vector<distributions::normal_inverse_chi_sq::Model> nich; void load (const protobuf::ProductModel & message); }; struct ProductModel::Mixture { ProductModel::Clustering::Mixture clustering; std::vector<distributions::dirichlet_discrete::Mixture<DD_DIM>> dd; std::vector<distributions::dirichlet_process_discrete::Mixture> dpd; std::vector<distributions::gamma_poisson::Mixture> gp; std::vector<distributions::normal_inverse_chi_sq::Mixture> nich; distributions::MixtureIdTracker id_tracker; void init_empty ( const ProductModel & model, rng_t & rng, size_t empty_group_count = 1); void load ( const ProductModel & model, const char * filename, rng_t & rng, size_t empty_roup_count = 1); void dump (const ProductModel & model, const char * filename); void add_value ( const ProductModel & model, size_t groupid, const Value & value, rng_t & rng); void remove_value ( const ProductModel & model, size_t groupid, const Value & value, rng_t & rng); void score ( const ProductModel & model, const Value & value, VectorFloat & scores, rng_t & rng); void sample_value ( const ProductModel & model, const VectorFloat & probs, Value & value, rng_t & rng); private: void _validate (const ProductModel & model); template<class Mixture> void init_empty_factors ( size_t empty_group_count, const std::vector<typename Mixture::Model> & models, std::vector<Mixture> & mixtures, rng_t & rng); template<class Fun> void apply_dense (const ProductModel & model, Fun & fun); template<class Fun> void apply_sparse ( const ProductModel & model, Fun & fun, const Value & value); template<class Fun> void set_sparse ( const ProductModel & model, Fun & fun, Value & value); struct validate_fun; struct load_group_fun; struct init_fun; struct dump_group_fun; struct add_group_fun; struct add_value_fun; struct remove_group_fun; struct remove_value_fun; struct score_fun; struct sample_fun; }; template<class Fun> inline void ProductModel::Mixture::apply_dense ( const ProductModel & model, Fun & fun) { //TODO("implement bb"); for (size_t i = 0; i < dd.size(); ++i) { fun(i, model.dd[i], dd[i]); } for (size_t i = 0; i < dpd.size(); ++i) { fun(i, model.dpd[i], dpd[i]); } for (size_t i = 0; i < gp.size(); ++i) { fun(i, model.gp[i], gp[i]); } for (size_t i = 0; i < nich.size(); ++i) { fun(i, model.nich[i], nich[i]); } } template<class Fun> inline void ProductModel::Mixture::apply_sparse ( const ProductModel & model, Fun & fun, const Value & value) { if (LOOM_DEBUG_LEVEL >= 2) { model.schema.validate(value); } size_t absolute_pos = 0; if (value.booleans_size()) { TODO("implement bb"); } else { absolute_pos += 0; } if (value.counts_size()) { size_t packed_pos = 0; for (size_t i = 0; i < dd.size(); ++i) { if (value.observed(absolute_pos++)) { fun(model.dd[i], dd[i], value.counts(packed_pos++)); } } for (size_t i = 0; i < dpd.size(); ++i) { if (value.observed(absolute_pos++)) { fun(model.dpd[i], dpd[i], value.counts(packed_pos++)); } } for (size_t i = 0; i < gp.size(); ++i) { if (value.observed(absolute_pos++)) { fun(model.gp[i], gp[i], value.counts(packed_pos++)); } } } else { absolute_pos += dd.size() + dpd.size() + gp.size(); } if (value.reals_size()) { size_t packed_pos = 0; for (size_t i = 0; i < nich.size(); ++i) { if (value.observed(absolute_pos++)) { fun(model.nich[i], nich[i], value.reals(packed_pos++)); } } } } template<class Fun> inline void ProductModel::Mixture::set_sparse ( const ProductModel & model, Fun & fun, Value & value) { if (LOOM_DEBUG_LEVEL >= 2) { model.schema.validate(value); } size_t absolute_pos = 0; if (value.booleans_size()) { TODO("implement bb"); } else { absolute_pos += 0; } if (value.counts_size()) { size_t packed_pos = 0; for (size_t i = 0; i < dd.size(); ++i) { if (value.observed(absolute_pos++)) { value.set_counts(packed_pos++, fun(model.dd[i], dd[i])); } } for (size_t i = 0; i < dpd.size(); ++i) { if (value.observed(absolute_pos++)) { value.set_counts(packed_pos++, fun(model.dpd[i], dpd[i])); } } for (size_t i = 0; i < gp.size(); ++i) { if (value.observed(absolute_pos++)) { value.set_counts(packed_pos++, fun(model.gp[i], gp[i])); } } } else { absolute_pos += dd.size() + dpd.size() + gp.size(); } if (value.reals_size()) { size_t packed_pos = 0; for (size_t i = 0; i < nich.size(); ++i) { if (value.observed(absolute_pos++)) { value.set_reals(packed_pos++, fun(model.nich[i], nich[i])); } } } } struct ProductModel::Mixture::validate_fun { const size_t group_count; template<class Mixture> void operator() ( size_t, const typename Mixture::Model &, const Mixture & mixture) { LOOM_ASSERT_EQ(mixture.groups.size(), group_count); } }; inline void ProductModel::Mixture::_validate ( const ProductModel & model) { if (LOOM_DEBUG_LEVEL >= 2) { const size_t group_count = clustering.counts().size(); validate_fun fun = {group_count}; apply_dense(model, fun); LOOM_ASSERT_EQ(id_tracker.packed_size(), group_count); } } struct ProductModel::Mixture::add_group_fun { rng_t & rng; template<class Mixture> void operator() ( size_t, const typename Mixture::Model & model, Mixture & mixture) { mixture.add_group(model, rng); } }; struct ProductModel::Mixture::add_value_fun { const size_t groupid; rng_t & rng; template<class Mixture> void operator() ( const typename Mixture::Model & model, Mixture & mixture, const typename Mixture::Value & value) { mixture.add_value(model, groupid, value, rng); } }; inline void ProductModel::Mixture::add_value ( const ProductModel & model, size_t groupid, const Value & value, rng_t & rng) { bool add_group = clustering.add_value(model.clustering, groupid); add_value_fun fun = {groupid, rng}; apply_sparse(model, fun, value); if (LOOM_UNLIKELY(add_group)) { add_group_fun fun = {rng}; apply_dense(model, fun); id_tracker.add_group(); _validate(model); } } struct ProductModel::Mixture::remove_group_fun { const size_t groupid; template<class Mixture> void operator() ( size_t, const typename Mixture::Model & model, Mixture & mixture) { mixture.remove_group(model, groupid); } }; struct ProductModel::Mixture::remove_value_fun { const size_t groupid; rng_t & rng; template<class Mixture> void operator() ( const typename Mixture::Model & model, Mixture & mixture, const typename Mixture::Value & value) { mixture.remove_value(model, groupid, value, rng); } }; inline void ProductModel::Mixture::remove_value ( const ProductModel & model, size_t groupid, const Value & value, rng_t & rng) { bool remove_group = clustering.remove_value(model.clustering, groupid); remove_value_fun fun = {groupid, rng}; apply_sparse(model, fun, value); if (LOOM_UNLIKELY(remove_group)) { remove_group_fun fun = {groupid}; apply_dense(model, fun); id_tracker.remove_group(groupid); _validate(model); } } struct ProductModel::Mixture::score_fun { VectorFloat & scores; rng_t & rng; template<class Mixture> void operator() ( const typename Mixture::Model & model, const Mixture & mixture, const typename Mixture::Value & value) { mixture.score_value(model, value, scores, rng); } }; inline void ProductModel::Mixture::score ( const ProductModel & model, const Value & value, VectorFloat & scores, rng_t & rng) { scores.resize(clustering.counts().size()); clustering.score(model.clustering, scores); score_fun fun = {scores, rng}; apply_sparse(model, fun, value); } struct ProductModel::Mixture::sample_fun { const size_t groupid; rng_t & rng; template<class Mixture> typename Mixture::Value operator() ( const typename Mixture::Model & model, const Mixture & mixture) { return model.sample_value(mixture.groups[groupid], rng); } }; inline void ProductModel::Mixture::sample_value ( const ProductModel & model, const VectorFloat & probs, Value & value, rng_t & rng) { size_t groupid = distributions::sample_from_probs(rng, probs); sample_fun fun = {groupid, rng}; set_sparse(model, fun, value); } } // namespace loom <commit_msg>Call sample_value from distributions namespace.<commit_after>#pragma once #include <vector> #include <distributions/clustering.hpp> #include <distributions/models/dd.hpp> #include <distributions/models/dpd.hpp> #include <distributions/models/nich.hpp> #include <distributions/models/gp.hpp> #include <distributions/mixture.hpp> #include <distributions/io/protobuf.hpp> #include "common.hpp" #include "protobuf.hpp" namespace loom { using distributions::rng_t; using distributions::VectorFloat; enum { DD_DIM = 256 }; struct ProductModel { typedef protobuf::ProductModel::SparseValue Value; typedef distributions::Clustering<int>::PitmanYor Clustering; struct Mixture; protobuf::SparseValueSchema schema; Clustering clustering; std::vector<distributions::dirichlet_discrete::Model<DD_DIM>> dd; std::vector<distributions::dirichlet_process_discrete::Model> dpd; std::vector<distributions::gamma_poisson::Model> gp; std::vector<distributions::normal_inverse_chi_sq::Model> nich; void load (const protobuf::ProductModel & message); }; struct ProductModel::Mixture { ProductModel::Clustering::Mixture clustering; std::vector<distributions::dirichlet_discrete::Mixture<DD_DIM>> dd; std::vector<distributions::dirichlet_process_discrete::Mixture> dpd; std::vector<distributions::gamma_poisson::Mixture> gp; std::vector<distributions::normal_inverse_chi_sq::Mixture> nich; distributions::MixtureIdTracker id_tracker; void init_empty ( const ProductModel & model, rng_t & rng, size_t empty_group_count = 1); void load ( const ProductModel & model, const char * filename, rng_t & rng, size_t empty_roup_count = 1); void dump (const ProductModel & model, const char * filename); void add_value ( const ProductModel & model, size_t groupid, const Value & value, rng_t & rng); void remove_value ( const ProductModel & model, size_t groupid, const Value & value, rng_t & rng); void score ( const ProductModel & model, const Value & value, VectorFloat & scores, rng_t & rng); void sample_value ( const ProductModel & model, const VectorFloat & probs, Value & value, rng_t & rng); private: void _validate (const ProductModel & model); template<class Mixture> void init_empty_factors ( size_t empty_group_count, const std::vector<typename Mixture::Model> & models, std::vector<Mixture> & mixtures, rng_t & rng); template<class Fun> void apply_dense (const ProductModel & model, Fun & fun); template<class Fun> void apply_sparse ( const ProductModel & model, Fun & fun, const Value & value); template<class Fun> void set_sparse ( const ProductModel & model, Fun & fun, Value & value); struct validate_fun; struct load_group_fun; struct init_fun; struct dump_group_fun; struct add_group_fun; struct add_value_fun; struct remove_group_fun; struct remove_value_fun; struct score_fun; struct sample_fun; }; template<class Fun> inline void ProductModel::Mixture::apply_dense ( const ProductModel & model, Fun & fun) { //TODO("implement bb"); for (size_t i = 0; i < dd.size(); ++i) { fun(i, model.dd[i], dd[i]); } for (size_t i = 0; i < dpd.size(); ++i) { fun(i, model.dpd[i], dpd[i]); } for (size_t i = 0; i < gp.size(); ++i) { fun(i, model.gp[i], gp[i]); } for (size_t i = 0; i < nich.size(); ++i) { fun(i, model.nich[i], nich[i]); } } template<class Fun> inline void ProductModel::Mixture::apply_sparse ( const ProductModel & model, Fun & fun, const Value & value) { if (LOOM_DEBUG_LEVEL >= 2) { model.schema.validate(value); } size_t absolute_pos = 0; if (value.booleans_size()) { TODO("implement bb"); } else { absolute_pos += 0; } if (value.counts_size()) { size_t packed_pos = 0; for (size_t i = 0; i < dd.size(); ++i) { if (value.observed(absolute_pos++)) { fun(model.dd[i], dd[i], value.counts(packed_pos++)); } } for (size_t i = 0; i < dpd.size(); ++i) { if (value.observed(absolute_pos++)) { fun(model.dpd[i], dpd[i], value.counts(packed_pos++)); } } for (size_t i = 0; i < gp.size(); ++i) { if (value.observed(absolute_pos++)) { fun(model.gp[i], gp[i], value.counts(packed_pos++)); } } } else { absolute_pos += dd.size() + dpd.size() + gp.size(); } if (value.reals_size()) { size_t packed_pos = 0; for (size_t i = 0; i < nich.size(); ++i) { if (value.observed(absolute_pos++)) { fun(model.nich[i], nich[i], value.reals(packed_pos++)); } } } } template<class Fun> inline void ProductModel::Mixture::set_sparse ( const ProductModel & model, Fun & fun, Value & value) { if (LOOM_DEBUG_LEVEL >= 2) { model.schema.validate(value); } size_t absolute_pos = 0; if (value.booleans_size()) { TODO("implement bb"); } else { absolute_pos += 0; } if (value.counts_size()) { size_t packed_pos = 0; for (size_t i = 0; i < dd.size(); ++i) { if (value.observed(absolute_pos++)) { value.set_counts(packed_pos++, fun(model.dd[i], dd[i])); } } for (size_t i = 0; i < dpd.size(); ++i) { if (value.observed(absolute_pos++)) { value.set_counts(packed_pos++, fun(model.dpd[i], dpd[i])); } } for (size_t i = 0; i < gp.size(); ++i) { if (value.observed(absolute_pos++)) { value.set_counts(packed_pos++, fun(model.gp[i], gp[i])); } } } else { absolute_pos += dd.size() + dpd.size() + gp.size(); } if (value.reals_size()) { size_t packed_pos = 0; for (size_t i = 0; i < nich.size(); ++i) { if (value.observed(absolute_pos++)) { value.set_reals(packed_pos++, fun(model.nich[i], nich[i])); } } } } struct ProductModel::Mixture::validate_fun { const size_t group_count; template<class Mixture> void operator() ( size_t, const typename Mixture::Model &, const Mixture & mixture) { LOOM_ASSERT_EQ(mixture.groups.size(), group_count); } }; inline void ProductModel::Mixture::_validate ( const ProductModel & model) { if (LOOM_DEBUG_LEVEL >= 2) { const size_t group_count = clustering.counts().size(); validate_fun fun = {group_count}; apply_dense(model, fun); LOOM_ASSERT_EQ(id_tracker.packed_size(), group_count); } } struct ProductModel::Mixture::add_group_fun { rng_t & rng; template<class Mixture> void operator() ( size_t, const typename Mixture::Model & model, Mixture & mixture) { mixture.add_group(model, rng); } }; struct ProductModel::Mixture::add_value_fun { const size_t groupid; rng_t & rng; template<class Mixture> void operator() ( const typename Mixture::Model & model, Mixture & mixture, const typename Mixture::Value & value) { mixture.add_value(model, groupid, value, rng); } }; inline void ProductModel::Mixture::add_value ( const ProductModel & model, size_t groupid, const Value & value, rng_t & rng) { bool add_group = clustering.add_value(model.clustering, groupid); add_value_fun fun = {groupid, rng}; apply_sparse(model, fun, value); if (LOOM_UNLIKELY(add_group)) { add_group_fun fun = {rng}; apply_dense(model, fun); id_tracker.add_group(); _validate(model); } } struct ProductModel::Mixture::remove_group_fun { const size_t groupid; template<class Mixture> void operator() ( size_t, const typename Mixture::Model & model, Mixture & mixture) { mixture.remove_group(model, groupid); } }; struct ProductModel::Mixture::remove_value_fun { const size_t groupid; rng_t & rng; template<class Mixture> void operator() ( const typename Mixture::Model & model, Mixture & mixture, const typename Mixture::Value & value) { mixture.remove_value(model, groupid, value, rng); } }; inline void ProductModel::Mixture::remove_value ( const ProductModel & model, size_t groupid, const Value & value, rng_t & rng) { bool remove_group = clustering.remove_value(model.clustering, groupid); remove_value_fun fun = {groupid, rng}; apply_sparse(model, fun, value); if (LOOM_UNLIKELY(remove_group)) { remove_group_fun fun = {groupid}; apply_dense(model, fun); id_tracker.remove_group(groupid); _validate(model); } } struct ProductModel::Mixture::score_fun { VectorFloat & scores; rng_t & rng; template<class Mixture> void operator() ( const typename Mixture::Model & model, const Mixture & mixture, const typename Mixture::Value & value) { mixture.score_value(model, value, scores, rng); } }; inline void ProductModel::Mixture::score ( const ProductModel & model, const Value & value, VectorFloat & scores, rng_t & rng) { scores.resize(clustering.counts().size()); clustering.score(model.clustering, scores); score_fun fun = {scores, rng}; apply_sparse(model, fun, value); } struct ProductModel::Mixture::sample_fun { const size_t groupid; rng_t & rng; template<class Mixture> typename Mixture::Value operator() ( const typename Mixture::Model & model, const Mixture & mixture) { return distributions::sample_value(model, mixture.groups[groupid], rng); } }; inline void ProductModel::Mixture::sample_value ( const ProductModel & model, const VectorFloat & probs, Value & value, rng_t & rng) { size_t groupid = distributions::sample_from_probs(rng, probs); sample_fun fun = {groupid, rng}; set_sparse(model, fun, value); } } // namespace loom <|endoftext|>
<commit_before>//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include <algorithm> #include "ExtrusionLine.h" #include "linearAlg2D.h" namespace cura { ExtrusionLine::ExtrusionLine(const size_t inset_idx, const bool is_odd) : inset_idx(inset_idx) , is_odd(is_odd) , is_closed(false) {} coord_t ExtrusionLine::getLength() const { if (junctions.empty()) { return 0; } coord_t len = 0; ExtrusionJunction prev = junctions.front(); for (const ExtrusionJunction& next : junctions) { len += vSize(next.p - prev.p); prev = next; } if (is_closed) { len += vSize(front().p - back().p); } return len; } coord_t ExtrusionLine::getMinimalWidth() const { return std::min_element(junctions.cbegin(), junctions.cend(), [](const ExtrusionJunction& l, const ExtrusionJunction& r) { return l.w < r.w; })->w; } void ExtrusionLine::simplify(const coord_t smallest_line_segment_squared, const coord_t allowed_error_distance_squared, const coord_t maximum_extrusion_area_deviation) { const size_t min_path_size = is_closed ? 3 : 2; if (junctions.size() <= min_path_size) { return; } // TODO: allow for the first point to be removed in case of simplifying closed Extrusionlines. /* ExtrusionLines are treated as (open) polylines, so in case an ExtrusionLine is actually a closed polygon, its * starting and ending points will be equal (or almost equal). Therefore, the simplification of the ExtrusionLine * should not touch the first and last points. As a result, start simplifying from point at index 1. * */ std::vector<ExtrusionJunction> new_junctions; // Starting junction should always exist in the simplified path new_junctions.emplace_back(junctions.front()); /* Initially, previous_previous is always the same as previous because, for open ExtrusionLines the last junction * cannot be taken into consideration when checking the points at index 1. For closed ExtrusionLines, the first and * last junctions are anyway the same. * */ ExtrusionJunction previous_previous = junctions.front(); ExtrusionJunction previous = junctions.front(); /* When removing a vertex, we check the height of the triangle of the area being removed from the original polygon by the simplification. However, when consecutively removing multiple vertices the height of the previously removed vertices w.r.t. the shortcut path changes. In order to not recompute the new height value of previously removed vertices we compute the height of a representative triangle, which covers the same amount of area as the area being cut off. We use the Shoelace formula to accumulate the area under the removed segments. This works by computing the area in a 'fan' where each of the blades of the fan go from the origin to one of the segments. While removing vertices the area in this fan accumulates. By subtracting the area of the blade connected to the short-cutting segment we obtain the total area of the cutoff region. From this area we compute the height of the representative triangle using the standard formula for a triangle area: A = .5*b*h */ const ExtrusionJunction& initial = junctions.at(1); coord_t accumulated_area_removed = previous.p.X * initial.p.Y - previous.p.Y * initial.p.X; // Twice the Shoelace formula for area of polygon per line segment. for (size_t point_idx = 1; point_idx < junctions.size() - 1; point_idx++) { const ExtrusionJunction& current = junctions[point_idx]; // Spill over in case of overflow, unless the [next] vertex will then be equal to [previous]. const bool spill_over = point_idx + 1 == junctions.size() && new_junctions.size() > 1; ExtrusionJunction& next = spill_over ? new_junctions[0] : junctions[point_idx + 1]; const coord_t removed_area_next = current.p.X * next.p.Y - current.p.Y * next.p.X; // Twice the Shoelace formula for area of polygon per line segment. const coord_t negative_area_closing = next.p.X * previous.p.Y - next.p.Y * previous.p.X; // Area between the origin and the short-cutting segment accumulated_area_removed += removed_area_next; const coord_t length2 = vSize2(current - previous); if (length2 < 25) { // We're allowed to always delete segments of less than 5 micron. The width in this case doesn't matter that much. continue; } const coord_t area_removed_so_far = accumulated_area_removed + negative_area_closing; // Close the shortcut area polygon const coord_t base_length_2 = vSize2(next - previous); if (base_length_2 == 0) // Two line segments form a line back and forth with no area. { continue; // Remove the junction (vertex). } //We want to check if the height of the triangle formed by previous, current and next vertices is less than allowed_error_distance_squared. //1/2 L = A [actual area is half of the computed shoelace value] // Shoelace formula is .5*(...) , but we simplify the computation and take out the .5 //A = 1/2 * b * h [triangle area formula] //L = b * h [apply above two and take out the 1/2] //h = L / b [divide by b] //h^2 = (L / b)^2 [square it] //h^2 = L^2 / b^2 [factor the divisor] const coord_t height_2 = area_removed_so_far * area_removed_so_far / base_length_2; coord_t weighted_average_width; const coord_t extrusion_area_error = calculateExtrusionAreaDeviationError(previous, current, next, weighted_average_width); if ((height_2 <= 1 //Almost exactly colinear (barring rounding errors). && LinearAlg2D::getDistFromLine(current.p, previous.p, next.p) <= 1) // Make sure that height_2 is not small because of cancellation of positive and negative areas // We shouldn't remove middle junctions of colinear segments if the area changed for the C-P segment is exceeding the maximum allowed && extrusion_area_error <= maximum_extrusion_area_deviation) { // Adjust the width of the entire P-N line as a weighted average of the widths of the P-C and C-N lines and // then remove the current junction (vertex). next.w = weighted_average_width; continue; } if (length2 < smallest_line_segment_squared && height_2 <= allowed_error_distance_squared) // Removing the junction (vertex) doesn't introduce too much error. { const coord_t next_length2 = vSize2(current - next); if (next_length2 > smallest_line_segment_squared) { // Special case; The next line is long. If we were to remove this, it could happen that we get quite noticeable artifacts. // We should instead move this point to a location where both edges are kept and then remove the previous point that we wanted to keep. // By taking the intersection of these two lines, we get a point that preserves the direction (so it makes the corner a bit more pointy). // We just need to be sure that the intersection point does not introduce an artifact itself. Point intersection_point; bool has_intersection = LinearAlg2D::lineLineIntersection(previous_previous.p, previous.p, current.p, next.p, intersection_point); if (!has_intersection || LinearAlg2D::getDist2FromLine(intersection_point, previous.p, current.p) > allowed_error_distance_squared || vSize2(intersection_point - previous.p) > smallest_line_segment_squared // The intersection point is way too far from the 'previous' || vSize2(intersection_point - next.p) > smallest_line_segment_squared) // and 'next' points, so it shouldn't replace 'current' { // We can't find a better spot for it, but the size of the line is more than 5 micron. // So the only thing we can do here is leave it in... } else { // New point seems like a valid one. const ExtrusionJunction new_to_add = ExtrusionJunction(intersection_point, current.w, current.perimeter_index); // If there was a previous point added, remove it. if(!new_junctions.empty()) { new_junctions.pop_back(); previous = previous_previous; } // The junction (vertex) is replaced by the new one. accumulated_area_removed = removed_area_next; // So that in the next iteration it's the area between the origin, [previous] and [current] previous_previous = previous; previous = new_to_add; // Note that "previous" is only updated if we don't remove the junction (vertex). new_junctions.push_back(new_to_add); continue; } } else { continue; // Remove the junction (vertex). } } // The junction (vertex) isn't removed. accumulated_area_removed = removed_area_next; // So that in the next iteration it's the area between the origin, [previous] and [current] previous_previous = previous; previous = current; // Note that "previous" is only updated if we don't remove the junction (vertex). new_junctions.push_back(current); } // Ending junction (vertex) should always exist in the simplified path new_junctions.emplace_back(junctions.back()); /* In case this is a closed polygon (instead of a poly-line-segments), the invariant that the first and last points are the same should be enforced. * Since one of them didn't move, and the other can't have been moved further than the constraints, if originally equal, they can simply be equated. */ if (vSize2(junctions.front().p - junctions.back().p) == 0) { new_junctions.back().p = junctions.front().p; } junctions = new_junctions; } coord_t ExtrusionLine::calculateExtrusionAreaDeviationError(ExtrusionJunction A, ExtrusionJunction B, ExtrusionJunction C, coord_t& weighted_average_width) { /* * A B C A C * --------------- ************** * | | ------------------------------------------ * | |--------------------------| B removed | |***************************| * | | | ---------> | | | * | |--------------------------| | |***************************| * | | ------------------------------------------ * --------------- ^ ************** * ^ C.w ^ * B.w new_width = weighted_average_width * * * ******** denote the total extrusion area deviation error in the consecutive segments as a result of using the * weighted-average width for the entire extrusion line. * * */ const coord_t ab_length = vSize(B - A); const coord_t bc_length = vSize(C - B); const coord_t width_diff = llabs(B.w - A.w); if (width_diff > 1) { // Adjust the width only if there is a difference, or else the rounding errors may produce the wrong // weighted average value. weighted_average_width = (ab_length * A.w + bc_length * B.w) / vSize(C - A); return llabs(A.w - weighted_average_width) * ab_length + llabs(B.w - weighted_average_width) * bc_length; } else { // If the width difference is very small, then select the width of the segment that is longer weighted_average_width = ab_length > bc_length ? A.w : B.w; return ab_length > bc_length ? width_diff * bc_length : width_diff * ab_length; } } } <commit_msg>Replace 'llabs' with more standard 'std::abs'.<commit_after>//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include <algorithm> #include "ExtrusionLine.h" #include "linearAlg2D.h" namespace cura { ExtrusionLine::ExtrusionLine(const size_t inset_idx, const bool is_odd) : inset_idx(inset_idx) , is_odd(is_odd) , is_closed(false) {} coord_t ExtrusionLine::getLength() const { if (junctions.empty()) { return 0; } coord_t len = 0; ExtrusionJunction prev = junctions.front(); for (const ExtrusionJunction& next : junctions) { len += vSize(next.p - prev.p); prev = next; } if (is_closed) { len += vSize(front().p - back().p); } return len; } coord_t ExtrusionLine::getMinimalWidth() const { return std::min_element(junctions.cbegin(), junctions.cend(), [](const ExtrusionJunction& l, const ExtrusionJunction& r) { return l.w < r.w; })->w; } void ExtrusionLine::simplify(const coord_t smallest_line_segment_squared, const coord_t allowed_error_distance_squared, const coord_t maximum_extrusion_area_deviation) { const size_t min_path_size = is_closed ? 3 : 2; if (junctions.size() <= min_path_size) { return; } // TODO: allow for the first point to be removed in case of simplifying closed Extrusionlines. /* ExtrusionLines are treated as (open) polylines, so in case an ExtrusionLine is actually a closed polygon, its * starting and ending points will be equal (or almost equal). Therefore, the simplification of the ExtrusionLine * should not touch the first and last points. As a result, start simplifying from point at index 1. * */ std::vector<ExtrusionJunction> new_junctions; // Starting junction should always exist in the simplified path new_junctions.emplace_back(junctions.front()); /* Initially, previous_previous is always the same as previous because, for open ExtrusionLines the last junction * cannot be taken into consideration when checking the points at index 1. For closed ExtrusionLines, the first and * last junctions are anyway the same. * */ ExtrusionJunction previous_previous = junctions.front(); ExtrusionJunction previous = junctions.front(); /* When removing a vertex, we check the height of the triangle of the area being removed from the original polygon by the simplification. However, when consecutively removing multiple vertices the height of the previously removed vertices w.r.t. the shortcut path changes. In order to not recompute the new height value of previously removed vertices we compute the height of a representative triangle, which covers the same amount of area as the area being cut off. We use the Shoelace formula to accumulate the area under the removed segments. This works by computing the area in a 'fan' where each of the blades of the fan go from the origin to one of the segments. While removing vertices the area in this fan accumulates. By subtracting the area of the blade connected to the short-cutting segment we obtain the total area of the cutoff region. From this area we compute the height of the representative triangle using the standard formula for a triangle area: A = .5*b*h */ const ExtrusionJunction& initial = junctions.at(1); coord_t accumulated_area_removed = previous.p.X * initial.p.Y - previous.p.Y * initial.p.X; // Twice the Shoelace formula for area of polygon per line segment. for (size_t point_idx = 1; point_idx < junctions.size() - 1; point_idx++) { const ExtrusionJunction& current = junctions[point_idx]; // Spill over in case of overflow, unless the [next] vertex will then be equal to [previous]. const bool spill_over = point_idx + 1 == junctions.size() && new_junctions.size() > 1; ExtrusionJunction& next = spill_over ? new_junctions[0] : junctions[point_idx + 1]; const coord_t removed_area_next = current.p.X * next.p.Y - current.p.Y * next.p.X; // Twice the Shoelace formula for area of polygon per line segment. const coord_t negative_area_closing = next.p.X * previous.p.Y - next.p.Y * previous.p.X; // Area between the origin and the short-cutting segment accumulated_area_removed += removed_area_next; const coord_t length2 = vSize2(current - previous); if (length2 < 25) { // We're allowed to always delete segments of less than 5 micron. The width in this case doesn't matter that much. continue; } const coord_t area_removed_so_far = accumulated_area_removed + negative_area_closing; // Close the shortcut area polygon const coord_t base_length_2 = vSize2(next - previous); if (base_length_2 == 0) // Two line segments form a line back and forth with no area. { continue; // Remove the junction (vertex). } //We want to check if the height of the triangle formed by previous, current and next vertices is less than allowed_error_distance_squared. //1/2 L = A [actual area is half of the computed shoelace value] // Shoelace formula is .5*(...) , but we simplify the computation and take out the .5 //A = 1/2 * b * h [triangle area formula] //L = b * h [apply above two and take out the 1/2] //h = L / b [divide by b] //h^2 = (L / b)^2 [square it] //h^2 = L^2 / b^2 [factor the divisor] const coord_t height_2 = area_removed_so_far * area_removed_so_far / base_length_2; coord_t weighted_average_width; const coord_t extrusion_area_error = calculateExtrusionAreaDeviationError(previous, current, next, weighted_average_width); if ((height_2 <= 1 //Almost exactly colinear (barring rounding errors). && LinearAlg2D::getDistFromLine(current.p, previous.p, next.p) <= 1) // Make sure that height_2 is not small because of cancellation of positive and negative areas // We shouldn't remove middle junctions of colinear segments if the area changed for the C-P segment is exceeding the maximum allowed && extrusion_area_error <= maximum_extrusion_area_deviation) { // Adjust the width of the entire P-N line as a weighted average of the widths of the P-C and C-N lines and // then remove the current junction (vertex). next.w = weighted_average_width; continue; } if (length2 < smallest_line_segment_squared && height_2 <= allowed_error_distance_squared) // Removing the junction (vertex) doesn't introduce too much error. { const coord_t next_length2 = vSize2(current - next); if (next_length2 > smallest_line_segment_squared) { // Special case; The next line is long. If we were to remove this, it could happen that we get quite noticeable artifacts. // We should instead move this point to a location where both edges are kept and then remove the previous point that we wanted to keep. // By taking the intersection of these two lines, we get a point that preserves the direction (so it makes the corner a bit more pointy). // We just need to be sure that the intersection point does not introduce an artifact itself. Point intersection_point; bool has_intersection = LinearAlg2D::lineLineIntersection(previous_previous.p, previous.p, current.p, next.p, intersection_point); if (!has_intersection || LinearAlg2D::getDist2FromLine(intersection_point, previous.p, current.p) > allowed_error_distance_squared || vSize2(intersection_point - previous.p) > smallest_line_segment_squared // The intersection point is way too far from the 'previous' || vSize2(intersection_point - next.p) > smallest_line_segment_squared) // and 'next' points, so it shouldn't replace 'current' { // We can't find a better spot for it, but the size of the line is more than 5 micron. // So the only thing we can do here is leave it in... } else { // New point seems like a valid one. const ExtrusionJunction new_to_add = ExtrusionJunction(intersection_point, current.w, current.perimeter_index); // If there was a previous point added, remove it. if(!new_junctions.empty()) { new_junctions.pop_back(); previous = previous_previous; } // The junction (vertex) is replaced by the new one. accumulated_area_removed = removed_area_next; // So that in the next iteration it's the area between the origin, [previous] and [current] previous_previous = previous; previous = new_to_add; // Note that "previous" is only updated if we don't remove the junction (vertex). new_junctions.push_back(new_to_add); continue; } } else { continue; // Remove the junction (vertex). } } // The junction (vertex) isn't removed. accumulated_area_removed = removed_area_next; // So that in the next iteration it's the area between the origin, [previous] and [current] previous_previous = previous; previous = current; // Note that "previous" is only updated if we don't remove the junction (vertex). new_junctions.push_back(current); } // Ending junction (vertex) should always exist in the simplified path new_junctions.emplace_back(junctions.back()); /* In case this is a closed polygon (instead of a poly-line-segments), the invariant that the first and last points are the same should be enforced. * Since one of them didn't move, and the other can't have been moved further than the constraints, if originally equal, they can simply be equated. */ if (vSize2(junctions.front().p - junctions.back().p) == 0) { new_junctions.back().p = junctions.front().p; } junctions = new_junctions; } coord_t ExtrusionLine::calculateExtrusionAreaDeviationError(ExtrusionJunction A, ExtrusionJunction B, ExtrusionJunction C, coord_t& weighted_average_width) { /* * A B C A C * --------------- ************** * | | ------------------------------------------ * | |--------------------------| B removed | |***************************| * | | | ---------> | | | * | |--------------------------| | |***************************| * | | ------------------------------------------ * --------------- ^ ************** * ^ C.w ^ * B.w new_width = weighted_average_width * * * ******** denote the total extrusion area deviation error in the consecutive segments as a result of using the * weighted-average width for the entire extrusion line. * * */ const coord_t ab_length = vSize(B - A); const coord_t bc_length = vSize(C - B); const coord_t width_diff = std::abs(B.w - A.w); if (width_diff > 1) { // Adjust the width only if there is a difference, or else the rounding errors may produce the wrong // weighted average value. weighted_average_width = (ab_length * A.w + bc_length * B.w) / vSize(C - A); return std::abs(A.w - weighted_average_width) * ab_length + std::abs(B.w - weighted_average_width) * bc_length; } else { // If the width difference is very small, then select the width of the segment that is longer weighted_average_width = ab_length > bc_length ? A.w : B.w; return ab_length > bc_length ? width_diff * bc_length : width_diff * ab_length; } } } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkWGL.h" #include "SkTDArray.h" #include "SkTSearch.h" bool SkWGLExtensions::hasExtension(HDC dc, const char* ext) const { if (NULL == this->fGetExtensionsString) { return false; } if (!strcmp("WGL_ARB_extensions_string", ext)) { return true; } const char* extensionString = this->getExtensionsString(dc); int extLength = strlen(ext); while (true) { int n = strcspn(extensionString, " "); if (n == extLength && 0 == strncmp(ext, extensionString, n)) { return true; } if (0 == extensionString[n]) { return false; } extensionString += n+1; } return false; } const char* SkWGLExtensions::getExtensionsString(HDC hdc) const { return fGetExtensionsString(hdc); } BOOL SkWGLExtensions::choosePixelFormat(HDC hdc, const int* piAttribIList, const FLOAT* pfAttribFList, UINT nMaxFormats, int* piFormats, UINT* nNumFormats) const { return fChoosePixelFormat(hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats); } BOOL SkWGLExtensions::getPixelFormatAttribiv(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues) const { return fGetPixelFormatAttribiv(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, piValues); } BOOL SkWGLExtensions::getPixelFormatAttribfv(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, float *pfValues) const { return fGetPixelFormatAttribfv(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, pfValues); } HGLRC SkWGLExtensions::createContextAttribs(HDC hDC, HGLRC hShareContext, const int *attribList) const { return fCreateContextAttribs(hDC, hShareContext, attribList); } namespace { struct PixelFormat { int fFormat; int fCoverageSamples; int fColorSamples; int fChoosePixelFormatRank; }; int compare_pf(const PixelFormat* a, const PixelFormat* b) { if (a->fCoverageSamples < b->fCoverageSamples) { return -1; } else if (b->fCoverageSamples < a->fCoverageSamples) { return 1; } else if (a->fColorSamples < b->fColorSamples) { return -1; } else if (b->fColorSamples < a->fColorSamples) { return 1; } else if (a->fChoosePixelFormatRank < b->fChoosePixelFormatRank) { return -1; } else if (b->fChoosePixelFormatRank < a->fChoosePixelFormatRank) { return 1; } return 0; } } int SkWGLExtensions::selectFormat(const int formats[], int formatCount, HDC dc, int desiredSampleCount) { PixelFormat desiredFormat = { 0, desiredSampleCount, 0, 0, }; SkTDArray<PixelFormat> rankedFormats; rankedFormats.setCount(formatCount); bool supportsCoverage = this->hasExtension(dc, "WGL_NV_multisample_coverage"); for (int i = 0; i < formatCount; ++i) { static const int queryAttrs[] = { SK_WGL_COVERAGE_SAMPLES, SK_WGL_COLOR_SAMPLES, }; int answers[2]; int queryAttrCnt = supportsCoverage ? 2 : 1; this->getPixelFormatAttribiv(dc, formats[i], 0, SK_ARRAY_COUNT(queryAttrs), queryAttrs, answers); rankedFormats[i].fFormat = formats[i]; rankedFormats[i].fCoverageSamples = answers[0]; rankedFormats[i].fColorSamples = answers[supportsCoverage ? 1 : 0]; rankedFormats[i].fChoosePixelFormatRank = i; } qsort(rankedFormats.begin(), rankedFormats.count(), sizeof(PixelFormat), SkCastForQSort(compare_pf)); int idx = SkTSearch<PixelFormat>(rankedFormats.begin(), rankedFormats.count(), desiredFormat, sizeof(PixelFormat), compare_pf); if (idx < 0) { idx = ~idx; } return rankedFormats[idx].fFormat; } namespace { #if defined(UNICODE) #define STR_LIT(X) L## #X #else #define STR_LIT(X) #X #endif #define DUMMY_CLASS STR_LIT("DummyClass") HWND create_dummy_window() { HMODULE module = GetModuleHandle(NULL); HWND dummy; RECT windowRect; windowRect.left = 0; windowRect.right = 8; windowRect.top = 0; windowRect.bottom = 8; WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) DefWindowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = module; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = DUMMY_CLASS; if(!RegisterClass(&wc)) { return 0; } DWORD style, exStyle; exStyle = WS_EX_CLIENTEDGE; style = WS_SYSMENU; AdjustWindowRectEx(&windowRect, style, false, exStyle); if(!(dummy = CreateWindowEx(exStyle, DUMMY_CLASS, STR_LIT("DummyWindow"), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | style, 0, 0, windowRect.right-windowRect.left, windowRect.bottom-windowRect.top, NULL, NULL, module, NULL))) { UnregisterClass(DUMMY_CLASS, module); return NULL; } ShowWindow(dummy, SW_HIDE); return dummy; } void destroy_dummy_window(HWND dummy) { DestroyWindow(dummy); HMODULE module = GetModuleHandle(NULL); UnregisterClass(DUMMY_CLASS, module); } } #define GET_PROC(NAME, SUFFIX) f##NAME = \ (##NAME##Proc) wglGetProcAddress("wgl" #NAME #SUFFIX) SkWGLExtensions::SkWGLExtensions() : fGetExtensionsString(NULL) , fChoosePixelFormat(NULL) , fGetPixelFormatAttribfv(NULL) , fGetPixelFormatAttribiv(NULL) , fCreateContextAttribs(NULL) { HDC prevDC = wglGetCurrentDC(); HGLRC prevGLRC = wglGetCurrentContext(); PIXELFORMATDESCRIPTOR dummyPFD; ZeroMemory(&dummyPFD, sizeof(dummyPFD)); dummyPFD.nSize = sizeof(dummyPFD); dummyPFD.nVersion = 1; dummyPFD.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL; dummyPFD.iPixelType = PFD_TYPE_RGBA; dummyPFD.cColorBits = 32; dummyPFD.cDepthBits = 0; dummyPFD.cStencilBits = 8; dummyPFD.iLayerType = PFD_MAIN_PLANE; HWND dummyWND = create_dummy_window(); if (dummyWND) { HDC dummyDC = GetDC(dummyWND); int dummyFormat = ChoosePixelFormat(dummyDC, &dummyPFD); SetPixelFormat(dummyDC, dummyFormat, &dummyPFD); HGLRC dummyGLRC = wglCreateContext(dummyDC); SkASSERT(dummyGLRC); wglMakeCurrent(dummyDC, dummyGLRC); GET_PROC(GetExtensionsString, ARB); GET_PROC(ChoosePixelFormat, ARB); GET_PROC(GetPixelFormatAttribiv, ARB); GET_PROC(GetPixelFormatAttribfv, ARB); GET_PROC(CreateContextAttribs, ARB); wglMakeCurrent(dummyDC, NULL); wglDeleteContext(dummyGLRC); destroy_dummy_window(dummyWND); } wglMakeCurrent(prevDC, prevGLRC); } <commit_msg>Fixed unused variable compiler complaint<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkWGL.h" #include "SkTDArray.h" #include "SkTSearch.h" bool SkWGLExtensions::hasExtension(HDC dc, const char* ext) const { if (NULL == this->fGetExtensionsString) { return false; } if (!strcmp("WGL_ARB_extensions_string", ext)) { return true; } const char* extensionString = this->getExtensionsString(dc); int extLength = strlen(ext); while (true) { int n = strcspn(extensionString, " "); if (n == extLength && 0 == strncmp(ext, extensionString, n)) { return true; } if (0 == extensionString[n]) { return false; } extensionString += n+1; } return false; } const char* SkWGLExtensions::getExtensionsString(HDC hdc) const { return fGetExtensionsString(hdc); } BOOL SkWGLExtensions::choosePixelFormat(HDC hdc, const int* piAttribIList, const FLOAT* pfAttribFList, UINT nMaxFormats, int* piFormats, UINT* nNumFormats) const { return fChoosePixelFormat(hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats); } BOOL SkWGLExtensions::getPixelFormatAttribiv(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues) const { return fGetPixelFormatAttribiv(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, piValues); } BOOL SkWGLExtensions::getPixelFormatAttribfv(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, float *pfValues) const { return fGetPixelFormatAttribfv(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, pfValues); } HGLRC SkWGLExtensions::createContextAttribs(HDC hDC, HGLRC hShareContext, const int *attribList) const { return fCreateContextAttribs(hDC, hShareContext, attribList); } namespace { struct PixelFormat { int fFormat; int fCoverageSamples; int fColorSamples; int fChoosePixelFormatRank; }; int compare_pf(const PixelFormat* a, const PixelFormat* b) { if (a->fCoverageSamples < b->fCoverageSamples) { return -1; } else if (b->fCoverageSamples < a->fCoverageSamples) { return 1; } else if (a->fColorSamples < b->fColorSamples) { return -1; } else if (b->fColorSamples < a->fColorSamples) { return 1; } else if (a->fChoosePixelFormatRank < b->fChoosePixelFormatRank) { return -1; } else if (b->fChoosePixelFormatRank < a->fChoosePixelFormatRank) { return 1; } return 0; } } int SkWGLExtensions::selectFormat(const int formats[], int formatCount, HDC dc, int desiredSampleCount) { PixelFormat desiredFormat = { 0, desiredSampleCount, 0, 0, }; SkTDArray<PixelFormat> rankedFormats; rankedFormats.setCount(formatCount); bool supportsCoverage = this->hasExtension(dc, "WGL_NV_multisample_coverage"); for (int i = 0; i < formatCount; ++i) { static const int queryAttrs[] = { SK_WGL_COVERAGE_SAMPLES, // Keep COLOR_SAMPLES at the end so it can be skipped SK_WGL_COLOR_SAMPLES, }; int answers[2]; int queryAttrCnt = supportsCoverage ? SK_ARRAY_COUNT(queryAttrs) : SK_ARRAY_COUNT(queryAttrs) - 1; this->getPixelFormatAttribiv(dc, formats[i], 0, queryAttrCnt, queryAttrs, answers); rankedFormats[i].fFormat = formats[i]; rankedFormats[i].fCoverageSamples = answers[0]; rankedFormats[i].fColorSamples = answers[supportsCoverage ? 1 : 0]; rankedFormats[i].fChoosePixelFormatRank = i; } qsort(rankedFormats.begin(), rankedFormats.count(), sizeof(PixelFormat), SkCastForQSort(compare_pf)); int idx = SkTSearch<PixelFormat>(rankedFormats.begin(), rankedFormats.count(), desiredFormat, sizeof(PixelFormat), compare_pf); if (idx < 0) { idx = ~idx; } return rankedFormats[idx].fFormat; } namespace { #if defined(UNICODE) #define STR_LIT(X) L## #X #else #define STR_LIT(X) #X #endif #define DUMMY_CLASS STR_LIT("DummyClass") HWND create_dummy_window() { HMODULE module = GetModuleHandle(NULL); HWND dummy; RECT windowRect; windowRect.left = 0; windowRect.right = 8; windowRect.top = 0; windowRect.bottom = 8; WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) DefWindowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = module; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = DUMMY_CLASS; if(!RegisterClass(&wc)) { return 0; } DWORD style, exStyle; exStyle = WS_EX_CLIENTEDGE; style = WS_SYSMENU; AdjustWindowRectEx(&windowRect, style, false, exStyle); if(!(dummy = CreateWindowEx(exStyle, DUMMY_CLASS, STR_LIT("DummyWindow"), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | style, 0, 0, windowRect.right-windowRect.left, windowRect.bottom-windowRect.top, NULL, NULL, module, NULL))) { UnregisterClass(DUMMY_CLASS, module); return NULL; } ShowWindow(dummy, SW_HIDE); return dummy; } void destroy_dummy_window(HWND dummy) { DestroyWindow(dummy); HMODULE module = GetModuleHandle(NULL); UnregisterClass(DUMMY_CLASS, module); } } #define GET_PROC(NAME, SUFFIX) f##NAME = \ (##NAME##Proc) wglGetProcAddress("wgl" #NAME #SUFFIX) SkWGLExtensions::SkWGLExtensions() : fGetExtensionsString(NULL) , fChoosePixelFormat(NULL) , fGetPixelFormatAttribfv(NULL) , fGetPixelFormatAttribiv(NULL) , fCreateContextAttribs(NULL) { HDC prevDC = wglGetCurrentDC(); HGLRC prevGLRC = wglGetCurrentContext(); PIXELFORMATDESCRIPTOR dummyPFD; ZeroMemory(&dummyPFD, sizeof(dummyPFD)); dummyPFD.nSize = sizeof(dummyPFD); dummyPFD.nVersion = 1; dummyPFD.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL; dummyPFD.iPixelType = PFD_TYPE_RGBA; dummyPFD.cColorBits = 32; dummyPFD.cDepthBits = 0; dummyPFD.cStencilBits = 8; dummyPFD.iLayerType = PFD_MAIN_PLANE; HWND dummyWND = create_dummy_window(); if (dummyWND) { HDC dummyDC = GetDC(dummyWND); int dummyFormat = ChoosePixelFormat(dummyDC, &dummyPFD); SetPixelFormat(dummyDC, dummyFormat, &dummyPFD); HGLRC dummyGLRC = wglCreateContext(dummyDC); SkASSERT(dummyGLRC); wglMakeCurrent(dummyDC, dummyGLRC); GET_PROC(GetExtensionsString, ARB); GET_PROC(ChoosePixelFormat, ARB); GET_PROC(GetPixelFormatAttribiv, ARB); GET_PROC(GetPixelFormatAttribfv, ARB); GET_PROC(CreateContextAttribs, ARB); wglMakeCurrent(dummyDC, NULL); wglDeleteContext(dummyGLRC); destroy_dummy_window(dummyWND); } wglMakeCurrent(prevDC, prevGLRC); } <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <ctime> #include "libtorrent/kademlia/node_id.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/broadcast_socket.hpp" // for is_local et.al #include "libtorrent/socket_io.hpp" // for hash_address #include "libtorrent/random.hpp" // for random namespace libtorrent { namespace dht { // returns the distance between the two nodes // using the kademlia XOR-metric node_id distance(node_id const& n1, node_id const& n2) { node_id ret; node_id::iterator k = ret.begin(); for (node_id::const_iterator i = n1.begin(), j = n2.begin() , end(n1.end()); i != end; ++i, ++j, ++k) { *k = *i ^ *j; } return ret; } // returns true if: distance(n1, ref) < distance(n2, ref) bool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref) { for (node_id::const_iterator i = n1.begin(), j = n2.begin() , k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k) { boost::uint8_t lhs = (*i ^ *k); boost::uint8_t rhs = (*j ^ *k); if (lhs < rhs) return true; if (lhs > rhs) return false; } return false; } // returns n in: 2^n <= distance(n1, n2) < 2^(n+1) // useful for finding out which bucket a node belongs to int distance_exp(node_id const& n1, node_id const& n2) { int byte = node_id::size - 1; for (node_id::const_iterator i = n1.begin(), j = n2.begin() , end(n1.end()); i != end; ++i, ++j, --byte) { TORRENT_ASSERT(byte >= 0); boost::uint8_t t = *i ^ *j; if (t == 0) continue; // we have found the first non-zero byte // return the bit-number of the first bit // that differs int bit = byte * 8; for (int b = 7; b >= 0; --b) if (t >= (1 << b)) return bit + b; return bit; } return 0; } struct static_ { static_() { std::srand((unsigned int)std::time(0)); } } static__; node_id generate_id_impl(address const& ip_, boost::uint32_t r) { boost::uint8_t* ip = 0; const static boost::uint8_t v4mask[] = { 0x03, 0x0f, 0x3f, 0xff }; const static boost::uint8_t v6mask[] = { 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff }; boost::uint8_t const* mask = 0; int num_octets = 0; address_v4::bytes_type b4; #if TORRENT_USE_IPV6 address_v6::bytes_type b6; if (ip_.is_v6()) { b6 = ip_.to_v6().to_bytes(); ip = &b6[0]; num_octets = 8; mask = v6mask; } else #endif { b4 = ip_.to_v4().to_bytes(); ip = &b4[0]; num_octets = 4; mask = v4mask; } for (int i = 0; i < num_octets; ++i) ip[i] &= mask[i]; hasher h; h.update((char*)ip, num_octets); boost::uint8_t rand = r & 0x7; h.update((char*)&r, 1); node_id id = h.final(); for (int i = 4; i < 19; ++i) id[i] = random(); id[19] = r; return id; } node_id generate_random_id() { char r[20]; for (int i = 0; i < 20; ++i) r[i] = random(); return hasher(r, 20).final(); } // verifies whether a node-id matches the IP it's used from // returns true if the node-id is OK coming from this source // and false otherwise. bool verify_id(node_id const& nid, address const& source_ip) { // no need to verify local IPs, they would be incorrect anyway if (is_local(source_ip)) return true; node_id h = generate_id_impl(source_ip, nid[19]); return memcmp(&nid[0], &h[0], 4) == 0; } node_id generate_id(address const& ip) { return generate_id_impl(ip, random()); } } } // namespace libtorrent::dht <commit_msg>and the typo in trunk as well<commit_after>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <algorithm> #include <ctime> #include "libtorrent/kademlia/node_id.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/broadcast_socket.hpp" // for is_local et.al #include "libtorrent/socket_io.hpp" // for hash_address #include "libtorrent/random.hpp" // for random namespace libtorrent { namespace dht { // returns the distance between the two nodes // using the kademlia XOR-metric node_id distance(node_id const& n1, node_id const& n2) { node_id ret; node_id::iterator k = ret.begin(); for (node_id::const_iterator i = n1.begin(), j = n2.begin() , end(n1.end()); i != end; ++i, ++j, ++k) { *k = *i ^ *j; } return ret; } // returns true if: distance(n1, ref) < distance(n2, ref) bool compare_ref(node_id const& n1, node_id const& n2, node_id const& ref) { for (node_id::const_iterator i = n1.begin(), j = n2.begin() , k = ref.begin(), end(n1.end()); i != end; ++i, ++j, ++k) { boost::uint8_t lhs = (*i ^ *k); boost::uint8_t rhs = (*j ^ *k); if (lhs < rhs) return true; if (lhs > rhs) return false; } return false; } // returns n in: 2^n <= distance(n1, n2) < 2^(n+1) // useful for finding out which bucket a node belongs to int distance_exp(node_id const& n1, node_id const& n2) { int byte = node_id::size - 1; for (node_id::const_iterator i = n1.begin(), j = n2.begin() , end(n1.end()); i != end; ++i, ++j, --byte) { TORRENT_ASSERT(byte >= 0); boost::uint8_t t = *i ^ *j; if (t == 0) continue; // we have found the first non-zero byte // return the bit-number of the first bit // that differs int bit = byte * 8; for (int b = 7; b >= 0; --b) if (t >= (1 << b)) return bit + b; return bit; } return 0; } struct static_ { static_() { std::srand((unsigned int)std::time(0)); } } static__; node_id generate_id_impl(address const& ip_, boost::uint32_t r) { boost::uint8_t* ip = 0; const static boost::uint8_t v4mask[] = { 0x03, 0x0f, 0x3f, 0xff }; const static boost::uint8_t v6mask[] = { 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff }; boost::uint8_t const* mask = 0; int num_octets = 0; address_v4::bytes_type b4; #if TORRENT_USE_IPV6 address_v6::bytes_type b6; if (ip_.is_v6()) { b6 = ip_.to_v6().to_bytes(); ip = &b6[0]; num_octets = 8; mask = v6mask; } else #endif { b4 = ip_.to_v4().to_bytes(); ip = &b4[0]; num_octets = 4; mask = v4mask; } for (int i = 0; i < num_octets; ++i) ip[i] &= mask[i]; hasher h; h.update((char*)ip, num_octets); boost::uint8_t rand = r & 0x7; h.update((char*)&rand, 1); node_id id = h.final(); for (int i = 4; i < 19; ++i) id[i] = random(); id[19] = r; return id; } node_id generate_random_id() { char r[20]; for (int i = 0; i < 20; ++i) r[i] = random(); return hasher(r, 20).final(); } // verifies whether a node-id matches the IP it's used from // returns true if the node-id is OK coming from this source // and false otherwise. bool verify_id(node_id const& nid, address const& source_ip) { // no need to verify local IPs, they would be incorrect anyway if (is_local(source_ip)) return true; node_id h = generate_id_impl(source_ip, nid[19]); return memcmp(&nid[0], &h[0], 4) == 0; } node_id generate_id(address const& ip) { return generate_id_impl(ip, random()); } } } // namespace libtorrent::dht <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/parameterFitting/CExperimentSet.cpp,v $ $Revision: 1.19 $ $Name: $ $Author: shoops $ $Date: 2006/04/20 15:28:42 $ End CVS Header */ #include <algorithm> #include <limits> #include <math.h> #include "copasi.h" #include "CExperimentSet.h" #include "CExperiment.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CKeyFactory.h" #include "utilities/utility.h" CExperimentSet::CExperimentSet(const std::string & name, const CCopasiContainer * pParent): CCopasiParameterGroup(name, pParent, "CExperimentSet"), mpExperiments(NULL) {initializeParameter();} CExperimentSet::CExperimentSet(const CExperimentSet & src, const CCopasiContainer * pParent): CCopasiParameterGroup(src, pParent), mpExperiments(NULL) {initializeParameter();} CExperimentSet::CExperimentSet(const CCopasiParameterGroup & group, const CCopasiContainer * pParent): CCopasiParameterGroup(group, pParent), mpExperiments(NULL) {initializeParameter();} CExperimentSet::~CExperimentSet() {} void CExperimentSet::initializeParameter() {elevateChildren();} bool CExperimentSet::elevateChildren() { index_iterator it = mValue.pGROUP->begin(); index_iterator end = mValue.pGROUP->end(); for (; it != end; ++it) if (!elevate<CExperiment, CCopasiParameterGroup>(*it)) return false; mpExperiments = static_cast<std::vector<CExperiment * > * >(mValue.pVOID); sort(); return true; } bool CExperimentSet::compile(const std::vector< CCopasiContainer * > listOfContainer) { bool success = true; // First we need to sort the experiments so that we can make use of continued // file reading. sort(); std::set< CCopasiObject * > DependentObjects; std::ifstream in; std::string CurrentFileName(""); unsigned C_INT32 CurrentLineNumber = 1; std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); for (it = mpExperiments->begin(); it != end; ++it) { if (CurrentFileName != (*it)->getFileName()) { CurrentFileName = (*it)->getFileName(); CurrentLineNumber = 1; if (in.is_open()) { in.close(); in.clear(); } in.open(CurrentFileName.c_str(), std::ios::binary); if (in.fail()) return false; // File can not be opened. } if (!(*it)->read(in, CurrentLineNumber)) return false; if (!(*it)->compile(listOfContainer)) return false; const std::map< CCopasiObject *, unsigned C_INT32 > & ExpDependentObjects = (*it)->getDependentObjects(); std::map< CCopasiObject *, unsigned C_INT32 >::const_iterator itObject = ExpDependentObjects.begin(); std::map< CCopasiObject *, unsigned C_INT32 >::const_iterator endObject = ExpDependentObjects.end(); for (; itObject != endObject; ++itObject) DependentObjects.insert(itObject->first); } mDependentObjects.resize(DependentObjects.size()); CCopasiObject ** ppInsert = mDependentObjects.array(); std::set< CCopasiObject * >::const_iterator itObject = DependentObjects.begin(); std::set< CCopasiObject * >::const_iterator endObject = DependentObjects.end(); for (; itObject != endObject; ++itObject, ++ppInsert) *ppInsert = *itObject; // Allocation and initialization of statistical information mDependentObjectiveValues.resize(mDependentObjects.size()); mDependentObjectiveValues = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentRMS.resize(mDependentObjects.size()); mDependentRMS = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentErrorMean.resize(mDependentObjects.size()); mDependentErrorMean = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentErrorMeanSD.resize(mDependentObjects.size()); mDependentErrorMeanSD = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentDataCount.resize(mDependentObjects.size()); mDependentDataCount = std::numeric_limits<unsigned C_INT32>::quiet_NaN(); return success; } bool CExperimentSet::calculateStatistics() { mDependentObjectiveValues.resize(mDependentObjects.size()); mDependentObjectiveValues = 0.0; mDependentRMS.resize(mDependentObjects.size()); mDependentRMS = 0.0; mDependentErrorMean.resize(mDependentObjects.size()); mDependentErrorMean = 0.0; mDependentErrorMeanSD.resize(mDependentObjects.size()); mDependentErrorMeanSD = 0.0; mDependentDataCount.resize(mDependentObjects.size()); mDependentDataCount = 0; // calclate the per experiment and per dependent value statistics. std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); unsigned C_INT32 i, Count; C_FLOAT64 Tmp; for (; it != end; ++it) { (*it)->calculateStatistics(); CCopasiObject *const* ppObject = mDependentObjects.array(); CCopasiObject *const* ppEnd = ppObject + mDependentObjects.size(); for (i = 0; ppObject != ppEnd; ++ppObject, ++i) { Count = (*it)->getCount(*ppObject); if (Count) { mDependentObjectiveValues[i] += (*it)->getObjectiveValue(*ppObject); Tmp = (*it)->getRMS(*ppObject); mDependentRMS[i] += Tmp * Tmp * Count; mDependentErrorMean[i] += (*it)->getErrorMean(*ppObject); mDependentDataCount[i] += Count; } } } unsigned C_INT32 imax = mDependentObjects.size(); for (i = 0; i != imax; i++) { Count = mDependentDataCount[i]; if (Count) { mDependentRMS[i] = sqrt(mDependentRMS[i] / Count); mDependentErrorMean[i] /= Count; } else { mDependentRMS[i] = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentErrorMean[i] = std::numeric_limits<C_FLOAT64>::quiet_NaN(); } } it = mpExperiments->begin(); // We need to loop again to calculate the std. deviation. for (; it != end; ++it) { CCopasiObject *const* ppObject = mDependentObjects.array(); CCopasiObject *const* ppEnd = ppObject + mDependentObjects.size(); for (i = 0; ppObject != ppEnd; ++ppObject, ++i) { Count = (*it)->getCount(*ppObject); if (Count) mDependentErrorMeanSD[i] += (*it)->getErrorMeanSD(*ppObject, mDependentErrorMean[i]); } } for (i = 0; i != imax; i++) { Count = mDependentDataCount[i]; if (Count) mDependentErrorMeanSD[i] = sqrt(mDependentErrorMeanSD[i] / Count); else mDependentErrorMeanSD[i] = std::numeric_limits<C_FLOAT64>::quiet_NaN(); } // :TODO: This is the time to call the output handler to plot the fitted points. for (it = mpExperiments->begin(), imax = 0; it != end; ++it) imax = std::max(imax, (*it)->getDependentData().numRows()); for (i = 0; i < imax; i++) { for (it = mpExperiments->begin(); it != end; ++it) (*it)->updateFittedPointValues(i); CCopasiDataModel::Global->output(COutputInterface::AFTER); } return true; } const CVector< CCopasiObject * > & CExperimentSet::getDependentObjects() const {return mDependentObjects;} const CVector< C_FLOAT64 > & CExperimentSet::getDependentObjectiveValues() const {return mDependentObjectiveValues;} const CVector< C_FLOAT64 > & CExperimentSet::getDependentRMS() const {return mDependentRMS;} const CVector< C_FLOAT64 > & CExperimentSet::getDependentErrorMean() const {return mDependentErrorMean;} const CVector< C_FLOAT64 > & CExperimentSet::getDependentErrorMeanSD() const {return mDependentErrorMeanSD;} CExperiment * CExperimentSet::addExperiment(const CExperiment & experiment) { // We need to make sure that the experiment name is unique. std::string name = experiment.getObjectName(); int i = 0; while (getParameter(name)) { i++; name = StringPrint("%s_%d", experiment.getObjectName().c_str(), i); } CExperiment * pExperiment = new CExperiment(experiment); pExperiment->setObjectName(name); addParameter(pExperiment); sort(); return pExperiment; } CExperiment * CExperimentSet::getExperiment(const unsigned C_INT32 & index) {return (*mpExperiments)[index];} const CExperiment * CExperimentSet::getExperiment(const unsigned C_INT32 & index) const {return (*mpExperiments)[index];} CExperiment * CExperimentSet::getExperiment(const std::string & name) {return static_cast<CExperiment *>(getGroup(name));} const CExperiment * CExperimentSet::getExperiment(const std::string & name) const {return static_cast<const CExperiment *>(getGroup(name));} const CCopasiTask::Type & CExperimentSet::getExperimentType(const unsigned C_INT32 & index) const {return getExperiment(index)->getExperimentType();} const CMatrix< C_FLOAT64 > & CExperimentSet::getIndependentData(const unsigned C_INT32 & index) const {return getExperiment(index)->getIndependentData();} const CMatrix< C_FLOAT64 > & CExperimentSet::getDependentData(const unsigned C_INT32 & index) const {return getExperiment(index)->getDependentData();} unsigned C_INT32 CExperimentSet::keyToIndex(const std::string & key) const { const CExperiment * pExp = dynamic_cast<const CExperiment *>(GlobalKeys.get(key)); if (!pExp) return C_INVALID_INDEX; unsigned C_INT32 i, imax = size(); for (i = 0; i < imax; i++) if (pExp == getExperiment(i)) return i; return C_INVALID_INDEX; } void CExperimentSet::sort() { std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); std::sort(it, end, &CExperiment::compare); return; } std::vector< std::string > CExperimentSet::getFileNames() const { std::vector< std::string > List; std::string currentFile = ""; std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); for (; it != end; ++it) if (currentFile != (*it)->getFileName()) { currentFile = (*it)->getFileName(); List.push_back(currentFile); } return List; } unsigned C_INT32 CExperimentSet::getDataPointCount() const { unsigned C_INT32 Count = 0; std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); for (; it != end; ++it) Count += (*it)->getDependentData().numRows() * (*it)->getDependentData().numCols(); return Count; } <commit_msg>Removed :TODO: comment :)<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/parameterFitting/CExperimentSet.cpp,v $ $Revision: 1.20 $ $Name: $ $Author: shoops $ $Date: 2006/04/21 19:15:56 $ End CVS Header */ #include <algorithm> #include <limits> #include <math.h> #include "copasi.h" #include "CExperimentSet.h" #include "CExperiment.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CKeyFactory.h" #include "utilities/utility.h" CExperimentSet::CExperimentSet(const std::string & name, const CCopasiContainer * pParent): CCopasiParameterGroup(name, pParent, "CExperimentSet"), mpExperiments(NULL) {initializeParameter();} CExperimentSet::CExperimentSet(const CExperimentSet & src, const CCopasiContainer * pParent): CCopasiParameterGroup(src, pParent), mpExperiments(NULL) {initializeParameter();} CExperimentSet::CExperimentSet(const CCopasiParameterGroup & group, const CCopasiContainer * pParent): CCopasiParameterGroup(group, pParent), mpExperiments(NULL) {initializeParameter();} CExperimentSet::~CExperimentSet() {} void CExperimentSet::initializeParameter() {elevateChildren();} bool CExperimentSet::elevateChildren() { index_iterator it = mValue.pGROUP->begin(); index_iterator end = mValue.pGROUP->end(); for (; it != end; ++it) if (!elevate<CExperiment, CCopasiParameterGroup>(*it)) return false; mpExperiments = static_cast<std::vector<CExperiment * > * >(mValue.pVOID); sort(); return true; } bool CExperimentSet::compile(const std::vector< CCopasiContainer * > listOfContainer) { bool success = true; // First we need to sort the experiments so that we can make use of continued // file reading. sort(); std::set< CCopasiObject * > DependentObjects; std::ifstream in; std::string CurrentFileName(""); unsigned C_INT32 CurrentLineNumber = 1; std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); for (it = mpExperiments->begin(); it != end; ++it) { if (CurrentFileName != (*it)->getFileName()) { CurrentFileName = (*it)->getFileName(); CurrentLineNumber = 1; if (in.is_open()) { in.close(); in.clear(); } in.open(CurrentFileName.c_str(), std::ios::binary); if (in.fail()) return false; // File can not be opened. } if (!(*it)->read(in, CurrentLineNumber)) return false; if (!(*it)->compile(listOfContainer)) return false; const std::map< CCopasiObject *, unsigned C_INT32 > & ExpDependentObjects = (*it)->getDependentObjects(); std::map< CCopasiObject *, unsigned C_INT32 >::const_iterator itObject = ExpDependentObjects.begin(); std::map< CCopasiObject *, unsigned C_INT32 >::const_iterator endObject = ExpDependentObjects.end(); for (; itObject != endObject; ++itObject) DependentObjects.insert(itObject->first); } mDependentObjects.resize(DependentObjects.size()); CCopasiObject ** ppInsert = mDependentObjects.array(); std::set< CCopasiObject * >::const_iterator itObject = DependentObjects.begin(); std::set< CCopasiObject * >::const_iterator endObject = DependentObjects.end(); for (; itObject != endObject; ++itObject, ++ppInsert) *ppInsert = *itObject; // Allocation and initialization of statistical information mDependentObjectiveValues.resize(mDependentObjects.size()); mDependentObjectiveValues = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentRMS.resize(mDependentObjects.size()); mDependentRMS = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentErrorMean.resize(mDependentObjects.size()); mDependentErrorMean = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentErrorMeanSD.resize(mDependentObjects.size()); mDependentErrorMeanSD = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentDataCount.resize(mDependentObjects.size()); mDependentDataCount = std::numeric_limits<unsigned C_INT32>::quiet_NaN(); return success; } bool CExperimentSet::calculateStatistics() { mDependentObjectiveValues.resize(mDependentObjects.size()); mDependentObjectiveValues = 0.0; mDependentRMS.resize(mDependentObjects.size()); mDependentRMS = 0.0; mDependentErrorMean.resize(mDependentObjects.size()); mDependentErrorMean = 0.0; mDependentErrorMeanSD.resize(mDependentObjects.size()); mDependentErrorMeanSD = 0.0; mDependentDataCount.resize(mDependentObjects.size()); mDependentDataCount = 0; // calclate the per experiment and per dependent value statistics. std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); unsigned C_INT32 i, Count; C_FLOAT64 Tmp; for (; it != end; ++it) { (*it)->calculateStatistics(); CCopasiObject *const* ppObject = mDependentObjects.array(); CCopasiObject *const* ppEnd = ppObject + mDependentObjects.size(); for (i = 0; ppObject != ppEnd; ++ppObject, ++i) { Count = (*it)->getCount(*ppObject); if (Count) { mDependentObjectiveValues[i] += (*it)->getObjectiveValue(*ppObject); Tmp = (*it)->getRMS(*ppObject); mDependentRMS[i] += Tmp * Tmp * Count; mDependentErrorMean[i] += (*it)->getErrorMean(*ppObject); mDependentDataCount[i] += Count; } } } unsigned C_INT32 imax = mDependentObjects.size(); for (i = 0; i != imax; i++) { Count = mDependentDataCount[i]; if (Count) { mDependentRMS[i] = sqrt(mDependentRMS[i] / Count); mDependentErrorMean[i] /= Count; } else { mDependentRMS[i] = std::numeric_limits<C_FLOAT64>::quiet_NaN(); mDependentErrorMean[i] = std::numeric_limits<C_FLOAT64>::quiet_NaN(); } } it = mpExperiments->begin(); // We need to loop again to calculate the std. deviation. for (; it != end; ++it) { CCopasiObject *const* ppObject = mDependentObjects.array(); CCopasiObject *const* ppEnd = ppObject + mDependentObjects.size(); for (i = 0; ppObject != ppEnd; ++ppObject, ++i) { Count = (*it)->getCount(*ppObject); if (Count) mDependentErrorMeanSD[i] += (*it)->getErrorMeanSD(*ppObject, mDependentErrorMean[i]); } } for (i = 0; i != imax; i++) { Count = mDependentDataCount[i]; if (Count) mDependentErrorMeanSD[i] = sqrt(mDependentErrorMeanSD[i] / Count); else mDependentErrorMeanSD[i] = std::numeric_limits<C_FLOAT64>::quiet_NaN(); } // This is the time to call the output handler to plot the fitted points. for (it = mpExperiments->begin(), imax = 0; it != end; ++it) imax = std::max(imax, (*it)->getDependentData().numRows()); for (i = 0; i < imax; i++) { for (it = mpExperiments->begin(); it != end; ++it) (*it)->updateFittedPointValues(i); CCopasiDataModel::Global->output(COutputInterface::AFTER); } return true; } const CVector< CCopasiObject * > & CExperimentSet::getDependentObjects() const {return mDependentObjects;} const CVector< C_FLOAT64 > & CExperimentSet::getDependentObjectiveValues() const {return mDependentObjectiveValues;} const CVector< C_FLOAT64 > & CExperimentSet::getDependentRMS() const {return mDependentRMS;} const CVector< C_FLOAT64 > & CExperimentSet::getDependentErrorMean() const {return mDependentErrorMean;} const CVector< C_FLOAT64 > & CExperimentSet::getDependentErrorMeanSD() const {return mDependentErrorMeanSD;} CExperiment * CExperimentSet::addExperiment(const CExperiment & experiment) { // We need to make sure that the experiment name is unique. std::string name = experiment.getObjectName(); int i = 0; while (getParameter(name)) { i++; name = StringPrint("%s_%d", experiment.getObjectName().c_str(), i); } CExperiment * pExperiment = new CExperiment(experiment); pExperiment->setObjectName(name); addParameter(pExperiment); sort(); return pExperiment; } CExperiment * CExperimentSet::getExperiment(const unsigned C_INT32 & index) {return (*mpExperiments)[index];} const CExperiment * CExperimentSet::getExperiment(const unsigned C_INT32 & index) const {return (*mpExperiments)[index];} CExperiment * CExperimentSet::getExperiment(const std::string & name) {return static_cast<CExperiment *>(getGroup(name));} const CExperiment * CExperimentSet::getExperiment(const std::string & name) const {return static_cast<const CExperiment *>(getGroup(name));} const CCopasiTask::Type & CExperimentSet::getExperimentType(const unsigned C_INT32 & index) const {return getExperiment(index)->getExperimentType();} const CMatrix< C_FLOAT64 > & CExperimentSet::getIndependentData(const unsigned C_INT32 & index) const {return getExperiment(index)->getIndependentData();} const CMatrix< C_FLOAT64 > & CExperimentSet::getDependentData(const unsigned C_INT32 & index) const {return getExperiment(index)->getDependentData();} unsigned C_INT32 CExperimentSet::keyToIndex(const std::string & key) const { const CExperiment * pExp = dynamic_cast<const CExperiment *>(GlobalKeys.get(key)); if (!pExp) return C_INVALID_INDEX; unsigned C_INT32 i, imax = size(); for (i = 0; i < imax; i++) if (pExp == getExperiment(i)) return i; return C_INVALID_INDEX; } void CExperimentSet::sort() { std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); std::sort(it, end, &CExperiment::compare); return; } std::vector< std::string > CExperimentSet::getFileNames() const { std::vector< std::string > List; std::string currentFile = ""; std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); for (; it != end; ++it) if (currentFile != (*it)->getFileName()) { currentFile = (*it)->getFileName(); List.push_back(currentFile); } return List; } unsigned C_INT32 CExperimentSet::getDataPointCount() const { unsigned C_INT32 Count = 0; std::vector< CExperiment * >::iterator it = mpExperiments->begin(); std::vector< CExperiment * >::iterator end = mpExperiments->end(); for (; it != end; ++it) Count += (*it)->getDependentData().numRows() * (*it)->getDependentData().numCols(); return Count; } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreMovableObject.h" #include "OgreSceneNode.h" #include "OgreTagPoint.h" #include "OgreLight.h" #include "OgreEntity.h" #include "OgreRoot.h" #include "OgreSceneManager.h" #include "OgreCamera.h" #include "OgreLodListener.h" namespace Ogre { //----------------------------------------------------------------------- //----------------------------------------------------------------------- uint32 MovableObject::msDefaultQueryFlags = 0xFFFFFFFF; uint32 MovableObject::msDefaultVisibilityFlags = 0xFFFFFFFF; //----------------------------------------------------------------------- MovableObject::MovableObject() : mCreator(0) , mManager(0) , mParentNode(0) , mParentIsTagPoint(false) , mVisible(true) , mDebugDisplay(false) , mUpperDistance(0) , mSquaredUpperDistance(0) , mBeyondFarDistance(false) , mRenderQueueID(RENDER_QUEUE_MAIN) , mRenderQueueIDSet(false) , mQueryFlags(msDefaultQueryFlags) , mVisibilityFlags(msDefaultVisibilityFlags) , mCastShadows(true) , mRenderingDisabled(false) , mListener(0) , mLightListUpdated(0) , mLightMask(0xFFFFFFFF) { } //----------------------------------------------------------------------- MovableObject::MovableObject(const String& name) : mName(name) , mCreator(0) , mManager(0) , mParentNode(0) , mParentIsTagPoint(false) , mVisible(true) , mDebugDisplay(false) , mUpperDistance(0) , mSquaredUpperDistance(0) , mBeyondFarDistance(false) , mRenderQueueID(RENDER_QUEUE_MAIN) , mRenderQueueIDSet(false) , mQueryFlags(msDefaultQueryFlags) , mVisibilityFlags(msDefaultVisibilityFlags) , mCastShadows(true) , mRenderingDisabled(false) , mListener(0) , mLightListUpdated(0) , mLightMask(0xFFFFFFFF) { } //----------------------------------------------------------------------- MovableObject::~MovableObject() { // Call listener (note, only called if there's something to do) if (mListener) { mListener->objectDestroyed(this); } if (mParentNode) { // detach from parent if (mParentIsTagPoint) { // May be we are a lod entity which not in the parent entity child object list, // call this method could safely ignore this case. static_cast<TagPoint*>(mParentNode)->getParentEntity()->detachObjectFromBone(this); } else { // May be we are a lod entity which not in the parent node child object list, // call this method could safely ignore this case. static_cast<SceneNode*>(mParentNode)->detachObject(this); } } } //----------------------------------------------------------------------- void MovableObject::_notifyAttached(Node* parent, bool isTagPoint) { assert(!mParentNode || !parent); bool different = (parent != mParentNode); mParentNode = parent; mParentIsTagPoint = isTagPoint; // Mark light list being dirty, simply decrease // counter by one for minimise overhead --mLightListUpdated; // Call listener (note, only called if there's something to do) if (mListener && different) { if (mParentNode) mListener->objectAttached(this); else mListener->objectDetached(this); } } //----------------------------------------------------------------------- Node* MovableObject::getParentNode(void) const { return mParentNode; } //----------------------------------------------------------------------- SceneNode* MovableObject::getParentSceneNode(void) const { if (mParentIsTagPoint) { TagPoint* tp = static_cast<TagPoint*>(mParentNode); return tp->getParentEntity()->getParentSceneNode(); } else { return static_cast<SceneNode*>(mParentNode); } } //----------------------------------------------------------------------- bool MovableObject::isAttached(void) const { return (mParentNode != 0); } //--------------------------------------------------------------------- void MovableObject::detachFromParent(void) { if (isAttached()) { if (mParentIsTagPoint) { TagPoint* tp = static_cast<TagPoint*>(mParentNode); tp->getParentEntity()->detachObjectFromBone(this); } else { SceneNode* sn = static_cast<SceneNode*>(mParentNode); sn->detachObject(this); } } } //----------------------------------------------------------------------- bool MovableObject::isInScene(void) const { if (mParentNode != 0) { if (mParentIsTagPoint) { TagPoint* tp = static_cast<TagPoint*>(mParentNode); return tp->getParentEntity()->isInScene(); } else { SceneNode* sn = static_cast<SceneNode*>(mParentNode); return sn->isInSceneGraph(); } } else { return false; } } //----------------------------------------------------------------------- void MovableObject::_notifyMoved(void) { // Mark light list being dirty, simply decrease // counter by one for minimise overhead --mLightListUpdated; // Notify listener if exists if (mListener) { mListener->objectMoved(this); } } //----------------------------------------------------------------------- void MovableObject::setVisible(bool visible) { mVisible = visible; } //----------------------------------------------------------------------- bool MovableObject::getVisible(void) const { return mVisible; } //----------------------------------------------------------------------- bool MovableObject::isVisible(void) const { if (!mVisible || mBeyondFarDistance || mRenderingDisabled) return false; SceneManager* sm = Root::getSingleton()._getCurrentSceneManager(); if (sm && !(mVisibilityFlags & sm->_getCombinedVisibilityMask())) return false; return true; } //----------------------------------------------------------------------- void MovableObject::_notifyCurrentCamera(Camera* cam) { if (mParentNode) { if (cam->getUseRenderingDistance() && mUpperDistance > 0) { Real rad = getBoundingRadius(); Real squaredDepth = mParentNode->getSquaredViewDepth(cam->getLodCamera()); // Max distance to still render Real maxDist = mUpperDistance + rad; if (squaredDepth > Math::Sqr(maxDist)) { mBeyondFarDistance = true; } else { mBeyondFarDistance = false; } } else { mBeyondFarDistance = false; } // Construct event object MovableObjectLodChangedEvent evt; evt.movableObject = this; evt.camera = cam; // Notify lod event listeners cam->getSceneManager()->_notifyMovableObjectLodChanged(evt); } mRenderingDisabled = mListener && !mListener->objectRendering(this, cam); } //----------------------------------------------------------------------- void MovableObject::setRenderQueueGroup(uint8 queueID) { assert(queueID <= RENDER_QUEUE_MAX && "Render queue out of range!"); mRenderQueueID = queueID; mRenderQueueIDSet = true; } //----------------------------------------------------------------------- uint8 MovableObject::getRenderQueueGroup(void) const { return mRenderQueueID; } //----------------------------------------------------------------------- const Matrix4& MovableObject::_getParentNodeFullTransform(void) const { if(mParentNode) { // object attached to a sceneNode return mParentNode->_getFullTransform(); } // fallback return Matrix4::IDENTITY; } //----------------------------------------------------------------------- const AxisAlignedBox& MovableObject::getWorldBoundingBox(bool derive) const { if (derive) { mWorldAABB = this->getBoundingBox(); mWorldAABB.transformAffine(_getParentNodeFullTransform()); } return mWorldAABB; } //----------------------------------------------------------------------- const Sphere& MovableObject::getWorldBoundingSphere(bool derive) const { if (derive) { mWorldBoundingSphere.setRadius(getBoundingRadius()); mWorldBoundingSphere.setCenter(mParentNode->_getDerivedPosition()); } return mWorldBoundingSphere; } //----------------------------------------------------------------------- const LightList& MovableObject::queryLights(void) const { // Try listener first if (mListener) { const LightList* lightList = mListener->objectQueryLights(this); if (lightList) { return *lightList; } } // Query from parent entity if exists if (mParentIsTagPoint) { TagPoint* tp = static_cast<TagPoint*>(mParentNode); return tp->getParentEntity()->queryLights(); } if (mParentNode) { SceneNode* sn = static_cast<SceneNode*>(mParentNode); // Make sure we only update this only if need. ulong frame = sn->getCreator()->_getLightsDirtyCounter(); if (mLightListUpdated != frame) { mLightListUpdated = frame; sn->findLights(mLightList, this->getBoundingRadius(), this->getLightMask()); } } else { mLightList.clear(); } return mLightList; } //----------------------------------------------------------------------- ShadowCaster::ShadowRenderableListIterator MovableObject::getShadowVolumeRenderableIterator( ShadowTechnique shadowTechnique, const Light* light, HardwareIndexBufferSharedPtr* indexBuffer, bool extrudeVertices, Real extrusionDist, unsigned long flags ) { static ShadowRenderableList dummyList; return ShadowRenderableListIterator(dummyList.begin(), dummyList.end()); } //----------------------------------------------------------------------- const AxisAlignedBox& MovableObject::getLightCapBounds(void) const { // Same as original bounds return getWorldBoundingBox(); } //----------------------------------------------------------------------- const AxisAlignedBox& MovableObject::getDarkCapBounds(const Light& light, Real extrusionDist) const { // Extrude own light cap bounds mWorldDarkCapBounds = getLightCapBounds(); this->extrudeBounds(mWorldDarkCapBounds, light.getAs4DVector(), extrusionDist); return mWorldDarkCapBounds; } //----------------------------------------------------------------------- Real MovableObject::getPointExtrusionDistance(const Light* l) const { if (mParentNode) { return getExtrusionDistance(mParentNode->_getDerivedPosition(), l); } else { return 0; } } //----------------------------------------------------------------------- uint32 MovableObject::getTypeFlags(void) const { if (mCreator) { return mCreator->getTypeFlags(); } else { return 0xFFFFFFFF; } } //--------------------------------------------------------------------- void MovableObject::setLightMask(uint32 lightMask) { this->mLightMask = lightMask; //make sure to request a new light list from the scene manager if mask changed mLightListUpdated = 0; } //--------------------------------------------------------------------- class MORecvShadVisitor : public Renderable::Visitor { public: bool anyReceiveShadows; MORecvShadVisitor() : anyReceiveShadows(false) { } void visit(Renderable* rend, ushort lodIndex, bool isDebug, Any* pAny = 0) { anyReceiveShadows = anyReceiveShadows || rend->getTechnique()->getParent()->getReceiveShadows(); } }; //--------------------------------------------------------------------- bool MovableObject::getReceivesShadows() { MORecvShadVisitor visitor; visitRenderables(&visitor); return visitor.anyReceiveShadows; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- MovableObject* MovableObjectFactory::createInstance( const String& name, SceneManager* manager, const NameValuePairList* params) { MovableObject* m = createInstanceImpl(name, params); m->_notifyCreator(this); m->_notifyManager(manager); return m; } } <commit_msg>Tolerate Renderable::getTechnique returning null in MORecvShadVisitor::visit<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2006 Torus Knot Software Ltd Also see acknowledgements in Readme.html This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreMovableObject.h" #include "OgreSceneNode.h" #include "OgreTagPoint.h" #include "OgreLight.h" #include "OgreEntity.h" #include "OgreRoot.h" #include "OgreSceneManager.h" #include "OgreCamera.h" #include "OgreLodListener.h" namespace Ogre { //----------------------------------------------------------------------- //----------------------------------------------------------------------- uint32 MovableObject::msDefaultQueryFlags = 0xFFFFFFFF; uint32 MovableObject::msDefaultVisibilityFlags = 0xFFFFFFFF; //----------------------------------------------------------------------- MovableObject::MovableObject() : mCreator(0) , mManager(0) , mParentNode(0) , mParentIsTagPoint(false) , mVisible(true) , mDebugDisplay(false) , mUpperDistance(0) , mSquaredUpperDistance(0) , mBeyondFarDistance(false) , mRenderQueueID(RENDER_QUEUE_MAIN) , mRenderQueueIDSet(false) , mQueryFlags(msDefaultQueryFlags) , mVisibilityFlags(msDefaultVisibilityFlags) , mCastShadows(true) , mRenderingDisabled(false) , mListener(0) , mLightListUpdated(0) , mLightMask(0xFFFFFFFF) { } //----------------------------------------------------------------------- MovableObject::MovableObject(const String& name) : mName(name) , mCreator(0) , mManager(0) , mParentNode(0) , mParentIsTagPoint(false) , mVisible(true) , mDebugDisplay(false) , mUpperDistance(0) , mSquaredUpperDistance(0) , mBeyondFarDistance(false) , mRenderQueueID(RENDER_QUEUE_MAIN) , mRenderQueueIDSet(false) , mQueryFlags(msDefaultQueryFlags) , mVisibilityFlags(msDefaultVisibilityFlags) , mCastShadows(true) , mRenderingDisabled(false) , mListener(0) , mLightListUpdated(0) , mLightMask(0xFFFFFFFF) { } //----------------------------------------------------------------------- MovableObject::~MovableObject() { // Call listener (note, only called if there's something to do) if (mListener) { mListener->objectDestroyed(this); } if (mParentNode) { // detach from parent if (mParentIsTagPoint) { // May be we are a lod entity which not in the parent entity child object list, // call this method could safely ignore this case. static_cast<TagPoint*>(mParentNode)->getParentEntity()->detachObjectFromBone(this); } else { // May be we are a lod entity which not in the parent node child object list, // call this method could safely ignore this case. static_cast<SceneNode*>(mParentNode)->detachObject(this); } } } //----------------------------------------------------------------------- void MovableObject::_notifyAttached(Node* parent, bool isTagPoint) { assert(!mParentNode || !parent); bool different = (parent != mParentNode); mParentNode = parent; mParentIsTagPoint = isTagPoint; // Mark light list being dirty, simply decrease // counter by one for minimise overhead --mLightListUpdated; // Call listener (note, only called if there's something to do) if (mListener && different) { if (mParentNode) mListener->objectAttached(this); else mListener->objectDetached(this); } } //----------------------------------------------------------------------- Node* MovableObject::getParentNode(void) const { return mParentNode; } //----------------------------------------------------------------------- SceneNode* MovableObject::getParentSceneNode(void) const { if (mParentIsTagPoint) { TagPoint* tp = static_cast<TagPoint*>(mParentNode); return tp->getParentEntity()->getParentSceneNode(); } else { return static_cast<SceneNode*>(mParentNode); } } //----------------------------------------------------------------------- bool MovableObject::isAttached(void) const { return (mParentNode != 0); } //--------------------------------------------------------------------- void MovableObject::detachFromParent(void) { if (isAttached()) { if (mParentIsTagPoint) { TagPoint* tp = static_cast<TagPoint*>(mParentNode); tp->getParentEntity()->detachObjectFromBone(this); } else { SceneNode* sn = static_cast<SceneNode*>(mParentNode); sn->detachObject(this); } } } //----------------------------------------------------------------------- bool MovableObject::isInScene(void) const { if (mParentNode != 0) { if (mParentIsTagPoint) { TagPoint* tp = static_cast<TagPoint*>(mParentNode); return tp->getParentEntity()->isInScene(); } else { SceneNode* sn = static_cast<SceneNode*>(mParentNode); return sn->isInSceneGraph(); } } else { return false; } } //----------------------------------------------------------------------- void MovableObject::_notifyMoved(void) { // Mark light list being dirty, simply decrease // counter by one for minimise overhead --mLightListUpdated; // Notify listener if exists if (mListener) { mListener->objectMoved(this); } } //----------------------------------------------------------------------- void MovableObject::setVisible(bool visible) { mVisible = visible; } //----------------------------------------------------------------------- bool MovableObject::getVisible(void) const { return mVisible; } //----------------------------------------------------------------------- bool MovableObject::isVisible(void) const { if (!mVisible || mBeyondFarDistance || mRenderingDisabled) return false; SceneManager* sm = Root::getSingleton()._getCurrentSceneManager(); if (sm && !(mVisibilityFlags & sm->_getCombinedVisibilityMask())) return false; return true; } //----------------------------------------------------------------------- void MovableObject::_notifyCurrentCamera(Camera* cam) { if (mParentNode) { if (cam->getUseRenderingDistance() && mUpperDistance > 0) { Real rad = getBoundingRadius(); Real squaredDepth = mParentNode->getSquaredViewDepth(cam->getLodCamera()); // Max distance to still render Real maxDist = mUpperDistance + rad; if (squaredDepth > Math::Sqr(maxDist)) { mBeyondFarDistance = true; } else { mBeyondFarDistance = false; } } else { mBeyondFarDistance = false; } // Construct event object MovableObjectLodChangedEvent evt; evt.movableObject = this; evt.camera = cam; // Notify lod event listeners cam->getSceneManager()->_notifyMovableObjectLodChanged(evt); } mRenderingDisabled = mListener && !mListener->objectRendering(this, cam); } //----------------------------------------------------------------------- void MovableObject::setRenderQueueGroup(uint8 queueID) { assert(queueID <= RENDER_QUEUE_MAX && "Render queue out of range!"); mRenderQueueID = queueID; mRenderQueueIDSet = true; } //----------------------------------------------------------------------- uint8 MovableObject::getRenderQueueGroup(void) const { return mRenderQueueID; } //----------------------------------------------------------------------- const Matrix4& MovableObject::_getParentNodeFullTransform(void) const { if(mParentNode) { // object attached to a sceneNode return mParentNode->_getFullTransform(); } // fallback return Matrix4::IDENTITY; } //----------------------------------------------------------------------- const AxisAlignedBox& MovableObject::getWorldBoundingBox(bool derive) const { if (derive) { mWorldAABB = this->getBoundingBox(); mWorldAABB.transformAffine(_getParentNodeFullTransform()); } return mWorldAABB; } //----------------------------------------------------------------------- const Sphere& MovableObject::getWorldBoundingSphere(bool derive) const { if (derive) { mWorldBoundingSphere.setRadius(getBoundingRadius()); mWorldBoundingSphere.setCenter(mParentNode->_getDerivedPosition()); } return mWorldBoundingSphere; } //----------------------------------------------------------------------- const LightList& MovableObject::queryLights(void) const { // Try listener first if (mListener) { const LightList* lightList = mListener->objectQueryLights(this); if (lightList) { return *lightList; } } // Query from parent entity if exists if (mParentIsTagPoint) { TagPoint* tp = static_cast<TagPoint*>(mParentNode); return tp->getParentEntity()->queryLights(); } if (mParentNode) { SceneNode* sn = static_cast<SceneNode*>(mParentNode); // Make sure we only update this only if need. ulong frame = sn->getCreator()->_getLightsDirtyCounter(); if (mLightListUpdated != frame) { mLightListUpdated = frame; sn->findLights(mLightList, this->getBoundingRadius(), this->getLightMask()); } } else { mLightList.clear(); } return mLightList; } //----------------------------------------------------------------------- ShadowCaster::ShadowRenderableListIterator MovableObject::getShadowVolumeRenderableIterator( ShadowTechnique shadowTechnique, const Light* light, HardwareIndexBufferSharedPtr* indexBuffer, bool extrudeVertices, Real extrusionDist, unsigned long flags ) { static ShadowRenderableList dummyList; return ShadowRenderableListIterator(dummyList.begin(), dummyList.end()); } //----------------------------------------------------------------------- const AxisAlignedBox& MovableObject::getLightCapBounds(void) const { // Same as original bounds return getWorldBoundingBox(); } //----------------------------------------------------------------------- const AxisAlignedBox& MovableObject::getDarkCapBounds(const Light& light, Real extrusionDist) const { // Extrude own light cap bounds mWorldDarkCapBounds = getLightCapBounds(); this->extrudeBounds(mWorldDarkCapBounds, light.getAs4DVector(), extrusionDist); return mWorldDarkCapBounds; } //----------------------------------------------------------------------- Real MovableObject::getPointExtrusionDistance(const Light* l) const { if (mParentNode) { return getExtrusionDistance(mParentNode->_getDerivedPosition(), l); } else { return 0; } } //----------------------------------------------------------------------- uint32 MovableObject::getTypeFlags(void) const { if (mCreator) { return mCreator->getTypeFlags(); } else { return 0xFFFFFFFF; } } //--------------------------------------------------------------------- void MovableObject::setLightMask(uint32 lightMask) { this->mLightMask = lightMask; //make sure to request a new light list from the scene manager if mask changed mLightListUpdated = 0; } //--------------------------------------------------------------------- class MORecvShadVisitor : public Renderable::Visitor { public: bool anyReceiveShadows; MORecvShadVisitor() : anyReceiveShadows(false) { } void visit(Renderable* rend, ushort lodIndex, bool isDebug, Any* pAny = 0) { anyReceiveShadows = anyReceiveShadows || (!rend->getTechnique() || rend->getTechnique()->getParent()->getReceiveShadows()); } }; //--------------------------------------------------------------------- bool MovableObject::getReceivesShadows() { MORecvShadVisitor visitor; visitRenderables(&visitor); return visitor.anyReceiveShadows; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- MovableObject* MovableObjectFactory::createInstance( const String& name, SceneManager* manager, const NameValuePairList* params) { MovableObject* m = createInstanceImpl(name, params); m->_notifyCreator(this); m->_notifyManager(manager); return m; } } <|endoftext|>
<commit_before>#include <cstdio> #include <queue> #include <iostream> using namespace std; struct inf { int t, mi, ma, i; } inp; struct pri { int n, d, t; }n, np; struct vinf { int d, t; }; struct hp2 { bool operator () (pri i, pri j) { if(i.d==j.d) { return i.t<j.t; } else return i.d>j.d; } }; int nodes, edges, optim, f, sof, l, r, m; vector<inf> nlist[1055]; int olist[555]; vinf vis[1055]; priority_queue<pri, vector<pri>, hp2> viser; bool tester(int far) { //cout<<far<<endl; //Try the tying situation. That may help. for(int i=1; i<=nodes; i++) vis[i].d=-1, vis[i].t=-1; np.n=1; np.d=0; np.t=1; vis[np.n].d=0; vis[np.n].t=1; viser.push(np); while (!viser.empty()) { n=viser.top(); viser.pop(); if(vis[n.n].d<n.d || vis[n.n].t!=n.t) continue; if(n.t==-1) { for(int i=0; i<nlist[n.n].size(); i++) { if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>n.d+nlist[n.n][i].ma) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].ma; vis[nlist[n.n][i].t].t=-1; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].ma; np.t=-1; viser.push(np); } } } else if(n.t==0) { for(int i=0; i<nlist[n.n].size(); i++) { if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>=n.d+nlist[n.n][i].mi) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].mi; vis[nlist[n.n][i].t].t=0; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].mi; np.t=0; viser.push(np); } } } else { for(int i=0; i<nlist[n.n].size(); i++) { if(n.t>far) { //cout<<n.n<<"1"<<nlist[n.n][i].t<<endl; if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>=n.d+nlist[n.n][i].mi) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].mi; vis[nlist[n.n][i].t].t=0; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].mi; np.t=0; viser.push(np); } } else if(nlist[n.n][i].i==olist[n.t]) { //cout<<n.n<<"2"<<nlist[n.n][i].t<<endl; if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>=n.d+nlist[n.n][i].mi) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].mi; vis[nlist[n.n][i].t].t=n.t+1; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].mi; np.t=n.t+1; viser.push(np); } } else { //cout<<n.n<<"3"<<nlist[n.n][i].t<<endl; if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>n.d+nlist[n.n][i].ma) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].ma; vis[nlist[n.n][i].t].t=-1; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].ma; np.t=-1; viser.push(np); } } } } } //0 means short, -1 long, and anything positive means part of the olist /*for(int i=1; i<=nodes; i++) { cout<<i<<" "<<vis[i].d<<" "<<vis[i].t<<endl; }*/ if(vis[2].t==0 || vis[2].t==far+1) return true; return false; } int main() { scanf("%d%d%d", &nodes, &edges, &optim); for(int i=1; i<=edges; i++) { scanf("%d%d%d%d", &f, &inp.t, &inp.mi, &inp.ma); inp.i=i; nlist[f].push_back(inp); } for(int i=1; i<=optim; i++) scanf("%d", &olist[i]); //Can probably remove this l=0; r=optim; while(l<=r) { m=(l+r)/2; if(tester(m)) { l=m+1; sof=m; } else r=m-1; } if(sof==optim) printf("Karel Obscuro le gustan los grafos\n"); else printf("%d\n", olist[sof+1]); return 0; } /* 4 5 3 1 2 100 1000 1 2 500 1000 2 2 1 1 1 2 1000 5000 1 2 1000 1000 2 3 3 */ <commit_msg>Update karel-obscuro-vs-karel.cpp<commit_after>//https://omegaup.com/arena/problem/karel-obscuro-vs-karel #include <cstdio> #include <queue> #include <iostream> using namespace std; struct inf { int t, mi, ma, i; } inp; struct pri { int n, d, t; }n, np; struct vinf { int d, t; }; struct hp2 { bool operator () (pri i, pri j) { if(i.d==j.d) { return i.t<j.t; } else return i.d>j.d; } }; int nodes, edges, optim, f, sof, l, r, m; vector<inf> nlist[1055]; int olist[555]; vinf vis[1055]; priority_queue<pri, vector<pri>, hp2> viser; bool tester(int far) { //cout<<far<<endl; //Try the tying situation. That may help. for(int i=1; i<=nodes; i++) vis[i].d=-1, vis[i].t=-1; np.n=1; np.d=0; np.t=1; vis[np.n].d=0; vis[np.n].t=1; viser.push(np); while (!viser.empty()) { n=viser.top(); viser.pop(); if(vis[n.n].d<n.d || vis[n.n].t!=n.t) continue; if(n.t==-1) { for(int i=0; i<nlist[n.n].size(); i++) { if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>n.d+nlist[n.n][i].ma) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].ma; vis[nlist[n.n][i].t].t=-1; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].ma; np.t=-1; viser.push(np); } } } else if(n.t==0) { for(int i=0; i<nlist[n.n].size(); i++) { if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>=n.d+nlist[n.n][i].mi) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].mi; vis[nlist[n.n][i].t].t=0; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].mi; np.t=0; viser.push(np); } } } else { for(int i=0; i<nlist[n.n].size(); i++) { if(n.t>far) { //cout<<n.n<<"1"<<nlist[n.n][i].t<<endl; if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>=n.d+nlist[n.n][i].mi) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].mi; vis[nlist[n.n][i].t].t=0; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].mi; np.t=0; viser.push(np); } } else if(nlist[n.n][i].i==olist[n.t]) { //cout<<n.n<<"2"<<nlist[n.n][i].t<<endl; if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>=n.d+nlist[n.n][i].mi) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].mi; vis[nlist[n.n][i].t].t=n.t+1; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].mi; np.t=n.t+1; viser.push(np); } } else { //cout<<n.n<<"3"<<nlist[n.n][i].t<<endl; if(vis[nlist[n.n][i].t].d==-1 || vis[nlist[n.n][i].t].d>n.d+nlist[n.n][i].ma) { vis[nlist[n.n][i].t].d=n.d+nlist[n.n][i].ma; vis[nlist[n.n][i].t].t=-1; np.n=nlist[n.n][i].t; np.d=n.d+nlist[n.n][i].ma; np.t=-1; viser.push(np); } } } } } //0 means short, -1 long, and anything positive means part of the olist /*for(int i=1; i<=nodes; i++) { cout<<i<<" "<<vis[i].d<<" "<<vis[i].t<<endl; }*/ if(vis[2].t==0 || vis[2].t==far+1) return true; return false; } int main() { scanf("%d%d%d", &nodes, &edges, &optim); for(int i=1; i<=edges; i++) { scanf("%d%d%d%d", &f, &inp.t, &inp.mi, &inp.ma); inp.i=i; nlist[f].push_back(inp); } for(int i=1; i<=optim; i++) scanf("%d", &olist[i]); //Can probably remove this l=0; r=optim; while(l<=r) { m=(l+r)/2; if(tester(m)) { l=m+1; sof=m; } else r=m-1; } if(sof==optim) printf("Karel Obscuro le gustan los grafos\n"); else printf("%d\n", olist[sof+1]); return 0; } /* 4 5 3 1 2 100 1000 1 2 500 1000 2 2 1 1 1 2 1000 5000 1 2 1000 1000 2 3 3 */ <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "validationinterface.h" #include <unordered_map> #include <boost/signals2/signal.hpp> struct ValidationInterfaceConnections { boost::signals2::scoped_connection UpdatedBlockTip; boost::signals2::scoped_connection SyncTransaction; boost::signals2::scoped_connection NotifyTransactionLock; boost::signals2::scoped_connection UpdatedTransaction; boost::signals2::scoped_connection SetBestChain; boost::signals2::scoped_connection Broadcast; boost::signals2::scoped_connection BlockChecked; boost::signals2::scoped_connection BlockFound; boost::signals2::scoped_connection ChainTip; }; struct MainSignalsInstance { // XX42 boost::signals2::signal<void(const uint256&)> EraseTransaction; /** Notifies listeners of updated block chain tip */ boost::signals2::signal<void (const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)> UpdatedBlockTip; /** A posInBlock value for SyncTransaction which indicates the transaction was conflicted, disconnected, or not in a block */ static const int SYNC_TRANSACTION_NOT_IN_BLOCK = -1; /** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */ boost::signals2::signal<void (const CTransaction &, const CBlockIndex *pindex, int posInBlock)> SyncTransaction; /** Notifies listeners of an updated transaction lock without new data. */ boost::signals2::signal<void (const CTransaction &)> NotifyTransactionLock; /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */ boost::signals2::signal<bool (const uint256 &)> UpdatedTransaction; /** Notifies listeners of a new active block chain. */ boost::signals2::signal<void (const CBlockLocator &)> SetBestChain; /** Tells listeners to broadcast their data. */ boost::signals2::signal<void (CConnman* connman)> Broadcast; /** Notifies listeners of a block validation result */ boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked; /** Notifies listeners that a block has been successfully mined */ boost::signals2::signal<void (const uint256 &)> BlockFound; /** Notifies listeners of a change to the tip of the active block chain. */ boost::signals2::signal<void (const CBlockIndex *, const CBlock *, Optional<SaplingMerkleTree>)> ChainTip; std::unordered_map<CValidationInterface*, ValidationInterfaceConnections> m_connMainSignals; }; static CMainSignals g_signals; CMainSignals::CMainSignals() { m_internals.reset(new MainSignalsInstance()); } CMainSignals& GetMainSignals() { return g_signals; } void RegisterValidationInterface(CValidationInterface* pwalletIn) { ValidationInterfaceConnections& conns = g_signals.m_internals->m_connMainSignals[pwalletIn]; conns.UpdatedBlockTip = g_signals.m_internals->UpdatedBlockTip.connect(std::bind(&CValidationInterface::UpdatedBlockTip, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); conns.SyncTransaction = g_signals.m_internals->SyncTransaction.connect(std::bind(&CValidationInterface::SyncTransaction, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); conns.ChainTip = g_signals.m_internals->ChainTip.connect(std::bind(&CValidationInterface::ChainTip, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); conns.NotifyTransactionLock = g_signals.m_internals->NotifyTransactionLock.connect(std::bind(&CValidationInterface::NotifyTransactionLock, pwalletIn, std::placeholders::_1)); conns.UpdatedTransaction = g_signals.m_internals->UpdatedTransaction.connect(std::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, std::placeholders::_1)); conns.SetBestChain = g_signals.m_internals->SetBestChain.connect(std::bind(&CValidationInterface::SetBestChain, pwalletIn, std::placeholders::_1)); conns.Broadcast = g_signals.m_internals->Broadcast.connect(std::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, std::placeholders::_1)); conns.BlockChecked = g_signals.m_internals->BlockChecked.connect(std::bind(&CValidationInterface::BlockChecked, pwalletIn, std::placeholders::_1, std::placeholders::_2)); conns.BlockFound = g_signals.m_internals->BlockFound.connect(std::bind(&CValidationInterface::ResetRequestCount, pwalletIn, std::placeholders::_1)); } void UnregisterValidationInterface(CValidationInterface* pwalletIn) { g_signals.m_internals->m_connMainSignals.erase(pwalletIn); } void UnregisterAllValidationInterfaces() { if (!g_signals.m_internals) { return; } g_signals.m_internals->m_connMainSignals.clear(); } void CMainSignals::UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) { m_internals->UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload); } void CMainSignals::SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int posInBlock) { m_internals->SyncTransaction(tx, pindex, posInBlock); } void CMainSignals::NotifyTransactionLock(const CTransaction& tx) { m_internals->NotifyTransactionLock(tx); } void CMainSignals::UpdatedTransaction(const uint256& hash) { m_internals->UpdatedTransaction(hash); } void CMainSignals::SetBestChain(const CBlockLocator& locator) { m_internals->SetBestChain(locator); } void CMainSignals::Broadcast(CConnman* connman) { m_internals->Broadcast(connman); } void CMainSignals::BlockChecked(const CBlock& block, const CValidationState& state) { m_internals->BlockChecked(block, state); } void CMainSignals::BlockFound(const uint256& hash) { m_internals->BlockFound(hash); } void CMainSignals::ChainTip(const CBlockIndex* pindex, const CBlock* block, Optional<SaplingMerkleTree> tree) { m_internals->ChainTip(pindex, block, tree); }<commit_msg>Check m_internals in UnregisterValidationInterface<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "validationinterface.h" #include <unordered_map> #include <boost/signals2/signal.hpp> struct ValidationInterfaceConnections { boost::signals2::scoped_connection UpdatedBlockTip; boost::signals2::scoped_connection SyncTransaction; boost::signals2::scoped_connection NotifyTransactionLock; boost::signals2::scoped_connection UpdatedTransaction; boost::signals2::scoped_connection SetBestChain; boost::signals2::scoped_connection Broadcast; boost::signals2::scoped_connection BlockChecked; boost::signals2::scoped_connection BlockFound; boost::signals2::scoped_connection ChainTip; }; struct MainSignalsInstance { // XX42 boost::signals2::signal<void(const uint256&)> EraseTransaction; /** Notifies listeners of updated block chain tip */ boost::signals2::signal<void (const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)> UpdatedBlockTip; /** A posInBlock value for SyncTransaction which indicates the transaction was conflicted, disconnected, or not in a block */ static const int SYNC_TRANSACTION_NOT_IN_BLOCK = -1; /** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */ boost::signals2::signal<void (const CTransaction &, const CBlockIndex *pindex, int posInBlock)> SyncTransaction; /** Notifies listeners of an updated transaction lock without new data. */ boost::signals2::signal<void (const CTransaction &)> NotifyTransactionLock; /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */ boost::signals2::signal<bool (const uint256 &)> UpdatedTransaction; /** Notifies listeners of a new active block chain. */ boost::signals2::signal<void (const CBlockLocator &)> SetBestChain; /** Tells listeners to broadcast their data. */ boost::signals2::signal<void (CConnman* connman)> Broadcast; /** Notifies listeners of a block validation result */ boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked; /** Notifies listeners that a block has been successfully mined */ boost::signals2::signal<void (const uint256 &)> BlockFound; /** Notifies listeners of a change to the tip of the active block chain. */ boost::signals2::signal<void (const CBlockIndex *, const CBlock *, Optional<SaplingMerkleTree>)> ChainTip; std::unordered_map<CValidationInterface*, ValidationInterfaceConnections> m_connMainSignals; }; static CMainSignals g_signals; CMainSignals::CMainSignals() { m_internals.reset(new MainSignalsInstance()); } CMainSignals& GetMainSignals() { return g_signals; } void RegisterValidationInterface(CValidationInterface* pwalletIn) { ValidationInterfaceConnections& conns = g_signals.m_internals->m_connMainSignals[pwalletIn]; conns.UpdatedBlockTip = g_signals.m_internals->UpdatedBlockTip.connect(std::bind(&CValidationInterface::UpdatedBlockTip, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); conns.SyncTransaction = g_signals.m_internals->SyncTransaction.connect(std::bind(&CValidationInterface::SyncTransaction, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); conns.ChainTip = g_signals.m_internals->ChainTip.connect(std::bind(&CValidationInterface::ChainTip, pwalletIn, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); conns.NotifyTransactionLock = g_signals.m_internals->NotifyTransactionLock.connect(std::bind(&CValidationInterface::NotifyTransactionLock, pwalletIn, std::placeholders::_1)); conns.UpdatedTransaction = g_signals.m_internals->UpdatedTransaction.connect(std::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, std::placeholders::_1)); conns.SetBestChain = g_signals.m_internals->SetBestChain.connect(std::bind(&CValidationInterface::SetBestChain, pwalletIn, std::placeholders::_1)); conns.Broadcast = g_signals.m_internals->Broadcast.connect(std::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn, std::placeholders::_1)); conns.BlockChecked = g_signals.m_internals->BlockChecked.connect(std::bind(&CValidationInterface::BlockChecked, pwalletIn, std::placeholders::_1, std::placeholders::_2)); conns.BlockFound = g_signals.m_internals->BlockFound.connect(std::bind(&CValidationInterface::ResetRequestCount, pwalletIn, std::placeholders::_1)); } void UnregisterValidationInterface(CValidationInterface* pwalletIn) { if (g_signals.m_internals) { g_signals.m_internals->m_connMainSignals.erase(pwalletIn); } } void UnregisterAllValidationInterfaces() { if (!g_signals.m_internals) { return; } g_signals.m_internals->m_connMainSignals.clear(); } void CMainSignals::UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) { m_internals->UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload); } void CMainSignals::SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int posInBlock) { m_internals->SyncTransaction(tx, pindex, posInBlock); } void CMainSignals::NotifyTransactionLock(const CTransaction& tx) { m_internals->NotifyTransactionLock(tx); } void CMainSignals::UpdatedTransaction(const uint256& hash) { m_internals->UpdatedTransaction(hash); } void CMainSignals::SetBestChain(const CBlockLocator& locator) { m_internals->SetBestChain(locator); } void CMainSignals::Broadcast(CConnman* connman) { m_internals->Broadcast(connman); } void CMainSignals::BlockChecked(const CBlock& block, const CValidationState& state) { m_internals->BlockChecked(block, state); } void CMainSignals::BlockFound(const uint256& hash) { m_internals->BlockFound(hash); } void CMainSignals::ChainTip(const CBlockIndex* pindex, const CBlock* block, Optional<SaplingMerkleTree> tree) { m_internals->ChainTip(pindex, block, tree); }<|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <fstream> #include <iostream> #include <Core/Algorithms/DataIO/ReadMatrix.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Datatypes/SparseRowMatrix.h> #include <Core/Datatypes/MatrixIO.h> #include <Core/Algorithms/DataIO/EigenMatrixFromScirunAsciiFormatConverter.h> #include <Core/Algorithms/Base/AlgorithmPreconditions.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> #include <boost/filesystem.hpp> #include <boost/thread.hpp> using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::DataIO; using namespace SCIRun::Core::Datatypes; namespace SCIRun { namespace Core { namespace Algorithms { namespace DataIO { class ReadMatrixAlgorithmPrivate { public: static boost::mutex fileCheckMutex_; }; boost::mutex ReadMatrixAlgorithmPrivate::fileCheckMutex_; }}}} ReadMatrixAlgorithm::ReadMatrixAlgorithm() { addParameter(Variables::Filename, std::string("")); } ReadMatrixAlgorithm::Outputs ReadMatrixAlgorithm::run(const ReadMatrixAlgorithm::Parameters& filename) const { { //BOOST FILESYSTEM BUG: it is not thread-safe. TODO: need to meld this locking code into the ENSURE_FILE_EXISTS macro. boost::lock_guard<boost::mutex> guard(ReadMatrixAlgorithmPrivate::fileCheckMutex_); ENSURE_FILE_EXISTS(filename); } if (boost::filesystem::extension(filename) == ".txt") { std::ifstream reader(filename.c_str()); DenseMatrixHandle matrix(boost::make_shared<DenseMatrix>()); reader >> *matrix; //std::cout << "ALGO OUTPUT:\n" << *matrix << std::endl; return matrix; } else if (boost::filesystem::extension(filename) == ".mat") { status("FOUND .mat file: assuming is SCIRUNv4 Matrix format."); PiostreamPtr stream = auto_istream(filename); if (!stream) { THROW_ALGORITHM_PROCESSING_ERROR("Error reading file '" + filename + "'."); } MatrixHandle matrix; Pio(*stream, matrix); if (!matrix) THROW_ALGORITHM_PROCESSING_ERROR("Import failed."); return matrix; } THROW_ALGORITHM_INPUT_ERROR("Unknown matrix file format"); } AlgorithmOutput ReadMatrixAlgorithm::run_generic(const AlgorithmInput& input) const { auto filename = get(Variables::Filename).getString(); auto file = run(filename); AlgorithmOutput output; output[Variables::MatrixLoaded] = file; return output; } <commit_msg>Temporary bug fix<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <fstream> #include <iostream> #include <Core/Algorithms/DataIO/ReadMatrix.h> #include <Core/Datatypes/DenseMatrix.h> #include <Core/Datatypes/SparseRowMatrix.h> #include <Core/Datatypes/MatrixIO.h> #include <Core/Algorithms/DataIO/EigenMatrixFromScirunAsciiFormatConverter.h> #include <Core/Algorithms/Base/AlgorithmPreconditions.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> #include <boost/filesystem.hpp> #include <boost/thread.hpp> using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::DataIO; using namespace SCIRun::Core::Datatypes; namespace SCIRun { namespace Core { namespace Algorithms { namespace DataIO { class ReadMatrixAlgorithmPrivate { public: static boost::mutex fileCheckMutex_; }; boost::mutex ReadMatrixAlgorithmPrivate::fileCheckMutex_; }}}} ReadMatrixAlgorithm::ReadMatrixAlgorithm() { addParameter(Variables::Filename, std::string("")); } ReadMatrixAlgorithm::Outputs ReadMatrixAlgorithm::run(const ReadMatrixAlgorithm::Parameters& filename) const { { std::cout << "locking mutex " << filename << std::endl; //TODO: I think putting this here avoids a deadlock/crash...but it will be moot once boost is upgraded. //BOOST FILESYSTEM BUG: it is not thread-safe. TODO: need to meld this locking code into the ENSURE_FILE_EXISTS macro. boost::lock_guard<boost::mutex> guard(ReadMatrixAlgorithmPrivate::fileCheckMutex_); ENSURE_FILE_EXISTS(filename); } if (boost::filesystem::extension(filename) == ".txt") { std::ifstream reader(filename.c_str()); DenseMatrixHandle matrix(boost::make_shared<DenseMatrix>()); reader >> *matrix; //std::cout << "ALGO OUTPUT:\n" << *matrix << std::endl; return matrix; } else if (boost::filesystem::extension(filename) == ".mat") { status("FOUND .mat file: assuming is SCIRUNv4 Matrix format."); PiostreamPtr stream = auto_istream(filename); if (!stream) { THROW_ALGORITHM_PROCESSING_ERROR("Error reading file '" + filename + "'."); } MatrixHandle matrix; Pio(*stream, matrix); if (!matrix) THROW_ALGORITHM_PROCESSING_ERROR("Import failed."); return matrix; } THROW_ALGORITHM_INPUT_ERROR("Unknown matrix file format"); } AlgorithmOutput ReadMatrixAlgorithm::run_generic(const AlgorithmInput& input) const { auto filename = get(Variables::Filename).getString(); auto file = run(filename); AlgorithmOutput output; output[Variables::MatrixLoaded] = file; return output; } <|endoftext|>
<commit_before><commit_msg>removed double definition of default template in sub_block<commit_after><|endoftext|>
<commit_before>#include <chrono> #include <thread> #include "SDL.h" #include "app.h" using namespace app; void App::mainLoop() { int i = 0; bool finished = false; bool leftMouseButtonDown = false; SDL_Event event = SDL_Event({ 0 }); std::chrono::system_clock::time_point now, frameEnd; std::chrono::microseconds frameTime = std::chrono::microseconds((long)(1000000.0/60.0)); while (!finished) { now = std::chrono::system_clock::now(); frameEnd = now + std::chrono::microseconds(frameTime); SDL_UpdateTexture(texture, NULL, pixels, 640 * sizeof(Uint32)); while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: finished = true; break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: finished = true; break; } case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT) leftMouseButtonDown = false; break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) leftMouseButtonDown = true; case SDL_MOUSEMOTION: if (leftMouseButtonDown) { int mouseX = event.motion.x; int mouseY = event.motion.y; pixels[mouseY * 640 + mouseX] = 0; } break; } } SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); std::this_thread::sleep_until(frameEnd); } } <commit_msg>Removed frame timer for performance<commit_after>#include <chrono> #include <thread> #include "SDL.h" #include "app.h" using namespace app; void App::mainLoop() { int i = 0; bool finished = false; bool leftMouseButtonDown = false; SDL_Event event = SDL_Event({ 0 }); std::chrono::system_clock::time_point now, frameEnd; std::chrono::microseconds frameTime = std::chrono::microseconds((long)(1000000.0/60.0)); while (!finished) { now = std::chrono::system_clock::now(); frameEnd = now + std::chrono::microseconds(frameTime); SDL_UpdateTexture(texture, NULL, pixels, 640 * sizeof(Uint32)); while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: finished = true; break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_ESCAPE: finished = true; break; } case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT) leftMouseButtonDown = false; break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) leftMouseButtonDown = true; case SDL_MOUSEMOTION: if (leftMouseButtonDown) { int mouseX = event.motion.x; int mouseY = event.motion.y; pixels[mouseY * 640 + mouseX] = 0; } break; } } SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); //std::this_thread::sleep_until(frameEnd); } } <|endoftext|>
<commit_before>#include <rendering/texture_2d.h> #include <unordered_map> namespace rendering { namespace { struct texture_format_traits { GLint internalformat; GLenum format; GLenum type; }; std::unordered_map<texture_2d::texture_format, texture_format_traits> format_traits = { { texture_2d::TEXTURE_FORMAT_RGBA8, {GL_RGBA8, GL_RGBA, GL_BYTE}}, { texture_2d::TEXTURE_FORMAT_RG16F, {GL_RG16F, GL_RG, GL_HALF_FLOAT}}, { texture_2d::TEXTURE_FORMAT_R8I, {GL_R8I, GL_RED_INTEGER, GL_BYTE}} }; } // unnamed namespace texture_2d::texture_2d(const util::extent& extent, texture_format format, const void *data) { glGenTextures(1, &tex); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, tex); auto traits = format_traits[format]; glTexImage2D(GL_TEXTURE_2D, 0, format, GLsizei(extent.width), GLsizei(extent.height), 0, traits.format, traits.type, data); GL_CHECK(); glActiveTexture(GL_TEXTURE0); } } // namespace rendering <commit_msg>use format traits to determine internalformat<commit_after>#include <rendering/texture_2d.h> #include <unordered_map> namespace rendering { namespace { struct texture_format_traits { GLint internalformat; GLenum format; GLenum type; }; std::unordered_map<texture_2d::texture_format, texture_format_traits> format_traits = { { texture_2d::TEXTURE_FORMAT_RGBA8, {GL_RGBA8, GL_RGBA, GL_BYTE}}, { texture_2d::TEXTURE_FORMAT_RG16F, {GL_RG16F, GL_RG, GL_HALF_FLOAT}}, { texture_2d::TEXTURE_FORMAT_R8I, {GL_R8I, GL_RED_INTEGER, GL_BYTE}} }; } // unnamed namespace texture_2d::texture_2d(const util::extent& extent, texture_format format, const void *data) { glGenTextures(1, &tex); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, tex); auto traits = format_traits[format]; glTexImage2D(GL_TEXTURE_2D, 0, traits.internalformat, GLsizei(extent.width), GLsizei(extent.height), 0, traits.format, traits.type, data); GL_CHECK(); glActiveTexture(GL_TEXTURE0); } } // namespace rendering <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dp_misc.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-04-13 12:07:02 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "dp_misc.h" #include "rtl/uri.hxx" #include "rtl/digest.h" #include "osl/file.hxx" #include "osl/pipe.hxx" #include "com/sun/star/util/XMacroExpander.hpp" using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using ::rtl::OUString; namespace dp_misc { //============================================================================== OUString expand_reg_url( OUString const & url, Reference< XComponentContext > const & xContext ) { Reference< util::XMacroExpander > xMacroExpander( xContext->getValueByName( OUSTR("/singletons/com.sun.star.util.theMacroExpander") ), UNO_QUERY_THROW ); if (url.matchIgnoreAsciiCaseAsciiL( RTL_CONSTASCII_STRINGPARAM("vnd.sun.star.expand:") )) { // cut protocol: OUString macro( url.copy( sizeof ("vnd.sun.star.expand:") -1 ) ); // decode uric class chars: macro = ::rtl::Uri::decode( macro, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 ); // expand macro string: OUString ret( xMacroExpander->expandMacros( macro ) ); // #if OSL_DEBUG_LEVEL > 1 // { // OUStringBuffer buf( 128 ); // buf.appendAscii( // RTL_CONSTASCII_STRINGPARAM(__FILE__" expand_reg_url(): ") ); // buf.append( url ); // buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" => ") ); // buf.append( macro ); // buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" => ") ); // buf.append( ret ); // OString cstr( // OUStringToOString( // buf.makeStringAndClear(), osl_getThreadTextEncoding() ) ); // OSL_TRACE( "%s", cstr.getStr() ); // } // #endif return ret; } else { return url; } } enum t_status { RUNNING, NOT_RUNNING, INIT_ME }; //============================================================================== bool office_is_running( Reference< XComponentContext > const & xContext ) { static t_status s_status = INIT_ME; if (s_status == INIT_ME) { Reference< util::XMacroExpander > xMacroExpander( xContext->getValueByName( OUSTR("/singletons/com.sun.star.util.theMacroExpander") ), UNO_QUERY_THROW ); OUString user_path( xMacroExpander->expandMacros( OUSTR( "${$SYSBINDIR/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}") ) ); // normalize path: ::osl::FileStatus status( FileStatusMask_FileURL ); ::osl::DirectoryItem dirItem; if (::osl::DirectoryItem::get( user_path, dirItem ) != ::osl::DirectoryItem::E_None || dirItem.getFileStatus( status ) != ::osl::DirectoryItem::E_None || !status.isValid( FileStatusMask_FileURL ) || ::osl::FileBase::getAbsoluteFileURL( OUString(), status.getFileURL(), user_path ) != ::osl::FileBase::E_None) { throw RuntimeException( OUSTR("Cannot normalize path ") + user_path, 0 ); } rtlDigest digest = rtl_digest_create( rtl_Digest_AlgorithmMD5 ); if (digest <= 0) { throw RuntimeException( OUSTR("cannot get digest rtl_Digest_AlgorithmMD5!"), 0 ); } sal_uInt8 const * data = reinterpret_cast< sal_uInt8 const * >(user_path.getStr()); sal_Size size = (user_path.getLength() * sizeof (sal_Unicode)); sal_uInt32 md5_key_len = rtl_digest_queryLength( digest ); sal_uInt8 * md5_buf = new sal_uInt8 [ md5_key_len ]; rtl_digest_init( digest, data, static_cast< sal_uInt32 >(size) ); rtl_digest_update( digest, data, static_cast< sal_uInt32 >(size) ); rtl_digest_get( digest, md5_buf, md5_key_len ); rtl_digest_destroy( digest ); // create hex-value string from the MD5 value to keep // the string size minimal ::rtl::OUStringBuffer buf; buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("SingleOfficeIPC_") ); for ( sal_uInt32 i = 0; i < md5_key_len; ++i ) buf.append( static_cast< sal_Int32 >(md5_buf[ i ]), 0x10 ); delete [] md5_buf; OUString pipe_id( buf.makeStringAndClear() ); ::osl::Security sec; ::osl::Pipe pipe( pipe_id, osl_Pipe_OPEN, sec ); s_status = (pipe.is() ? RUNNING : NOT_RUNNING); } return (s_status == RUNNING); } } <commit_msg>INTEGRATION: CWS pkgchkcfgfix1 (1.2.2); FILE MERGED 2004/04/16 12:06:05 jb 1.2.2.1: #116376# Assume that no office runs, if user installation does not exist<commit_after>/************************************************************************* * * $RCSfile: dp_misc.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: svesik $ $Date: 2004-04-20 11:04:00 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "dp_misc.h" #include "rtl/uri.hxx" #include "rtl/digest.h" #include "osl/file.hxx" #include "osl/pipe.hxx" #include "com/sun/star/util/XMacroExpander.hpp" using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using ::rtl::OUString; namespace dp_misc { //============================================================================== OUString expand_reg_url( OUString const & url, Reference< XComponentContext > const & xContext ) { Reference< util::XMacroExpander > xMacroExpander( xContext->getValueByName( OUSTR("/singletons/com.sun.star.util.theMacroExpander") ), UNO_QUERY_THROW ); if (url.matchIgnoreAsciiCaseAsciiL( RTL_CONSTASCII_STRINGPARAM("vnd.sun.star.expand:") )) { // cut protocol: OUString macro( url.copy( sizeof ("vnd.sun.star.expand:") -1 ) ); // decode uric class chars: macro = ::rtl::Uri::decode( macro, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 ); // expand macro string: OUString ret( xMacroExpander->expandMacros( macro ) ); // #if OSL_DEBUG_LEVEL > 1 // { // OUStringBuffer buf( 128 ); // buf.appendAscii( // RTL_CONSTASCII_STRINGPARAM(__FILE__" expand_reg_url(): ") ); // buf.append( url ); // buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" => ") ); // buf.append( macro ); // buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" => ") ); // buf.append( ret ); // OString cstr( // OUStringToOString( // buf.makeStringAndClear(), osl_getThreadTextEncoding() ) ); // OSL_TRACE( "%s", cstr.getStr() ); // } // #endif return ret; } else { return url; } } enum t_status { RUNNING, NOT_RUNNING, INIT_ME }; //============================================================================== bool office_is_running( Reference< XComponentContext > const & xContext ) { static t_status s_status = INIT_ME; if (s_status == INIT_ME) { Reference< util::XMacroExpander > xMacroExpander( xContext->getValueByName( OUSTR("/singletons/com.sun.star.util.theMacroExpander") ), UNO_QUERY_THROW ); OUString user_path( xMacroExpander->expandMacros( OUSTR( "${$SYSBINDIR/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}") ) ); // normalize path: ::osl::FileStatus status( FileStatusMask_FileURL ); ::osl::DirectoryItem dirItem; if (::osl::DirectoryItem::get( user_path, dirItem ) != ::osl::DirectoryItem::E_None || dirItem.getFileStatus( status ) != ::osl::DirectoryItem::E_None || !status.isValid( FileStatusMask_FileURL ) || ::osl::FileBase::getAbsoluteFileURL( OUString(), status.getFileURL(), user_path ) != ::osl::FileBase::E_None) { return false; } rtlDigest digest = rtl_digest_create( rtl_Digest_AlgorithmMD5 ); if (digest <= 0) { throw RuntimeException( OUSTR("cannot get digest rtl_Digest_AlgorithmMD5!"), 0 ); } sal_uInt8 const * data = reinterpret_cast< sal_uInt8 const * >(user_path.getStr()); sal_Size size = (user_path.getLength() * sizeof (sal_Unicode)); sal_uInt32 md5_key_len = rtl_digest_queryLength( digest ); sal_uInt8 * md5_buf = new sal_uInt8 [ md5_key_len ]; rtl_digest_init( digest, data, static_cast< sal_uInt32 >(size) ); rtl_digest_update( digest, data, static_cast< sal_uInt32 >(size) ); rtl_digest_get( digest, md5_buf, md5_key_len ); rtl_digest_destroy( digest ); // create hex-value string from the MD5 value to keep // the string size minimal ::rtl::OUStringBuffer buf; buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("SingleOfficeIPC_") ); for ( sal_uInt32 i = 0; i < md5_key_len; ++i ) buf.append( static_cast< sal_Int32 >(md5_buf[ i ]), 0x10 ); delete [] md5_buf; OUString pipe_id( buf.makeStringAndClear() ); ::osl::Security sec; ::osl::Pipe pipe( pipe_id, osl_Pipe_OPEN, sec ); s_status = (pipe.is() ? RUNNING : NOT_RUNNING); } return (s_status == RUNNING); } } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, John Haddon. All rights reserved. // Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" // must be the first include #include <fstream> #include "IECorePython/Wrapper.h" #include "IECorePython/RunTimeTypedBinding.h" #include "IECorePython/ScopedGILLock.h" #include "Gaffer/ScriptNode.h" #include "Gaffer/Context.h" #include "Gaffer/ApplicationRoot.h" #include "Gaffer/StandardSet.h" #include "Gaffer/CompoundDataPlug.h" #include "GafferBindings/ScriptNodeBinding.h" #include "GafferBindings/SignalBinding.h" #include "GafferBindings/NodeBinding.h" using namespace boost::python; using namespace Gaffer; namespace GafferBindings { /// The ScriptNodeWrapper class implements the scripting /// components of the ScriptNode base class. In this way /// scripting is available provided that the ScriptNode was /// created from python. class ScriptNodeWrapper : public NodeWrapper<ScriptNode> { public : ScriptNodeWrapper( PyObject *self, const std::string &name ) : NodeWrapper<ScriptNode>( self, name ) { } virtual ~ScriptNodeWrapper() { } virtual void execute( const std::string &pythonScript, Node *parent = 0 ) { IECorePython::ScopedGILLock gilLock; object e = executionDict( parent ); exec( pythonScript.c_str(), e, e ); scriptExecutedSignal()( this, pythonScript ); } void executeFile( const std::string &pythonFile, Node *parent = 0 ) { const std::string pythonScript = readFile( pythonFile ); execute( pythonScript, parent ); } virtual PyObject *evaluate( const std::string &pythonExpression, Node *parent = 0 ) { IECorePython::ScopedGILLock gilLock; object e = executionDict( parent ); object result = eval( pythonExpression.c_str(), e, e ); scriptEvaluatedSignal()( this, pythonExpression, result.ptr() ); // make a reference to keep the result alive - the caller then // assumes responsibility for dealing with this Py_XINCREF( result.ptr() ); return result.ptr(); } virtual std::string serialise( const Node *parent = 0, const Set *filter = 0 ) const { Serialisation serialisation( parent ? parent : this, "parent", filter ); return serialisation.result(); } virtual void serialiseToFile( const std::string &fileName, const Node *parent, const Set *filter ) const { std::string s = serialise( parent, filter ); std::ofstream f( fileName.c_str() ); if( !f.good() ) { throw IECore::IOException( "Unable to open file \"" + fileName + "\"" ); } f << s; if( !f.good() ) { throw IECore::IOException( "Failed to write to \"" + fileName + "\"" ); } } virtual void load() { const std::string s = readFile( fileNamePlug()->getValue() ); deleteNodes(); variablesPlug()->clearChildren(); execute( s ); UndoContext undoDisabled( this, UndoContext::Disabled ); unsavedChangesPlug()->setValue( false ); } virtual void save() const { serialiseToFile( fileNamePlug()->getValue(), 0, 0 ); UndoContext undoDisabled( const_cast<ScriptNodeWrapper *>( this ), UndoContext::Disabled ); const_cast<BoolPlug *>( unsavedChangesPlug() )->setValue( false ); } private : std::string readFile( const std::string &fileName ) { std::ifstream f( fileName.c_str() ); if( !f.good() ) { throw IECore::IOException( "Unable to open file \"" + fileName + "\"" ); } std::string s; while( !f.eof() ) { if( !f.good() ) { throw IECore::IOException( "Failed to read from \"" + fileName + "\"" ); } std::string line; std::getline( f, line ); s += line + "\n"; } return s; } // the dict returned will form both the locals and the globals for the execute() // and evaluate() methods. it's not possible to have a separate locals // and globals dictionary and have things work as intended. see // ScriptNodeTest.testClassScope() for an example, and // http://bugs.python.org/issue991196 for an explanation. object executionDict( Node *parent ) { dict result; object builtIn = import( "__builtin__" ); result["__builtins__"] = builtIn; object gafferModule = import( "Gaffer" ); result["Gaffer"] = gafferModule; result["script"] = object( ScriptNodePtr( this ) ); result["parent"] = object( NodePtr( parent ? parent : this ) ); return result; } }; IE_CORE_DECLAREPTR( ScriptNodeWrapper ) struct ScriptEvaluatedSlotCaller { boost::signals::detail::unusable operator()( boost::python::object slot, ScriptNodePtr node, const std::string script, PyObject *result ) { try { boost::python::object o( handle<>( borrowed( result ) ) ); slot( node, script, o ); } catch( const error_already_set &e ) { PyErr_PrintEx( 0 ); // clears error status } return boost::signals::detail::unusable(); } }; static ContextPtr context( ScriptNode &s ) { return s.context(); } static ApplicationRootPtr applicationRoot( ScriptNode &s ) { return s.applicationRoot(); } static StandardSetPtr selection( ScriptNode &s ) { return s.selection(); } class ScriptNodeSerialiser : public NodeSerialiser { virtual bool childNeedsSerialisation( const Gaffer::GraphComponent *child ) const { if( child->isInstanceOf( Node::staticTypeId() ) ) { return true; } return NodeSerialiser::childNeedsSerialisation( child ); } virtual bool childNeedsConstruction( const Gaffer::GraphComponent *child ) const { if( child->isInstanceOf( Node::staticTypeId() ) ) { return true; } return NodeSerialiser::childNeedsConstruction( child ); } }; struct ActionSlotCaller { boost::signals::detail::unusable operator()( boost::python::object slot, ScriptNodePtr script, ConstActionPtr action, Action::Stage stage ) { try { slot( script, IECore::constPointerCast<Action>( action ), stage ); } catch( const error_already_set &e ) { PyErr_PrintEx( 0 ); // clears the error status } return boost::signals::detail::unusable(); } }; struct UndoAddedSlotCaller { boost::signals::detail::unusable operator()( boost::python::object slot, ScriptNodePtr script ) { try { slot( script ); } catch( const error_already_set &e ) { PyErr_PrintEx( 0 ); // clears the error status } return boost::signals::detail::unusable(); } }; void bindScriptNode() { scope s = NodeClass<ScriptNode, ScriptNodeWrapperPtr>() .def( "applicationRoot", &applicationRoot ) .def( "selection", &selection ) .def( "undoAvailable", &ScriptNode::undoAvailable ) .def( "undo", &ScriptNode::undo ) .def( "redoAvailable", &ScriptNode::redoAvailable ) .def( "redo", &ScriptNode::redo ) .def( "currentActionStage", &ScriptNode::currentActionStage ) .def( "actionSignal", &ScriptNode::actionSignal, return_internal_reference<1>() ) .def( "undoAddedSignal", &ScriptNode::undoAddedSignal, return_internal_reference<1>() ) .def( "copy", &ScriptNode::copy, ( arg_( "parent" ) = object(), arg_( "filter" ) = object() ) ) .def( "cut", &ScriptNode::cut, ( arg_( "parent" ) = object(), arg_( "filter" ) = object() ) ) .def( "paste", &ScriptNode::paste, ( arg_( "parent" ) = object() ) ) .def( "deleteNodes", &ScriptNode::deleteNodes, ( arg_( "parent" ) = object(), arg_( "filter" ) = object(), arg_( "reconnect" ) = true ) ) .def( "execute", &ScriptNode::execute, ( arg_( "parent" ) = object() ) ) .def( "executeFile", &ScriptNode::executeFile, ( arg_( "fileName" ), arg_( "parent" ) = object() ) ) .def( "evaluate", &ScriptNode::evaluate, ( arg_( "parent" ) = object() ) ) .def( "scriptExecutedSignal", &ScriptNode::scriptExecutedSignal, return_internal_reference<1>() ) .def( "scriptEvaluatedSignal", &ScriptNode::scriptEvaluatedSignal, return_internal_reference<1>() ) .def( "serialise", &ScriptNode::serialise, ( arg_( "parent" ) = object(), arg_( "filter" ) = object() ) ) .def( "serialiseToFile", &ScriptNode::serialiseToFile, ( arg_( "fileName" ), arg_( "parent" ) = object(), arg_( "filter" ) = object() ) ) .def( "save", &ScriptNode::save ) .def( "load", &ScriptNode::load ) .def( "context", &context ) ; SignalBinder<ScriptNode::ActionSignal, DefaultSignalCaller<ScriptNode::ActionSignal>, ActionSlotCaller>::bind( "ActionSignal" ); SignalBinder<ScriptNode::UndoAddedSignal, DefaultSignalCaller<ScriptNode::UndoAddedSignal>, UndoAddedSlotCaller>::bind( "UndoAddedSignal" ); SignalBinder<ScriptNode::ScriptExecutedSignal>::bind( "ScriptExecutedSignal" ); SignalBinder<ScriptNode::ScriptEvaluatedSignal, DefaultSignalCaller<ScriptNode::ScriptEvaluatedSignal>, ScriptEvaluatedSlotCaller>::bind( "ScriptEvaluatedSignal" ); Serialisation::registerSerialiser( ScriptNode::staticTypeId(), new ScriptNodeSerialiser ); } } // namespace GafferBindings <commit_msg>put a gil release in the python bindings for ScriptNode::deleteNodes in case it triggers a python evaluation<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, John Haddon. All rights reserved. // Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "boost/python.hpp" // must be the first include #include <fstream> #include "IECorePython/Wrapper.h" #include "IECorePython/RunTimeTypedBinding.h" #include "IECorePython/ScopedGILLock.h" #include "IECorePython/ScopedGILRelease.h" #include "Gaffer/ScriptNode.h" #include "Gaffer/Context.h" #include "Gaffer/ApplicationRoot.h" #include "Gaffer/StandardSet.h" #include "Gaffer/CompoundDataPlug.h" #include "GafferBindings/ScriptNodeBinding.h" #include "GafferBindings/SignalBinding.h" #include "GafferBindings/NodeBinding.h" using namespace boost::python; using namespace Gaffer; namespace GafferBindings { /// The ScriptNodeWrapper class implements the scripting /// components of the ScriptNode base class. In this way /// scripting is available provided that the ScriptNode was /// created from python. class ScriptNodeWrapper : public NodeWrapper<ScriptNode> { public : ScriptNodeWrapper( PyObject *self, const std::string &name ) : NodeWrapper<ScriptNode>( self, name ) { } virtual ~ScriptNodeWrapper() { } virtual void execute( const std::string &pythonScript, Node *parent = 0 ) { IECorePython::ScopedGILLock gilLock; object e = executionDict( parent ); exec( pythonScript.c_str(), e, e ); scriptExecutedSignal()( this, pythonScript ); } void executeFile( const std::string &pythonFile, Node *parent = 0 ) { const std::string pythonScript = readFile( pythonFile ); execute( pythonScript, parent ); } virtual PyObject *evaluate( const std::string &pythonExpression, Node *parent = 0 ) { IECorePython::ScopedGILLock gilLock; object e = executionDict( parent ); object result = eval( pythonExpression.c_str(), e, e ); scriptEvaluatedSignal()( this, pythonExpression, result.ptr() ); // make a reference to keep the result alive - the caller then // assumes responsibility for dealing with this Py_XINCREF( result.ptr() ); return result.ptr(); } virtual std::string serialise( const Node *parent = 0, const Set *filter = 0 ) const { Serialisation serialisation( parent ? parent : this, "parent", filter ); return serialisation.result(); } virtual void serialiseToFile( const std::string &fileName, const Node *parent, const Set *filter ) const { std::string s = serialise( parent, filter ); std::ofstream f( fileName.c_str() ); if( !f.good() ) { throw IECore::IOException( "Unable to open file \"" + fileName + "\"" ); } f << s; if( !f.good() ) { throw IECore::IOException( "Failed to write to \"" + fileName + "\"" ); } } virtual void load() { const std::string s = readFile( fileNamePlug()->getValue() ); deleteNodes(); variablesPlug()->clearChildren(); execute( s ); UndoContext undoDisabled( this, UndoContext::Disabled ); unsavedChangesPlug()->setValue( false ); } virtual void save() const { serialiseToFile( fileNamePlug()->getValue(), 0, 0 ); UndoContext undoDisabled( const_cast<ScriptNodeWrapper *>( this ), UndoContext::Disabled ); const_cast<BoolPlug *>( unsavedChangesPlug() )->setValue( false ); } private : std::string readFile( const std::string &fileName ) { std::ifstream f( fileName.c_str() ); if( !f.good() ) { throw IECore::IOException( "Unable to open file \"" + fileName + "\"" ); } std::string s; while( !f.eof() ) { if( !f.good() ) { throw IECore::IOException( "Failed to read from \"" + fileName + "\"" ); } std::string line; std::getline( f, line ); s += line + "\n"; } return s; } // the dict returned will form both the locals and the globals for the execute() // and evaluate() methods. it's not possible to have a separate locals // and globals dictionary and have things work as intended. see // ScriptNodeTest.testClassScope() for an example, and // http://bugs.python.org/issue991196 for an explanation. object executionDict( Node *parent ) { dict result; object builtIn = import( "__builtin__" ); result["__builtins__"] = builtIn; object gafferModule = import( "Gaffer" ); result["Gaffer"] = gafferModule; result["script"] = object( ScriptNodePtr( this ) ); result["parent"] = object( NodePtr( parent ? parent : this ) ); return result; } }; IE_CORE_DECLAREPTR( ScriptNodeWrapper ) struct ScriptEvaluatedSlotCaller { boost::signals::detail::unusable operator()( boost::python::object slot, ScriptNodePtr node, const std::string script, PyObject *result ) { try { boost::python::object o( handle<>( borrowed( result ) ) ); slot( node, script, o ); } catch( const error_already_set &e ) { PyErr_PrintEx( 0 ); // clears error status } return boost::signals::detail::unusable(); } }; static ContextPtr context( ScriptNode &s ) { return s.context(); } static ApplicationRootPtr applicationRoot( ScriptNode &s ) { return s.applicationRoot(); } static StandardSetPtr selection( ScriptNode &s ) { return s.selection(); } static void deleteNodes( ScriptNode &s, Node *parent, const Set *filter, bool reconnect ) { IECorePython::ScopedGILRelease r; s.deleteNodes( parent, filter, reconnect ); } class ScriptNodeSerialiser : public NodeSerialiser { virtual bool childNeedsSerialisation( const Gaffer::GraphComponent *child ) const { if( child->isInstanceOf( Node::staticTypeId() ) ) { return true; } return NodeSerialiser::childNeedsSerialisation( child ); } virtual bool childNeedsConstruction( const Gaffer::GraphComponent *child ) const { if( child->isInstanceOf( Node::staticTypeId() ) ) { return true; } return NodeSerialiser::childNeedsConstruction( child ); } }; struct ActionSlotCaller { boost::signals::detail::unusable operator()( boost::python::object slot, ScriptNodePtr script, ConstActionPtr action, Action::Stage stage ) { try { slot( script, IECore::constPointerCast<Action>( action ), stage ); } catch( const error_already_set &e ) { PyErr_PrintEx( 0 ); // clears the error status } return boost::signals::detail::unusable(); } }; struct UndoAddedSlotCaller { boost::signals::detail::unusable operator()( boost::python::object slot, ScriptNodePtr script ) { try { slot( script ); } catch( const error_already_set &e ) { PyErr_PrintEx( 0 ); // clears the error status } return boost::signals::detail::unusable(); } }; void bindScriptNode() { scope s = NodeClass<ScriptNode, ScriptNodeWrapperPtr>() .def( "applicationRoot", &applicationRoot ) .def( "selection", &selection ) .def( "undoAvailable", &ScriptNode::undoAvailable ) .def( "undo", &ScriptNode::undo ) .def( "redoAvailable", &ScriptNode::redoAvailable ) .def( "redo", &ScriptNode::redo ) .def( "currentActionStage", &ScriptNode::currentActionStage ) .def( "actionSignal", &ScriptNode::actionSignal, return_internal_reference<1>() ) .def( "undoAddedSignal", &ScriptNode::undoAddedSignal, return_internal_reference<1>() ) .def( "copy", &ScriptNode::copy, ( arg_( "parent" ) = object(), arg_( "filter" ) = object() ) ) .def( "cut", &ScriptNode::cut, ( arg_( "parent" ) = object(), arg_( "filter" ) = object() ) ) .def( "paste", &ScriptNode::paste, ( arg_( "parent" ) = object() ) ) .def( "deleteNodes", &deleteNodes, ( arg_( "parent" ) = object(), arg_( "filter" ) = object(), arg_( "reconnect" ) = true ) ) .def( "execute", &ScriptNode::execute, ( arg_( "parent" ) = object() ) ) .def( "executeFile", &ScriptNode::executeFile, ( arg_( "fileName" ), arg_( "parent" ) = object() ) ) .def( "evaluate", &ScriptNode::evaluate, ( arg_( "parent" ) = object() ) ) .def( "scriptExecutedSignal", &ScriptNode::scriptExecutedSignal, return_internal_reference<1>() ) .def( "scriptEvaluatedSignal", &ScriptNode::scriptEvaluatedSignal, return_internal_reference<1>() ) .def( "serialise", &ScriptNode::serialise, ( arg_( "parent" ) = object(), arg_( "filter" ) = object() ) ) .def( "serialiseToFile", &ScriptNode::serialiseToFile, ( arg_( "fileName" ), arg_( "parent" ) = object(), arg_( "filter" ) = object() ) ) .def( "save", &ScriptNode::save ) .def( "load", &ScriptNode::load ) .def( "context", &context ) ; SignalBinder<ScriptNode::ActionSignal, DefaultSignalCaller<ScriptNode::ActionSignal>, ActionSlotCaller>::bind( "ActionSignal" ); SignalBinder<ScriptNode::UndoAddedSignal, DefaultSignalCaller<ScriptNode::UndoAddedSignal>, UndoAddedSlotCaller>::bind( "UndoAddedSignal" ); SignalBinder<ScriptNode::ScriptExecutedSignal>::bind( "ScriptExecutedSignal" ); SignalBinder<ScriptNode::ScriptEvaluatedSignal, DefaultSignalCaller<ScriptNode::ScriptEvaluatedSignal>, ScriptEvaluatedSlotCaller>::bind( "ScriptEvaluatedSignal" ); Serialisation::registerSerialiser( ScriptNode::staticTypeId(), new ScriptNodeSerialiser ); } } // namespace GafferBindings <|endoftext|>