text
stringlengths
54
60.6k
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3056 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 2042310 by chui@ocl-promo-incrementor on 2019/12/08 03:00:03<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3057 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // LLVM 'GCCAS' UTILITY // // This utility is designed to be used by the GCC frontend for creating bytecode // files from its intermediate LLVM assembly. The requirements for this utility // are thus slightly different than that of the standard `as' util. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/LoadValueNumbering.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/Parser.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Scalar.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <memory> #include <fstream> namespace { cl::opt<std::string> InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-")); cl::opt<std::string> OutputFilename("o", cl::desc("Override output filename"), cl::value_desc("filename")); cl::opt<bool> Verify("verify", cl::desc("Verify each pass result")); cl::opt<bool> DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); } static inline void addPass(PassManager &PM, Pass *P) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (Verify) PM.add(createVerifierPass()); } void AddConfiguredTransformationPasses(PassManager &PM) { PM.add(createVerifierPass()); // Verify that input is correct addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp addPass(PM, createFunctionResolvingPass()); // Resolve (...) functions addPass(PM, createRaiseAllocationsPass()); // call %malloc -> malloc inst addPass(PM, createGlobalDCEPass()); // Remove unused globals addPass(PM, createPruneEHPass()); // Remove dead EH info if (!DisableInline) addPass(PM, createFunctionInliningPass()); // Inline small functions addPass(PM, createInstructionCombiningPass()); // Cleanup code for raise addPass(PM, createRaisePointerReferencesPass());// Recover type information addPass(PM, createTailDuplicationPass()); // Simplify cfg by copying code addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas addPass(PM, createTailCallEliminationPass()); // Eliminate tail calls addPass(PM, createInstructionCombiningPass()); // Combine silly seq's addPass(PM, createReassociatePass()); // Reassociate expressions addPass(PM, createInstructionCombiningPass()); // Combine silly seq's addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createLICMPass()); // Hoist loop invariants addPass(PM, createLoadValueNumberingPass()); // GVN for load instructions addPass(PM, createGCSEPass()); // Remove common subexprs addPass(PM, createSCCPPass()); // Constant prop with SCCP // Run instcombine after redundancy elimination to exploit opportunities // opened up by them. addPass(PM, createInstructionCombiningPass()); addPass(PM, createIndVarSimplifyPass()); // Canonicalize indvars addPass(PM, createAggressiveDCEPass()); // SSA based 'Aggressive DCE' addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createDeadTypeEliminationPass()); // Eliminate dead types addPass(PM, createConstantMergePass()); // Merge dup global constants } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n"); std::auto_ptr<Module> M; try { // Parse the file now... M.reset(ParseAssemblyFile(InputFilename)); } catch (const ParseException &E) { std::cerr << argv[0] << ": " << E.getMessage() << "\n"; return 1; } if (M.get() == 0) { std::cerr << argv[0] << ": assembly didn't read correctly.\n"; return 1; } std::ostream *Out = 0; if (OutputFilename == "") { // Didn't specify an output filename? if (InputFilename == "-") { OutputFilename = "-"; } else { std::string IFN = InputFilename; int Len = IFN.length(); if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s? OutputFilename = std::string(IFN.begin(), IFN.end()-2); } else { OutputFilename = IFN; // Append a .o to it } OutputFilename += ".o"; } } if (OutputFilename == "-") Out = &std::cout; else { Out = new std::ofstream(OutputFilename.c_str(), std::ios::out); // Make sure that the Out file gets unlinked from the disk if we get a // signal RemoveFileOnSignal(OutputFilename); } if (!Out->good()) { std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; return 1; } // In addition to just parsing the input from GCC, we also want to spiff it up // a little bit. Do this now. // PassManager Passes; // Add an appropriate TargetData instance for this module... Passes.add(new TargetData("gccas", M.get())); // Add all of the transformation passes to the pass manager to do the cleanup // and optimization of the GCC output. // AddConfiguredTransformationPasses(Passes); // Write bytecode to file... Passes.add(new WriteBytecodePass(Out)); // Run our queue of passes all at once now, efficiently. Passes.run(*M.get()); if (Out != &std::cout) delete Out; return 0; } <commit_msg>The levelraise pass is a broken old piece of crufty code that should be left on the side of the road without a second thought.<commit_after>//===----------------------------------------------------------------------===// // LLVM 'GCCAS' UTILITY // // This utility is designed to be used by the GCC frontend for creating bytecode // files from its intermediate LLVM assembly. The requirements for this utility // are thus slightly different than that of the standard `as' util. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/LoadValueNumbering.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/Parser.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Scalar.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <memory> #include <fstream> namespace { cl::opt<std::string> InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-")); cl::opt<std::string> OutputFilename("o", cl::desc("Override output filename"), cl::value_desc("filename")); cl::opt<bool> Verify("verify", cl::desc("Verify each pass result")); cl::opt<bool> DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); } static inline void addPass(PassManager &PM, Pass *P) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (Verify) PM.add(createVerifierPass()); } void AddConfiguredTransformationPasses(PassManager &PM) { PM.add(createVerifierPass()); // Verify that input is correct addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp addPass(PM, createFunctionResolvingPass()); // Resolve (...) functions addPass(PM, createRaiseAllocationsPass()); // call %malloc -> malloc inst addPass(PM, createGlobalDCEPass()); // Remove unused globals addPass(PM, createPruneEHPass()); // Remove dead EH info if (!DisableInline) addPass(PM, createFunctionInliningPass()); // Inline small functions addPass(PM, createInstructionCombiningPass()); // Cleanup code for raise // FIXME: levelraise pass disabled until it can be rewritten at a later date. //addPass(PM, createRaisePointerReferencesPass());// Recover type information addPass(PM, createTailDuplicationPass()); // Simplify cfg by copying code addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas addPass(PM, createTailCallEliminationPass()); // Eliminate tail calls addPass(PM, createInstructionCombiningPass()); // Combine silly seq's addPass(PM, createReassociatePass()); // Reassociate expressions addPass(PM, createInstructionCombiningPass()); // Combine silly seq's addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createLICMPass()); // Hoist loop invariants addPass(PM, createLoadValueNumberingPass()); // GVN for load instructions addPass(PM, createGCSEPass()); // Remove common subexprs addPass(PM, createSCCPPass()); // Constant prop with SCCP // Run instcombine after redundancy elimination to exploit opportunities // opened up by them. addPass(PM, createInstructionCombiningPass()); addPass(PM, createIndVarSimplifyPass()); // Canonicalize indvars addPass(PM, createAggressiveDCEPass()); // SSA based 'Aggressive DCE' addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createDeadTypeEliminationPass()); // Eliminate dead types addPass(PM, createConstantMergePass()); // Merge dup global constants } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n"); std::auto_ptr<Module> M; try { // Parse the file now... M.reset(ParseAssemblyFile(InputFilename)); } catch (const ParseException &E) { std::cerr << argv[0] << ": " << E.getMessage() << "\n"; return 1; } if (M.get() == 0) { std::cerr << argv[0] << ": assembly didn't read correctly.\n"; return 1; } std::ostream *Out = 0; if (OutputFilename == "") { // Didn't specify an output filename? if (InputFilename == "-") { OutputFilename = "-"; } else { std::string IFN = InputFilename; int Len = IFN.length(); if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s? OutputFilename = std::string(IFN.begin(), IFN.end()-2); } else { OutputFilename = IFN; // Append a .o to it } OutputFilename += ".o"; } } if (OutputFilename == "-") Out = &std::cout; else { Out = new std::ofstream(OutputFilename.c_str(), std::ios::out); // Make sure that the Out file gets unlinked from the disk if we get a // signal RemoveFileOnSignal(OutputFilename); } if (!Out->good()) { std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; return 1; } // In addition to just parsing the input from GCC, we also want to spiff it up // a little bit. Do this now. // PassManager Passes; // Add an appropriate TargetData instance for this module... Passes.add(new TargetData("gccas", M.get())); // Add all of the transformation passes to the pass manager to do the cleanup // and optimization of the GCC output. // AddConfiguredTransformationPasses(Passes); // Write bytecode to file... Passes.add(new WriteBytecodePass(Out)); // Run our queue of passes all at once now, efficiently. Passes.run(*M.get()); if (Out != &std::cout) delete Out; return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2061 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1246830 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/03/13 04:00:10<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 2062 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2919 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1793646 by chui@ocl-promo-incrementor on 2019/06/09 03:00:08<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2920 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1789 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1146133 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/04/30 03:00:13<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1790 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1817 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1158545 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/06/06 03:00:12<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME # define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER # define AMD_PLATFORM_BUILD_NUMBER 1818 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER # define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO # define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO # define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \ DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2451 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>P4 to Git Change 1431230 by johtaylo@johtaylo-jtincrementor-increment on 2017/07/07 03:01:11<commit_after>// // Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved. // #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 2452 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>// // DummyRenderer.cpp // Glob3 Mobile // // Created by Agustín Trujillo Pino on 02/05/11. // Copyright 2011 Universidad de Las Palmas. All rights reserved. // #include "DummyRenderer.hpp" #include "Context.hpp" #include "GL.hpp" #include "Planet.hpp" #include "Vector3D.hpp" DummyRenderer::~DummyRenderer() { delete[] _index; delete[] _vertices; } void DummyRenderer::initialize(const InitializationContext* ic) { int res = 12; _vertices = new float[res * res * 3]; _numIndices = 2 * (res - 1) * (res + 1); _index = new int[_numIndices]; // create vertices if (ic != NULL && ic->getPlanet() != NULL) _halfSize = ic->getPlanet()->getRadii().x() / 2.0; else _halfSize = 7e6; int n = 0; for (int j = 0; j < res; j++) { for (int i = 0; i < res; i++) { _vertices[n++] = (float) 0; _vertices[n++] = (float) (-_halfSize + i / (float) (res - 1) * 2*_halfSize); _vertices[n++] = (float) (_halfSize - j / (float) (res - 1) * 2*_halfSize); } } n = 0; for (int j = 0; j < res - 1; j++) { if (j > 0) _index[n++] = (char) (j * res); for (int i = 0; i < res; i++) { _index[n++] = (char) (j * res + i); _index[n++] = (char) (j * res + i + res); } _index[n++] = (char) (j * res + 2 * res - 1); } } bool DummyRenderer::onTouchEvent(const EventContext* ec, const TouchEvent* touchEvent){ return false; } int DummyRenderer::render(const RenderContext* rc) { // obtaing gl object reference GL *gl = rc->getGL(); gl->enableVerticesPosition(); // insert pointers gl->disableTextures(); gl->vertexPointer(3, 0, _vertices); { // draw a red square gl->color((float) 1, (float) 0, (float) 0, 1); gl->pushMatrix(); //MutableMatrix44D T = GLU::translationMatrix(Vector3D(halfSize,0,0)); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(_halfSize,0,0)); gl->multMatrixf(T); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a green square gl->color((float) 0, (float) 1, (float) 0, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(0,_halfSize,0)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(90), Vector3D(0,0,1)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a blue square gl->color((float) 0, (float) 0, (float) 1, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(0,-_halfSize,0)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(-90), Vector3D(0,0,1)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a purple square gl->color((float) 1, (float) 0, (float) 1, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(0,0,-_halfSize)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(90), Vector3D(0,1,0)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a cian square gl->color((float) 0, (float) 1, (float) 1, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(0,0,_halfSize)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(-90), Vector3D(0,1,0)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a grey square gl->color((float) 0.5, (float) 0.5, (float) 0.5, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(-_halfSize,0,0)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(180), Vector3D(0,0,1)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } gl->enableTextures(); return Renderer::maxTimeToRender; } <commit_msg>DummyRenderer fixed<commit_after>// // DummyRenderer.cpp // Glob3 Mobile // // Created by Agustín Trujillo Pino on 02/05/11. // Copyright 2011 Universidad de Las Palmas. All rights reserved. // #include "DummyRenderer.hpp" #include "Context.hpp" #include "GL.hpp" #include "Planet.hpp" #include "Vector3D.hpp" DummyRenderer::~DummyRenderer() { delete[] _index; delete[] _vertices; } void DummyRenderer::initialize(const InitializationContext* ic) { int res = 12; _vertices = new float[res * res * 3]; _numIndices = 2 * (res - 1) * (res + 1); _index = new int[_numIndices]; // create vertices if (ic != NULL && ic->getPlanet() != NULL) _halfSize = ic->getPlanet()->getRadii().x() / 2.0; else _halfSize = 7e6; int n = 0; for (int j = 0; j < res; j++) { for (int i = 0; i < res; i++) { _vertices[n++] = (float) 0; _vertices[n++] = (float) (-_halfSize + i / (float) (res - 1) * 2*_halfSize); _vertices[n++] = (float) (_halfSize - j / (float) (res - 1) * 2*_halfSize); } } n = 0; for (int j = 0; j < res - 1; j++) { if (j > 0) _index[n++] = (char) (j * res); for (int i = 0; i < res; i++) { _index[n++] = (j * res + i); _index[n++] = (j * res + i + res); } _index[n++] = (j * res + 2 * res - 1); } } bool DummyRenderer::onTouchEvent(const EventContext* ec, const TouchEvent* touchEvent){ return false; } int DummyRenderer::render(const RenderContext* rc) { // obtaing gl object reference GL *gl = rc->getGL(); gl->enableVerticesPosition(); // insert pointers gl->disableTextures(); gl->vertexPointer(3, 0, _vertices); { // draw a red square gl->color((float) 1, (float) 0, (float) 0, 1); gl->pushMatrix(); //MutableMatrix44D T = GLU::translationMatrix(Vector3D(halfSize,0,0)); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(_halfSize,0,0)); gl->multMatrixf(T); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a green square gl->color((float) 0, (float) 1, (float) 0, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(0,_halfSize,0)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(90), Vector3D(0,0,1)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a blue square gl->color((float) 0, (float) 0, (float) 1, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(0,-_halfSize,0)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(-90), Vector3D(0,0,1)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a purple square gl->color((float) 1, (float) 0, (float) 1, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(0,0,-_halfSize)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(90), Vector3D(0,1,0)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a cian square gl->color((float) 0, (float) 1, (float) 1, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(0,0,_halfSize)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(-90), Vector3D(0,1,0)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } { // draw a grey square gl->color((float) 0.5, (float) 0.5, (float) 0.5, 1); gl->pushMatrix(); MutableMatrix44D T = MutableMatrix44D::createTranslationMatrix(Vector3D(-_halfSize,0,0)); MutableMatrix44D R = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(180), Vector3D(0,0,1)); gl->multMatrixf(T.multiply(R)); gl->drawTriangleStrip(_numIndices, _index); gl->popMatrix(); } gl->enableTextures(); return Renderer::maxTimeToRender; } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/mepoo/shared_chunk.hpp" #include "iceoryx_posh/internal/popo/waitset/guard_condition.hpp" #include "iceoryx_posh/internal/popo/waitset/wait_set.hpp" #include "iceoryx_posh/mepoo/chunk_header.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "test.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::popo; using namespace iox::cxx; using namespace iox::mepoo; class WaitSet_test : public Test { public: static constexpr uint16_t MAX_NUMBER_OF_CONDITIONS_WITHOUT_GUARD = iox::popo::MAX_NUMBER_OF_CONDITIONS - 1; static constexpr size_t MEGABYTE = 1 << 20; static constexpr size_t MEMORY_SIZE = 1 * MEGABYTE; const uint64_t HISTORY_SIZE = 16; static constexpr uint32_t MAX_NUMBER_QUEUES = 128; char memory[MEMORY_SIZE]; iox::posix::Allocator allocator{memory, MEMORY_SIZE}; MemPool mempool{128, 20, &allocator, &allocator}; MemPool chunkMgmtPool{128, 20, &allocator, &allocator}; WaitSet m_waitset; Condition m_condition; vector<Condition, MAX_NUMBER_OF_CONDITIONS_WITHOUT_GUARD> m_conditionVector; void SetUp() { for (auto currentCondition : m_conditionVector) { m_conditionVector.push_back(m_condition); } }; void TearDown() { m_conditionVector.clear(); }; }; // TEST_F(WaitSet_test, NoAttachResultsInError) // { // } TEST_F(WaitSet_test, AttachSingleConditionSuccessful) { EXPECT_TRUE(m_waitset.attachCondition(m_conditionVector.front())); } TEST_F(WaitSet_test, AttachSameConditionTwiceResultsInOneFailure) { m_waitset.attachCondition(m_conditionVector.front()); EXPECT_FALSE(m_waitset.attachCondition(m_conditionVector.front())); } TEST_F(WaitSet_test, AttachMultipleConditionSuccessful) { for (auto currentCondition : m_conditionVector) { EXPECT_TRUE(m_waitset.attachCondition(currentCondition)); } } TEST_F(WaitSet_test, AttachTooManyConditionsResultsInFailure) { for (auto currentCondition : m_conditionVector) { m_waitset.attachCondition(currentCondition); } Condition extraCondition; EXPECT_FALSE(m_waitset.attachCondition(extraCondition)); } TEST_F(WaitSet_test, DetachSingleConditionSuccessful) { m_waitset.attachCondition(m_conditionVector.front()); EXPECT_TRUE(m_waitset.detachCondition(m_conditionVector.front())); } TEST_F(WaitSet_test, DetachMultipleleConditionsSuccessful) { for (auto currentCondition : m_conditionVector) { m_waitset.attachCondition(currentCondition); } for (auto currentCondition : m_conditionVector) { EXPECT_TRUE(m_waitset.detachCondition(currentCondition)); } } TEST_F(WaitSet_test, DetachConditionNotInListResultsInFailure) { EXPECT_FALSE(m_waitset.detachCondition(m_conditionVector.front())); } TEST_F(WaitSet_test, DetachUnknownConditionResultsInFailure) { m_waitset.attachCondition(m_conditionVector.front()); EXPECT_FALSE(m_waitset.detachCondition(m_conditionVector.back())); } // TEST_F(WaitSet_test, TimedWaitWithSignalAlreadySetResultsInImmediateTrigger){} // TEST_F(WaitSet_test, SignalSetWhileWaitingInTimedWaitResultsInTrigger){} // TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInTrigger){} // TEST_F(WaitSet_test, TimedWaitWithInvalidConditionResultsInFailure){} // TEST_F(WaitSet_test, TimedWaitWithInvalidTimeResultsInFailure){} // TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInTrigger){} // TEST_F(WaitSet_test, WaitWithoutSignalResultsInBlocking){} // TEST_F(WaitSet_test, WaitWithSignalAlreadySetResultsInImmediateTrigger){} // TEST_F(WaitSet_test, SignalSetWhileWaitWaitResultsInTrigger){} // TEST_F(WaitSet_test, WaitWithInvalidConditionResultsInBlocking){} <commit_msg>iox-#25: Add condition var in test<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/mepoo/shared_chunk.hpp" #include "iceoryx_posh/internal/popo/waitset/condition.hpp" #include "iceoryx_posh/internal/popo/waitset/condition_variable_data.hpp" #include "iceoryx_posh/internal/popo/waitset/condition_variable_signaler.hpp" #include "iceoryx_posh/internal/popo/waitset/guard_condition.hpp" #include "iceoryx_posh/internal/popo/waitset/wait_set.hpp" #include "iceoryx_posh/mepoo/chunk_header.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "test.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::popo; using namespace iox::cxx; using namespace iox::mepoo; class WaitSet_test : public Test { public: static constexpr uint16_t MAX_NUMBER_OF_CONDITIONS_WITHOUT_GUARD = iox::popo::MAX_NUMBER_OF_CONDITIONS - 1; static constexpr size_t MEGABYTE = 1 << 20; static constexpr size_t MEMORY_SIZE = 1 * MEGABYTE; const uint64_t HISTORY_SIZE = 16; static constexpr uint32_t MAX_NUMBER_QUEUES = 128; char memory[MEMORY_SIZE]; iox::posix::Allocator allocator{memory, MEMORY_SIZE}; MemPool mempool{128, 20, &allocator, &allocator}; MemPool chunkMgmtPool{128, 20, &allocator, &allocator}; Condition m_condition; ConditionVariableData m_condVarData; WaitSet m_waitset; ConditionVariableSignaler m_signaler{&m_condVarData}; vector<Condition, MAX_NUMBER_OF_CONDITIONS_WITHOUT_GUARD> m_conditionVector; void SetUp() { m_condition.attachConditionVariable(&m_condVarData); for (auto currentCondition : m_conditionVector) { m_conditionVector.push_back(m_condition); } }; void TearDown() { m_conditionVector.clear(); }; }; // TEST_F(WaitSet_test, NoAttachResultsInError) // { // } TEST_F(WaitSet_test, AttachSingleConditionSuccessful) { EXPECT_TRUE(m_waitset.attachCondition(m_conditionVector.front())); } TEST_F(WaitSet_test, AttachSameConditionTwiceResultsInOneFailure) { m_waitset.attachCondition(m_conditionVector.front()); EXPECT_FALSE(m_waitset.attachCondition(m_conditionVector.front())); } TEST_F(WaitSet_test, AttachMultipleConditionSuccessful) { for (auto currentCondition : m_conditionVector) { EXPECT_TRUE(m_waitset.attachCondition(currentCondition)); } } TEST_F(WaitSet_test, AttachTooManyConditionsResultsInFailure) { for (auto currentCondition : m_conditionVector) { m_waitset.attachCondition(currentCondition); } Condition extraCondition; EXPECT_FALSE(m_waitset.attachCondition(extraCondition)); } TEST_F(WaitSet_test, DetachSingleConditionSuccessful) { m_waitset.attachCondition(m_conditionVector.front()); EXPECT_TRUE(m_waitset.detachCondition(m_conditionVector.front())); } TEST_F(WaitSet_test, DetachMultipleleConditionsSuccessful) { for (auto currentCondition : m_conditionVector) { m_waitset.attachCondition(currentCondition); } for (auto currentCondition : m_conditionVector) { EXPECT_TRUE(m_waitset.detachCondition(currentCondition)); } } TEST_F(WaitSet_test, DetachConditionNotInListResultsInFailure) { EXPECT_FALSE(m_waitset.detachCondition(m_conditionVector.front())); } TEST_F(WaitSet_test, DetachUnknownConditionResultsInFailure) { m_waitset.attachCondition(m_conditionVector.front()); EXPECT_FALSE(m_waitset.detachCondition(m_conditionVector.back())); } // TEST_F(WaitSet_test, TimedWaitWithSignalAlreadySetResultsInImmediateTrigger){} // TEST_F(WaitSet_test, SignalSetWhileWaitingInTimedWaitResultsInTrigger){} // TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInTrigger){} // TEST_F(WaitSet_test, TimedWaitWithInvalidConditionResultsInFailure){} // TEST_F(WaitSet_test, TimedWaitWithInvalidTimeResultsInFailure){} // TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInTrigger){} // TEST_F(WaitSet_test, WaitWithoutSignalResultsInBlocking){} // TEST_F(WaitSet_test, WaitWithSignalAlreadySetResultsInImmediateTrigger){} // TEST_F(WaitSet_test, SignalSetWhileWaitWaitResultsInTrigger){} // TEST_F(WaitSet_test, WaitWithInvalidConditionResultsInBlocking){} <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "MountingCoordinator.h" #ifdef RN_SHADOW_TREE_INTROSPECTION #include <glog/logging.h> #include <sstream> #endif #include <condition_variable> #include <react/renderer/mounting/ShadowViewMutation.h> namespace facebook { namespace react { MountingCoordinator::MountingCoordinator( ShadowTreeRevision baseRevision, std::weak_ptr<MountingOverrideDelegate const> delegate, bool enableReparentingDetection) : surfaceId_(baseRevision.rootShadowNode->getSurfaceId()), baseRevision_(baseRevision), mountingOverrideDelegate_(delegate), telemetryController_(*this), enableReparentingDetection_(enableReparentingDetection) { #ifdef RN_SHADOW_TREE_INTROSPECTION stubViewTree_ = stubViewTreeFromShadowNode(*baseRevision_.rootShadowNode); #endif } SurfaceId MountingCoordinator::getSurfaceId() const { return surfaceId_; } void MountingCoordinator::push(ShadowTreeRevision const &revision) const { { std::lock_guard<std::mutex> lock(mutex_); assert( !lastRevision_.has_value() || revision.number != lastRevision_->number); if (!lastRevision_.has_value() || lastRevision_->number < revision.number) { lastRevision_ = revision; } } signal_.notify_all(); } void MountingCoordinator::revoke() const { std::lock_guard<std::mutex> lock(mutex_); // We have two goals here. // 1. We need to stop retaining `ShadowNode`s to not prolong their lifetime // to prevent them from overliving `ComponentDescriptor`s. // 2. A possible call to `pullTransaction()` should return empty optional. baseRevision_.rootShadowNode.reset(); lastRevision_.reset(); } bool MountingCoordinator::waitForTransaction( std::chrono::duration<double> timeout) const { std::unique_lock<std::mutex> lock(mutex_); return signal_.wait_for( lock, timeout, [this]() { return lastRevision_.has_value(); }); } void MountingCoordinator::updateBaseRevision( ShadowTreeRevision const &baseRevision) const { baseRevision_ = std::move(baseRevision); } void MountingCoordinator::resetLatestRevision() const { lastRevision_.reset(); } better::optional<MountingTransaction> MountingCoordinator::pullTransaction() const { std::lock_guard<std::mutex> lock(mutex_); auto transaction = better::optional<MountingTransaction>{}; // Base case if (lastRevision_.has_value()) { number_++; auto telemetry = lastRevision_->telemetry; telemetry.willDiff(); auto mutations = calculateShadowViewMutations( *baseRevision_.rootShadowNode, *lastRevision_->rootShadowNode); telemetry.didDiff(); baseRevision_ = std::move(*lastRevision_); lastRevision_.reset(); transaction = MountingTransaction{ surfaceId_, number_, std::move(mutations), telemetry}; } // Override case auto mountingOverrideDelegate = mountingOverrideDelegate_.lock(); auto shouldOverridePullTransaction = mountingOverrideDelegate && mountingOverrideDelegate->shouldOverridePullTransaction(); if (shouldOverridePullTransaction) { auto mutations = ShadowViewMutation::List{}; auto telemetry = TransactionTelemetry{}; if (transaction.has_value()) { mutations = transaction->getMutations(); telemetry = transaction->getTelemetry(); } else { telemetry.willLayout(); telemetry.didLayout(); telemetry.willCommit(); telemetry.didCommit(); } transaction = mountingOverrideDelegate->pullTransaction( surfaceId_, number_, telemetry, std::move(mutations)); } #ifdef RN_SHADOW_TREE_INTROSPECTION if (transaction.has_value()) { // We have something to validate. auto mutations = transaction->getMutations(); // No matter what the source of the transaction is, it must be able to // mutate the existing stub view tree. stubViewTree_.mutate(mutations); // If the transaction was overridden, we don't have a model of the shadow // tree therefore we cannot validate the validity of the mutation // instructions. if (!shouldOverridePullTransaction) { auto line = std::string{}; auto stubViewTree = stubViewTreeFromShadowNode(*baseRevision_.rootShadowNode); if (stubViewTree_ != stubViewTree) { std::stringstream ssOldTree( baseRevision_.rootShadowNode->getDebugDescription()); while (std::getline(ssOldTree, line, '\n')) { LOG(ERROR) << "Old tree:" << line; } std::stringstream ssMutations(getDebugDescription(mutations, {})); while (std::getline(ssMutations, line, '\n')) { LOG(ERROR) << "Mutations:" << line; } std::stringstream ssNewTree( lastRevision_->rootShadowNode->getDebugDescription()); while (std::getline(ssNewTree, line, '\n')) { LOG(ERROR) << "New tree:" << line; } } assert( (stubViewTree_ == stubViewTree) && "Incorrect set of mutations detected."); } } #endif return transaction; } TelemetryController const &MountingCoordinator::getTelemetryController() const { return telemetryController_; } } // namespace react } // namespace facebook <commit_msg>Fix MountingCoordinator override mode<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "MountingCoordinator.h" #ifdef RN_SHADOW_TREE_INTROSPECTION #include <glog/logging.h> #include <sstream> #endif #include <condition_variable> #include <react/renderer/mounting/ShadowViewMutation.h> namespace facebook { namespace react { MountingCoordinator::MountingCoordinator( ShadowTreeRevision baseRevision, std::weak_ptr<MountingOverrideDelegate const> delegate, bool enableReparentingDetection) : surfaceId_(baseRevision.rootShadowNode->getSurfaceId()), baseRevision_(baseRevision), mountingOverrideDelegate_(delegate), telemetryController_(*this), enableReparentingDetection_(enableReparentingDetection) { #ifdef RN_SHADOW_TREE_INTROSPECTION stubViewTree_ = stubViewTreeFromShadowNode(*baseRevision_.rootShadowNode); #endif } SurfaceId MountingCoordinator::getSurfaceId() const { return surfaceId_; } void MountingCoordinator::push(ShadowTreeRevision const &revision) const { { std::lock_guard<std::mutex> lock(mutex_); assert( !lastRevision_.has_value() || revision.number != lastRevision_->number); if (!lastRevision_.has_value() || lastRevision_->number < revision.number) { lastRevision_ = revision; } } signal_.notify_all(); } void MountingCoordinator::revoke() const { std::lock_guard<std::mutex> lock(mutex_); // We have two goals here. // 1. We need to stop retaining `ShadowNode`s to not prolong their lifetime // to prevent them from overliving `ComponentDescriptor`s. // 2. A possible call to `pullTransaction()` should return empty optional. baseRevision_.rootShadowNode.reset(); lastRevision_.reset(); } bool MountingCoordinator::waitForTransaction( std::chrono::duration<double> timeout) const { std::unique_lock<std::mutex> lock(mutex_); return signal_.wait_for( lock, timeout, [this]() { return lastRevision_.has_value(); }); } void MountingCoordinator::updateBaseRevision( ShadowTreeRevision const &baseRevision) const { baseRevision_ = std::move(baseRevision); } void MountingCoordinator::resetLatestRevision() const { lastRevision_.reset(); } better::optional<MountingTransaction> MountingCoordinator::pullTransaction() const { std::lock_guard<std::mutex> lock(mutex_); auto transaction = better::optional<MountingTransaction>{}; // Base case if (lastRevision_.has_value()) { number_++; auto telemetry = lastRevision_->telemetry; telemetry.willDiff(); auto mutations = calculateShadowViewMutations( *baseRevision_.rootShadowNode, *lastRevision_->rootShadowNode); telemetry.didDiff(); baseRevision_ = std::move(*lastRevision_); lastRevision_.reset(); transaction = MountingTransaction{ surfaceId_, number_, std::move(mutations), telemetry}; } // Override case auto mountingOverrideDelegate = mountingOverrideDelegate_.lock(); auto shouldOverridePullTransaction = mountingOverrideDelegate && mountingOverrideDelegate->shouldOverridePullTransaction(); if (shouldOverridePullTransaction) { auto mutations = ShadowViewMutation::List{}; auto telemetry = TransactionTelemetry{}; if (transaction.has_value()) { mutations = transaction->getMutations(); telemetry = transaction->getTelemetry(); } else { number_++; telemetry.willLayout(); telemetry.didLayout(); telemetry.willCommit(); telemetry.didCommit(); telemetry.willDiff(); telemetry.didDiff(); } transaction = mountingOverrideDelegate->pullTransaction( surfaceId_, number_, telemetry, std::move(mutations)); } #ifdef RN_SHADOW_TREE_INTROSPECTION if (transaction.has_value()) { // We have something to validate. auto mutations = transaction->getMutations(); // No matter what the source of the transaction is, it must be able to // mutate the existing stub view tree. stubViewTree_.mutate(mutations); // If the transaction was overridden, we don't have a model of the shadow // tree therefore we cannot validate the validity of the mutation // instructions. if (!shouldOverridePullTransaction) { auto line = std::string{}; auto stubViewTree = stubViewTreeFromShadowNode(*baseRevision_.rootShadowNode); if (stubViewTree_ != stubViewTree) { std::stringstream ssOldTree( baseRevision_.rootShadowNode->getDebugDescription()); while (std::getline(ssOldTree, line, '\n')) { LOG(ERROR) << "Old tree:" << line; } std::stringstream ssMutations(getDebugDescription(mutations, {})); while (std::getline(ssMutations, line, '\n')) { LOG(ERROR) << "Mutations:" << line; } std::stringstream ssNewTree( lastRevision_->rootShadowNode->getDebugDescription()); while (std::getline(ssNewTree, line, '\n')) { LOG(ERROR) << "New tree:" << line; } } assert( (stubViewTree_ == stubViewTree) && "Incorrect set of mutations detected."); } } #endif return transaction; } TelemetryController const &MountingCoordinator::getTelemetryController() const { return telemetryController_; } } // namespace react } // namespace facebook <|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-2009 Torus Knot Software Ltd 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 "OgreGLSLESExtSupport.h" #include "OgreLogManager.h" namespace Ogre { //----------------------------------------------------------------------------- String logObjectInfo(const String& msg, const GLuint obj) { String logMessage = msg; if (obj > 0) { GLint infologLength = 0; if(glIsShader(obj)) { glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength); GL_CHECK_ERROR } else if(glIsProgram(obj)) { glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength); GL_CHECK_ERROR } if (infologLength > 0) { GLint charsWritten = 0; //GLchar * infoLog = OGRE_NEW GLchar[infologLength]; char * infoLog = new char [infologLength]; if(glIsShader(obj)) { glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog); GL_CHECK_ERROR } else if(glIsProgram(obj)) { glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog); GL_CHECK_ERROR } logMessage += "\n" + String(infoLog); OGRE_DELETE [] infoLog; } } LogManager::getSingleton().logMessage(logMessage); return logMessage; } } // namespace Ogre <commit_msg>Move the logMessage call for GLSL ES linking logs so that there is only output if there is an error.<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-2009 Torus Knot Software Ltd 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 "OgreGLSLESExtSupport.h" #include "OgreLogManager.h" namespace Ogre { //----------------------------------------------------------------------------- String logObjectInfo(const String& msg, const GLuint obj) { String logMessage = msg; if (obj > 0) { GLint infologLength = 0; if(glIsShader(obj)) { glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength); GL_CHECK_ERROR } else if(glIsProgram(obj)) { glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength); GL_CHECK_ERROR } if (infologLength > 0) { GLint charsWritten = 0; //GLchar * infoLog = OGRE_NEW GLchar[infologLength]; char * infoLog = new char [infologLength]; if(glIsShader(obj)) { glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog); GL_CHECK_ERROR } else if(glIsProgram(obj)) { glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog); GL_CHECK_ERROR } logMessage += "\n" + String(infoLog); LogManager::getSingleton().logMessage(logMessage); OGRE_DELETE [] infoLog; } } return logMessage; } } // namespace Ogre <|endoftext|>
<commit_before>#include "FullScreen.h" #include "ShaderFactory.hpp" using namespace Device; using namespace Rendering::PostProcessing; using namespace Rendering::Shader; using namespace Rendering::Texture; using namespace Rendering::Manager; using namespace Rendering::RenderState; void FullScreen::Initialize(Device::DirectX& dx, const InitParam& param, ShaderManager& shaderManager) { std::string folderPath = ""; { Factory::ShaderFactory pathFinder(nullptr); std::string path = pathFinder.FetchShaderFullPath(param.shaderFileName); Utility::String::ParseDirectory(path, &folderPath, nullptr, nullptr); } assert(folderPath.empty() == false);// "Error!, Invalid File Path" std::vector<ShaderMacro> vsMacro; std::string vsKey = "FullScreenVS"; _psUniqueKey = param.shaderFileName + ":" + param.psName; // VS { if (param.useViewInfo) { vsMacro.emplace_back("USE_VIEW_INFORMATION"); vsKey += ":[ViewInfoMacro]:"; } if (param.useMSAAMacro) { vsMacro.push_back(dx.GetMSAAShaderMacro()); constexpr char* key = ":[MSAA]:"; vsKey += key; _psUniqueKey += key; } } if (param.psMacros) { for (auto iter : (*param.psMacros)) _psUniqueKey += ":[" + iter.GetName() + "/" + iter.GetDefinition() + "]"; } _vs = shaderManager.GetPool<VertexShader>().Find(vsKey); if (_vs == nullptr) { // Setting Vertex Shader { std::vector<D3D11_INPUT_ELEMENT_DESC> nullDeclations; auto blob = shaderManager.GetCompiler().CreateBlob(folderPath, param.shaderFileName, "vs", "FullScreenVS", false, &vsMacro); _vs = std::make_shared<VertexShader>(blob, vsKey); _vs->Initialize(dx, nullDeclations); shaderManager.GetPool<VertexShader>().Add(vsKey, _vs); } } _ps = shaderManager.GetPool<PixelShader>().Find(_psUniqueKey); if (_ps == nullptr) { auto blob = shaderManager.GetCompiler().CreateBlob(folderPath, param.shaderFileName, "ps", param.psName, false, param.psMacros); _ps = std::make_shared<PixelShader>(blob, _psUniqueKey); _ps->Initialize(dx); shaderManager.GetPool<PixelShader>().Add(_psUniqueKey, _ps); } } void FullScreen::Render(Device::DirectX& dx, RenderTexture& outResultRT, bool useOutRTViewportSize) const { if(useOutRTViewportSize) { const auto& size = outResultRT.GetSize().Cast<float>(); dx.SetViewport(Rect<float>(0.0f, 0.0f, size.w, size.h)); } dx.SetRenderTarget(outResultRT); dx.SetDepthStencilState(DepthState::DisableDepthTest, 0); dx.SetBlendState(BlendState::Opaque); _vs->BindShaderToContext(dx); _vs->BindInputLayoutToContext(dx); _ps->BindShaderToContext(dx); dx.SetPrimitiveTopology(PrimitiveTopology::TriangleStrip); dx.SetRasterizerState(RasterizerState::CWDefault); dx.GetContext()->Draw(3, 0); dx.SetPrimitiveTopology(PrimitiveTopology::TriangleList); dx.ReSetRenderTargets(1); }<commit_msg>FullScreen - 코드 정리<commit_after>#include "FullScreen.h" #include "ShaderFactory.hpp" using namespace Device; using namespace Rendering::PostProcessing; using namespace Rendering::Shader; using namespace Rendering::Texture; using namespace Rendering::Manager; using namespace Rendering::RenderState; void FullScreen::Initialize(Device::DirectX& dx, const InitParam& param, ShaderManager& shaderManager) { std::string folderPath = ""; { Factory::ShaderFactory pathFinder(nullptr); std::string path = pathFinder.FetchShaderFullPath(param.shaderFileName); Utility::String::ParseDirectory(path, &folderPath, nullptr, nullptr); } assert(folderPath.empty() == false);// "Error!, Invalid File Path" std::vector<ShaderMacro> vsMacro; std::string vsKey = "FullScreenVS"; _psUniqueKey = param.shaderFileName + ":" + param.psName; // VS { if (param.useViewInfo) { vsMacro.emplace_back("USE_VIEW_INFORMATION"); vsKey += ":[ViewInfoMacro]:"; } if (param.useMSAAMacro) { vsMacro.push_back(dx.GetMSAAShaderMacro()); constexpr char* key = ":[MSAA]:"; vsKey += key; _psUniqueKey += key; } } if (param.psMacros) { for (auto iter : (*param.psMacros)) _psUniqueKey += ":[" + iter.GetName() + "/" + iter.GetDefinition() + "]"; } _vs = shaderManager.GetPool<VertexShader>().Find(vsKey); if (_vs == nullptr) { // Setting Vertex Shader { std::vector<D3D11_INPUT_ELEMENT_DESC> nullDeclations; auto blob = shaderManager.GetCompiler().CreateBlob(folderPath, param.shaderFileName, "vs", "FullScreenVS", false, &vsMacro); _vs = std::make_shared<VertexShader>(blob, vsKey); _vs->Initialize(dx, nullDeclations); shaderManager.GetPool<VertexShader>().Add(vsKey, _vs); } } _ps = shaderManager.GetPool<PixelShader>().Find(_psUniqueKey); if (_ps == nullptr) { auto blob = shaderManager.GetCompiler().CreateBlob(folderPath, param.shaderFileName, "ps", param.psName, false, param.psMacros); _ps = std::make_shared<PixelShader>(blob, _psUniqueKey); _ps->Initialize(dx); shaderManager.GetPool<PixelShader>().Add(_psUniqueKey, _ps); } } void FullScreen::Render(Device::DirectX& dx, RenderTexture& outResultRT, bool useOutRTViewportSize) const { if(useOutRTViewportSize) { const auto& size = outResultRT.GetSize().Cast<float>(); dx.SetViewport(Rect<float>(0.0f, 0.0f, size.w, size.h)); } auto rtv = outResultRT.GetRaw(); dx.SetRenderTarget(outResultRT); dx.SetDepthStencilState(DepthState::DisableDepthTest, 0); dx.SetBlendState(BlendState::Opaque); dx.SetPrimitiveTopology(PrimitiveTopology::TriangleStrip); dx.SetRasterizerState(RasterizerState::CWDefault); _vs->BindShaderToContext(dx); _vs->BindInputLayoutToContext(dx); _ps->BindShaderToContext(dx); dx.GetContext()->Draw(3, 0); dx.SetPrimitiveTopology(PrimitiveTopology::TriangleList); dx.ReSetRenderTargets(1); }<|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/geolocation/geolocation_dispatcher_host.h" #include <map> #include <set> #include <utility> #include "base/bind.h" #include "content/browser/geolocation/geolocation_provider_impl.h" #include "content/browser/renderer_host/render_message_filter.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/public/browser/geolocation_permission_context.h" #include "content/public/common/geoposition.h" #include "content/common/geolocation_messages.h" namespace content { namespace { void NotifyArbitratorPermissionGranted() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); GeolocationProviderImpl::GetInstance()->UserDidOptIntoLocationServices(); } void SendGeolocationPermissionResponse(int render_process_id, int render_view_id, int bridge_id, bool allowed) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); RenderViewHostImpl* r = RenderViewHostImpl::FromID(render_process_id, render_view_id); if (!r) return; r->Send(new GeolocationMsg_PermissionSet(render_view_id, bridge_id, allowed)); if (allowed) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&NotifyArbitratorPermissionGranted)); } } class GeolocationDispatcherHostImpl : public GeolocationDispatcherHost { public: GeolocationDispatcherHostImpl( int render_process_id, GeolocationPermissionContext* geolocation_permission_context); // GeolocationDispatcherHost virtual bool OnMessageReceived(const IPC::Message& msg, bool* msg_was_ok) OVERRIDE; private: virtual ~GeolocationDispatcherHostImpl(); void OnRequestPermission(int render_view_id, int bridge_id, const GURL& requesting_frame); void OnCancelPermissionRequest(int render_view_id, int bridge_id, const GURL& requesting_frame); void OnStartUpdating(int render_view_id, const GURL& requesting_frame, bool enable_high_accuracy); void OnStopUpdating(int render_view_id); // Updates the |location_arbitrator_| with the currently required update // options, based on |renderer_high_accuracy_|. void RefreshHighAccuracy(); void OnLocationUpdate(const Geoposition& position); int render_process_id_; scoped_refptr<GeolocationPermissionContext> geolocation_permission_context_; // Iterated when sending location updates to renderer processes. The fan out // to individual bridge IDs happens renderer side, in order to minimize // context switches. // Only used on the IO thread. std::set<int> geolocation_renderer_ids_; // Maps renderer_id to whether high accuracy is requestd for this particular // bridge. std::map<int, bool> renderer_high_accuracy_; // Only set whilst we are registered with the arbitrator. GeolocationProviderImpl* location_provider_; GeolocationProviderImpl::LocationUpdateCallback callback_; DISALLOW_COPY_AND_ASSIGN(GeolocationDispatcherHostImpl); }; GeolocationDispatcherHostImpl::GeolocationDispatcherHostImpl( int render_process_id, GeolocationPermissionContext* geolocation_permission_context) : render_process_id_(render_process_id), geolocation_permission_context_(geolocation_permission_context), location_provider_(NULL) { callback_ = base::Bind( &GeolocationDispatcherHostImpl::OnLocationUpdate, base::Unretained(this)); // This is initialized by ResourceMessageFilter. Do not add any non-trivial // initialization here, defer to OnRegisterBridge which is triggered whenever // a javascript geolocation object is actually initialized. } GeolocationDispatcherHostImpl::~GeolocationDispatcherHostImpl() { if (location_provider_) location_provider_->RemoveLocationUpdateCallback(callback_); } bool GeolocationDispatcherHostImpl::OnMessageReceived( const IPC::Message& msg, bool* msg_was_ok) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); *msg_was_ok = true; bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX(GeolocationDispatcherHostImpl, msg, *msg_was_ok) IPC_MESSAGE_HANDLER(GeolocationHostMsg_CancelPermissionRequest, OnCancelPermissionRequest) IPC_MESSAGE_HANDLER(GeolocationHostMsg_RequestPermission, OnRequestPermission) IPC_MESSAGE_HANDLER(GeolocationHostMsg_StartUpdating, OnStartUpdating) IPC_MESSAGE_HANDLER(GeolocationHostMsg_StopUpdating, OnStopUpdating) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void GeolocationDispatcherHostImpl::OnLocationUpdate( const Geoposition& geoposition) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); for (std::set<int>::iterator it = geolocation_renderer_ids_.begin(); it != geolocation_renderer_ids_.end(); ++it) { Send(new GeolocationMsg_PositionUpdated(*it, geoposition)); } } void GeolocationDispatcherHostImpl::OnRequestPermission( int render_view_id, int bridge_id, const GURL& requesting_frame) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << __FUNCTION__ << " " << render_process_id_ << ":" << render_view_id << ":" << bridge_id; if (geolocation_permission_context_.get()) { geolocation_permission_context_->RequestGeolocationPermission( render_process_id_, render_view_id, bridge_id, requesting_frame, base::Bind(&SendGeolocationPermissionResponse, render_process_id_, render_view_id, bridge_id)); } else { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&SendGeolocationPermissionResponse, render_process_id_, render_view_id, bridge_id, true)); } } void GeolocationDispatcherHostImpl::OnCancelPermissionRequest( int render_view_id, int bridge_id, const GURL& requesting_frame) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << __FUNCTION__ << " " << render_process_id_ << ":" << render_view_id << ":" << bridge_id; if (geolocation_permission_context_.get()) { geolocation_permission_context_->CancelGeolocationPermissionRequest( render_process_id_, render_view_id, bridge_id, requesting_frame); } } void GeolocationDispatcherHostImpl::OnStartUpdating( int render_view_id, const GURL& requesting_frame, bool enable_high_accuracy) { // StartUpdating() can be invoked as a result of high-accuracy mode // being enabled / disabled. No need to record the dispatcher again. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << __FUNCTION__ << " " << render_process_id_ << ":" << render_view_id; if (!geolocation_renderer_ids_.count(render_view_id)) geolocation_renderer_ids_.insert(render_view_id); renderer_high_accuracy_[render_view_id] = enable_high_accuracy; RefreshHighAccuracy(); } void GeolocationDispatcherHostImpl::OnStopUpdating(int render_view_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << __FUNCTION__ << " " << render_process_id_ << ":" << render_view_id; if (renderer_high_accuracy_.erase(render_view_id)) RefreshHighAccuracy(); DCHECK_EQ(1U, geolocation_renderer_ids_.count(render_view_id)); geolocation_renderer_ids_.erase(render_view_id); } void GeolocationDispatcherHostImpl::RefreshHighAccuracy() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (renderer_high_accuracy_.empty()) { if (location_provider_) { location_provider_->RemoveLocationUpdateCallback(callback_); location_provider_ = NULL; } } else { if (!location_provider_) location_provider_ = GeolocationProviderImpl::GetInstance(); // Re-add to re-establish our options, in case they changed. bool use_high_accuracy = false; std::map<int, bool>::iterator i = renderer_high_accuracy_.begin(); for (; i != renderer_high_accuracy_.end(); ++i) { if (i->second) { use_high_accuracy = true; break; } } location_provider_->AddLocationUpdateCallback(callback_, use_high_accuracy); } } } // namespace // GeolocationDispatcherHost -------------------------------------------------- // static GeolocationDispatcherHost* GeolocationDispatcherHost::New( int render_process_id, GeolocationPermissionContext* geolocation_permission_context) { return new GeolocationDispatcherHostImpl( render_process_id, geolocation_permission_context); } GeolocationDispatcherHost::GeolocationDispatcherHost() { } GeolocationDispatcherHost::~GeolocationDispatcherHost() { } } // namespace content <commit_msg>Renaming and comment fixing in geolocation_dispatcher_host.cc.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/geolocation/geolocation_dispatcher_host.h" #include <map> #include <set> #include <utility> #include "base/bind.h" #include "content/browser/geolocation/geolocation_provider_impl.h" #include "content/browser/renderer_host/render_message_filter.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/public/browser/geolocation_permission_context.h" #include "content/public/common/geoposition.h" #include "content/common/geolocation_messages.h" namespace content { namespace { void NotifyGeolocationProviderPermissionGranted() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); GeolocationProviderImpl::GetInstance()->UserDidOptIntoLocationServices(); } void SendGeolocationPermissionResponse(int render_process_id, int render_view_id, int bridge_id, bool allowed) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); RenderViewHostImpl* render_view_host = RenderViewHostImpl::FromID(render_process_id, render_view_id); if (!render_view_host) return; render_view_host->Send( new GeolocationMsg_PermissionSet(render_view_id, bridge_id, allowed)); if (allowed) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&NotifyGeolocationProviderPermissionGranted)); } } class GeolocationDispatcherHostImpl : public GeolocationDispatcherHost { public: GeolocationDispatcherHostImpl( int render_process_id, GeolocationPermissionContext* geolocation_permission_context); // GeolocationDispatcherHost virtual bool OnMessageReceived(const IPC::Message& msg, bool* msg_was_ok) OVERRIDE; private: virtual ~GeolocationDispatcherHostImpl(); void OnRequestPermission(int render_view_id, int bridge_id, const GURL& requesting_frame); void OnCancelPermissionRequest(int render_view_id, int bridge_id, const GURL& requesting_frame); void OnStartUpdating(int render_view_id, const GURL& requesting_frame, bool enable_high_accuracy); void OnStopUpdating(int render_view_id); // Updates the |geolocation_provider_| with the currently required update // options, based on |renderer_high_accuracy_|. void RefreshHighAccuracy(); void OnLocationUpdate(const Geoposition& position); int render_process_id_; scoped_refptr<GeolocationPermissionContext> geolocation_permission_context_; // Iterated when sending location updates to renderer processes. The fan out // to individual bridge IDs happens renderer side, in order to minimize // context switches. // Only used on the IO thread. std::set<int> geolocation_renderer_ids_; // Maps renderer_id to whether high accuracy is requested for this particular // bridge. std::map<int, bool> renderer_high_accuracy_; // Only set whilst we are registered with the geolocation provider. GeolocationProviderImpl* geolocation_provider_; GeolocationProviderImpl::LocationUpdateCallback callback_; DISALLOW_COPY_AND_ASSIGN(GeolocationDispatcherHostImpl); }; GeolocationDispatcherHostImpl::GeolocationDispatcherHostImpl( int render_process_id, GeolocationPermissionContext* geolocation_permission_context) : render_process_id_(render_process_id), geolocation_permission_context_(geolocation_permission_context), geolocation_provider_(NULL) { callback_ = base::Bind( &GeolocationDispatcherHostImpl::OnLocationUpdate, base::Unretained(this)); // This is initialized by ResourceMessageFilter. Do not add any non-trivial // initialization here, defer to OnRegisterBridge which is triggered whenever // a javascript geolocation object is actually initialized. } GeolocationDispatcherHostImpl::~GeolocationDispatcherHostImpl() { if (geolocation_provider_) geolocation_provider_->RemoveLocationUpdateCallback(callback_); } bool GeolocationDispatcherHostImpl::OnMessageReceived( const IPC::Message& msg, bool* msg_was_ok) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); *msg_was_ok = true; bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX(GeolocationDispatcherHostImpl, msg, *msg_was_ok) IPC_MESSAGE_HANDLER(GeolocationHostMsg_CancelPermissionRequest, OnCancelPermissionRequest) IPC_MESSAGE_HANDLER(GeolocationHostMsg_RequestPermission, OnRequestPermission) IPC_MESSAGE_HANDLER(GeolocationHostMsg_StartUpdating, OnStartUpdating) IPC_MESSAGE_HANDLER(GeolocationHostMsg_StopUpdating, OnStopUpdating) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void GeolocationDispatcherHostImpl::OnLocationUpdate( const Geoposition& geoposition) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); for (std::set<int>::iterator it = geolocation_renderer_ids_.begin(); it != geolocation_renderer_ids_.end(); ++it) { Send(new GeolocationMsg_PositionUpdated(*it, geoposition)); } } void GeolocationDispatcherHostImpl::OnRequestPermission( int render_view_id, int bridge_id, const GURL& requesting_frame) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << __FUNCTION__ << " " << render_process_id_ << ":" << render_view_id << ":" << bridge_id; if (geolocation_permission_context_.get()) { geolocation_permission_context_->RequestGeolocationPermission( render_process_id_, render_view_id, bridge_id, requesting_frame, base::Bind(&SendGeolocationPermissionResponse, render_process_id_, render_view_id, bridge_id)); } else { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&SendGeolocationPermissionResponse, render_process_id_, render_view_id, bridge_id, true)); } } void GeolocationDispatcherHostImpl::OnCancelPermissionRequest( int render_view_id, int bridge_id, const GURL& requesting_frame) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << __FUNCTION__ << " " << render_process_id_ << ":" << render_view_id << ":" << bridge_id; if (geolocation_permission_context_.get()) { geolocation_permission_context_->CancelGeolocationPermissionRequest( render_process_id_, render_view_id, bridge_id, requesting_frame); } } void GeolocationDispatcherHostImpl::OnStartUpdating( int render_view_id, const GURL& requesting_frame, bool enable_high_accuracy) { // StartUpdating() can be invoked as a result of high-accuracy mode // being enabled / disabled. No need to record the dispatcher again. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << __FUNCTION__ << " " << render_process_id_ << ":" << render_view_id; if (!geolocation_renderer_ids_.count(render_view_id)) geolocation_renderer_ids_.insert(render_view_id); renderer_high_accuracy_[render_view_id] = enable_high_accuracy; RefreshHighAccuracy(); } void GeolocationDispatcherHostImpl::OnStopUpdating(int render_view_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DVLOG(1) << __FUNCTION__ << " " << render_process_id_ << ":" << render_view_id; if (renderer_high_accuracy_.erase(render_view_id)) RefreshHighAccuracy(); DCHECK_EQ(1U, geolocation_renderer_ids_.count(render_view_id)); geolocation_renderer_ids_.erase(render_view_id); } void GeolocationDispatcherHostImpl::RefreshHighAccuracy() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (renderer_high_accuracy_.empty()) { if (geolocation_provider_) { geolocation_provider_->RemoveLocationUpdateCallback(callback_); geolocation_provider_ = NULL; } } else { if (!geolocation_provider_) geolocation_provider_ = GeolocationProviderImpl::GetInstance(); // Re-add to re-establish our options, in case they changed. bool use_high_accuracy = false; std::map<int, bool>::iterator i = renderer_high_accuracy_.begin(); for (; i != renderer_high_accuracy_.end(); ++i) { if (i->second) { use_high_accuracy = true; break; } } geolocation_provider_->AddLocationUpdateCallback( callback_, use_high_accuracy); } } } // namespace // GeolocationDispatcherHost -------------------------------------------------- // static GeolocationDispatcherHost* GeolocationDispatcherHost::New( int render_process_id, GeolocationPermissionContext* geolocation_permission_context) { return new GeolocationDispatcherHostImpl( render_process_id, geolocation_permission_context); } GeolocationDispatcherHost::GeolocationDispatcherHost() { } GeolocationDispatcherHost::~GeolocationDispatcherHost() { } } // namespace content <|endoftext|>
<commit_before>/** * File : T.cpp * Author : Kazune Takahashi * Created : 2/4/2019, 11:51:23 AM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <numeric> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll MOD = 1000000007; // https://atcoder.jp/contests/tdpc/submissions/4169434 を参考にする。 typedef vector<ll> Poly; ll mod_power(ll x, ll k) { if (k == 0) { return 1; } if (k % 2 == 0) { ll t = mod_power(x, k / 2); return (t * t) % MOD; } return (mod_power(x, k - 1) * x) % MOD; } ll mod_rev(ll x) { return mod_power(x, MOD - 2); } void reduce(Poly &v) { while (!v.empty() && v.back() % MOD != 0) { v.pop_back(); } } Poly X_k(int k, ll a) { vector<ll> p(k + 1, 0); p[k] = a % MOD; return p; } Poly X_k(int k) { vector<ll> p(k + 1, 0); p[k] = 1; return p; } bool is_zero(Poly p) { reduce(p); return p.empty(); } Poly operator+(Poly p, Poly q) { reduce(p); reduce(q); if (p.size() < q.size()) { return q + p; } else { for (auto i = 0; i < (int)q.size(); i++) { p[i] += q[i]; p[i] %= MOD; } } reduce(p); return p; } Poly operator-(Poly p) { reduce(p); for (auto i = 0; i < (int)p.size(); i++) { p[i] %= MOD; p[i] = MOD - p[i]; p[i] %= MOD; } reduce(p); return p; } Poly operator-(Poly p, Poly q) { return p + (-q); } Poly operator*(Poly p, Poly q) { reduce(p); reduce(q); Poly res(p.size() + q.size() - 1, 0); for (auto i = 0; i < (int)res.size(); i++) { for (auto j = 0; j <= i; j++) { if (j < (int)p.size() && i - j < (int)q.size()) { res[i] += (p[j] * q[i - j]) % MOD; res[i] %= MOD; } } } reduce(res); return res; } Poly operator*(Poly p, ll k) { reduce(p); Poly res(p.size()); for (auto i = 0; i < (int)p.size(); i++) { res[i] = (p[i] * k) % MOD; } reduce(res); return res; } Poly operator*(ll k, Poly p) { return p * k; } Poly monic(Poly p) { reduce(p); if (is_zero(p)) { return p; } ll m = p.back(); ll rev_m = mod_rev(m); return rev_m * p; } bool is_monic(const Poly &p) { return (p.back() == 1); } Poly shift(Poly &p, int k) { reduce(p); Poly res(p.size() + k); for (auto i = 0; i < k; i++) { res[i] = 0; } for (auto i = k; i < (int)res.size(); i++) { res[i] = p[i - k]; } return res; } Poly operator%(Poly p, Poly q) { reduce(p); reduce(q); if (p.size() < q.size()) { return p; } if (!is_monic(q)) { return p % monic(q); } Poly s_q = shift(q, p.size() - q.size()); Poly res = (p - p.back() * s_q); reduce(res); return res % q; } Poly mod_power(Poly q, ll k) { if (k == 0) { return {1}; } if (k % 2 == 0) { Poly t = mod_power(q, k / 2); return (t * t) % q; } return (mod_power(q, k - 1) * X_k(1)) % q; } ll K, N; Poly k; vector<ll> a; int main() { cin >> K >> N; if (N <= K) { cout << 1 << endl; return 0; } k = Poly(K + 1); for (auto i = 0; i < K; i++) { k[i] = 1; } k[K] = 1; a = vector<ll>(2 * K - 1); for (auto i = 0; i < K; i++) { a[i] = 1; } for (auto i = K; i < 2 * K - 1; i++) { a[i] = 0; for (auto j = 0; j < K; j++) { a[i] += (a[i - 1 - j] * k[K - 1 - j]) % MOD; a[i] %= MOD; } } for (auto i = 0; i < K; i++) { k[i] = MOD - k[i]; k[i] %= MOD; } Poly f = mod_power(k, N - 1 - K); ll ans = 0; for (auto i = 0; i < min(K, (ll)f.size()); i++) { ans += f[i] * a[K - 1 + i]; ans %= MOD; } cout << ans << endl; }<commit_msg>tried T.cpp to 'T'<commit_after>/** * File : T.cpp * Author : Kazune Takahashi * Created : 2/4/2019, 11:51:23 AM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <numeric> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll MOD = 1000000007; // https://atcoder.jp/contests/tdpc/submissions/4169434 を参考にする。 typedef vector<ll> Poly; ll mod_power(ll x, ll k) { if (k == 0) { return 1; } if (k % 2 == 0) { ll t = mod_power(x, k / 2); return (t * t) % MOD; } return (mod_power(x, k - 1) * x) % MOD; } ll mod_rev(ll x) { return mod_power(x, MOD - 2); } void reduce(Poly &v) { while (!v.empty() && v.back() % MOD != 0) { v.pop_back(); } } Poly X_k(int k, ll a) { vector<ll> p(k + 1, 0); p[k] = a % MOD; return p; } Poly X_k(int k) { vector<ll> p(k + 1, 0); p[k] = 1; return p; } bool is_zero(Poly p) { reduce(p); return p.empty(); } Poly operator+(Poly p, Poly q) { reduce(p); reduce(q); if (p.size() < q.size()) { return q + p; } else { for (auto i = 0; i < (int)q.size(); i++) { p[i] += q[i]; p[i] %= MOD; } } reduce(p); return p; } Poly operator-(Poly p) { reduce(p); for (auto i = 0; i < (int)p.size(); i++) { p[i] %= MOD; p[i] = MOD - p[i]; p[i] %= MOD; } reduce(p); return p; } Poly operator-(Poly p, Poly q) { return p + (-q); } Poly operator*(Poly p, Poly q) { reduce(p); reduce(q); Poly res(p.size() + q.size() - 1, 0); for (auto i = 0; i < (int)res.size(); i++) { for (auto j = 0; j <= i; j++) { if (j < (int)p.size() && i - j < (int)q.size()) { res[i] += (p[j] * q[i - j]) % MOD; res[i] %= MOD; } } } reduce(res); return res; } Poly operator*(Poly p, ll k) { reduce(p); Poly res(p.size()); for (auto i = 0; i < (int)p.size(); i++) { res[i] = (p[i] * k) % MOD; } reduce(res); return res; } Poly operator*(ll k, Poly p) { return p * k; } Poly monic(Poly p) { reduce(p); if (is_zero(p)) { return p; } ll m = p.back(); ll rev_m = mod_rev(m); return rev_m * p; } bool is_monic(const Poly &p) { return (p.back() == 1); } Poly shift(Poly &p, int k) { reduce(p); Poly res(p.size() + k); for (auto i = 0; i < k; i++) { res[i] = 0; } for (auto i = k; i < (int)res.size(); i++) { res[i] = p[i - k]; } return res; } Poly operator%(Poly p, Poly q) { reduce(p); reduce(q); if (p.size() < q.size()) { return p; } if (!is_monic(q)) { return p % monic(q); } Poly s_q = shift(q, p.size() - q.size()); Poly res = (p - p.back() * s_q); reduce(res); return res % q; } Poly mod_power(Poly q, ll k) { if (k == 0) { return {1}; } if (k % 2 == 0) { Poly t = mod_power(q, k / 2); return (t * t) % q; } return (mod_power(q, k - 1) * X_k(1)) % q; } ll K, N; Poly k; vector<ll> a; int main() { cin >> K >> N; if (N <= K) { cout << 1 << endl; return 0; } k = Poly(K + 1); for (auto i = 0; i < K; i++) { k[i] = 1; } k[K] = 1; a = vector<ll>(2 * K - 1); for (auto i = 0; i < K; i++) { a[i] = 1; } for (auto i = K; i < 2 * K - 1; i++) { a[i] = 0; for (auto j = 0; j < K; j++) { a[i] += (a[i - 1 - j] * k[K - 1 - j]) % MOD; a[i] %= MOD; } } cerr << "aaa" << endl; for (auto i = 0; i < K; i++) { k[i] = MOD - k[i]; k[i] %= MOD; } Poly f = mod_power(k, N - 1 - K); ll ans = 0; for (auto i = 0; i < min(K, (ll)f.size()); i++) { ans += f[i] * a[K - 1 + i]; ans %= MOD; } cout << ans << endl; }<|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) Wolf Vollprecht, Johan Mabille and Sylvain Corlay * * Copyright (c) QuantStack * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XTENSOR_TYPE_CASTER_HPP #define XTENSOR_TYPE_CASTER_HPP #include <cstddef> #include <algorithm> #include <vector> #include "xtensor/xtensor.hpp" #include <pybind11/numpy.h> #include <pybind11/pybind11.h> namespace pybind11 { namespace detail { // Casts a strided expression type to numpy array.If given a base, // the numpy array references the src data, otherwise it'll make a copy. // The writeable attributes lets you specify writeable flag for the array. template <typename Type> handle xtensor_array_cast(const Type& src, handle base = handle(), bool writeable = true) { // TODO: make use of xt::pyarray instead of array. std::vector<std::size_t> python_strides(src.strides().size()); std::transform(src.strides().begin(), src.strides().end(), python_strides.begin(), [](auto v) { return sizeof(typename Type::value_type) * v; }); std::vector<std::size_t> python_shape(src.shape().size()); std::copy(src.shape().begin(), src.shape().end(), python_shape.begin()); array a(python_shape, python_strides, &*(src.begin()), base); if (!writeable) { array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_; } return a.release(); } // Takes an lvalue ref to some strided expression type and a (python) base object, creating a numpy array that // reference the expression object's data with `base` as the python-registered base class (if omitted, // the base will be set to None, and lifetime management is up to the caller). The numpy array is // non-writeable if the given type is const. template <typename Type, typename CType> handle xtensor_ref_array(CType& src, handle parent = none()) { return xtensor_array_cast<Type>(src, parent, !std::is_const<CType>::value); } // Takes a pointer to a strided expression, builds a capsule around it, then returns a numpy // array that references the encapsulated data with a python-side reference to the capsule to tie // its destruction to that of any dependent python objects. Const-ness is determined by whether or // not the CType of the pointer given is const. template <typename Type, typename CType> handle xtensor_encapsulate(CType* src) { capsule base(src, [](void* o) { delete static_cast<CType*>(o); }); return xtensor_ref_array<Type>(*src, base); } // Base class of type_caster for strided expressions template <class Type> struct xtensor_type_caster_base { bool load(handle src, bool) { return false; } private: // Cast implementation template <typename CType> static handle cast_impl(CType* src, return_value_policy policy, handle parent) { switch (policy) { case return_value_policy::take_ownership: case return_value_policy::automatic: return xtensor_encapsulate<Type>(src); case return_value_policy::move: return xtensor_encapsulate<Type>(new CType(std::move(*src))); case return_value_policy::copy: return xtensor_array_cast<Type>(*src); case return_value_policy::reference: case return_value_policy::automatic_reference: return xtensor_ref_array<Type>(*src); case return_value_policy::reference_internal: return xtensor_ref_array<Type>(*src, parent); default: throw cast_error("unhandled return_value_policy: should not happen!"); }; } public: // Normal returned non-reference, non-const value: static handle cast(Type&& src, return_value_policy /* policy */, handle parent) { return cast_impl(&src, return_value_policy::move, parent); } // If you return a non-reference const, we mark the numpy array readonly: static handle cast(const Type&& src, return_value_policy /* policy */, handle parent) { return cast_impl(&src, return_value_policy::move, parent); } // lvalue reference return; default (automatic) becomes copy static handle cast(Type& src, return_value_policy policy, handle parent) { if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) { policy = return_value_policy::copy; } return cast_impl(&src, policy, parent); } // const lvalue reference return; default (automatic) becomes copy static handle cast(const Type& src, return_value_policy policy, handle parent) { if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) { policy = return_value_policy::copy; } return cast(&src, policy, parent); } // non-const pointer return static handle cast(Type* src, return_value_policy policy, handle parent) { return cast_impl(src, policy, parent); } // const pointer return static handle cast(const Type* src, return_value_policy policy, handle parent) { return cast_impl(src, policy, parent); } #ifdef PYBIND11_DESCR // The macro is removed from pybind11 since 2.3 static PYBIND11_DESCR name() { return _("xt::xtensor"); } #else static constexpr auto name = _("xt::xtensor"); #endif template <typename T> using cast_op_type = cast_op_type<T>; }; } } #endif <commit_msg>Fixing warning<commit_after>/*************************************************************************** * Copyright (c) Wolf Vollprecht, Johan Mabille and Sylvain Corlay * * Copyright (c) QuantStack * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XTENSOR_TYPE_CASTER_HPP #define XTENSOR_TYPE_CASTER_HPP #include <cstddef> #include <algorithm> #include <vector> #include "xtensor/xtensor.hpp" #include <pybind11/numpy.h> #include <pybind11/pybind11.h> namespace pybind11 { namespace detail { // Casts a strided expression type to numpy array.If given a base, // the numpy array references the src data, otherwise it'll make a copy. // The writeable attributes lets you specify writeable flag for the array. template <typename Type> handle xtensor_array_cast(const Type& src, handle base = handle(), bool writeable = true) { // TODO: make use of xt::pyarray instead of array. std::vector<std::size_t> python_strides(src.strides().size()); std::transform(src.strides().begin(), src.strides().end(), python_strides.begin(), [](auto v) { return sizeof(typename Type::value_type) * v; }); std::vector<std::size_t> python_shape(src.shape().size()); std::copy(src.shape().begin(), src.shape().end(), python_shape.begin()); array a(python_shape, python_strides, &*(src.begin()), base); if (!writeable) { array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_; } return a.release(); } // Takes an lvalue ref to some strided expression type and a (python) base object, creating a numpy array that // reference the expression object's data with `base` as the python-registered base class (if omitted, // the base will be set to None, and lifetime management is up to the caller). The numpy array is // non-writeable if the given type is const. template <typename Type, typename CType> handle xtensor_ref_array(CType& src, handle parent = none()) { return xtensor_array_cast<Type>(src, parent, !std::is_const<CType>::value); } // Takes a pointer to a strided expression, builds a capsule around it, then returns a numpy // array that references the encapsulated data with a python-side reference to the capsule to tie // its destruction to that of any dependent python objects. Const-ness is determined by whether or // not the CType of the pointer given is const. template <typename Type, typename CType> handle xtensor_encapsulate(CType* src) { capsule base(src, [](void* o) { delete static_cast<CType*>(o); }); return xtensor_ref_array<Type>(*src, base); } // Base class of type_caster for strided expressions template <class Type> struct xtensor_type_caster_base { bool load(handle /*src*/, bool) { return false; } private: // Cast implementation template <typename CType> static handle cast_impl(CType* src, return_value_policy policy, handle parent) { switch (policy) { case return_value_policy::take_ownership: case return_value_policy::automatic: return xtensor_encapsulate<Type>(src); case return_value_policy::move: return xtensor_encapsulate<Type>(new CType(std::move(*src))); case return_value_policy::copy: return xtensor_array_cast<Type>(*src); case return_value_policy::reference: case return_value_policy::automatic_reference: return xtensor_ref_array<Type>(*src); case return_value_policy::reference_internal: return xtensor_ref_array<Type>(*src, parent); default: throw cast_error("unhandled return_value_policy: should not happen!"); }; } public: // Normal returned non-reference, non-const value: static handle cast(Type&& src, return_value_policy /* policy */, handle parent) { return cast_impl(&src, return_value_policy::move, parent); } // If you return a non-reference const, we mark the numpy array readonly: static handle cast(const Type&& src, return_value_policy /* policy */, handle parent) { return cast_impl(&src, return_value_policy::move, parent); } // lvalue reference return; default (automatic) becomes copy static handle cast(Type& src, return_value_policy policy, handle parent) { if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) { policy = return_value_policy::copy; } return cast_impl(&src, policy, parent); } // const lvalue reference return; default (automatic) becomes copy static handle cast(const Type& src, return_value_policy policy, handle parent) { if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) { policy = return_value_policy::copy; } return cast(&src, policy, parent); } // non-const pointer return static handle cast(Type* src, return_value_policy policy, handle parent) { return cast_impl(src, policy, parent); } // const pointer return static handle cast(const Type* src, return_value_policy policy, handle parent) { return cast_impl(src, policy, parent); } #ifdef PYBIND11_DESCR // The macro is removed from pybind11 since 2.3 static PYBIND11_DESCR name() { return _("xt::xtensor"); } #else static constexpr auto name = _("xt::xtensor"); #endif template <typename T> using cast_op_type = cast_op_type<T>; }; } } #endif <|endoftext|>
<commit_before>// // This file contains the class InputDialog. // An InputDialog object prompts for an input string using a simple // dialog box. The InputDialog class is also a good example of how // to use the ROOT GUI classes via the interpreter. Since interpreted // classes can not call virtual functions via base class pointers, all // GUI objects are used by composition instead of by inheritance. // // This file contains also some utility functions that use // the InputDialog class to either get a string, integer or // floating point number. There are also two functions showing // how to use the file open and save dialogs. The utility functions are: // // const char *OpenFileDialog() // const char *SaveFileDialog() // const char *GetStringDialog(const char *prompt, const char *defval) // Int_t GetIntegerDialog(const char *prompt, Int_t defval) // Float_t GetFloatDialog(const char *prompt, Float_t defval) // // To use the InputDialog class and the utility functions you just // have to load the Dialogs.C file as follows: // .L Dialogs.C // // Now you can use them like: // { // const char *file = OpenFileDialog(); // Int_t run = GetIntegerDialog("Give run number:", 0); // Int_t event = GetIntegerDialog("Give event number:", 0); // printf("analyse run %d, event %d from file %s\n", run ,event, file); // } // /////////////////////////////////////////////////////////////////////////// // // // Input Dialog Widget // // // /////////////////////////////////////////////////////////////////////////// class InputDialog { private: TGTransientFrame *fDialog; // transient frame, main dialog window TGTextEntry *fTE; // text entry widget containing TList *fWidgets; // keep track of widgets to be deleted in dtor char *fRetStr; // address to store return string public: InputDialog(const char *prompt, const char *defval, char *retstr); ~InputDialog(); void ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2); }; InputDialog::~InputDialog() { // Cleanup dialog. fWidgets->Delete(); delete fWidgets; delete fTE; delete fDialog; } InputDialog::InputDialog(const char *prompt, const char *defval, char *retstr) { // Create simple input dialog. fWidgets = new TList; TGWindow *main = gClient->GetRoot(); fDialog = new TGTransientFrame(main, main, 10, 10); // command to be executed by buttons and text entry widget char cmd[128]; sprintf(cmd, "{long r__ptr=0x%lx; ((InputDialog*)r__ptr)->ProcessMessage($MSG,$PARM1,$PARM2);}", (Long_t)this); // create prompt label and textentry widget TGLabel *label = new TGLabel(fDialog, prompt); fWidgets->Add(label); TGTextBuffer *tbuf = new TGTextBuffer(256); //will be deleted by TGtextEntry tbuf->AddText(0, defval); fTE = new TGTextEntry(fDialog, tbuf); fTE->Resize(260, fTE->GetDefaultHeight()); fTE->SetCommand(cmd); TGLayoutHints *l1 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0); TGLayoutHints *l2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5); fWidgets->Add(l1); fWidgets->Add(l2); fDialog->AddFrame(label, l1); fDialog->AddFrame(fTE, l2); // create frame and layout hints for Ok and Cancel buttons TGHorizontalFrame *hf = new TGHorizontalFrame(fDialog, 60, 20, kFixedWidth); TGLayoutHints *l3 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0); // put hf as last in list to be deleted fWidgets->Add(l3); // create OK and Cancel buttons in their own frame (hf) UInt_t nb = 0, width = 0, height = 0; TGTextButton *b; b = new TGTextButton(hf, "&Ok", cmd, 1); fWidgets->Add(b); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; b = new TGTextButton(hf, "&Cancel", cmd, 2); fWidgets->Add(b); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; // place button frame (hf) at the bottom TGLayoutHints *l4 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5); fWidgets->Add(l4); fWidgets->Add(hf); fDialog->AddFrame(hf, l4); // keep buttons centered and with the same width hf->Resize((width + 20) * nb, height); // set dialog title fDialog->SetWindowName("Get Input"); // map all widgets and calculate size of dialog fDialog->MapSubwindows(); width = fDialog->GetDefaultWidth(); height = fDialog->GetDefaultHeight(); fDialog->Resize(width, height); // position relative to the parent window (which is the root window) Window_t wdum; int ax, ay; gVirtualX->TranslateCoordinates(main->GetId(), main->GetId(), (((TGFrame *) main)->GetWidth() - width) >> 1, (((TGFrame *) main)->GetHeight() - height) >> 1, ax, ay, wdum); fDialog->Move(ax, ay); fDialog->SetWMPosition(ax, ay); // make the message box non-resizable fDialog->SetWMSize(width, height); fDialog->SetWMSizeHints(width, height, width, height, 0, 0); fDialog->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH | kMWMDecorMaximize | kMWMDecorMinimize | kMWMDecorMenu, kMWMFuncAll | kMWMFuncResize | kMWMFuncMaximize | kMWMFuncMinimize, kMWMInputModeless); // popup dialog and wait till user replies fDialog->MapWindow(); fRetStr = retstr; gClient->WaitFor(fDialog); } void InputDialog::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Handle button and text enter events switch (GET_MSG(msg)) { case kC_COMMAND: switch (GET_SUBMSG(msg)) { case kCM_BUTTON: switch (parm1) { case 1: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; case 2: fRetStr[0] = 0; delete this; break; } default: break; } break; case kC_TEXTENTRY: switch (GET_SUBMSG(msg)) { case kTE_ENTER: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; default: break; } break; default: break; } } //--- Utility Functions -------------------------------------------------------- const char *OpenFileDialog() { // Prompt for file to be opened. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gOpenAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gOpenAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDOpen, &fi); return fi.fFilename; } const char *SaveFileDialog() { // Prompt for file to be saved. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gSaveAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gSaveAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDSave, &fi); return fi.fFilename; } const char *GetStringDialog(const char *prompt, const char *defval) { // Prompt for string. The typed in string is returned. static char answer[128]; new InputDialog(prompt, defval, answer); return answer; } Int_t GetIntegerDialog(const char *prompt, Int_t defval) { // Prompt for integer. The typed in integer is returned. static char answer[32]; char defv[32]; sprintf(defv, "%d", defval); new InputDialog(prompt, defv, answer); return atoi(answer); } Float_t GetFloatDialog(const char *prompt, Float_t defval) { // Prompt for float. The typed in float is returned. static char answer[32]; char defv[32]; sprintf(defv, "%f", defval); new InputDialog(prompt, defv, answer); return atof(answer); } <commit_msg>Fix Jira #ROOT-8404 macro Dialogs.C does not compile and crashes<commit_after>// // This file contains the class InputDialog. // An InputDialog object prompts for an input string using a simple // dialog box. The InputDialog class is also a good example of how // to use the ROOT GUI classes via the interpreter. Since interpreted // classes can not call virtual functions via base class pointers, all // GUI objects are used by composition instead of by inheritance. // // This file contains also some utility functions that use // the InputDialog class to either get a string, integer or // floating point number. There are also two functions showing // how to use the file open and save dialogs. The utility functions are: // // const char *OpenFileDialog() // const char *SaveFileDialog() // const char *GetStringDialog(const char *prompt, const char *defval) // Int_t GetIntegerDialog(const char *prompt, Int_t defval) // Float_t GetFloatDialog(const char *prompt, Float_t defval) // // To use the InputDialog class and the utility functions you just // have to load the Dialogs.C file as follows: // .L Dialogs.C // // Now you can use them like: // { // const char *file = OpenFileDialog(); // Int_t run = GetIntegerDialog("Give run number:", 0); // Int_t event = GetIntegerDialog("Give event number:", 0); // printf("analyse run %d, event %d from file %s\n", run ,event, file); // } // #include "TList.h" #include "TGLabel.h" #include "TGButton.h" #include "TGText.h" #include "TGFileDialog.h" #include "TGTextEntry.h" /////////////////////////////////////////////////////////////////////////// // // // Input Dialog Widget // // // /////////////////////////////////////////////////////////////////////////// class InputDialog { private: TGTransientFrame *fDialog; // transient frame, main dialog window TGTextEntry *fTE; // text entry widget containing char *fRetStr; // address to store return string public: InputDialog(const char *prompt, const char *defval, char *retstr); ~InputDialog(); void ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2); }; InputDialog::~InputDialog() { // Cleanup dialog. fDialog->DeleteWindow(); // cleanup and delete fDialog } InputDialog::InputDialog(const char *prompt, const char *defval, char *retstr) { // Create simple input dialog. const TGWindow *main = gClient->GetRoot(); fDialog = new TGTransientFrame(main, main, 10, 10); fDialog->SetCleanup(kDeepCleanup); // command to be executed by buttons and text entry widget char cmd[128]; sprintf(cmd, "{long r__ptr=0x%lx; ((InputDialog*)r__ptr)->ProcessMessage($MSG,$PARM1,$PARM2);}", (Long_t)this); // create prompt label and textentry widget TGLabel *label = new TGLabel(fDialog, prompt); TGTextBuffer *tbuf = new TGTextBuffer(256); //will be deleted by TGtextEntry tbuf->AddText(0, defval); fTE = new TGTextEntry(fDialog, tbuf); fTE->Resize(260, fTE->GetDefaultHeight()); fTE->SetCommand(cmd); TGLayoutHints *l1 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 0); TGLayoutHints *l2 = new TGLayoutHints(kLHintsTop | kLHintsLeft, 5, 5, 5, 5); fDialog->AddFrame(label, l1); fDialog->AddFrame(fTE, l2); // create frame and layout hints for Ok and Cancel buttons TGHorizontalFrame *hf = new TGHorizontalFrame(fDialog, 60, 20, kFixedWidth); TGLayoutHints *l3 = new TGLayoutHints(kLHintsCenterY | kLHintsExpandX, 5, 5, 0, 0); // create OK and Cancel buttons in their own frame (hf) UInt_t nb = 0, width = 0, height = 0; TGTextButton *b; b = new TGTextButton(hf, "&Ok", cmd, 1); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; b = new TGTextButton(hf, "&Cancel", cmd, 2); b->Associate(fDialog); hf->AddFrame(b, l3); height = b->GetDefaultHeight(); width = TMath::Max(width, b->GetDefaultWidth()); ++nb; // place button frame (hf) at the bottom TGLayoutHints *l4 = new TGLayoutHints(kLHintsBottom | kLHintsCenterX, 0, 0, 5, 5); fDialog->AddFrame(hf, l4); // keep buttons centered and with the same width hf->Resize((width + 20) * nb, height); // set dialog title fDialog->SetWindowName("Get Input"); // map all widgets and calculate size of dialog fDialog->MapSubwindows(); width = fDialog->GetDefaultWidth(); height = fDialog->GetDefaultHeight(); fDialog->Resize(width, height); // position relative to the parent window (which is the root window) Window_t wdum; int ax, ay; gVirtualX->TranslateCoordinates(main->GetId(), main->GetId(), (((TGFrame *) main)->GetWidth() - width) >> 1, (((TGFrame *) main)->GetHeight() - height) >> 1, ax, ay, wdum); fDialog->Move(ax, ay); fDialog->SetWMPosition(ax, ay); // make the message box non-resizable fDialog->SetWMSize(width, height); fDialog->SetWMSizeHints(width, height, width, height, 0, 0); fDialog->SetMWMHints(kMWMDecorAll | kMWMDecorResizeH | kMWMDecorMaximize | kMWMDecorMinimize | kMWMDecorMenu, kMWMFuncAll | kMWMFuncResize | kMWMFuncMaximize | kMWMFuncMinimize, kMWMInputModeless); // popup dialog and wait till user replies fDialog->MapWindow(); fRetStr = retstr; gClient->WaitFor(fDialog); } void InputDialog::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Handle button and text enter events switch (GET_MSG(msg)) { case kC_COMMAND: switch (GET_SUBMSG(msg)) { case kCM_BUTTON: switch (parm1) { case 1: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; case 2: fRetStr[0] = 0; delete this; break; } default: break; } break; case kC_TEXTENTRY: switch (GET_SUBMSG(msg)) { case kTE_ENTER: // here copy the string from text buffer to return variable strcpy(fRetStr, fTE->GetBuffer()->GetString()); delete this; break; default: break; } break; default: break; } } //--- Utility Functions -------------------------------------------------------- const char *OpenFileDialog() { // Prompt for file to be opened. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gOpenAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gOpenAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDOpen, &fi); return fi.fFilename; } const char *SaveFileDialog() { // Prompt for file to be saved. Depending on navigation in // dialog the current working directory can be changed. // The returned file name is always with respect to the // current directory. const char *gSaveAsTypes[] = { "Macro files", "*.C", "ROOT files", "*.root", "PostScript", "*.ps", "Encapsulated PostScript", "*.eps", "Gif files", "*.gif", "All files", "*", 0, 0 }; static TGFileInfo fi; fi.fFileTypes = gSaveAsTypes; new TGFileDialog(gClient->GetRoot(), gClient->GetRoot(), kFDSave, &fi); return fi.fFilename; } const char *GetStringDialog(const char *prompt, const char *defval) { // Prompt for string. The typed in string is returned. static char answer[128]; new InputDialog(prompt, defval, answer); return answer; } Int_t GetIntegerDialog(const char *prompt, Int_t defval) { // Prompt for integer. The typed in integer is returned. static char answer[32]; char defv[32]; sprintf(defv, "%d", defval); new InputDialog(prompt, defv, answer); return atoi(answer); } Float_t GetFloatDialog(const char *prompt, Float_t defval) { // Prompt for float. The typed in float is returned. static char answer[32]; char defv[32]; sprintf(defv, "%f", defval); new InputDialog(prompt, defv, answer); return atof(answer); } <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/spiel.h" #include "open_spiel/spiel_utils.h" #include "open_spiel/tests/basic_tests.h" namespace open_spiel { namespace quoridor { namespace { namespace testing = open_spiel::testing; void BasicQuoridorTests() { testing::LoadGameTest("quoridor(board_size=5)"); testing::NoChanceOutcomesTest(*LoadGame("quoridor()")); testing::RandomSimTest(*LoadGame("quoridor"), 10); for (int i = 5; i <= 13; i++) { testing::RandomSimTest( *LoadGame(absl::StrCat("quoridor(board_size=", i, ")")), 5); } testing::RandomSimTest( *LoadGame("quoridor(board_size=9,wall_count=5)"), 3); // Ansi colors! testing::RandomSimTest( *LoadGame("quoridor", {{"board_size", GameParameter(9)}, {"ansi_color_output", GameParameter(true)}}), 3); testing::RandomSimTest( *LoadGame("quoridor(board_size=5,ansi_color_output=True)"), 3); testing::RandomSimBenchmark("quoridor(board_size=5)", 1000); testing::RandomSimBenchmark("quoridor(board_size=9)", 100); testing::RandomSimBenchmark("quoridor(board_size=19)", 10); } } // namespace } // namespace quoridor } // namespace open_spiel int main(int argc, char** argv) { open_spiel::quoridor::BasicQuoridorTests(); } <commit_msg>Add a benchmark warmup. Otherwise it has higher variance, especially if all the previous tests are commented out to reduce console output.<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include "open_spiel/spiel.h" #include "open_spiel/spiel_utils.h" #include "open_spiel/tests/basic_tests.h" namespace open_spiel { namespace quoridor { namespace { namespace testing = open_spiel::testing; void BasicQuoridorTests() { testing::LoadGameTest("quoridor(board_size=5)"); testing::NoChanceOutcomesTest(*LoadGame("quoridor()")); testing::RandomSimTest(*LoadGame("quoridor"), 10); for (int i = 5; i <= 13; i++) { testing::RandomSimTest( *LoadGame(absl::StrCat("quoridor(board_size=", i, ")")), 5); } testing::RandomSimTest( *LoadGame("quoridor(board_size=9,wall_count=5)"), 3); // Ansi colors! testing::RandomSimTest( *LoadGame("quoridor", {{"board_size", GameParameter(9)}, {"ansi_color_output", GameParameter(true)}}), 3); testing::RandomSimTest( *LoadGame("quoridor(board_size=5,ansi_color_output=True)"), 3); std::cout << "Benchmark warmup:" << std::endl; testing::RandomSimBenchmark("quoridor(board_size=5)", 1000); std::cout << std::endl; std::cout << "Real:" << std::endl; testing::RandomSimBenchmark("quoridor(board_size=5)", 10000); testing::RandomSimBenchmark("quoridor(board_size=9)", 1000); testing::RandomSimBenchmark("quoridor(board_size=19)", 10); } } // namespace } // namespace quoridor } // namespace open_spiel int main(int argc, char** argv) { open_spiel::quoridor::BasicQuoridorTests(); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Javier López-Gómez <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "DefinitionShadower.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Utils/AST.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclContextInternals.h" #include "clang/AST/Stmt.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { /// \brief Returns whether the given source location is a Cling input line. If /// it came from the prompt, the file is a virtual file with overriden contents. static bool typedInClingPrompt(FullSourceLoc L) { if (L.isInvalid()) return false; const SourceManager &SM = L.getManager(); const FileID FID = SM.getFileID(L); return SM.isFileOverridden(SM.getFileEntryForID(FID)) && (SM.getFileID(SM.getIncludeLoc(FID)) == SM.getMainFileID()); } /// \brief Returns whether the given {Function,Tag,Var}Decl/TemplateDecl is a definition. static bool isDefinition(const Decl *D) { if (auto FD = dyn_cast<FunctionDecl>(D)) return FD->isThisDeclarationADefinition(); if (auto TD = dyn_cast<TagDecl>(D)) return TD->isThisDeclarationADefinition(); if (auto VD = dyn_cast<VarDecl>(D)) return VD->isThisDeclarationADefinition(); if (auto TD = dyn_cast<TemplateDecl>(D)) return isDefinition(TD->getTemplatedDecl()); return true; } /// \brief Returns whether the given declaration is a template instantiation /// or specialization. static bool isInstantiationOrSpecialization(const Decl *D) { if (auto FD = dyn_cast<FunctionDecl>(D)) return FD->isTemplateInstantiation() || FD->isFunctionTemplateSpecialization(); if (auto CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) return CTSD->getSpecializationKind() != TSK_Undeclared; if (auto VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) return VTSD->getSpecializationKind() != TSK_Undeclared; return false; } DefinitionShadower::DefinitionShadower(Sema& S, Interpreter& I) : ASTTransformer(&S), m_Context(S.getASTContext()), m_Interp(I), m_TU(S.getASTContext().getTranslationUnitDecl()) {} bool DefinitionShadower::isClingShadowNamespace(const DeclContext *DC) { auto NS = dyn_cast<NamespaceDecl>(DC); return NS && NS->getName().startswith("__cling_N5"); } void DefinitionShadower::hideDecl(clang::NamedDecl *D) const { // FIXME: this hides a decl from SemaLookup (there is no unloading). For // (large) L-values, this might be a memory leak. Should this be fixed? if (Scope* S = m_Sema->getScopeForContext(m_TU)) { S->RemoveDecl(D); if (utils::Analyze::isOnScopeChains(D, *m_Sema)) m_Sema->IdResolver.RemoveDecl(D); } clang::StoredDeclsList &SDL = (*m_TU->getLookupPtr())[D->getDeclName()]; if (SDL.getAsVector() || SDL.getAsDecl() == D) SDL.remove(D); if (InterpreterCallbacks *IC = m_Interp.getCallbacks()) IC->DefinitionShadowed(D); } void DefinitionShadower::invalidatePreviousDefinitions(NamedDecl *D) const { LookupResult Previous(*m_Sema, D->getDeclName(), D->getLocation(), Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); m_Sema->LookupQualifiedName(Previous, m_TU); for (auto Prev : Previous) { if (Prev == D) continue; if (isDefinition(Prev) && !isDefinition(D)) continue; // If the found declaration is a function overload, do not invalidate it. // For templated functions, Sema::IsOverload() does the right thing as per // C++ [temp.over.link]p4. if (isa<FunctionDecl>(Prev) && isa<FunctionDecl>(D) && m_Sema->IsOverload(cast<FunctionDecl>(D), cast<FunctionDecl>(Prev), /*IsForUsingDecl=*/false)) continue; if (isa<FunctionTemplateDecl>(Prev) && isa<FunctionTemplateDecl>(D) && m_Sema->IsOverload(cast<FunctionTemplateDecl>(D)->getTemplatedDecl(), cast<FunctionTemplateDecl>(Prev)->getTemplatedDecl(), /*IsForUsingDecl=*/false)) continue; hideDecl(Prev); // For unscoped enumerations, also invalidate all enumerators. if (EnumDecl *ED = dyn_cast<EnumDecl>(Prev)) { if (!ED->isTransparentContext()) continue; for (auto &J : ED->decls()) if (NamedDecl *ND = dyn_cast<NamedDecl>(J)) hideDecl(ND); } } // Ignore any forward declaration issued after a definition. Fixes "error // : reference to 'xxx' is ambiguous" in `class C {}; class C; C foo;`. if (!Previous.empty() && !isDefinition(D)) D->setInvalidDecl(); } void DefinitionShadower::invalidatePreviousDefinitions(FunctionDecl *D) const { const CompilationOptions &CO = getTransaction()->getCompilationOpts(); if (utils::Analyze::IsWrapper(D)) { if (!CO.DeclarationExtraction) return; // DeclExtractor shall move local declarations to the TU. Invalidate all // previous definitions (that may clash) before it runs. auto CS = dyn_cast<CompoundStmt>(D->getBody()); for (auto &I : CS->body()) { auto DS = dyn_cast<DeclStmt>(I); if (!DS) continue; for (auto &J : DS->decls()) if (auto ND = dyn_cast<NamedDecl>(J)) invalidatePreviousDefinitions(ND); } } else invalidatePreviousDefinitions(cast<NamedDecl>(D)); } void DefinitionShadower::invalidatePreviousDefinitions(Decl *D) const { if (auto FD = dyn_cast<FunctionDecl>(D)) invalidatePreviousDefinitions(FD); else if (auto ND = dyn_cast<NamedDecl>(D)) invalidatePreviousDefinitions(ND); } ASTTransformer::Result DefinitionShadower::Transform(Decl* D) { Transaction *T = getTransaction(); if (!T->getCompilationOpts().EnableShadowing) return Result(D, true); // For variable templates, Transform() is invoked with a VarDecl; get the // corresponding VarTemplateDecl. if (auto VD = dyn_cast<VarDecl>(D)) if (auto VTD = VD->getDescribedVarTemplate()) D = VTD; // Disable definition shadowing for some specific cases. if (D->getLexicalDeclContext() != m_TU || D->isInvalidDecl() || isa<UsingDirectiveDecl>(D) || isa<UsingDecl>(D) || isa<NamespaceDecl>(D) || isInstantiationOrSpecialization(D) || !typedInClingPrompt(FullSourceLoc{D->getLocation(), m_Context.getSourceManager()})) return Result(D, true); // Each transaction gets at most a `__cling_N5xxx' namespace. If `T' already // has one, reuse it. auto NS = T->getDefinitionShadowNS(); if (!NS) { NS = NamespaceDecl::Create(m_Context, m_TU, /*inline=*/true, SourceLocation(), SourceLocation(), &m_Context.Idents.get("__cling_N5" + std::to_string(m_UniqueNameCounter++)), nullptr); //NS->setImplicit(); m_TU->addDecl(NS); T->setDefinitionShadowNS(NS); } m_TU->removeDecl(D); if (isa<CXXRecordDecl>(D->getDeclContext())) D->setLexicalDeclContext(NS); else D->setDeclContext(NS); // An instantiated function template inherits the declaration context of the // templated decl. This is used for name mangling; fix it to avoid clashing. if (auto FTD = dyn_cast<FunctionTemplateDecl>(D)) FTD->getTemplatedDecl()->setDeclContext(NS); NS->addDecl(D); // Invalidate previous definitions so that LookupResult::resolveKind() does not // mark resolution as ambiguous. invalidatePreviousDefinitions(D); return Result(D, true); } } // end namespace cling <commit_msg>Improve "[cling] DefinitionShadower: allow shadowing of non-user-defined declarations (#6571)"<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Javier López-Gómez <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "DefinitionShadower.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Utils/AST.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclContextInternals.h" #include "clang/AST/Stmt.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Sema.h" #include <algorithm> using namespace clang; namespace cling { /// \brief Returns whether the given source location is a Cling input line. If /// it came from the prompt, the file is a virtual file with overriden contents. static bool typedInClingPrompt(FullSourceLoc L) { if (L.isInvalid()) return false; const SourceManager &SM = L.getManager(); const FileID FID = SM.getFileID(L); return SM.isFileOverridden(SM.getFileEntryForID(FID)) && (SM.getFileID(SM.getIncludeLoc(FID)) == SM.getMainFileID()); } /// \brief Returns whether the given {Function,Tag,Var}Decl/TemplateDecl is a definition. static bool isDefinition(const Decl *D) { if (auto FD = dyn_cast<FunctionDecl>(D)) return FD->isThisDeclarationADefinition(); if (auto TD = dyn_cast<TagDecl>(D)) return TD->isThisDeclarationADefinition(); if (auto VD = dyn_cast<VarDecl>(D)) return VD->isThisDeclarationADefinition(); if (auto TD = dyn_cast<TemplateDecl>(D)) return isDefinition(TD->getTemplatedDecl()); return true; } /// \brief Returns whether the given declaration is a template instantiation /// or specialization. static bool isInstantiationOrSpecialization(const Decl *D) { if (auto FD = dyn_cast<FunctionDecl>(D)) return FD->isTemplateInstantiation() || FD->isFunctionTemplateSpecialization(); if (auto CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) return CTSD->getSpecializationKind() != TSK_Undeclared; if (auto VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) return VTSD->getSpecializationKind() != TSK_Undeclared; return false; } DefinitionShadower::DefinitionShadower(Sema& S, Interpreter& I) : ASTTransformer(&S), m_Context(S.getASTContext()), m_Interp(I), m_TU(S.getASTContext().getTranslationUnitDecl()) {} bool DefinitionShadower::isClingShadowNamespace(const DeclContext *DC) { auto NS = dyn_cast<NamespaceDecl>(DC); return NS && NS->getName().startswith("__cling_N5"); } void DefinitionShadower::hideDecl(clang::NamedDecl *D) const { // FIXME: this hides a decl from SemaLookup (there is no unloading). For // (large) L-values, this might be a memory leak. Should this be fixed? if (Scope* S = m_Sema->getScopeForContext(m_TU)) { S->RemoveDecl(D); if (utils::Analyze::isOnScopeChains(D, *m_Sema)) m_Sema->IdResolver.RemoveDecl(D); } clang::StoredDeclsList &SDL = (*m_TU->getLookupPtr())[D->getDeclName()]; if (SDL.getAsDecl() == D) { SDL.setOnlyValue(nullptr); } if (auto Vec = SDL.getAsVector()) { // FIXME: investigate why StoredDeclList has duplicated entries coming from PCM. Vec->erase(std::remove_if(Vec->begin(), Vec->end(), [D](Decl *Other) { return cast<Decl>(D) == Other; }), Vec->end()); } if (InterpreterCallbacks *IC = m_Interp.getCallbacks()) IC->DefinitionShadowed(D); } void DefinitionShadower::invalidatePreviousDefinitions(NamedDecl *D) const { LookupResult Previous(*m_Sema, D->getDeclName(), D->getLocation(), Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); m_Sema->LookupQualifiedName(Previous, m_TU); for (auto Prev : Previous) { if (Prev == D) continue; if (isDefinition(Prev) && !isDefinition(D)) continue; // If the found declaration is a function overload, do not invalidate it. // For templated functions, Sema::IsOverload() does the right thing as per // C++ [temp.over.link]p4. if (isa<FunctionDecl>(Prev) && isa<FunctionDecl>(D) && m_Sema->IsOverload(cast<FunctionDecl>(D), cast<FunctionDecl>(Prev), /*IsForUsingDecl=*/false)) continue; if (isa<FunctionTemplateDecl>(Prev) && isa<FunctionTemplateDecl>(D) && m_Sema->IsOverload(cast<FunctionTemplateDecl>(D)->getTemplatedDecl(), cast<FunctionTemplateDecl>(Prev)->getTemplatedDecl(), /*IsForUsingDecl=*/false)) continue; hideDecl(Prev); // For unscoped enumerations, also invalidate all enumerators. if (EnumDecl *ED = dyn_cast<EnumDecl>(Prev)) { if (!ED->isTransparentContext()) continue; for (auto &J : ED->decls()) if (NamedDecl *ND = dyn_cast<NamedDecl>(J)) hideDecl(ND); } } // Ignore any forward declaration issued after a definition. Fixes "error // : reference to 'xxx' is ambiguous" in `class C {}; class C; C foo;`. if (!Previous.empty() && !isDefinition(D)) D->setInvalidDecl(); } void DefinitionShadower::invalidatePreviousDefinitions(FunctionDecl *D) const { const CompilationOptions &CO = getTransaction()->getCompilationOpts(); if (utils::Analyze::IsWrapper(D)) { if (!CO.DeclarationExtraction) return; // DeclExtractor shall move local declarations to the TU. Invalidate all // previous definitions (that may clash) before it runs. auto CS = dyn_cast<CompoundStmt>(D->getBody()); for (auto &I : CS->body()) { auto DS = dyn_cast<DeclStmt>(I); if (!DS) continue; for (auto &J : DS->decls()) if (auto ND = dyn_cast<NamedDecl>(J)) invalidatePreviousDefinitions(ND); } } else invalidatePreviousDefinitions(cast<NamedDecl>(D)); } void DefinitionShadower::invalidatePreviousDefinitions(Decl *D) const { if (auto FD = dyn_cast<FunctionDecl>(D)) invalidatePreviousDefinitions(FD); else if (auto ND = dyn_cast<NamedDecl>(D)) invalidatePreviousDefinitions(ND); } ASTTransformer::Result DefinitionShadower::Transform(Decl* D) { Transaction *T = getTransaction(); if (!T->getCompilationOpts().EnableShadowing) return Result(D, true); // For variable templates, Transform() is invoked with a VarDecl; get the // corresponding VarTemplateDecl. if (auto VD = dyn_cast<VarDecl>(D)) if (auto VTD = VD->getDescribedVarTemplate()) D = VTD; // Disable definition shadowing for some specific cases. if (D->getLexicalDeclContext() != m_TU || D->isInvalidDecl() || isa<UsingDirectiveDecl>(D) || isa<UsingDecl>(D) || isa<NamespaceDecl>(D) || isInstantiationOrSpecialization(D) || !typedInClingPrompt(FullSourceLoc{D->getLocation(), m_Context.getSourceManager()})) return Result(D, true); // Each transaction gets at most a `__cling_N5xxx' namespace. If `T' already // has one, reuse it. auto NS = T->getDefinitionShadowNS(); if (!NS) { NS = NamespaceDecl::Create(m_Context, m_TU, /*inline=*/true, SourceLocation(), SourceLocation(), &m_Context.Idents.get("__cling_N5" + std::to_string(m_UniqueNameCounter++)), nullptr); //NS->setImplicit(); m_TU->addDecl(NS); T->setDefinitionShadowNS(NS); } m_TU->removeDecl(D); if (isa<CXXRecordDecl>(D->getDeclContext())) D->setLexicalDeclContext(NS); else D->setDeclContext(NS); // An instantiated function template inherits the declaration context of the // templated decl. This is used for name mangling; fix it to avoid clashing. if (auto FTD = dyn_cast<FunctionTemplateDecl>(D)) FTD->getTemplatedDecl()->setDeclContext(NS); NS->addDecl(D); // Invalidate previous definitions so that LookupResult::resolveKind() does not // mark resolution as ambiguous. invalidatePreviousDefinitions(D); return Result(D, true); } } // end namespace cling <|endoftext|>
<commit_before>// RUN: cat %s | %cling -I%p | FileCheck %s // This file should be used as regression test for the meta processing subsystem // Reproducers of fixed bugs should be put here // PR #93092 // Don't remove the spaces and tabs .L cling/Interpreter/Interpreter.h .x ./DotXable.h(5) // CHECK: 5 // End PR #93092 <commit_msg>Make sure that we have proper case preventing such scenario as from today.<commit_after>// RUN: cat %s | %cling -I%p | FileCheck %s // This file should be used as regression test for the meta processing subsystem // Reproducers of fixed bugs should be put here // PR #93092 // Don't remove the spaces and tabs .L cling/Interpreter/Interpreter.h .x ./DotXable.h(5) // CHECK: 5 // End PR #93092 .X ./DotXable(10) // CHECK: 10 <|endoftext|>
<commit_before>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r option. // //===----------------------------------------------------------------------===// #include "Support/CommandLine.h" #include "Support/FileUtilities.h" #include <iostream> #include <cmath> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } /// OpenFile - mmap the specified file into the address space for reading, and /// return the length and address of the buffer. static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){ BufPtr = (char*)ReadFileIntoAddressSpace(Filename, Len); if (BufPtr == 0) { std::cerr << "Error: cannot open file '" << Filename << "'\n"; exit(2); } } static bool isNumberChar(char C) { switch (C) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '+': case '-': case 'e': case 'E': return true; default: return false; } } static char *BackupNumber(char *Pos, char *FirstChar) { // If we didn't stop in the middle of a number, don't backup. if (!isNumberChar(*Pos)) return Pos; // Otherwise, return to the start of the number. while (Pos > FirstChar && isNumberChar(Pos[-1])) --Pos; return Pos; } static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) { char *F1NumEnd, *F2NumEnd; double V1, V2; // If we stop on numbers, compare their difference. if (isNumberChar(*F1P) && isNumberChar(*F2P)) { V1 = strtod(F1P, &F1NumEnd); V2 = strtod(F2P, &F2NumEnd); } else { // Otherwise, the diff failed. F1NumEnd = F1P; F2NumEnd = F2P; } if (F1NumEnd == F1P || F2NumEnd == F2P) { std::cerr << "Comparison failed, not a numeric difference.\n"; exit(1); } // Check to see if these are inside the absolute tolerance if (AbsTolerance < std::abs(V1-V2)) { // Nope, check the relative tolerance... double Diff; if (V2) Diff = std::abs(V1/V2 - 1.0); else if (V1) Diff = std::abs(V2/V1 - 1.0); else Diff = 0; // Both zero. if (Diff > RelTolerance) { std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = " << Diff << "\n"; std::cerr << "Out of tolerance: rel/abs: " << RelTolerance << "/" << AbsTolerance << "\n"; exit(1); } } // Otherwise, advance our read pointers to the end of the numbers. F1P = F1NumEnd; F2P = F2NumEnd; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); // mmap in the files. unsigned File1Len, File2Len; char *File1Start, *File2Start; OpenFile(File1, File1Len, File1Start); OpenFile(File2, File2Len, File2Start); // Okay, now that we opened the files, scan them for the first difference. char *File1End = File1Start+File1Len; char *File2End = File2Start+File2Len; char *F1P = File1Start; char *F2P = File2Start; while (1) { // Scan for the end of file or first difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; if (F1P >= File1End || F2P >= File2End) break; // Okay, we must have found a difference. Backup to the start of the // current number each stream is at so that we can compare from the // beginning. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); } // Okay, we reached the end of file. If both files are at the end, we // succeeded. if (F1P >= File1End && F2P >= File2End) return 0; // Otherwise, we might have run off the end due to a number, backup and retry. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); // If we found the end, we succeeded. if (F1P >= File1End && F2P >= File2End) return 0; return 1; } <commit_msg>Get rid of "might be uninitialized" warnings when compiling with GCC 3.3.2<commit_after>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r option. // //===----------------------------------------------------------------------===// #include "Support/CommandLine.h" #include "Support/FileUtilities.h" #include <iostream> #include <cmath> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } /// OpenFile - mmap the specified file into the address space for reading, and /// return the length and address of the buffer. static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){ BufPtr = (char*)ReadFileIntoAddressSpace(Filename, Len); if (BufPtr == 0) { std::cerr << "Error: cannot open file '" << Filename << "'\n"; exit(2); } } static bool isNumberChar(char C) { switch (C) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '+': case '-': case 'e': case 'E': return true; default: return false; } } static char *BackupNumber(char *Pos, char *FirstChar) { // If we didn't stop in the middle of a number, don't backup. if (!isNumberChar(*Pos)) return Pos; // Otherwise, return to the start of the number. while (Pos > FirstChar && isNumberChar(Pos[-1])) --Pos; return Pos; } static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) { char *F1NumEnd, *F2NumEnd; double V1 = 0.0, V2 = 0.0; // If we stop on numbers, compare their difference. if (isNumberChar(*F1P) && isNumberChar(*F2P)) { V1 = strtod(F1P, &F1NumEnd); V2 = strtod(F2P, &F2NumEnd); } else { // Otherwise, the diff failed. F1NumEnd = F1P; F2NumEnd = F2P; } if (F1NumEnd == F1P || F2NumEnd == F2P) { std::cerr << "Comparison failed, not a numeric difference.\n"; exit(1); } // Check to see if these are inside the absolute tolerance if (AbsTolerance < std::abs(V1-V2)) { // Nope, check the relative tolerance... double Diff; if (V2) Diff = std::abs(V1/V2 - 1.0); else if (V1) Diff = std::abs(V2/V1 - 1.0); else Diff = 0; // Both zero. if (Diff > RelTolerance) { std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = " << Diff << "\n"; std::cerr << "Out of tolerance: rel/abs: " << RelTolerance << "/" << AbsTolerance << "\n"; exit(1); } } // Otherwise, advance our read pointers to the end of the numbers. F1P = F1NumEnd; F2P = F2NumEnd; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); // mmap in the files. unsigned File1Len, File2Len; char *File1Start, *File2Start; OpenFile(File1, File1Len, File1Start); OpenFile(File2, File2Len, File2Start); // Okay, now that we opened the files, scan them for the first difference. char *File1End = File1Start+File1Len; char *File2End = File2Start+File2Len; char *F1P = File1Start; char *F2P = File2Start; while (1) { // Scan for the end of file or first difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; if (F1P >= File1End || F2P >= File2End) break; // Okay, we must have found a difference. Backup to the start of the // current number each stream is at so that we can compare from the // beginning. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); } // Okay, we reached the end of file. If both files are at the end, we // succeeded. if (F1P >= File1End && F2P >= File2End) return 0; // Otherwise, we might have run off the end due to a number, backup and retry. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); // If we found the end, we succeeded. if (F1P >= File1End && F2P >= File2End) return 0; return 1; } <|endoftext|>
<commit_before>#include <cstddef> #include <cstdint> #include <cwchar> #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <shlobj.h> #include <Macros.hpp> #include <Config.hpp> #include <Globals.hpp> #include <ClassFactory.hpp> HMODULE ModuleInstance; std::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved) { switch( Reason ) { case DLL_PROCESS_ATTACH: { ModuleInstance = hDLL; DisableThreadLibraryCalls(hDLL); break; } } return true; } /// Registers this DLL as a COM server extern "C" HRESULT __stdcall DllRegisterServer() { WCHAR ModulePath[MAX_PATH]; GetModuleFileNameW( ModuleInstance, ModulePath, MAX_PATH ); const SaiThumb::RegistryEntry Registry[] = { { HKEY_CURRENT_USER, L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID, nullptr, REG_SZ, SaiThumbHandlerName }, { HKEY_CURRENT_USER, L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID L"\\InProcServer32", nullptr, REG_SZ, ModulePath }, { HKEY_CURRENT_USER, L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID L"\\InProcServer32", L"ThreadingModel", REG_SZ, L"Apartment" }, { HKEY_CURRENT_USER, L"Software\\Classes\\" SaiThumbHandlerExtension L"\\ShellEx\\" IThumbnailProviderCLSID, nullptr, REG_SZ, SaiThumbHandlerCLSID }, }; for( std::size_t i = 0; i < countof(Registry); i++ ) { HKEY CurKey; const SaiThumb::RegistryEntry& CurReg = Registry[i]; RegCreateKeyExW( CurReg.Root, CurReg.KeyName, 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nullptr, &CurKey, nullptr ); RegSetValueExW( CurKey, CurReg.KeyValue, 0, CurReg.ValueType, reinterpret_cast<const unsigned char*>(CurReg.Data), static_cast<std::uint32_t>((std::wcslen(CurReg.Data) + 1) * sizeof(wchar_t)) ); RegCloseKey(CurKey); } HKEY CurKey; RegCreateKeyExW( HKEY_CURRENT_USER, L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID, 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nullptr, &CurKey, nullptr ); DWORD DisableProcessIsolation = 1; RegSetValueExW( CurKey, L"DisableProcessIsolation", 0, REG_DWORD, reinterpret_cast<const unsigned char*>(&DisableProcessIsolation), sizeof(DWORD) ); RegCloseKey(CurKey); RegCreateKeyExW( HKEY_CURRENT_USER, L"Software\\Classes\\" SaiThumbHandlerExtension, 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nullptr, &CurKey, nullptr ); DWORD Treatment = 2; RegSetValueExW( CurKey, L"Treatment", 0, REG_DWORD, reinterpret_cast<const unsigned char*>(&Treatment), sizeof(DWORD) ); RegCloseKey(CurKey); SHChangeNotify( SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nullptr, nullptr ); return S_OK; } /// Unregisters this DLL as a COM server extern "C" HRESULT __stdcall DllUnregisterServer() { const wchar_t* RegistryFolders[] = { L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID, L"Software\\Classes\\" SaiThumbHandlerExtension }; for( std::size_t i = 0; i < countof(RegistryFolders); i++ ) { RegDeleteTreeW( HKEY_CURRENT_USER, RegistryFolders[i] ); } return S_OK; } extern "C" HRESULT __stdcall DllCanUnloadNow() { return Globals::ReferenceGet() ? S_FALSE : S_OK; } extern "C" HRESULT __stdcall DllGetClassObject( const IID& rclsid, const IID& riid, void** ppv) { if( ppv == nullptr ) { return E_INVALIDARG; } IID ThumbHandlerCLSID; IIDFromString(SaiThumbHandlerCLSID, &ThumbHandlerCLSID); if( !IsEqualCLSID(ThumbHandlerCLSID,rclsid) ) { return CLASS_E_CLASSNOTAVAILABLE; } CClassFactory* ClassFactory = new CClassFactory(); if( ClassFactory == nullptr ) { return E_OUTOFMEMORY; } const HRESULT Result = ClassFactory->QueryInterface(riid, ppv); ClassFactory->Release(); return Result; } <commit_msg>Remove caching of module handle<commit_after>#include <cstddef> #include <cstdint> #include <cwchar> #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <shlobj.h> #include <Macros.hpp> #include <Config.hpp> #include <Globals.hpp> #include <ClassFactory.hpp> extern "C" IMAGE_DOS_HEADER __ImageBase; std::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved) { switch( Reason ) { case DLL_PROCESS_ATTACH: { DisableThreadLibraryCalls(hDLL); break; } } return true; } /// Registers this DLL as a COM server extern "C" HRESULT __stdcall DllRegisterServer() { WCHAR ModulePath[MAX_PATH]; GetModuleFileNameW( reinterpret_cast<HMODULE>(&__ImageBase), ModulePath, MAX_PATH ); const SaiThumb::RegistryEntry Registry[] = { { HKEY_CURRENT_USER, L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID, nullptr, REG_SZ, SaiThumbHandlerName }, { HKEY_CURRENT_USER, L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID L"\\InProcServer32", nullptr, REG_SZ, ModulePath }, { HKEY_CURRENT_USER, L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID L"\\InProcServer32", L"ThreadingModel", REG_SZ, L"Apartment" }, { HKEY_CURRENT_USER, L"Software\\Classes\\" SaiThumbHandlerExtension L"\\ShellEx\\" IThumbnailProviderCLSID, nullptr, REG_SZ, SaiThumbHandlerCLSID }, }; for( std::size_t i = 0; i < countof(Registry); i++ ) { HKEY CurKey; const SaiThumb::RegistryEntry& CurReg = Registry[i]; RegCreateKeyExW( CurReg.Root, CurReg.KeyName, 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nullptr, &CurKey, nullptr ); RegSetValueExW( CurKey, CurReg.KeyValue, 0, CurReg.ValueType, reinterpret_cast<const unsigned char*>(CurReg.Data), static_cast<std::uint32_t>((std::wcslen(CurReg.Data) + 1) * sizeof(wchar_t)) ); RegCloseKey(CurKey); } HKEY CurKey; RegCreateKeyExW( HKEY_CURRENT_USER, L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID, 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nullptr, &CurKey, nullptr ); DWORD DisableProcessIsolation = 1; RegSetValueExW( CurKey, L"DisableProcessIsolation", 0, REG_DWORD, reinterpret_cast<const unsigned char*>(&DisableProcessIsolation), sizeof(DWORD) ); RegCloseKey(CurKey); RegCreateKeyExW( HKEY_CURRENT_USER, L"Software\\Classes\\" SaiThumbHandlerExtension, 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, nullptr, &CurKey, nullptr ); DWORD Treatment = 2; RegSetValueExW( CurKey, L"Treatment", 0, REG_DWORD, reinterpret_cast<const unsigned char*>(&Treatment), sizeof(DWORD) ); RegCloseKey(CurKey); SHChangeNotify( SHCNE_ASSOCCHANGED, SHCNF_IDLIST, nullptr, nullptr ); return S_OK; } /// Unregisters this DLL as a COM server extern "C" HRESULT __stdcall DllUnregisterServer() { const wchar_t* RegistryFolders[] = { L"Software\\Classes\\CLSID\\" SaiThumbHandlerCLSID, L"Software\\Classes\\" SaiThumbHandlerExtension }; for( std::size_t i = 0; i < countof(RegistryFolders); i++ ) { RegDeleteTreeW( HKEY_CURRENT_USER, RegistryFolders[i] ); } return S_OK; } extern "C" HRESULT __stdcall DllCanUnloadNow() { return Globals::ReferenceGet() ? S_FALSE : S_OK; } extern "C" HRESULT __stdcall DllGetClassObject( const IID& rclsid, const IID& riid, void** ppv) { if( ppv == nullptr ) { return E_INVALIDARG; } IID ThumbHandlerCLSID; IIDFromString(SaiThumbHandlerCLSID, &ThumbHandlerCLSID); if( !IsEqualCLSID(ThumbHandlerCLSID,rclsid) ) { return CLASS_E_CLASSNOTAVAILABLE; } CClassFactory* ClassFactory = new CClassFactory(); if( ClassFactory == nullptr ) { return E_OUTOFMEMORY; } const HRESULT Result = ClassFactory->QueryInterface(riid, ppv); ClassFactory->Release(); return Result; } <|endoftext|>
<commit_before>#include <ctrcommon/app.hpp> #include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <stdio.h> #include <sstream> #include <iomanip> #include <sys/dirent.h> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "FBI v1.3.3" << "\n"; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; stream << "Y - Receive an app over the network" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; std::string batchInfo = ""; auto onProgress = [&](u64 pos, u64 totalSize) { std::stringstream details; details << batchInfo; details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n"; details << "Press B to cancel."; u32 progress = (u32) (((double) pos / (double) totalSize) * 100); uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress); inputPoll(); return !inputIsPressed(BUTTON_B); }; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { if(netInstall && !exit) { screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN); if(file.fd == NULL) { netInstall = false; continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } fclose(file.fd); continue; } uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); u32 currItem = 0; for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; std::string fileName = (*it).name; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { if(mode == INSTALL_CIA) { std::stringstream batchInstallStream; batchInstallStream << fileName << " (" << currItem << ")" << "\n"; batchInfo = batchInstallStream.str(); AppResult ret = appInstallFile(destination, path, onProgress); batchInfo = ""; if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } } else { std::stringstream deleteStream; deleteStream << "Deleting CIA..." << "\n"; deleteStream << fileName << " (" << currItem << ")" << "\n"; uiDisplayMessage(TOP_SCREEN, deleteStream.str()); if(!fsDelete(path)) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } currItem++; } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { uiDisplayMessage(TOP_SCREEN, "Deleting CIA..."); if(fsDelete(path)) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiDisplayMessage(BOTTOM_SCREEN, "Loading title list..."); uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(exit) { break; } } platformCleanup(); return 0; } <commit_msg>Don't stop batch installations for items that already exist.<commit_after>#include <ctrcommon/app.hpp> #include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <stdio.h> #include <sstream> #include <iomanip> #include <sys/dirent.h> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "FBI v1.3.4" << "\n"; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; stream << "Y - Receive an app over the network" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; std::string batchInfo = ""; auto onProgress = [&](u64 pos, u64 totalSize) { std::stringstream details; details << batchInfo; details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n"; details << "Press B to cancel."; u32 progress = (u32) (((double) pos / (double) totalSize) * 100); uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress); inputPoll(); return !inputIsPressed(BUTTON_B); }; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { if(netInstall && !exit) { screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN); if(file.fd == NULL) { netInstall = false; continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } fclose(file.fd); continue; } uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); u32 currItem = 0; for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; std::string fileName = (*it).name; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { if(mode == INSTALL_CIA) { std::stringstream batchInstallStream; batchInstallStream << fileName << " (" << currItem << ")" << "\n"; batchInfo = batchInstallStream.str(); AppResult ret = appInstallFile(destination, path, onProgress); batchInfo = ""; if(ret != APP_SUCCESS) { Error error = platformGetError(); platformSetError(error); std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); if(error.module != MODULE_AM || error.description != DESCRIPTION_ALREADY_EXISTS) { failed = true; break; } } } else { std::stringstream deleteStream; deleteStream << "Deleting CIA..." << "\n"; deleteStream << fileName << " (" << currItem << ")" << "\n"; uiDisplayMessage(TOP_SCREEN, deleteStream.str()); if(!fsDelete(path)) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } currItem++; } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { uiDisplayMessage(TOP_SCREEN, "Deleting CIA..."); if(fsDelete(path)) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiDisplayMessage(BOTTOM_SCREEN, "Loading title list..."); uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(exit) { break; } } platformCleanup(); return 0; } <|endoftext|>
<commit_before>/** * @file linux_volume_catcher.cpp * @brief A Linux-specific, PulseAudio-specific hack to detect and volume-adjust new audio sources * * @cond * $LicenseInfo:firstyear=2010&license=viewergpl$ * * Copyright (c) 2010, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlife.com/developers/opensource/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at http://secondlife.com/developers/opensource/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ * @endcond */ #include "linden_common.h" #include <glib.h> #include <pulse/introspect.h> #include <pulse/context.h> #include <pulse/subscribe.h> #include <pulse/glib-mainloop.h> // There's no special reason why we want the *glib* PA mainloop, but the generic polling implementation seems broken. #include "linux_volume_catcher.h" //////////////////////////////////////////////////// // PulseAudio requires a chain of callbacks with C linkage extern "C" { void callback_discovered_sinkinput(pa_context *context, const pa_sink_input_info *i, int eol, void *userdata); void callback_subscription_alert(pa_context *context, pa_subscription_event_type_t t, uint32_t index, void *userdata); void callback_context_state(pa_context *context, void *userdata); } class LinuxVolumeCatcherImpl { public: LinuxVolumeCatcherImpl(); ~LinuxVolumeCatcherImpl(); void setVolume(F32 volume); void pump(void); // for internal use - can't be private because used from our C callbacks void init(); void cleanup(); void update_all_volumes(F32 volume); void update_index_volume(U32 index, F32 volume); void connected_okay(); std::set<U32> mSinkInputIndices; std::map<U32,U32> mSinkInputNumChannels; F32 mDesiredVolume; pa_glib_mainloop *mMainloop; pa_context *mPAContext; bool mConnected; }; LinuxVolumeCatcherImpl::LinuxVolumeCatcherImpl() : mDesiredVolume(0.0f), mMainloop(NULL), mPAContext(NULL), mConnected(false) { init(); } LinuxVolumeCatcherImpl::~LinuxVolumeCatcherImpl() { cleanup(); } void LinuxVolumeCatcherImpl::init() { // try to be as robust as possible because PA's interface is a // bit fragile and (for our purposes) we'd rather simply not function // than crash mMainloop = pa_glib_mainloop_new(g_main_context_default()); if (mMainloop) { pa_mainloop_api *api = pa_glib_mainloop_get_api(mMainloop); if (api) { pa_proplist *proplist = pa_proplist_new(); if (proplist) { pa_proplist_sets(proplist, PA_PROP_APPLICATION_ICON_NAME, "multimedia-player"); pa_proplist_sets(proplist, PA_PROP_APPLICATION_ID, "com.secondlife.viewer.mediaplugvoladjust"); pa_proplist_sets(proplist, PA_PROP_APPLICATION_NAME, "SL Plugin Volume Adjuster"); pa_proplist_sets(proplist, PA_PROP_APPLICATION_VERSION, "1"); // plain old pa_context_new() is broken! mPAContext = pa_context_new_with_proplist(api, NULL, proplist); pa_proplist_free(proplist); } } } // Now we've set up a PA context and mainloop, try connecting the // PA context to a PA daemon. if (mPAContext) { pa_context_set_state_callback(mPAContext, callback_context_state, this); pa_context_flags_t cflags = (pa_context_flags)0; // maybe add PA_CONTEXT_NOAUTOSPAWN? if (pa_context_connect(mPAContext, NULL, cflags, NULL) >= 0) { // Okay! We haven't definitely connected, but we // haven't definitely failed yet. } else { // Failed to connect to PA manager... we'll leave // things like that. Perhaps we should try again later. } } } void LinuxVolumeCatcherImpl::cleanup() { // there's some cleanup we could do, but do nothing... for now. mConnected = false; } void LinuxVolumeCatcherImpl::setVolume(F32 volume) { mDesiredVolume = volume; if (mConnected && mPAContext) { update_all_volumes(mDesiredVolume); } pump(); } void LinuxVolumeCatcherImpl::pump() { gboolean may_block = FALSE; g_main_context_iteration(g_main_context_default(), may_block); } void LinuxVolumeCatcherImpl::connected_okay() { pa_operation *op; // fetch global list of existing sinkinputs if ((op = pa_context_get_sink_input_info_list(mPAContext, callback_discovered_sinkinput, this))) { pa_operation_unref(op); } // subscribe to future global sinkinput changes pa_context_set_subscribe_callback(mPAContext, callback_subscription_alert, this); if ((op = pa_context_subscribe(mPAContext, (pa_subscription_mask_t) (PA_SUBSCRIPTION_MASK_SINK_INPUT), NULL, NULL))) { pa_operation_unref(op); } } void LinuxVolumeCatcherImpl::update_all_volumes(F32 volume) { for (std::set<U32>::iterator it = mSinkInputIndices.begin(); it != mSinkInputIndices.end(); ++it) { update_index_volume(*it, volume); } } void LinuxVolumeCatcherImpl::update_index_volume(U32 index, F32 volume) { static pa_cvolume cvol; pa_cvolume_set(&cvol, mSinkInputNumChannels[index], pa_sw_volume_from_linear(volume)); pa_context *c = mPAContext; uint32_t idx = index; const pa_cvolume *cvolumep = &cvol; pa_context_success_cb_t cb = NULL; // okay as null void *userdata = NULL; // okay as null pa_operation *op; if ((op = pa_context_set_sink_input_volume(c, idx, cvolumep, cb, userdata))) { pa_operation_unref(op); } } void callback_discovered_sinkinput(pa_context *context, const pa_sink_input_info *sii, int eol, void *userdata) { LinuxVolumeCatcherImpl *impl = dynamic_cast<LinuxVolumeCatcherImpl*>((LinuxVolumeCatcherImpl*)userdata); llassert(impl); if (0 == eol) { pa_proplist *proplist = sii->proplist; pid_t sinkpid = atoll(pa_proplist_gets(proplist, PA_PROP_APPLICATION_PROCESS_ID)); fprintf(stderr, "Found sinkinput #%d, name=%s, pid=%d\t", sii->index, sii->name, int(sinkpid)); if (sinkpid == getpid()) // does the discovered sinkinput belong to this process? { bool is_new = (impl->mSinkInputIndices.find(sii->index) == impl->mSinkInputIndices.end()); impl->mSinkInputIndices.insert(sii->index); impl->mSinkInputNumChannels[sii->index] = sii->channel_map.channels; if (is_new) { // new! fprintf(stderr, "\nJACKPOT!\n"); impl->update_index_volume(sii->index, impl->mDesiredVolume); } else { // seen it already, do nothing. } } } } void callback_subscription_alert(pa_context *context, pa_subscription_event_type_t t, uint32_t index, void *userdata) { LinuxVolumeCatcherImpl *impl = dynamic_cast<LinuxVolumeCatcherImpl*>((LinuxVolumeCatcherImpl*)userdata); llassert(impl); switch (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) { case PA_SUBSCRIPTION_EVENT_SINK_INPUT: if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { // forget this sinkinput, if we were caring about it impl->mSinkInputIndices.erase(index); impl->mSinkInputNumChannels.erase(index); } else { // ask for more info about this new sinkinput pa_operation *op; if ((op = pa_context_get_sink_input_info(impl->mPAContext, index, callback_discovered_sinkinput, impl))) { pa_operation_unref(op); } } break; default:; } } void callback_context_state(pa_context *context, void *userdata) { LinuxVolumeCatcherImpl *impl = dynamic_cast<LinuxVolumeCatcherImpl*>((LinuxVolumeCatcherImpl*)userdata); llassert(impl); switch (pa_context_get_state(context)) { case PA_CONTEXT_READY: impl->mConnected = true; impl->connected_okay(); break; case PA_CONTEXT_TERMINATED: impl->mConnected = false; break; case PA_CONTEXT_FAILED: impl->mConnected = false; break; default:; } } ///////////////////////////////////////////////////// LinuxVolumeCatcher::LinuxVolumeCatcher() { pimpl = new LinuxVolumeCatcherImpl(); } LinuxVolumeCatcher::~LinuxVolumeCatcher() { delete pimpl; pimpl = NULL; } void LinuxVolumeCatcher::setVolume(F32 volume) { llassert(pimpl); pimpl->setVolume(volume); } void LinuxVolumeCatcher::pump() { llassert(pimpl); pimpl->pump(); } <commit_msg>document the linux_volume_catcher high-level design<commit_after>/** * @file linux_volume_catcher.cpp * @brief A Linux-specific, PulseAudio-specific hack to detect and volume-adjust new audio sources * * @cond * $LicenseInfo:firstyear=2010&license=viewergpl$ * * Copyright (c) 2010, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlife.com/developers/opensource/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at http://secondlife.com/developers/opensource/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ * @endcond */ /* The high-level design is as follows: 1) Connect to the PulseAudio daemon 2) Watch for the creation of new audio players connecting to the daemon (this includes ALSA clients running on the PulseAudio emulation layer, such as Flash plugins) 3) Examine the audio player's PID to see if it belongs to our own process 4) If so, tell PA to adjust the volume of that audio player ('sink input' in PA parlance) 5) Keep a list of all living audio players that we care about, adjust the volumes of all of them when we get a new setVolume() call */ #include "linden_common.h" #include <glib.h> #include <pulse/introspect.h> #include <pulse/context.h> #include <pulse/subscribe.h> #include <pulse/glib-mainloop.h> // There's no special reason why we want the *glib* PA mainloop, but the generic polling implementation seems broken. #include "linux_volume_catcher.h" //////////////////////////////////////////////////// // PulseAudio requires a chain of callbacks with C linkage extern "C" { void callback_discovered_sinkinput(pa_context *context, const pa_sink_input_info *i, int eol, void *userdata); void callback_subscription_alert(pa_context *context, pa_subscription_event_type_t t, uint32_t index, void *userdata); void callback_context_state(pa_context *context, void *userdata); } class LinuxVolumeCatcherImpl { public: LinuxVolumeCatcherImpl(); ~LinuxVolumeCatcherImpl(); void setVolume(F32 volume); void pump(void); // for internal use - can't be private because used from our C callbacks void init(); void cleanup(); void update_all_volumes(F32 volume); void update_index_volume(U32 index, F32 volume); void connected_okay(); std::set<U32> mSinkInputIndices; std::map<U32,U32> mSinkInputNumChannels; F32 mDesiredVolume; pa_glib_mainloop *mMainloop; pa_context *mPAContext; bool mConnected; }; LinuxVolumeCatcherImpl::LinuxVolumeCatcherImpl() : mDesiredVolume(0.0f), mMainloop(NULL), mPAContext(NULL), mConnected(false) { init(); } LinuxVolumeCatcherImpl::~LinuxVolumeCatcherImpl() { cleanup(); } void LinuxVolumeCatcherImpl::init() { // try to be as robust as possible because PA's interface is a // bit fragile and (for our purposes) we'd rather simply not function // than crash mMainloop = pa_glib_mainloop_new(g_main_context_default()); if (mMainloop) { pa_mainloop_api *api = pa_glib_mainloop_get_api(mMainloop); if (api) { pa_proplist *proplist = pa_proplist_new(); if (proplist) { pa_proplist_sets(proplist, PA_PROP_APPLICATION_ICON_NAME, "multimedia-player"); pa_proplist_sets(proplist, PA_PROP_APPLICATION_ID, "com.secondlife.viewer.mediaplugvoladjust"); pa_proplist_sets(proplist, PA_PROP_APPLICATION_NAME, "SL Plugin Volume Adjuster"); pa_proplist_sets(proplist, PA_PROP_APPLICATION_VERSION, "1"); // plain old pa_context_new() is broken! mPAContext = pa_context_new_with_proplist(api, NULL, proplist); pa_proplist_free(proplist); } } } // Now we've set up a PA context and mainloop, try connecting the // PA context to a PA daemon. if (mPAContext) { pa_context_set_state_callback(mPAContext, callback_context_state, this); pa_context_flags_t cflags = (pa_context_flags)0; // maybe add PA_CONTEXT_NOAUTOSPAWN? if (pa_context_connect(mPAContext, NULL, cflags, NULL) >= 0) { // Okay! We haven't definitely connected, but we // haven't definitely failed yet. } else { // Failed to connect to PA manager... we'll leave // things like that. Perhaps we should try again later. } } } void LinuxVolumeCatcherImpl::cleanup() { // there's some cleanup we could do, but do nothing... for now. mConnected = false; } void LinuxVolumeCatcherImpl::setVolume(F32 volume) { mDesiredVolume = volume; if (mConnected && mPAContext) { update_all_volumes(mDesiredVolume); } pump(); } void LinuxVolumeCatcherImpl::pump() { gboolean may_block = FALSE; g_main_context_iteration(g_main_context_default(), may_block); } void LinuxVolumeCatcherImpl::connected_okay() { pa_operation *op; // fetch global list of existing sinkinputs if ((op = pa_context_get_sink_input_info_list(mPAContext, callback_discovered_sinkinput, this))) { pa_operation_unref(op); } // subscribe to future global sinkinput changes pa_context_set_subscribe_callback(mPAContext, callback_subscription_alert, this); if ((op = pa_context_subscribe(mPAContext, (pa_subscription_mask_t) (PA_SUBSCRIPTION_MASK_SINK_INPUT), NULL, NULL))) { pa_operation_unref(op); } } void LinuxVolumeCatcherImpl::update_all_volumes(F32 volume) { for (std::set<U32>::iterator it = mSinkInputIndices.begin(); it != mSinkInputIndices.end(); ++it) { update_index_volume(*it, volume); } } void LinuxVolumeCatcherImpl::update_index_volume(U32 index, F32 volume) { static pa_cvolume cvol; pa_cvolume_set(&cvol, mSinkInputNumChannels[index], pa_sw_volume_from_linear(volume)); pa_context *c = mPAContext; uint32_t idx = index; const pa_cvolume *cvolumep = &cvol; pa_context_success_cb_t cb = NULL; // okay as null void *userdata = NULL; // okay as null pa_operation *op; if ((op = pa_context_set_sink_input_volume(c, idx, cvolumep, cb, userdata))) { pa_operation_unref(op); } } void callback_discovered_sinkinput(pa_context *context, const pa_sink_input_info *sii, int eol, void *userdata) { LinuxVolumeCatcherImpl *impl = dynamic_cast<LinuxVolumeCatcherImpl*>((LinuxVolumeCatcherImpl*)userdata); llassert(impl); if (0 == eol) { pa_proplist *proplist = sii->proplist; pid_t sinkpid = atoll(pa_proplist_gets(proplist, PA_PROP_APPLICATION_PROCESS_ID)); fprintf(stderr, "Found sinkinput #%d, name=%s, pid=%d\t", sii->index, sii->name, int(sinkpid)); if (sinkpid == getpid()) // does the discovered sinkinput belong to this process? { bool is_new = (impl->mSinkInputIndices.find(sii->index) == impl->mSinkInputIndices.end()); impl->mSinkInputIndices.insert(sii->index); impl->mSinkInputNumChannels[sii->index] = sii->channel_map.channels; if (is_new) { // new! fprintf(stderr, "\nJACKPOT!\n"); impl->update_index_volume(sii->index, impl->mDesiredVolume); } else { // seen it already, do nothing. } } } } void callback_subscription_alert(pa_context *context, pa_subscription_event_type_t t, uint32_t index, void *userdata) { LinuxVolumeCatcherImpl *impl = dynamic_cast<LinuxVolumeCatcherImpl*>((LinuxVolumeCatcherImpl*)userdata); llassert(impl); switch (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) { case PA_SUBSCRIPTION_EVENT_SINK_INPUT: if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { // forget this sinkinput, if we were caring about it impl->mSinkInputIndices.erase(index); impl->mSinkInputNumChannels.erase(index); } else { // ask for more info about this new sinkinput pa_operation *op; if ((op = pa_context_get_sink_input_info(impl->mPAContext, index, callback_discovered_sinkinput, impl))) { pa_operation_unref(op); } } break; default:; } } void callback_context_state(pa_context *context, void *userdata) { LinuxVolumeCatcherImpl *impl = dynamic_cast<LinuxVolumeCatcherImpl*>((LinuxVolumeCatcherImpl*)userdata); llassert(impl); switch (pa_context_get_state(context)) { case PA_CONTEXT_READY: impl->mConnected = true; impl->connected_okay(); break; case PA_CONTEXT_TERMINATED: impl->mConnected = false; break; case PA_CONTEXT_FAILED: impl->mConnected = false; break; default:; } } ///////////////////////////////////////////////////// LinuxVolumeCatcher::LinuxVolumeCatcher() { pimpl = new LinuxVolumeCatcherImpl(); } LinuxVolumeCatcher::~LinuxVolumeCatcher() { delete pimpl; pimpl = NULL; } void LinuxVolumeCatcher::setVolume(F32 volume) { llassert(pimpl); pimpl->setVolume(volume); } void LinuxVolumeCatcher::pump() { llassert(pimpl); pimpl->pump(); } <|endoftext|>
<commit_before>#include <math.h> #include "GameIncludes.h" #ifdef __APPLE__ #include <Glut/glut.h> #else #define FREEGLUT_STATIC #include <GL/glut.h> #endif #include "TweakAnt/AntTweakBar.h" // PI #define GL_PI 3.14159f // Current size of window. int width = 600; int height = 600; // old values for the window (used to come back from fullscreen) int oldWidth = width; int oldHeight = height; // Current position of the window int winPosX = 0; int winPosY = 0; // Bounds of viewing frustum. double nearPlane = 1.0; double farPlane = 100.0; // Viewing angle. const static double DEFAULT_FOVY = 60.0; static double fovy = DEFAULT_FOVY; //camera rotation static GLint rot = 0; //camera location static const GLfloat DEFAULT_RADIUS = 10.0f; static const GLfloat BIRD_SIGHT_RADIUS = 45.0f; static GLfloat currentRadius = DEFAULT_RADIUS; static GLfloat locX = 25.0f; static GLfloat locY = 0.0f; static GLfloat locZ = 25.0f + DEFAULT_RADIUS; static GLfloat yaw = 0.0f; static GLfloat pitch = 0.0f; GLfloat color[] = { 0.0f, 1.0f, 0.0f}; static bool wireframeView; static bool birdSightView; static bool mouseLook; bool keyStates[256]; bool funcKeyStates[256]; int keyModifier = NULL; static bool isInFullScreenMode; static bool isDebugMode = true; static GLfloat denom = 4.0f; //used for zoom effect const static int CENTER_X = width / 2; const static int CENTER_Y = height / 2; Player player; LevelRenderer levelRenderer; Base base; Robot robot; void calculate45DegreesForLocY() { locY = currentRadius * tan(GL_PI / 4); } void commanderCamera() { gluLookAt(locX + currentRadius * sin(rot * 1.0f / 8), locY, locZ - currentRadius + currentRadius * cos(rot * 1.0f / 8), locX, 0, locZ - currentRadius, 0, 1, 0); } void freeLookCamera() { GLfloat toAddY = pitch / 128.0f; gluLookAt(locX, locY, locZ, locX - sin(yaw * 1.0f / 64), locY - toAddY, locZ + cos(yaw * 1.0f / 64), 0.0f, 1.0f, 0.0f); } // Respond to window resizing, preserving proportions. void reshapeMainWindow (int newWidth, int newHeight) { width = newWidth; height = newHeight; glViewport(0, 0, width, height); TwWindowSize(width, height); } void funcKeyOperations() { if (funcKeyStates[GLUT_KEY_LEFT]) { if (!mouseLook) { GLfloat moveVector[] = {sin(rot * 1.0f / 8), cos(rot * 1.0f / 8)}; locZ += moveVector[0]; locX -= moveVector[1]; } else { GLfloat moveVector[] = {sin(yaw * 1.0f / 64), -cos(yaw * 1.0f / 64)}; locX -= moveVector[1]; locZ += moveVector[0]; } glutPostRedisplay(); } else if (funcKeyStates[GLUT_KEY_RIGHT]) { if (!mouseLook) { GLfloat moveVector[] = {sin(rot * 1.0f / 8), cos(rot * 1.0f / 8)}; locZ -= moveVector[0]; locX += moveVector[1]; } else { GLfloat moveVector[] = {sin(yaw * 1.0f / 64), -cos(yaw * 1.0f / 64)}; locX += moveVector[1]; locZ -= moveVector[0]; } glutPostRedisplay(); } if (funcKeyStates[GLUT_KEY_UP]) { if (!mouseLook) { GLfloat moveVector[] = {sin(rot * 1.0f / 8), cos(rot * 1.0f / 8)}; locZ -= moveVector[1]; locX -= moveVector[0]; } else { GLfloat moveVector[] = {sin(yaw * 1.0f / 64), -cos(yaw * 1.0f / 64), sin(pitch * 1.0f / 64)}; locX -= moveVector[0]; locZ -= moveVector[1]; locY -= moveVector[2]; } glutPostRedisplay(); } else if (funcKeyStates[GLUT_KEY_DOWN]) { if (!mouseLook) { GLfloat moveVector[] = {sin(rot * 1.0f / 8), cos(rot * 1.0f / 8)}; locZ += moveVector[1]; locX += moveVector[0]; } else { GLfloat moveVector[] = {sin(yaw * 1.0f / 64), -cos(yaw * 1.0f / 64), sin(pitch * 1.0f / 64)}; locX += moveVector[0]; locZ += moveVector[1]; locY += moveVector[2]; } glutPostRedisplay(); } if (funcKeyStates[GLUT_KEY_PAGE_UP]) { if (!mouseLook) { rot++; glutPostRedisplay(); } } else if (funcKeyStates[GLUT_KEY_PAGE_DOWN]) { if (!mouseLook) { rot--; glutPostRedisplay(); } } else if (funcKeyStates[GLUT_KEY_END]) { rot = 0; } } void keyOperations() { if (keyModifier == GLUT_ACTIVE_ALT && keyStates[13]) { isInFullScreenMode = !isInFullScreenMode; if (isInFullScreenMode) { oldWidth = width; oldHeight = height; winPosX = glutGet(GLUT_WINDOW_X); winPosY = glutGet(GLUT_WINDOW_Y); glutFullScreen(); } else { glutPositionWindow(winPosX, winPosY); glutReshapeWindow(oldWidth, oldHeight); } } if (keyStates[99]) //c { mouseLook = !mouseLook; fovy = DEFAULT_FOVY; calculate45DegreesForLocY(); denom = 4.0f; } if (keyStates[122]) //z { birdSightView = !birdSightView; mouseLook = false; GLfloat zeeDistanze = BIRD_SIGHT_RADIUS - DEFAULT_RADIUS; if (birdSightView) { currentRadius = BIRD_SIGHT_RADIUS; locZ += zeeDistanze; } else { currentRadius = DEFAULT_RADIUS; locZ -= zeeDistanze; } calculate45DegreesForLocY(); } if (keyStates[119])//w { wireframeView = !wireframeView; if(wireframeView) { glDisable(GL_DEPTH_TEST); glPolygonMode(GL_BACK, GL_LINE); glPolygonMode(GL_FRONT, GL_LINE); } else { glEnable(GL_DEPTH_TEST); glPolygonMode(GL_BACK, GL_FILL); glPolygonMode(GL_FRONT, GL_FILL); } } if (keyStates[116]) //t { robot.changeTop(); } if (keyStates[121]) //y { robot.changeMiddle(); } if (keyStates[117]) //u { robot.changeBottom(); } if (keyStates[45]) //- { if (denom != 4.0f && !mouseLook) { fovy++; denom -= 0.25f; locY = currentRadius * tan(GL_PI / denom); glutPostRedisplay(); } } else if (keyStates[61] && !mouseLook) //= { if (fovy > 10) { fovy--; denom += 0.25f; locY = currentRadius * tan(GL_PI / denom); glutPostRedisplay(); } } else if (keyStates[48]) //0 { fovy = DEFAULT_FOVY; calculate45DegreesForLocY(); denom = 4.0f; } else if (keyStates['d']) { isDebugMode = !isDebugMode; if (isDebugMode) { glutSetCursor(GLUT_CURSOR_LEFT_ARROW); TwDefine(" Debugging visible=true "); } else { glutSetCursor(GLUT_CURSOR_NONE); TwDefine(" Debugging visible=false "); } } if (keyStates[27]) { //escape TwTerminate(); exit(0); } memset(keyStates, 0, sizeof(keyStates)); } void render() { //clears the buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); funcKeyOperations(); keyOperations(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); levelRenderer.render(); //Drawing robot models on map glPushMatrix(); glTranslatef(15,0,40); player.draw(); glTranslatef(1,0,0); base.draw(); glTranslatef(7,0,5); robot.draw(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fovy, GLfloat(width) / GLfloat(height), nearPlane, farPlane); if (!mouseLook) commanderCamera(); else freeLookCamera(); if (isDebugMode) { TwDraw(); } glutSwapBuffers(); glutPostRedisplay(); } void functionKeyUp(int key, int x, int y) { funcKeyStates[key] = false; glutPostRedisplay(); } void functionKeys(int key, int x, int y) { funcKeyStates[key] = true; glutPostRedisplay(); } void keyUp(unsigned char key, int x, int y) { keyStates[key] = false; keyModifier = NULL; //Checks for uppercase if (key >= 65 && key <= 90) keyStates[key + 32] = false; glutPostRedisplay(); } void keyboardKeys(unsigned char key, int x, int y) { keyStates[key] = true; keyModifier = glutGetModifiers(); //Checks for uppercase if (key >= 65 && key <= 90) keyStates[key + 32] = true; glutPostRedisplay(); } void OnKey(unsigned char key, int x, int y) { TwEventKeyboardGLUT(key, x, y); keyboardKeys(key, x, y); } void init() { glEnable(GL_DEPTH_TEST); wireframeView = false; birdSightView = false; mouseLook = false; isInFullScreenMode = false; for (int i = 0; i < 256; i++) { keyStates[i] = false; funcKeyStates[i] = false; } calculate45DegreesForLocY(); } void passiveMotionFunc(int x, int y) { int diffX, diffY; diffX = x - CENTER_X; diffY = y - CENTER_Y; if (diffX != 0 || diffY != 0) { if (!isDebugMode) { //SetCursorPos(CENTER_X + glutGet(GLUT_WINDOW_X), CENTER_Y + glutGet(GLUT_WINDOW_Y)); glutWarpPointer(CENTER_X, CENTER_Y); } yaw += diffX; pitch += diffY; glutPostRedisplay(); } } void motionFunc(int x, int y){} int main (int argc, char **argv) { // GLUT initialization. glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(width, height); glutCreateWindow("Battle Royale Near Earth"); TwInit(TW_OPENGL, NULL); //callbacks glutReshapeFunc(reshapeMainWindow); glutSpecialFunc(functionKeys); glutKeyboardUpFunc(keyUp); glutSpecialUpFunc(functionKeyUp); glutDisplayFunc(render); TwBar *myBar; myBar = TwNewBar("Debugging"); TwWindowSize(width, height); //Camera TwAddVarRW(myBar, "Radius", TW_TYPE_FLOAT, &currentRadius, " group=Camera"); TwAddVarRW(myBar, "(M)ouseLook", TW_TYPE_BOOLCPP, &mouseLook, "group=Camera true=Yes false=No key=m"); //Location TwAddVarRW(myBar, "Location (X)", TW_TYPE_FLOAT, &locX, " group=Location step=1 keyIncr=x keyDecr=X"); TwAddVarRW(myBar, "Location (Y)", TW_TYPE_FLOAT, &locY, " group=Location step=1 keyIncr=y keyDecr=Y"); TwAddVarRW(myBar, "Location (Z)", TW_TYPE_FLOAT, &locZ, " group=Location step=1 keyIncr=z keyDecr=Z"); //Rotation TwAddVarRW(myBar, "(R)otation", TW_TYPE_INT32, &rot, " group=Rotation step=1 keyIncr=r keyDecr=R min=0 max=360"); TwAddVarRW(myBar, "Yaw", TW_TYPE_FLOAT, &yaw, " group=Rotation"); TwAddVarRW(myBar, "Pitch", TW_TYPE_FLOAT, &pitch, " group=Rotation"); TwAddVarRW(myBar, "Color", TW_TYPE_COLOR3F, &color, ""); TwDefine(" Debugging/Location group=Camera \n Debugging/Rotation group=Camera "); glutMouseFunc((GLUTmousebuttonfun)TwEventMouseButtonGLUT); glutKeyboardFunc((GLUTkeyboardfun)OnKey); //mouse motion glutMotionFunc(motionFunc); glutPassiveMotionFunc(passiveMotionFunc); init(); glutMainLoop(); return 0; } <commit_msg>Changed AntTweak transparency to improve readability<commit_after>#include <math.h> #include "GameIncludes.h" #ifdef __APPLE__ #include <Glut/glut.h> #else #define FREEGLUT_STATIC #include <GL/glut.h> #endif #include "TweakAnt/AntTweakBar.h" // PI #define GL_PI 3.14159f // Current size of window. int width = 600; int height = 600; // old values for the window (used to come back from fullscreen) int oldWidth = width; int oldHeight = height; // Current position of the window int winPosX = 0; int winPosY = 0; // Bounds of viewing frustum. double nearPlane = 1.0; double farPlane = 100.0; // Viewing angle. const static double DEFAULT_FOVY = 60.0; static double fovy = DEFAULT_FOVY; //camera rotation static GLint rot = 0; //camera location static const GLfloat DEFAULT_RADIUS = 10.0f; static const GLfloat BIRD_SIGHT_RADIUS = 45.0f; static GLfloat currentRadius = DEFAULT_RADIUS; static GLfloat locX = 25.0f; static GLfloat locY = 0.0f; static GLfloat locZ = 25.0f + DEFAULT_RADIUS; static GLfloat yaw = 0.0f; static GLfloat pitch = 0.0f; GLfloat color[] = { 0.0f, 1.0f, 0.0f}; static bool wireframeView; static bool birdSightView; static bool mouseLook; bool keyStates[256]; bool funcKeyStates[256]; int keyModifier = NULL; static bool isInFullScreenMode; static bool isDebugMode = true; static GLfloat denom = 4.0f; //used for zoom effect const static int CENTER_X = width / 2; const static int CENTER_Y = height / 2; Player player; LevelRenderer levelRenderer; Base base; Robot robot; void calculate45DegreesForLocY() { locY = currentRadius * tan(GL_PI / 4); } void commanderCamera() { gluLookAt(locX + currentRadius * sin(rot * 1.0f / 8), locY, locZ - currentRadius + currentRadius * cos(rot * 1.0f / 8), locX, 0, locZ - currentRadius, 0, 1, 0); } void freeLookCamera() { GLfloat toAddY = pitch / 128.0f; gluLookAt(locX, locY, locZ, locX - sin(yaw * 1.0f / 64), locY - toAddY, locZ + cos(yaw * 1.0f / 64), 0.0f, 1.0f, 0.0f); } // Respond to window resizing, preserving proportions. void reshapeMainWindow (int newWidth, int newHeight) { width = newWidth; height = newHeight; glViewport(0, 0, width, height); TwWindowSize(width, height); } void funcKeyOperations() { if (funcKeyStates[GLUT_KEY_LEFT]) { if (!mouseLook) { GLfloat moveVector[] = {sin(rot * 1.0f / 8), cos(rot * 1.0f / 8)}; locZ += moveVector[0]; locX -= moveVector[1]; } else { GLfloat moveVector[] = {sin(yaw * 1.0f / 64), -cos(yaw * 1.0f / 64)}; locX -= moveVector[1]; locZ += moveVector[0]; } glutPostRedisplay(); } else if (funcKeyStates[GLUT_KEY_RIGHT]) { if (!mouseLook) { GLfloat moveVector[] = {sin(rot * 1.0f / 8), cos(rot * 1.0f / 8)}; locZ -= moveVector[0]; locX += moveVector[1]; } else { GLfloat moveVector[] = {sin(yaw * 1.0f / 64), -cos(yaw * 1.0f / 64)}; locX += moveVector[1]; locZ -= moveVector[0]; } glutPostRedisplay(); } if (funcKeyStates[GLUT_KEY_UP]) { if (!mouseLook) { GLfloat moveVector[] = {sin(rot * 1.0f / 8), cos(rot * 1.0f / 8)}; locZ -= moveVector[1]; locX -= moveVector[0]; } else { GLfloat moveVector[] = {sin(yaw * 1.0f / 64), -cos(yaw * 1.0f / 64), sin(pitch * 1.0f / 64)}; locX -= moveVector[0]; locZ -= moveVector[1]; locY -= moveVector[2]; } glutPostRedisplay(); } else if (funcKeyStates[GLUT_KEY_DOWN]) { if (!mouseLook) { GLfloat moveVector[] = {sin(rot * 1.0f / 8), cos(rot * 1.0f / 8)}; locZ += moveVector[1]; locX += moveVector[0]; } else { GLfloat moveVector[] = {sin(yaw * 1.0f / 64), -cos(yaw * 1.0f / 64), sin(pitch * 1.0f / 64)}; locX += moveVector[0]; locZ += moveVector[1]; locY += moveVector[2]; } glutPostRedisplay(); } if (funcKeyStates[GLUT_KEY_PAGE_UP]) { if (!mouseLook) { rot++; glutPostRedisplay(); } } else if (funcKeyStates[GLUT_KEY_PAGE_DOWN]) { if (!mouseLook) { rot--; glutPostRedisplay(); } } else if (funcKeyStates[GLUT_KEY_END]) { rot = 0; } } void keyOperations() { if (keyModifier == GLUT_ACTIVE_ALT && keyStates[13]) { isInFullScreenMode = !isInFullScreenMode; if (isInFullScreenMode) { oldWidth = width; oldHeight = height; winPosX = glutGet(GLUT_WINDOW_X); winPosY = glutGet(GLUT_WINDOW_Y); glutFullScreen(); } else { glutPositionWindow(winPosX, winPosY); glutReshapeWindow(oldWidth, oldHeight); } } if (keyStates[99]) //c { mouseLook = !mouseLook; fovy = DEFAULT_FOVY; calculate45DegreesForLocY(); denom = 4.0f; } if (keyStates[122]) //z { birdSightView = !birdSightView; mouseLook = false; GLfloat zeeDistanze = BIRD_SIGHT_RADIUS - DEFAULT_RADIUS; if (birdSightView) { currentRadius = BIRD_SIGHT_RADIUS; locZ += zeeDistanze; } else { currentRadius = DEFAULT_RADIUS; locZ -= zeeDistanze; } calculate45DegreesForLocY(); } if (keyStates[119])//w { wireframeView = !wireframeView; if(wireframeView) { glDisable(GL_DEPTH_TEST); glPolygonMode(GL_BACK, GL_LINE); glPolygonMode(GL_FRONT, GL_LINE); } else { glEnable(GL_DEPTH_TEST); glPolygonMode(GL_BACK, GL_FILL); glPolygonMode(GL_FRONT, GL_FILL); } } if (keyStates[116]) //t { robot.changeTop(); } if (keyStates[121]) //y { robot.changeMiddle(); } if (keyStates[117]) //u { robot.changeBottom(); } if (keyStates[45]) //- { if (denom != 4.0f && !mouseLook) { fovy++; denom -= 0.25f; locY = currentRadius * tan(GL_PI / denom); glutPostRedisplay(); } } else if (keyStates[61] && !mouseLook) //= { if (fovy > 10) { fovy--; denom += 0.25f; locY = currentRadius * tan(GL_PI / denom); glutPostRedisplay(); } } else if (keyStates[48]) //0 { fovy = DEFAULT_FOVY; calculate45DegreesForLocY(); denom = 4.0f; } else if (keyStates['d']) { isDebugMode = !isDebugMode; if (isDebugMode) { glutSetCursor(GLUT_CURSOR_LEFT_ARROW); TwDefine(" Debugging visible=true "); } else { glutSetCursor(GLUT_CURSOR_NONE); TwDefine(" Debugging visible=false "); } } if (keyStates[27]) { //escape TwTerminate(); exit(0); } memset(keyStates, 0, sizeof(keyStates)); } void render() { //clears the buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); funcKeyOperations(); keyOperations(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); levelRenderer.render(); //Drawing robot models on map glPushMatrix(); glTranslatef(15,0,40); player.draw(); glTranslatef(1,0,0); base.draw(); glTranslatef(7,0,5); robot.draw(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fovy, GLfloat(width) / GLfloat(height), nearPlane, farPlane); if (!mouseLook) commanderCamera(); else freeLookCamera(); if (isDebugMode) { TwDraw(); } glutSwapBuffers(); glutPostRedisplay(); } void functionKeyUp(int key, int x, int y) { funcKeyStates[key] = false; glutPostRedisplay(); } void functionKeys(int key, int x, int y) { funcKeyStates[key] = true; glutPostRedisplay(); } void keyUp(unsigned char key, int x, int y) { keyStates[key] = false; keyModifier = NULL; //Checks for uppercase if (key >= 65 && key <= 90) keyStates[key + 32] = false; glutPostRedisplay(); } void keyboardKeys(unsigned char key, int x, int y) { keyStates[key] = true; keyModifier = glutGetModifiers(); //Checks for uppercase if (key >= 65 && key <= 90) keyStates[key + 32] = true; glutPostRedisplay(); } void OnKey(unsigned char key, int x, int y) { TwEventKeyboardGLUT(key, x, y); keyboardKeys(key, x, y); } void init() { glEnable(GL_DEPTH_TEST); wireframeView = false; birdSightView = false; mouseLook = false; isInFullScreenMode = false; for (int i = 0; i < 256; i++) { keyStates[i] = false; funcKeyStates[i] = false; } calculate45DegreesForLocY(); } void passiveMotionFunc(int x, int y) { int diffX, diffY; diffX = x - CENTER_X; diffY = y - CENTER_Y; if (diffX != 0 || diffY != 0) { if (!isDebugMode) { //SetCursorPos(CENTER_X + glutGet(GLUT_WINDOW_X), CENTER_Y + glutGet(GLUT_WINDOW_Y)); glutWarpPointer(CENTER_X, CENTER_Y); } yaw += diffX; pitch += diffY; glutPostRedisplay(); } } void motionFunc(int x, int y){} int main (int argc, char **argv) { // GLUT initialization. glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(width, height); glutCreateWindow("Battle Royale Near Earth"); TwInit(TW_OPENGL, NULL); //callbacks glutReshapeFunc(reshapeMainWindow); glutSpecialFunc(functionKeys); glutKeyboardUpFunc(keyUp); glutSpecialUpFunc(functionKeyUp); glutDisplayFunc(render); TwBar *myBar; myBar = TwNewBar("Debugging"); TwWindowSize(width, height); TwDefine(" Debugging alpha=150 "); //Camera TwAddVarRW(myBar, "Radius", TW_TYPE_FLOAT, &currentRadius, " group=Camera"); TwAddVarRW(myBar, "(M)ouseLook", TW_TYPE_BOOLCPP, &mouseLook, "group=Camera true=Yes false=No key=m"); //Location TwAddVarRW(myBar, "Location (X)", TW_TYPE_FLOAT, &locX, " group=Location step=1 keyIncr=x keyDecr=X"); TwAddVarRW(myBar, "Location (Y)", TW_TYPE_FLOAT, &locY, " group=Location step=1 keyIncr=y keyDecr=Y"); TwAddVarRW(myBar, "Location (Z)", TW_TYPE_FLOAT, &locZ, " group=Location step=1 keyIncr=z keyDecr=Z"); //Rotation TwAddVarRW(myBar, "(R)otation", TW_TYPE_INT32, &rot, " group=Rotation step=1 keyIncr=r keyDecr=R min=0 max=360"); TwAddVarRW(myBar, "Yaw", TW_TYPE_FLOAT, &yaw, " group=Rotation"); TwAddVarRW(myBar, "Pitch", TW_TYPE_FLOAT, &pitch, " group=Rotation"); TwAddVarRW(myBar, "Color", TW_TYPE_COLOR3F, &color, ""); TwDefine(" Debugging/Location group=Camera \n Debugging/Rotation group=Camera "); glutMouseFunc((GLUTmousebuttonfun)TwEventMouseButtonGLUT); glutKeyboardFunc((GLUTkeyboardfun)OnKey); //mouse motion glutMotionFunc(motionFunc); glutPassiveMotionFunc(passiveMotionFunc); init(); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>/** * This file is part of Slideshow. * Copyright (C) 2008-2010 David Sveningsson <[email protected]> * * Slideshow 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. * * Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "SwitchState.h" #include "TransitionState.h" #include "VideoState.h" #include "ViewState.h" #include "exception.h" #include "Log.h" #include <cstring> State* SwitchState::action(bool &flip){ if ( !browser() ){ return new ViewState(this); } /* get next slide */ slide_context_t slide = browser()->get_next_file(); struct autofree_t { autofree_t(slide_context_t& s): s(s){} ~autofree_t(){ free(s.filename); free(s.assembler); } slide_context_t& s; }; autofree_t container(slide); if ( !(slide.filename && slide.assembler) ){ Log::message(Log::Warning, "Kernel: Queue is empty\n"); } /* @todo make something factory-like */ if ( strcmp("image", slide.assembler) == 0 || strcmp("text", slide.assembler) == 0 ){ Log::message(Log::Debug, "Kernel: Switching to image \"%s\"\n", slide.filename); try { gfx()->load_image( slide.filename ); } catch ( exception& e ) { Log::message(Log::Warning, "Kernel: Failed to load image '%s': %s\n", slide.filename, e.what()); return new ViewState(this); } return new TransitionState(this); } else if ( strcmp("video", slide.assembler) == 0 ){ Log::message(Log::Debug, "Kernel: Playing video \"%s\"\n", slide.filename); return new VideoState(this, slide.filename); } else { Log::message(Log::Warning, "Unhandled assembler \"%s\" for \"%s\"\n", slide.assembler, slide.filename); return new ViewState(this); } } <commit_msg>early error<commit_after>/** * This file is part of Slideshow. * Copyright (C) 2008-2010 David Sveningsson <[email protected]> * * Slideshow 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. * * Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "SwitchState.h" #include "TransitionState.h" #include "VideoState.h" #include "ViewState.h" #include "exception.h" #include "Log.h" #include <cstring> State* SwitchState::action(bool &flip){ if ( !browser() ){ return new ViewState(this); } /* get next slide */ slide_context_t slide = browser()->get_next_file(); struct autofree_t { autofree_t(slide_context_t& s): s(s){} ~autofree_t(){ free(s.filename); free(s.assembler); } slide_context_t& s; }; autofree_t container(slide); if ( !(slide.filename && slide.assembler) ){ Log::message(Log::Warning, "Kernel: Queue is empty\n"); return new ViewState(this); } /* @todo make something factory-like */ if ( strcmp("image", slide.assembler) == 0 || strcmp("text", slide.assembler) == 0 ){ Log::message(Log::Debug, "Kernel: Switching to image \"%s\"\n", slide.filename); try { gfx()->load_image( slide.filename ); } catch ( exception& e ) { Log::message(Log::Warning, "Kernel: Failed to load image '%s': %s\n", slide.filename, e.what()); return new ViewState(this); } return new TransitionState(this); } else if ( strcmp("video", slide.assembler) == 0 ){ Log::message(Log::Debug, "Kernel: Playing video \"%s\"\n", slide.filename); return new VideoState(this, slide.filename); } else { Log::message(Log::Warning, "Unhandled assembler \"%s\" for \"%s\"\n", slide.assembler, slide.filename); return new ViewState(this); } } <|endoftext|>
<commit_before>#include <ctrcommon/app.hpp> #include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <stdio.h> #include <sstream> #include <iomanip> #include <sys/dirent.h> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; stream << "Y - Receive an app over the network" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; auto onProgress = [&](u64 pos, u64 totalSize) { std::stringstream details; details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n"; details << "Press B to cancel."; u32 progress = (u32) (((double) pos / (double) totalSize) * 100); uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress); inputPoll(); return !inputIsPressed(BUTTON_B); }; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { if(netInstall && !exit) { screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN); if(file.fd == NULL) { netInstall = false; continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } fclose(file.fd); continue; } uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; std::string fileName = (*it).name; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } } else { if(!fsDelete(path)) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { if(fsDelete(path)) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiDisplayMessage(BOTTOM_SCREEN, "Loading title list..."); uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(exit) { break; } } platformCleanup(); return 0; } <commit_msg>Add version indicator.<commit_after>#include <ctrcommon/app.hpp> #include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <stdio.h> #include <sstream> #include <iomanip> #include <sys/dirent.h> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "FBI v1.3.2" << "\n"; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; stream << "Y - Receive an app over the network" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; auto onProgress = [&](u64 pos, u64 totalSize) { std::stringstream details; details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n"; details << "Press B to cancel."; u32 progress = (u32) (((double) pos / (double) totalSize) * 100); uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress); inputPoll(); return !inputIsPressed(BUTTON_B); }; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { if(netInstall && !exit) { screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN); if(file.fd == NULL) { netInstall = false; continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } fclose(file.fd); continue; } uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; std::string fileName = (*it).name; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } } else { if(!fsDelete(path)) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { if(fsDelete(path)) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiDisplayMessage(BOTTOM_SCREEN, "Loading title list..."); uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(exit) { break; } } platformCleanup(); return 0; } <|endoftext|>
<commit_before> #include "easylogging++.h" #include <sstream> _INITIALIZE_EASYLOGGINGPP class Vehicle { public: Vehicle(const std::string& make_, const std::string& model_, unsigned int year_ = 2013, const std::string& version_ = "") : make_(make_), model_(model_), year_(year_), version_(version_) {} std::string toString(void) const { std::stringstream ss; ss << "[" << make_ << " " << model_ << " " << year_ << (version_.size() > 0 ? " " : "") << version_ << "]"; return ss.str(); } friend std::ostream& operator<<(std::ostream& w, const Vehicle& v); private: std::string make_; std::string model_; int year_; std::string version_; }; std::ostream& operator<<(std::ostream& w, const Vehicle& v) { w << "(" << v.make_ << " " << v.model_ << " " << v.year_ << (v.version_.size() > 0 ? " " : "") << v.version_ << ")"; return w; } void vectorLogs() { std::vector<std::string> stringVec; std::vector<Vehicle> vehicleVec; stringVec.push_back("stringVec"); vehicleVec.push_back(Vehicle("Honda", "Accord", 2013, "vehicleVec")); LINFO << "stringVec : " << stringVec; LINFO << "vehicleVec : " << vehicleVec; } void listLogs() { std::list<std::string> stringList; std::list<std::string*> stringPtrList; std::list<Vehicle> vehicleList; std::list<Vehicle*> vehiclePtrList; stringList.push_back("stringList"); stringPtrList.push_back(new std::string("stringPtrList")); vehicleList.push_back(Vehicle("Honda", "Accord", 2013, "vehicleList")); vehiclePtrList.push_back(new Vehicle("Honda", "Accord", 2013, "vehiclePtrList")); LINFO << "stringList : " << stringList; LINFO << "stringPtrList : " << stringPtrList; LINFO << "vehicleList : " << vehicleList; LINFO << "vehiclePtrList : " << vehiclePtrList; } void otherContainerLogs() { std::map<int, std::string> map_; map_.insert (std::pair<int, std::string>(1, "one")); map_.insert (std::pair<int, std::string>(2, "two")); LINFO << "Map: " << map_; std::queue<int> queue_; queue_.push(77); queue_.push(16); LINFO << queue_; std::bitset<10> bitset_ (std::string("10110")); LINFO << bitset_; int pqueueArr_[]= { 10, 60, 50, 20 }; std::priority_queue< int, std::vector<int>, std::greater<int> > pqueue (pqueueArr_, pqueueArr_ + 4); LINFO << pqueue; std::deque<int> mydeque_ (3,100); mydeque_.at(1) = 200; std::stack<int> stack_ (mydeque_); LINFO << stack_; std::stack<std::string*> stackStr_; stackStr_.push (new std::string("test")); LINFO << stackStr_; delete stackStr_.top(); } int main(void) { vectorLogs(); listLogs(); otherContainerLogs(); return 0; } <commit_msg>memory fix in sample<commit_after> #include "easylogging++.h" #include <sstream> _INITIALIZE_EASYLOGGINGPP class Vehicle { public: Vehicle(const std::string& make_, const std::string& model_, unsigned int year_ = 2013, const std::string& version_ = "") : make_(make_), model_(model_), year_(year_), version_(version_) {} std::string toString(void) const { std::stringstream ss; ss << "[" << make_ << " " << model_ << " " << year_ << (version_.size() > 0 ? " " : "") << version_ << "]"; return ss.str(); } friend std::ostream& operator<<(std::ostream& w, const Vehicle& v); private: std::string make_; std::string model_; int year_; std::string version_; }; std::ostream& operator<<(std::ostream& w, const Vehicle& v) { w << "(" << v.make_ << " " << v.model_ << " " << v.year_ << (v.version_.size() > 0 ? " " : "") << v.version_ << ")"; return w; } void vectorLogs() { std::vector<std::string> stringVec; std::vector<Vehicle> vehicleVec; stringVec.push_back("stringVec"); vehicleVec.push_back(Vehicle("Honda", "Accord", 2013, "vehicleVec")); LINFO << "stringVec : " << stringVec; LINFO << "vehicleVec : " << vehicleVec; } void listLogs() { std::list<std::string> stringList; std::vector<std::string*> stringPtrList; std::list<Vehicle> vehicleList; std::vector<Vehicle*> vehiclePtrList; stringList.push_back("stringList"); stringPtrList.push_back(new std::string("stringPtrList")); vehicleList.push_back(Vehicle("Honda", "Accord", 2013, "vehicleList")); vehiclePtrList.push_back(new Vehicle("Honda", "Accord", 2013, "vehiclePtrList")); LINFO << "stringList : " << stringList; LINFO << "stringPtrList : " << stringPtrList; LINFO << "vehicleList : " << vehicleList; LINFO << "vehiclePtrList : " << vehiclePtrList; delete stringPtrList.at(0); delete vehiclePtrList.at(0); } void otherContainerLogs() { std::map<int, std::string> map_; map_.insert (std::pair<int, std::string>(1, "one")); map_.insert (std::pair<int, std::string>(2, "two")); LINFO << "Map: " << map_; std::queue<int> queue_; queue_.push(77); queue_.push(16); LINFO << queue_; std::bitset<10> bitset_ (std::string("10110")); LINFO << bitset_; int pqueueArr_[]= { 10, 60, 50, 20 }; std::priority_queue< int, std::vector<int>, std::greater<int> > pqueue (pqueueArr_, pqueueArr_ + 4); LINFO << pqueue; std::deque<int> mydeque_ (3,100); mydeque_.at(1) = 200; std::stack<int> stack_ (mydeque_); LINFO << stack_; std::stack<std::string*> stackStr_; stackStr_.push (new std::string("test")); LINFO << stackStr_; delete stackStr_.top(); } int main(void) { vectorLogs(); listLogs(); otherContainerLogs(); return 0; } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #undef NDEBUG // sg #include "SceneGraph.h" #include "sg/common/Texture2D.h" #include "sg/geometry/TriangleMesh.h" #define TINYOBJLOADER_IMPLEMENTATION // define this in only *one* .cc #include "../3rdParty/tiny_obj_loader.h" #include <cstring> #include <sstream> namespace ospray { namespace sg { std::shared_ptr<Texture2D> loadTexture(const FileName &fullPath, const bool preferLinear = false) { std::shared_ptr<Texture2D> tex = Texture2D::load(fullPath, preferLinear); if (!tex) std::cout << "could not load texture " << fullPath.str() << " !\n"; return tex; } void addTextureIfNeeded(Material &node, const std::string &type, const FileName &texName, const FileName &containingPath, bool preferLinear = false) { if (!texName.str().empty()) { auto tex = loadTexture(containingPath + texName, preferLinear); if (tex) { tex->setName(type); node.setChild(type, tex); } } } static inline float parseFloatString(std::string valueString) { std::stringstream valueStream(valueString); float value; valueStream >> value; return value; } static inline vec3f parseVec3fString(std::string valueString) { std::stringstream valueStream(valueString); vec3f value; valueStream >> value.x >> value.y >> value.z; return value; } static inline void parseParameterString(std::string typeAndValueString, std::string &paramType, ospcommon::utility::Any &paramValue) { std::stringstream typeAndValueStream(typeAndValueString); typeAndValueStream >> paramType; std::string paramValueString; getline(typeAndValueStream, paramValueString); if (paramType == "float") { paramValue = parseFloatString(paramValueString); } else if (paramType == "vec3f") { paramValue = parseVec3fString(paramValueString); } else { // Unknown type. paramValue = typeAndValueString; } } static inline std::vector<std::shared_ptr<Material>> createSgMaterials( std::vector<tinyobj::material_t> &mats, const FileName &containingPath) { std::vector<std::shared_ptr<Material>> sgMaterials; for (auto &mat : mats) { auto matNodePtr = createNode(mat.name, "Material")->nodeAs<Material>(); auto &matNode = *matNodePtr; for (auto &param : mat.unknown_parameter) { if (param.first == "type") { matNode["type"].setValue(param.second); std::cout << "Creating material node of type " << param.second << std::endl; } else { std::string paramType; ospcommon::utility::Any paramValue; parseParameterString(param.second, paramType, paramValue); matNode.createChildWithValue(param.first, paramType, paramValue); std::cout << "Parsed parameter " << param.first << " of type " << paramType << std::endl; } } matNode["d"].setValue(mat.dissolve); matNode["Ka"].setValue( vec3f(mat.ambient[0], mat.ambient[1], mat.ambient[2])); matNode["Kd"].setValue( vec3f(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2])); matNode["Ks"].setValue( vec3f(mat.specular[0], mat.specular[1], mat.specular[2])); addTextureIfNeeded( matNode, "map_Ka", mat.ambient_texname, containingPath); addTextureIfNeeded( matNode, "map_Kd", mat.diffuse_texname, containingPath); addTextureIfNeeded( matNode, "map_Ks", mat.specular_texname, containingPath); addTextureIfNeeded(matNode, "map_Ns", mat.specular_highlight_texname, containingPath, true); addTextureIfNeeded( matNode, "map_bump", mat.bump_texname, containingPath); addTextureIfNeeded( matNode, "map_d", mat.alpha_texname, containingPath, true); sgMaterials.push_back(matNodePtr); } return sgMaterials; } void importOBJ(const std::shared_ptr<Node> &world, const FileName &fileName) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; auto containingPath = fileName.path().str() + '/'; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, fileName.c_str(), containingPath.c_str()); if (!err.empty()) std::cerr << "#ospsg: obj parsing warning(s)...\n" << err << std::endl; if (!ret) { std::cerr << "#ospsg: FATAL error parsing obj file, no geometry added" << " to the scene!" << std::endl; return; } auto sgMaterials = createSgMaterials(materials, containingPath); std::string base_name = fileName.name() + '_'; int shapeId = 0; for (auto &shape : shapes) { for (int numVertsInFace : shape.mesh.num_face_vertices) { if (numVertsInFace != 3) { std::cerr << "Warning: more thant 3 verts in face!"; PRINT(numVertsInFace); } } auto name = base_name + std::to_string(shapeId++) + '_' + shape.name; auto mesh = createNode(name, "TriangleMesh")->nodeAs<TriangleMesh>(); auto v = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>(); auto numSrcIndices = shape.mesh.indices.size(); v->v.reserve(numSrcIndices); auto vi = createNode("index", "DataVector3i")->nodeAs<DataVector3i>(); vi->v.reserve(numSrcIndices / 3); auto vn = createNode("normal", "DataVector3f")->nodeAs<DataVector3f>(); vn->v.reserve(numSrcIndices); auto vt = createNode("texcoord", "DataVector2f")->nodeAs<DataVector2f>(); vt->v.reserve(numSrcIndices); for (int i = 0; i < shape.mesh.indices.size(); i += 3) { auto idx0 = shape.mesh.indices[i + 0]; auto idx1 = shape.mesh.indices[i + 1]; auto idx2 = shape.mesh.indices[i + 2]; auto prim = vec3i(i + 0, i + 1, i + 2); vi->push_back(prim); v->push_back(vec3f(attrib.vertices[idx0.vertex_index * 3 + 0], attrib.vertices[idx0.vertex_index * 3 + 1], attrib.vertices[idx0.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx1.vertex_index * 3 + 0], attrib.vertices[idx1.vertex_index * 3 + 1], attrib.vertices[idx1.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx2.vertex_index * 3 + 0], attrib.vertices[idx2.vertex_index * 3 + 1], attrib.vertices[idx2.vertex_index * 3 + 2])); if (!attrib.normals.empty()) { vn->push_back(vec3f(attrib.normals[idx0.normal_index * 3 + 0], attrib.normals[idx0.normal_index * 3 + 1], attrib.normals[idx0.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx1.normal_index * 3 + 0], attrib.normals[idx1.normal_index * 3 + 1], attrib.normals[idx1.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx2.normal_index * 3 + 0], attrib.normals[idx2.normal_index * 3 + 1], attrib.normals[idx2.normal_index * 3 + 2])); } if (!attrib.texcoords.empty()) { vt->push_back(vec2f(attrib.texcoords[idx0.texcoord_index * 2 + 0], attrib.texcoords[idx0.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx1.texcoord_index * 2 + 0], attrib.texcoords[idx1.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx2.texcoord_index * 2 + 0], attrib.texcoords[idx2.texcoord_index * 2 + 1])); } } mesh->add(v); mesh->add(vi); if (!vn->empty()) mesh->add(vn); if (!vt->empty()) mesh->add(vt); auto matIdx = shape.mesh.material_ids[0]; if (!sgMaterials.empty()) { if (matIdx >= 0) mesh->setChild("material", sgMaterials[matIdx]); else mesh->setChild("material", sgMaterials[0]); } auto model = createNode(name + "_model", "Model"); model->add(mesh); auto instance = createNode(name + "_instance", "Instance"); instance->setChild("model", model); model->setParent(instance); world->add(instance); } } } // ::ospray::sg } // ::ospray <commit_msg>if a node type doesn't exist in .mtl file, continue on<commit_after>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #undef NDEBUG // sg #include "SceneGraph.h" #include "sg/common/Texture2D.h" #include "sg/geometry/TriangleMesh.h" #define TINYOBJLOADER_IMPLEMENTATION // define this in only *one* .cc #include "../3rdParty/tiny_obj_loader.h" #include <cstring> #include <sstream> namespace ospray { namespace sg { std::shared_ptr<Texture2D> loadTexture(const FileName &fullPath, const bool preferLinear = false) { std::shared_ptr<Texture2D> tex = Texture2D::load(fullPath, preferLinear); if (!tex) std::cout << "could not load texture " << fullPath.str() << " !\n"; return tex; } void addTextureIfNeeded(Material &node, const std::string &type, const FileName &texName, const FileName &containingPath, bool preferLinear = false) { if (!texName.str().empty()) { auto tex = loadTexture(containingPath + texName, preferLinear); if (tex) { tex->setName(type); node.setChild(type, tex); } } } static inline float parseFloatString(std::string valueString) { std::stringstream valueStream(valueString); float value; valueStream >> value; return value; } static inline vec3f parseVec3fString(std::string valueString) { std::stringstream valueStream(valueString); vec3f value; valueStream >> value.x >> value.y >> value.z; return value; } static inline void parseParameterString(std::string typeAndValueString, std::string &paramType, ospcommon::utility::Any &paramValue) { std::stringstream typeAndValueStream(typeAndValueString); typeAndValueStream >> paramType; std::string paramValueString; getline(typeAndValueStream, paramValueString); if (paramType == "float") { paramValue = parseFloatString(paramValueString); } else if (paramType == "vec3f") { paramValue = parseVec3fString(paramValueString); } else { // Unknown type. paramValue = typeAndValueString; } } static inline std::vector<std::shared_ptr<Material>> createSgMaterials( std::vector<tinyobj::material_t> &mats, const FileName &containingPath) { std::vector<std::shared_ptr<Material>> sgMaterials; for (auto &mat : mats) { auto matNodePtr = createNode(mat.name, "Material")->nodeAs<Material>(); auto &matNode = *matNodePtr; for (auto &param : mat.unknown_parameter) { if (param.first == "type") { matNode["type"].setValue(param.second); std::cout << "Creating material node of type " << param.second << std::endl; } else { std::string paramType; ospcommon::utility::Any paramValue; parseParameterString(param.second, paramType, paramValue); try { matNode.createChildWithValue(param.first, paramType, paramValue); } catch (const std::runtime_error &) { // NOTE(jda) - silently move on if parsed node type doesn't exist } } } matNode["d"].setValue(mat.dissolve); matNode["Ka"].setValue( vec3f(mat.ambient[0], mat.ambient[1], mat.ambient[2])); matNode["Kd"].setValue( vec3f(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2])); matNode["Ks"].setValue( vec3f(mat.specular[0], mat.specular[1], mat.specular[2])); addTextureIfNeeded( matNode, "map_Ka", mat.ambient_texname, containingPath); addTextureIfNeeded( matNode, "map_Kd", mat.diffuse_texname, containingPath); addTextureIfNeeded( matNode, "map_Ks", mat.specular_texname, containingPath); addTextureIfNeeded(matNode, "map_Ns", mat.specular_highlight_texname, containingPath, true); addTextureIfNeeded( matNode, "map_bump", mat.bump_texname, containingPath); addTextureIfNeeded( matNode, "map_d", mat.alpha_texname, containingPath, true); sgMaterials.push_back(matNodePtr); } return sgMaterials; } void importOBJ(const std::shared_ptr<Node> &world, const FileName &fileName) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; auto containingPath = fileName.path().str() + '/'; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, fileName.c_str(), containingPath.c_str()); if (!err.empty()) std::cerr << "#ospsg: obj parsing warning(s)...\n" << err << std::endl; if (!ret) { std::cerr << "#ospsg: FATAL error parsing obj file, no geometry added" << " to the scene!" << std::endl; return; } auto sgMaterials = createSgMaterials(materials, containingPath); std::string base_name = fileName.name() + '_'; int shapeId = 0; for (auto &shape : shapes) { for (int numVertsInFace : shape.mesh.num_face_vertices) { if (numVertsInFace != 3) { std::cerr << "Warning: more thant 3 verts in face!"; PRINT(numVertsInFace); } } auto name = base_name + std::to_string(shapeId++) + '_' + shape.name; auto mesh = createNode(name, "TriangleMesh")->nodeAs<TriangleMesh>(); auto v = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>(); auto numSrcIndices = shape.mesh.indices.size(); v->v.reserve(numSrcIndices); auto vi = createNode("index", "DataVector3i")->nodeAs<DataVector3i>(); vi->v.reserve(numSrcIndices / 3); auto vn = createNode("normal", "DataVector3f")->nodeAs<DataVector3f>(); vn->v.reserve(numSrcIndices); auto vt = createNode("texcoord", "DataVector2f")->nodeAs<DataVector2f>(); vt->v.reserve(numSrcIndices); for (int i = 0; i < shape.mesh.indices.size(); i += 3) { auto idx0 = shape.mesh.indices[i + 0]; auto idx1 = shape.mesh.indices[i + 1]; auto idx2 = shape.mesh.indices[i + 2]; auto prim = vec3i(i + 0, i + 1, i + 2); vi->push_back(prim); v->push_back(vec3f(attrib.vertices[idx0.vertex_index * 3 + 0], attrib.vertices[idx0.vertex_index * 3 + 1], attrib.vertices[idx0.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx1.vertex_index * 3 + 0], attrib.vertices[idx1.vertex_index * 3 + 1], attrib.vertices[idx1.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx2.vertex_index * 3 + 0], attrib.vertices[idx2.vertex_index * 3 + 1], attrib.vertices[idx2.vertex_index * 3 + 2])); if (!attrib.normals.empty()) { vn->push_back(vec3f(attrib.normals[idx0.normal_index * 3 + 0], attrib.normals[idx0.normal_index * 3 + 1], attrib.normals[idx0.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx1.normal_index * 3 + 0], attrib.normals[idx1.normal_index * 3 + 1], attrib.normals[idx1.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx2.normal_index * 3 + 0], attrib.normals[idx2.normal_index * 3 + 1], attrib.normals[idx2.normal_index * 3 + 2])); } if (!attrib.texcoords.empty()) { vt->push_back(vec2f(attrib.texcoords[idx0.texcoord_index * 2 + 0], attrib.texcoords[idx0.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx1.texcoord_index * 2 + 0], attrib.texcoords[idx1.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx2.texcoord_index * 2 + 0], attrib.texcoords[idx2.texcoord_index * 2 + 1])); } } mesh->add(v); mesh->add(vi); if (!vn->empty()) mesh->add(vn); if (!vt->empty()) mesh->add(vt); auto matIdx = shape.mesh.material_ids[0]; if (!sgMaterials.empty()) { if (matIdx >= 0) mesh->setChild("material", sgMaterials[matIdx]); else mesh->setChild("material", sgMaterials[0]); } auto model = createNode(name + "_model", "Model"); model->add(mesh); auto instance = createNode(name + "_instance", "Instance"); instance->setChild("model", model); model->setParent(instance); world->add(instance); } } } // ::ospray::sg } // ::ospray <|endoftext|>
<commit_before>#pragma once #ifdef __WIN32 #define EGL_HELPER_DISABLED #endif #include <iostream> #include <SDL.h> #include <fastuidraw/util/util.hpp> #include <fastuidraw/util/reference_counted.hpp> #include <fastuidraw/util/api_callback.hpp> #include "stream_holder.hpp" struct wl_egl_window; class egl_helper: public fastuidraw::reference_counted<egl_helper>::non_concurrent { public: class params { public: params(void): m_msaa(0) {} int m_red_bits, m_green_bits, m_blue_bits, m_alpha_bits; int m_depth_bits, m_stencil_bits; // 0 means no MSAA, all other values are enabled and number samples int m_msaa; int m_gles_major_version; int m_gles_minor_version; }; egl_helper(const fastuidraw::reference_counted_ptr<StreamHolder> &str, const params &P, SDL_Window *w); ~egl_helper(); void make_current(void); void swap_buffers(void); static void* egl_get_proc(fastuidraw::c_string name); void print_info(std::ostream &dst); private: void *m_ctx; void *m_surface; void *m_dpy; struct wl_egl_window *m_wl_window; fastuidraw::reference_counted_ptr<fastuidraw::APICallbackSet::CallBack> m_logger; }; <commit_msg>Correct compilation guard for Windows<commit_after>#pragma once #ifdef _WIN32 #define EGL_HELPER_DISABLED #endif #include <iostream> #include <SDL.h> #include <fastuidraw/util/util.hpp> #include <fastuidraw/util/reference_counted.hpp> #include <fastuidraw/util/api_callback.hpp> #include "stream_holder.hpp" struct wl_egl_window; class egl_helper: public fastuidraw::reference_counted<egl_helper>::non_concurrent { public: class params { public: params(void): m_msaa(0) {} int m_red_bits, m_green_bits, m_blue_bits, m_alpha_bits; int m_depth_bits, m_stencil_bits; // 0 means no MSAA, all other values are enabled and number samples int m_msaa; int m_gles_major_version; int m_gles_minor_version; }; egl_helper(const fastuidraw::reference_counted_ptr<StreamHolder> &str, const params &P, SDL_Window *w); ~egl_helper(); void make_current(void); void swap_buffers(void); static void* egl_get_proc(fastuidraw::c_string name); void print_info(std::ostream &dst); private: void *m_ctx; void *m_surface; void *m_dpy; struct wl_egl_window *m_wl_window; fastuidraw::reference_counted_ptr<fastuidraw::APICallbackSet::CallBack> m_logger; }; <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #undef NDEBUG // sg #include "SceneGraph.h" #include "sg/common/Texture2D.h" #include "sg/geometry/TriangleMesh.h" #define TINYOBJLOADER_IMPLEMENTATION // define this in only *one* .cc #include "../3rdParty/tiny_obj_loader.h" #include <cstring> #include <sstream> namespace ospray { namespace sg { std::shared_ptr<Texture2D> loadTexture(const FileName &fullPath, const bool preferLinear = false) { std::shared_ptr<Texture2D> tex = Texture2D::load(fullPath, preferLinear); if (!tex) std::cout << "could not load texture " << fullPath.str() << " !\n"; return tex; } void addTextureIfNeeded(Material &node, const std::string &name, const FileName &texName, const FileName &containingPath, bool preferLinear = false) { if (!texName.str().empty()) { auto tex = loadTexture(containingPath + texName, preferLinear); if (tex) { tex->setName(name); node.setChild(name, tex); } } } static inline void parseParameterString(std::string typeAndValueString, std::string &paramType, ospcommon::utility::Any &paramValue) { std::stringstream typeAndValueStream(typeAndValueString); std::string paramValueString; getline(typeAndValueStream, paramValueString); std::vector<float> floats; std::stringstream valueStream(typeAndValueString); float val; while (valueStream >> val) floats.push_back(val); if (floats.size() == 1) { paramType = "float"; paramValue = floats[0]; } else if (floats.size() == 2) { paramType = "vec2f"; paramValue = vec2f(floats[0], floats[1]); } else if (floats.size() == 3) { paramType = "vec3f"; paramValue = vec3f(floats[0], floats[1], floats[2]); } else { // Unknown type. paramValue = typeAndValueString; } } static inline std::shared_ptr<MaterialList> createSgMaterials( std::vector<tinyobj::material_t> &mats, const FileName &containingPath) { auto sgMaterials = createNode("materialList", "MaterialList")->nodeAs<MaterialList>(); for (auto &mat : mats) { auto matNodePtr = createNode(mat.name, "Material")->nodeAs<Material>(); auto &matNode = *matNodePtr; bool addOBJparams = true; for (auto &param : mat.unknown_parameter) { if (param.first == "type") { matNode["type"] = param.second; std::cout << "Creating material node of type " << param.second << std::endl; addOBJparams = false; } else { std::string paramType; ospcommon::utility::Any paramValue; parseParameterString(param.second, paramType, paramValue); try { matNode.createChildWithValue(param.first, paramType, paramValue); } catch (const std::runtime_error &) { // NOTE(jda) - silently move on if parsed node type doesn't exist // maybe it's a texture, try it addTextureIfNeeded(matNode, param.first, param.second, containingPath); } } } if (addOBJparams) { matNode["d"] = mat.dissolve; matNode["Kd"] = vec3f(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2]); matNode["Ks"] = vec3f(mat.specular[0], mat.specular[1], mat.specular[2]); addTextureIfNeeded( matNode, "map_Kd", mat.diffuse_texname, containingPath); addTextureIfNeeded( matNode, "map_Ks", mat.specular_texname, containingPath); addTextureIfNeeded(matNode, "map_Ns", mat.specular_highlight_texname, containingPath, true); addTextureIfNeeded( matNode, "map_bump", mat.bump_texname, containingPath); addTextureIfNeeded( matNode, "map_d", mat.alpha_texname, containingPath, true); } sgMaterials->push_back(matNodePtr); } return sgMaterials; } void importOBJ(const std::shared_ptr<Node> &world, const FileName &fileName) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; auto containingPath = fileName.path().str() + '/'; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, fileName.c_str(), containingPath.c_str()); if (!err.empty()) std::cerr << "#ospsg: obj parsing warning(s)...\n" << err << std::endl; if (!ret) { std::cerr << "#ospsg: FATAL error parsing obj file, no geometry added" << " to the scene!" << std::endl; return; } auto sgMaterials = createSgMaterials(materials, containingPath); std::string base_name = fileName.name() + '_'; int shapeId = 0; for (auto &shape : shapes) { for (int numVertsInFace : shape.mesh.num_face_vertices) { if (numVertsInFace != 3) { std::cerr << "Warning: more thant 3 verts in face!"; PRINT(numVertsInFace); } } auto name = base_name + std::to_string(shapeId++) + '_' + shape.name; auto mesh = createNode(name, "TriangleMesh")->nodeAs<TriangleMesh>(); auto v = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>(); auto numSrcIndices = shape.mesh.indices.size(); v->v.reserve(numSrcIndices); auto vi = createNode("index", "DataVector3i")->nodeAs<DataVector3i>(); vi->v.reserve(numSrcIndices / 3); auto vn = createNode("normal", "DataVector3f")->nodeAs<DataVector3f>(); vn->v.reserve(numSrcIndices); auto vt = createNode("texcoord", "DataVector2f")->nodeAs<DataVector2f>(); vt->v.reserve(numSrcIndices); for (int i = 0; i < shape.mesh.indices.size(); i += 3) { auto idx0 = shape.mesh.indices[i + 0]; auto idx1 = shape.mesh.indices[i + 1]; auto idx2 = shape.mesh.indices[i + 2]; auto prim = vec3i(i + 0, i + 1, i + 2); vi->push_back(prim); v->push_back(vec3f(attrib.vertices[idx0.vertex_index * 3 + 0], attrib.vertices[idx0.vertex_index * 3 + 1], attrib.vertices[idx0.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx1.vertex_index * 3 + 0], attrib.vertices[idx1.vertex_index * 3 + 1], attrib.vertices[idx1.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx2.vertex_index * 3 + 0], attrib.vertices[idx2.vertex_index * 3 + 1], attrib.vertices[idx2.vertex_index * 3 + 2])); // TODO create missing normals&texcoords if only some faces have them if (!attrib.normals.empty() && idx0.normal_index != -1) { vn->push_back(vec3f(attrib.normals[idx0.normal_index * 3 + 0], attrib.normals[idx0.normal_index * 3 + 1], attrib.normals[idx0.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx1.normal_index * 3 + 0], attrib.normals[idx1.normal_index * 3 + 1], attrib.normals[idx1.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx2.normal_index * 3 + 0], attrib.normals[idx2.normal_index * 3 + 1], attrib.normals[idx2.normal_index * 3 + 2])); } if (!attrib.texcoords.empty() && idx0.texcoord_index != -1) { vt->push_back(vec2f(attrib.texcoords[idx0.texcoord_index * 2 + 0], attrib.texcoords[idx0.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx1.texcoord_index * 2 + 0], attrib.texcoords[idx1.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx2.texcoord_index * 2 + 0], attrib.texcoords[idx2.texcoord_index * 2 + 1])); } } mesh->add(v); mesh->add(vi); if (!vn->empty()) mesh->add(vn); if (!vt->empty()) mesh->add(vt); auto pmids = createNode("prim.materialID", "DataVector1i")->nodeAs<DataVector1i>(); auto numMatIds = shape.mesh.material_ids.size(); pmids->v.reserve(numMatIds); for (auto id : shape.mesh.material_ids) pmids->v.push_back(id); mesh->add(pmids); mesh->add(sgMaterials); auto model = createNode(name + "_model", "Model"); model->add(mesh); auto instance = createNode(name + "_instance", "Instance"); instance->setChild("model", model); model->setParent(instance); world->add(instance); } } } // ::ospray::sg } // ::ospray <commit_msg>flatten .obj shapes (no instancing), better performance for demos<commit_after>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #undef NDEBUG // sg #include "SceneGraph.h" #include "sg/common/Texture2D.h" #include "sg/geometry/TriangleMesh.h" #define TINYOBJLOADER_IMPLEMENTATION // define this in only *one* .cc #include "../3rdParty/tiny_obj_loader.h" #include <cstring> #include <sstream> namespace ospray { namespace sg { std::shared_ptr<Texture2D> loadTexture(const FileName &fullPath, const bool preferLinear = false) { std::shared_ptr<Texture2D> tex = Texture2D::load(fullPath, preferLinear); if (!tex) std::cout << "could not load texture " << fullPath.str() << " !\n"; return tex; } void addTextureIfNeeded(Material &node, const std::string &name, const FileName &texName, const FileName &containingPath, bool preferLinear = false) { if (!texName.str().empty()) { auto tex = loadTexture(containingPath + texName, preferLinear); if (tex) { tex->setName(name); node.setChild(name, tex); } } } static inline void parseParameterString(std::string typeAndValueString, std::string &paramType, ospcommon::utility::Any &paramValue) { std::stringstream typeAndValueStream(typeAndValueString); std::string paramValueString; getline(typeAndValueStream, paramValueString); std::vector<float> floats; std::stringstream valueStream(typeAndValueString); float val; while (valueStream >> val) floats.push_back(val); if (floats.size() == 1) { paramType = "float"; paramValue = floats[0]; } else if (floats.size() == 2) { paramType = "vec2f"; paramValue = vec2f(floats[0], floats[1]); } else if (floats.size() == 3) { paramType = "vec3f"; paramValue = vec3f(floats[0], floats[1], floats[2]); } else { // Unknown type. paramValue = typeAndValueString; } } static inline std::shared_ptr<MaterialList> createSgMaterials( std::vector<tinyobj::material_t> &mats, const FileName &containingPath) { auto sgMaterials = createNode("materialList", "MaterialList")->nodeAs<MaterialList>(); for (auto &mat : mats) { auto matNodePtr = createNode(mat.name, "Material")->nodeAs<Material>(); auto &matNode = *matNodePtr; bool addOBJparams = true; for (auto &param : mat.unknown_parameter) { if (param.first == "type") { matNode["type"] = param.second; std::cout << "Creating material node of type " << param.second << std::endl; addOBJparams = false; } else { std::string paramType; ospcommon::utility::Any paramValue; parseParameterString(param.second, paramType, paramValue); try { matNode.createChildWithValue(param.first, paramType, paramValue); } catch (const std::runtime_error &) { // NOTE(jda) - silently move on if parsed node type doesn't exist // maybe it's a texture, try it addTextureIfNeeded(matNode, param.first, param.second, containingPath); } } } if (addOBJparams) { matNode["d"] = mat.dissolve; matNode["Kd"] = vec3f(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2]); matNode["Ks"] = vec3f(mat.specular[0], mat.specular[1], mat.specular[2]); addTextureIfNeeded( matNode, "map_Kd", mat.diffuse_texname, containingPath); addTextureIfNeeded( matNode, "map_Ks", mat.specular_texname, containingPath); addTextureIfNeeded(matNode, "map_Ns", mat.specular_highlight_texname, containingPath, true); addTextureIfNeeded( matNode, "map_bump", mat.bump_texname, containingPath); addTextureIfNeeded( matNode, "map_d", mat.alpha_texname, containingPath, true); } sgMaterials->push_back(matNodePtr); } return sgMaterials; } void importOBJ(const std::shared_ptr<Node> &world, const FileName &fileName) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; auto containingPath = fileName.path().str() + '/'; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, fileName.c_str(), containingPath.c_str()); if (!err.empty()) std::cerr << "#ospsg: obj parsing warning(s)...\n" << err << std::endl; if (!ret) { std::cerr << "#ospsg: FATAL error parsing obj file, no geometry added" << " to the scene!" << std::endl; return; } auto sgMaterials = createSgMaterials(materials, containingPath); std::string base_name = fileName.name() + '_'; int shapeId = 0; for (auto &shape : shapes) { for (int numVertsInFace : shape.mesh.num_face_vertices) { if (numVertsInFace != 3) { std::cerr << "Warning: more thant 3 verts in face!"; PRINT(numVertsInFace); } } auto name = base_name + std::to_string(shapeId++) + '_' + shape.name; auto mesh = createNode(name, "TriangleMesh")->nodeAs<TriangleMesh>(); auto v = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>(); auto numSrcIndices = shape.mesh.indices.size(); v->v.reserve(numSrcIndices); auto vi = createNode("index", "DataVector3i")->nodeAs<DataVector3i>(); vi->v.reserve(numSrcIndices / 3); auto vn = createNode("normal", "DataVector3f")->nodeAs<DataVector3f>(); vn->v.reserve(numSrcIndices); auto vt = createNode("texcoord", "DataVector2f")->nodeAs<DataVector2f>(); vt->v.reserve(numSrcIndices); for (int i = 0; i < shape.mesh.indices.size(); i += 3) { auto idx0 = shape.mesh.indices[i + 0]; auto idx1 = shape.mesh.indices[i + 1]; auto idx2 = shape.mesh.indices[i + 2]; auto prim = vec3i(i + 0, i + 1, i + 2); vi->push_back(prim); v->push_back(vec3f(attrib.vertices[idx0.vertex_index * 3 + 0], attrib.vertices[idx0.vertex_index * 3 + 1], attrib.vertices[idx0.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx1.vertex_index * 3 + 0], attrib.vertices[idx1.vertex_index * 3 + 1], attrib.vertices[idx1.vertex_index * 3 + 2])); v->push_back(vec3f(attrib.vertices[idx2.vertex_index * 3 + 0], attrib.vertices[idx2.vertex_index * 3 + 1], attrib.vertices[idx2.vertex_index * 3 + 2])); // TODO create missing normals&texcoords if only some faces have them if (!attrib.normals.empty() && idx0.normal_index != -1) { vn->push_back(vec3f(attrib.normals[idx0.normal_index * 3 + 0], attrib.normals[idx0.normal_index * 3 + 1], attrib.normals[idx0.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx1.normal_index * 3 + 0], attrib.normals[idx1.normal_index * 3 + 1], attrib.normals[idx1.normal_index * 3 + 2])); vn->push_back(vec3f(attrib.normals[idx2.normal_index * 3 + 0], attrib.normals[idx2.normal_index * 3 + 1], attrib.normals[idx2.normal_index * 3 + 2])); } if (!attrib.texcoords.empty() && idx0.texcoord_index != -1) { vt->push_back(vec2f(attrib.texcoords[idx0.texcoord_index * 2 + 0], attrib.texcoords[idx0.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx1.texcoord_index * 2 + 0], attrib.texcoords[idx1.texcoord_index * 2 + 1])); vt->push_back(vec2f(attrib.texcoords[idx2.texcoord_index * 2 + 0], attrib.texcoords[idx2.texcoord_index * 2 + 1])); } } mesh->add(v); mesh->add(vi); if (!vn->empty()) mesh->add(vn); if (!vt->empty()) mesh->add(vt); auto pmids = createNode("prim.materialID", "DataVector1i")->nodeAs<DataVector1i>(); auto numMatIds = shape.mesh.material_ids.size(); pmids->v.reserve(numMatIds); for (auto id : shape.mesh.material_ids) pmids->v.push_back(id); mesh->add(pmids); mesh->add(sgMaterials); auto model = createNode(name + "_model", "Model"); model->add(mesh); // TODO: Large .obj models with lots of groups run much slower with each // group put in a separate instance. In the future, we want to // support letting the user (ospExampleViewer, for starters) // specify if each group should be placed in an instance or not. #if 0 auto instance = createNode(name + "_instance", "Instance"); instance->setChild("model", model); model->setParent(instance); world->add(instance); #else world->add(mesh); #endif } } } // ::ospray::sg } // ::ospray <|endoftext|>
<commit_before>// CLP includes #include "itkimage2segimageCLP.h" // DCMQI includes #undef HAVE_SSTREAM // Avoid redefinition warning #include "dcmqi/ImageSEGConverter.h" int main(int argc, char *argv[]) { PARSE_ARGS; if (segImageFiles.empty()){ cerr << "Error: No input image files specified!" << endl; return EXIT_FAILURE; } if(dicomImageFiles.empty() && dicomDirectory.empty()){ cerr << "Error: No input DICOM files specified!" << endl; return EXIT_FAILURE; } if(metaDataFileName.empty()){ cerr << "Error: Input metadata file must be specified!" << endl; return EXIT_FAILURE; } if(outputSEGFileName.empty()){ cerr << "Error: Output DICOM file must be specified!" << endl; return EXIT_FAILURE; } vector<ShortImageType::Pointer> segmentations; for(size_t segFileNumber=0; segFileNumber<segImageFiles.size(); segFileNumber++){ ShortReaderType::Pointer reader = ShortReaderType::New(); reader->SetFileName(segImageFiles[segFileNumber]); reader->Update(); ShortImageType::Pointer labelImage = reader->GetOutput(); segmentations.push_back(labelImage); } vector<DcmDataset*> dcmDatasets; DcmFileFormat* sliceFF = new DcmFileFormat(); for(size_t dcmFileNumber=0; dcmFileNumber<dicomImageFiles.size(); dcmFileNumber++){ if(sliceFF->loadFile(dicomImageFiles[dcmFileNumber].c_str()).good()){ dcmDatasets.push_back(sliceFF->getAndRemoveDataset()); } } if(dicomDirectory.size()){ OFList<OFString> fileList; if(OFStandard::searchDirectoryRecursively(dicomDirectory.c_str(), fileList)) { OFIterator<OFString> fileListIterator; for(fileListIterator=fileList.begin(); fileListIterator!=fileList.end(); fileListIterator++) { if(sliceFF->loadFile(*fileListIterator).good()){ dcmDatasets.push_back(sliceFF->getAndRemoveDataset()); } } } } ifstream metainfoStream(metaDataFileName.c_str(), ios_base::binary); std::string metadata( (std::istreambuf_iterator<char>(metainfoStream) ), (std::istreambuf_iterator<char>())); DcmDataset* result = dcmqi::ImageSEGConverter::itkimage2dcmSegmentation(dcmDatasets, segmentations, metadata, skipEmptySlices); if (result == NULL){ return EXIT_FAILURE; } else { DcmFileFormat segdocFF(result); bool compress = false; if(compress){ CHECK_COND(segdocFF.saveFile(outputSEGFileName.c_str(), EXS_DeflatedLittleEndianExplicit)); } else { CHECK_COND(segdocFF.saveFile(outputSEGFileName.c_str(), EXS_LittleEndianExplicit)); } COUT << "Saved segmentation as " << outputSEGFileName << endl; } delete sliceFF; for(size_t i=0;i<dcmDatasets.size();i++) { delete dcmDatasets[i]; } if (result != NULL) delete result; return EXIT_SUCCESS; } <commit_msg>ENH: added error message in case that input DICOM files/directory couldn't be loaded<commit_after>// CLP includes #include "itkimage2segimageCLP.h" // DCMQI includes #undef HAVE_SSTREAM // Avoid redefinition warning #include "dcmqi/ImageSEGConverter.h" int main(int argc, char *argv[]) { PARSE_ARGS; if (segImageFiles.empty()){ cerr << "Error: No input image files specified!" << endl; return EXIT_FAILURE; } if(dicomImageFiles.empty() && dicomDirectory.empty()){ cerr << "Error: No input DICOM files specified!" << endl; return EXIT_FAILURE; } if(metaDataFileName.empty()){ cerr << "Error: Input metadata file must be specified!" << endl; return EXIT_FAILURE; } if(outputSEGFileName.empty()){ cerr << "Error: Output DICOM file must be specified!" << endl; return EXIT_FAILURE; } vector<ShortImageType::Pointer> segmentations; for(size_t segFileNumber=0; segFileNumber<segImageFiles.size(); segFileNumber++){ ShortReaderType::Pointer reader = ShortReaderType::New(); reader->SetFileName(segImageFiles[segFileNumber]); reader->Update(); ShortImageType::Pointer labelImage = reader->GetOutput(); segmentations.push_back(labelImage); } vector<DcmDataset*> dcmDatasets; DcmFileFormat* sliceFF = new DcmFileFormat(); for(size_t dcmFileNumber=0; dcmFileNumber<dicomImageFiles.size(); dcmFileNumber++){ if(sliceFF->loadFile(dicomImageFiles[dcmFileNumber].c_str()).good()){ dcmDatasets.push_back(sliceFF->getAndRemoveDataset()); } } if(dicomDirectory.size()){ OFList<OFString> fileList; if(OFStandard::searchDirectoryRecursively(dicomDirectory.c_str(), fileList)) { OFIterator<OFString> fileListIterator; for(fileListIterator=fileList.begin(); fileListIterator!=fileList.end(); fileListIterator++) { if(sliceFF->loadFile(*fileListIterator).good()){ dcmDatasets.push_back(sliceFF->getAndRemoveDataset()); } } } } if(dcmDatasets.empty()){ cerr << "Error: no DICOM could be loaded from the specified list/directory" << endl; return EXIT_FAILURE; } ifstream metainfoStream(metaDataFileName.c_str(), ios_base::binary); std::string metadata( (std::istreambuf_iterator<char>(metainfoStream) ), (std::istreambuf_iterator<char>())); DcmDataset* result = dcmqi::ImageSEGConverter::itkimage2dcmSegmentation(dcmDatasets, segmentations, metadata, skipEmptySlices); if (result == NULL){ return EXIT_FAILURE; } else { DcmFileFormat segdocFF(result); bool compress = false; if(compress){ CHECK_COND(segdocFF.saveFile(outputSEGFileName.c_str(), EXS_DeflatedLittleEndianExplicit)); } else { CHECK_COND(segdocFF.saveFile(outputSEGFileName.c_str(), EXS_LittleEndianExplicit)); } COUT << "Saved segmentation as " << outputSEGFileName << endl; } delete sliceFF; for(size_t i=0;i<dcmDatasets.size();i++) { delete dcmDatasets[i]; } if (result != NULL) delete result; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT GmbH * %% * 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. * #L% */ #include "AccessController.h" #include <tuple> #include "LocalDomainAccessController.h" #include "joynr/LocalCapabilitiesDirectory.h" #include "joynr/JoynrMessage.h" #include "joynr/types/DiscoveryEntry.h" #include "joynr/Request.h" #include "joynr/SubscriptionRequest.h" #include "joynr/BroadcastSubscriptionRequest.h" #include "joynr/system/RoutingTypes/Address.h" #include "joynr/serializer/Serializer.h" namespace joynr { using namespace infrastructure; using namespace infrastructure::DacTypes; using namespace types; INIT_LOGGER(AccessController); //--------- InternalConsumerPermissionCallbacks -------------------------------- class AccessController::LdacConsumerPermissionCallback : public LocalDomainAccessController::IGetConsumerPermissionCallback { public: LdacConsumerPermissionCallback( AccessController& owningAccessController, const JoynrMessage& message, const std::string& domain, const std::string& interfaceName, TrustLevel::Enum trustlevel, std::shared_ptr<IAccessController::IHasConsumerPermissionCallback> callback); // Callbacks made from the LocalDomainAccessController void consumerPermission(Permission::Enum permission) override; void operationNeeded() override; private: AccessController& owningAccessController; JoynrMessage message; std::string domain; std::string interfaceName; TrustLevel::Enum trustlevel; std::shared_ptr<IAccessController::IHasConsumerPermissionCallback> callback; bool convertToBool(Permission::Enum permission); }; AccessController::LdacConsumerPermissionCallback::LdacConsumerPermissionCallback( AccessController& parent, const JoynrMessage& message, const std::string& domain, const std::string& interfaceName, TrustLevel::Enum trustlevel, std::shared_ptr<IAccessController::IHasConsumerPermissionCallback> callback) : owningAccessController(parent), message(message), domain(domain), interfaceName(interfaceName), trustlevel(trustlevel), callback(callback) { } void AccessController::LdacConsumerPermissionCallback::consumerPermission( Permission::Enum permission) { bool hasPermission = convertToBool(permission); if (!hasPermission) { JOYNR_LOG_ERROR(owningAccessController.logger, "Message {} to domain {}, interface {} failed ACL check", message.getHeaderMessageId(), domain, interfaceName); } callback->hasConsumerPermission(hasPermission); } void AccessController::LdacConsumerPermissionCallback::operationNeeded() { std::string operation; const std::string messageType = message.getType(); if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_ONE_WAY) { try { OneWayRequest request; joynr::serializer::deserializeFromJson(request, message.getPayload()); operation = request.getMethodName(); } catch (const std::exception& e) { JOYNR_LOG_ERROR(logger, "could not deserialize OneWayRequest - error {}", e.what()); } } else if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_REQUEST) { try { Request request; joynr::serializer::deserializeFromJson(request, message.getPayload()); operation = request.getMethodName(); } catch (const std::exception& e) { JOYNR_LOG_ERROR(logger, "could not deserialize Request - error {}", e.what()); } } else if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST) { try { SubscriptionRequest request; joynr::serializer::deserializeFromJson(request, message.getPayload()); operation = request.getSubscribeToName(); } catch (const std::invalid_argument& e) { JOYNR_LOG_ERROR( logger, "could not deserialize SubscriptionRequest - error {}", e.what()); } } else if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST) { try { BroadcastSubscriptionRequest request; joynr::serializer::deserializeFromJson(request, message.getPayload()); operation = request.getSubscribeToName(); } catch (const std::invalid_argument& e) { JOYNR_LOG_ERROR(logger, "could not deserialize BroadcastSubscriptionRequest - error {}", e.what()); } } if (operation.empty()) { JOYNR_LOG_ERROR(owningAccessController.logger, "Could not deserialize request"); callback->hasConsumerPermission(false); return; } // Get the permission for given operation Permission::Enum permission = owningAccessController.localDomainAccessController.getConsumerPermission( message.getHeaderCreatorUserId(), domain, interfaceName, operation, trustlevel); bool hasPermission = convertToBool(permission); if (!hasPermission) { JOYNR_LOG_ERROR(owningAccessController.logger, "Message {} to domain {}, interface/operation {}/{} failed ACL check", message.getHeaderMessageId(), domain, interfaceName, operation); } callback->hasConsumerPermission(hasPermission); } bool AccessController::LdacConsumerPermissionCallback::convertToBool(Permission::Enum permission) { switch (permission) { case Permission::YES: return true; case Permission::ASK: assert(false && "Permission.ASK user dialog not yet implemented."); return false; case Permission::NO: return false; default: return false; } } //--------- AccessController --------------------------------------------------- class AccessController::ProviderRegistrationObserver : public LocalCapabilitiesDirectory::IProviderRegistrationObserver { public: explicit ProviderRegistrationObserver(LocalDomainAccessController& localDomainAccessController) : localDomainAccessController(localDomainAccessController) { } void onProviderAdd(const DiscoveryEntry& discoveryEntry) override { std::ignore = discoveryEntry; // Ignored } void onProviderRemove(const DiscoveryEntry& discoveryEntry) override { localDomainAccessController.unregisterProvider( discoveryEntry.getDomain(), discoveryEntry.getInterfaceName()); } private: LocalDomainAccessController& localDomainAccessController; }; AccessController::AccessController(LocalCapabilitiesDirectory& localCapabilitiesDirectory, LocalDomainAccessController& localDomainAccessController) : localCapabilitiesDirectory(localCapabilitiesDirectory), localDomainAccessController(localDomainAccessController), providerRegistrationObserver( std::make_shared<ProviderRegistrationObserver>(localDomainAccessController)), whitelistParticipantIds() { localCapabilitiesDirectory.addProviderRegistrationObserver(providerRegistrationObserver); } AccessController::~AccessController() { localCapabilitiesDirectory.removeProviderRegistrationObserver(providerRegistrationObserver); } void AccessController::addParticipantToWhitelist(const std::string& participantId) { whitelistParticipantIds.push_back(participantId); } bool AccessController::needsPermissionCheck(const JoynrMessage& message) { if (util::vectorContains(whitelistParticipantIds, message.getHeaderTo())) { return false; } std::string messageType = message.getType(); if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_MULTICAST || messageType == JoynrMessage::VALUE_MESSAGE_TYPE_PUBLICATION || messageType == JoynrMessage::VALUE_MESSAGE_TYPE_REPLY || messageType == JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY) { // reply messages don't need permission check // they are filtered by request reply ID or subscritpion ID return false; } // If this point is reached, checking is required return true; } void AccessController::hasConsumerPermission( const JoynrMessage& message, std::shared_ptr<IAccessController::IHasConsumerPermissionCallback> callback) { if (!needsPermissionCheck(message)) { callback->hasConsumerPermission(true); return; } // Get the domain and interface of the message destination std::string participantId = message.getHeaderTo(); std::function<void(const types::DiscoveryEntry&)> lookupSuccessCallback = [this, message, callback, participantId](const types::DiscoveryEntry& discoveryEntry) { if (discoveryEntry.getParticipantId() != participantId) { JOYNR_LOG_ERROR( logger, "Failed to get capabilities for participantId {}", participantId); callback->hasConsumerPermission(false); return; } std::string domain = discoveryEntry.getDomain(); std::string interfaceName = discoveryEntry.getInterfaceName(); // Create a callback object auto ldacCallback = std::make_shared<LdacConsumerPermissionCallback>( *this, message, domain, interfaceName, TrustLevel::HIGH, callback); // Try to determine permission without expensive message deserialization // For now TrustLevel::HIGH is assumed. std::string msgCreatorUid = message.getHeaderCreatorUserId(); localDomainAccessController.getConsumerPermission( msgCreatorUid, domain, interfaceName, TrustLevel::HIGH, ldacCallback); }; std::function<void(const joynr::exceptions::ProviderRuntimeException&)> lookupErrorCallback = [callback](const joynr::exceptions::ProviderRuntimeException& exception) { std::ignore = exception; callback->hasConsumerPermission(false); }; localCapabilitiesDirectory.lookup(participantId, lookupSuccessCallback, lookupErrorCallback); } bool AccessController::hasProviderPermission(const std::string& userId, TrustLevel::Enum trustLevel, const std::string& domain, const std::string& interfaceName) { std::ignore = userId; std::ignore = trustLevel; std::ignore = domain; std::ignore = interfaceName; assert(false && "Not yet implemented."); return true; } } // namespace joynr <commit_msg>[C++] Extract operation name from MulticastSubscriptionRequest objects in AC.<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "AccessController.h" #include <tuple> #include "LocalDomainAccessController.h" #include "joynr/LocalCapabilitiesDirectory.h" #include "joynr/JoynrMessage.h" #include "joynr/types/DiscoveryEntry.h" #include "joynr/Request.h" #include "joynr/SubscriptionRequest.h" #include "joynr/BroadcastSubscriptionRequest.h" #include "joynr/MulticastSubscriptionRequest.h" #include "joynr/system/RoutingTypes/Address.h" #include "joynr/serializer/Serializer.h" namespace joynr { using namespace infrastructure; using namespace infrastructure::DacTypes; using namespace types; INIT_LOGGER(AccessController); //--------- InternalConsumerPermissionCallbacks -------------------------------- class AccessController::LdacConsumerPermissionCallback : public LocalDomainAccessController::IGetConsumerPermissionCallback { public: LdacConsumerPermissionCallback( AccessController& owningAccessController, const JoynrMessage& message, const std::string& domain, const std::string& interfaceName, TrustLevel::Enum trustlevel, std::shared_ptr<IAccessController::IHasConsumerPermissionCallback> callback); // Callbacks made from the LocalDomainAccessController void consumerPermission(Permission::Enum permission) override; void operationNeeded() override; private: AccessController& owningAccessController; JoynrMessage message; std::string domain; std::string interfaceName; TrustLevel::Enum trustlevel; std::shared_ptr<IAccessController::IHasConsumerPermissionCallback> callback; bool convertToBool(Permission::Enum permission); }; AccessController::LdacConsumerPermissionCallback::LdacConsumerPermissionCallback( AccessController& parent, const JoynrMessage& message, const std::string& domain, const std::string& interfaceName, TrustLevel::Enum trustlevel, std::shared_ptr<IAccessController::IHasConsumerPermissionCallback> callback) : owningAccessController(parent), message(message), domain(domain), interfaceName(interfaceName), trustlevel(trustlevel), callback(callback) { } void AccessController::LdacConsumerPermissionCallback::consumerPermission( Permission::Enum permission) { bool hasPermission = convertToBool(permission); if (!hasPermission) { JOYNR_LOG_ERROR(owningAccessController.logger, "Message {} to domain {}, interface {} failed ACL check", message.getHeaderMessageId(), domain, interfaceName); } callback->hasConsumerPermission(hasPermission); } void AccessController::LdacConsumerPermissionCallback::operationNeeded() { std::string operation; const std::string messageType = message.getType(); if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_ONE_WAY) { try { OneWayRequest request; joynr::serializer::deserializeFromJson(request, message.getPayload()); operation = request.getMethodName(); } catch (const std::exception& e) { JOYNR_LOG_ERROR(logger, "could not deserialize OneWayRequest - error {}", e.what()); } } else if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_REQUEST) { try { Request request; joynr::serializer::deserializeFromJson(request, message.getPayload()); operation = request.getMethodName(); } catch (const std::exception& e) { JOYNR_LOG_ERROR(logger, "could not deserialize Request - error {}", e.what()); } } else if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST) { try { SubscriptionRequest request; joynr::serializer::deserializeFromJson(request, message.getPayload()); operation = request.getSubscribeToName(); } catch (const std::invalid_argument& e) { JOYNR_LOG_ERROR( logger, "could not deserialize SubscriptionRequest - error {}", e.what()); } } else if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST) { try { BroadcastSubscriptionRequest request; joynr::serializer::deserializeFromJson(request, message.getPayload()); operation = request.getSubscribeToName(); } catch (const std::invalid_argument& e) { JOYNR_LOG_ERROR(logger, "could not deserialize BroadcastSubscriptionRequest - error {}", e.what()); } } else if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST) { try { MulticastSubscriptionRequest request; joynr::serializer::deserializeFromJson(request, message.getPayload()); operation = request.getSubscribeToName(); } catch (const std::invalid_argument& e) { JOYNR_LOG_ERROR(logger, "could not deserialize MulticastSubscriptionRequest - error {}", e.what()); } } if (operation.empty()) { JOYNR_LOG_ERROR(owningAccessController.logger, "Could not deserialize request"); callback->hasConsumerPermission(false); return; } // Get the permission for given operation Permission::Enum permission = owningAccessController.localDomainAccessController.getConsumerPermission( message.getHeaderCreatorUserId(), domain, interfaceName, operation, trustlevel); bool hasPermission = convertToBool(permission); if (!hasPermission) { JOYNR_LOG_ERROR(owningAccessController.logger, "Message {} to domain {}, interface/operation {}/{} failed ACL check", message.getHeaderMessageId(), domain, interfaceName, operation); } callback->hasConsumerPermission(hasPermission); } bool AccessController::LdacConsumerPermissionCallback::convertToBool(Permission::Enum permission) { switch (permission) { case Permission::YES: return true; case Permission::ASK: assert(false && "Permission.ASK user dialog not yet implemented."); return false; case Permission::NO: return false; default: return false; } } //--------- AccessController --------------------------------------------------- class AccessController::ProviderRegistrationObserver : public LocalCapabilitiesDirectory::IProviderRegistrationObserver { public: explicit ProviderRegistrationObserver(LocalDomainAccessController& localDomainAccessController) : localDomainAccessController(localDomainAccessController) { } void onProviderAdd(const DiscoveryEntry& discoveryEntry) override { std::ignore = discoveryEntry; // Ignored } void onProviderRemove(const DiscoveryEntry& discoveryEntry) override { localDomainAccessController.unregisterProvider( discoveryEntry.getDomain(), discoveryEntry.getInterfaceName()); } private: LocalDomainAccessController& localDomainAccessController; }; AccessController::AccessController(LocalCapabilitiesDirectory& localCapabilitiesDirectory, LocalDomainAccessController& localDomainAccessController) : localCapabilitiesDirectory(localCapabilitiesDirectory), localDomainAccessController(localDomainAccessController), providerRegistrationObserver( std::make_shared<ProviderRegistrationObserver>(localDomainAccessController)), whitelistParticipantIds() { localCapabilitiesDirectory.addProviderRegistrationObserver(providerRegistrationObserver); } AccessController::~AccessController() { localCapabilitiesDirectory.removeProviderRegistrationObserver(providerRegistrationObserver); } void AccessController::addParticipantToWhitelist(const std::string& participantId) { whitelistParticipantIds.push_back(participantId); } bool AccessController::needsPermissionCheck(const JoynrMessage& message) { if (util::vectorContains(whitelistParticipantIds, message.getHeaderTo())) { return false; } std::string messageType = message.getType(); if (messageType == JoynrMessage::VALUE_MESSAGE_TYPE_MULTICAST || messageType == JoynrMessage::VALUE_MESSAGE_TYPE_PUBLICATION || messageType == JoynrMessage::VALUE_MESSAGE_TYPE_REPLY || messageType == JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY) { // reply messages don't need permission check // they are filtered by request reply ID or subscritpion ID return false; } // If this point is reached, checking is required return true; } void AccessController::hasConsumerPermission( const JoynrMessage& message, std::shared_ptr<IAccessController::IHasConsumerPermissionCallback> callback) { if (!needsPermissionCheck(message)) { callback->hasConsumerPermission(true); return; } // Get the domain and interface of the message destination std::string participantId = message.getHeaderTo(); std::function<void(const types::DiscoveryEntry&)> lookupSuccessCallback = [this, message, callback, participantId](const types::DiscoveryEntry& discoveryEntry) { if (discoveryEntry.getParticipantId() != participantId) { JOYNR_LOG_ERROR( logger, "Failed to get capabilities for participantId {}", participantId); callback->hasConsumerPermission(false); return; } std::string domain = discoveryEntry.getDomain(); std::string interfaceName = discoveryEntry.getInterfaceName(); // Create a callback object auto ldacCallback = std::make_shared<LdacConsumerPermissionCallback>( *this, message, domain, interfaceName, TrustLevel::HIGH, callback); // Try to determine permission without expensive message deserialization // For now TrustLevel::HIGH is assumed. std::string msgCreatorUid = message.getHeaderCreatorUserId(); localDomainAccessController.getConsumerPermission( msgCreatorUid, domain, interfaceName, TrustLevel::HIGH, ldacCallback); }; std::function<void(const joynr::exceptions::ProviderRuntimeException&)> lookupErrorCallback = [callback](const joynr::exceptions::ProviderRuntimeException& exception) { std::ignore = exception; callback->hasConsumerPermission(false); }; localCapabilitiesDirectory.lookup(participantId, lookupSuccessCallback, lookupErrorCallback); } bool AccessController::hasProviderPermission(const std::string& userId, TrustLevel::Enum trustLevel, const std::string& domain, const std::string& interfaceName) { std::ignore = userId; std::ignore = trustLevel; std::ignore = domain; std::ignore = interfaceName; assert(false && "Not yet implemented."); return true; } } // namespace joynr <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "monowriter.h" using namespace std; namespace essentia { namespace streaming { const char* MonoWriter::name = essentia::standard::MonoWriter::name; const char* MonoWriter::category = essentia::standard::MonoWriter::category; const char* MonoWriter::description = essentia::standard::MonoWriter::description; void MonoWriter::reset() { Algorithm::reset(); int recommendedBufferSize; try { recommendedBufferSize = _audioCtx.create(parameter("filename").toString(), parameter("format").toString(), 1, // nChannels parameter("sampleRate").toInt(), parameter("bitrate").toInt()*1000); } catch (EssentiaException& e) { throw EssentiaException("MonoWriter: Error creating audio file: ", e.what()); } _audio.setAcquireSize(recommendedBufferSize); _audio.setReleaseSize(recommendedBufferSize); } void MonoWriter::configure() { if (!parameter("filename").isConfigured() || parameter("filename").toString().empty()) { // no file has been specified or retarded name specified, do nothing _configured = false; return; } reset(); _configured = true; } AlgorithmStatus MonoWriter::process() { if (!_configured) { throw EssentiaException("MonoWriter: Trying to call process() on an MonoWriter algo which hasn't been correctly configured"); } if (!_audioCtx.isOpen()) _audioCtx.open(); EXEC_DEBUG("process()"); AlgorithmStatus status = acquireData(); if (status != OK) { if (!shouldStop()) return status; // encode whatever is left over int available = _audio.available(); if (available == 0) { EXEC_DEBUG("End of stream. There are 0 available tokens"); shouldStop(true); _audioCtx.close(); return FINISHED; } EXEC_DEBUG("Audio frame could not be fully acquired."); EXEC_DEBUG("There are " << available << " available tokens"); _audio.setAcquireSize(available); _audio.setReleaseSize(available); return process(); } try { _audioCtx.write(_audio.tokens()); } catch (EssentiaException& e) { throw EssentiaException("MonoWriter: error writing to audio file: ", e.what()); } releaseData(); return OK; } } // namespace streaming } // namespace essentia #include "algorithmfactory.h" namespace essentia { namespace standard { const char* MonoWriter::name = "MonoWriter"; const char* MonoWriter::category = "Input/output"; const char* MonoWriter::description = DOC("This algorithm writes a mono audio stream to a file.\n\n" "Supported formats are wav, aiff, mp3, flac and ogg. An exception is thrown when other extensions are given. Note that to encode in mp3 format it is mandatory that ffmpeg was configured with mp3 enabled.\n\n" "If the file specified by filename could not be opened or the header of the file omits channel's information, an exception is thrown."); void MonoWriter::createInnerNetwork() { _writer = streaming::AlgorithmFactory::create("MonoWriter"); _audiogen = new streaming::VectorInput<AudioSample, 1024>(); _audiogen->output("data") >> _writer->input("audio"); _network = new scheduler::Network(_audiogen); } void MonoWriter::configure() { _writer->configure(INHERIT("filename"), INHERIT("format"), INHERIT("sampleRate")); _configured = true; } void MonoWriter::compute() { if (!_configured) { throw EssentiaException("MonoWriter: Trying to call compute() on an MonoWriter algo which hasn't been correctly configured..."); } const vector<AudioSample>& audio = _audio.get(); _audiogen->setVector(&audio); _network->run(); // TODO: should we reset it here, same as MonoLoader to allow it to write twice in a row? } } // namespace standard } // namespace essentia <commit_msg>Update doc for MonoWriter<commit_after>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia 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 (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "monowriter.h" using namespace std; namespace essentia { namespace streaming { const char* MonoWriter::name = essentia::standard::MonoWriter::name; const char* MonoWriter::category = essentia::standard::MonoWriter::category; const char* MonoWriter::description = essentia::standard::MonoWriter::description; void MonoWriter::reset() { Algorithm::reset(); int recommendedBufferSize; try { recommendedBufferSize = _audioCtx.create(parameter("filename").toString(), parameter("format").toString(), 1, // nChannels parameter("sampleRate").toInt(), parameter("bitrate").toInt()*1000); } catch (EssentiaException& e) { throw EssentiaException("MonoWriter: Error creating audio file: ", e.what()); } _audio.setAcquireSize(recommendedBufferSize); _audio.setReleaseSize(recommendedBufferSize); } void MonoWriter::configure() { if (!parameter("filename").isConfigured() || parameter("filename").toString().empty()) { // no file has been specified or retarded name specified, do nothing _configured = false; return; } reset(); _configured = true; } AlgorithmStatus MonoWriter::process() { if (!_configured) { throw EssentiaException("MonoWriter: Trying to call process() on an MonoWriter algo which hasn't been correctly configured"); } if (!_audioCtx.isOpen()) _audioCtx.open(); EXEC_DEBUG("process()"); AlgorithmStatus status = acquireData(); if (status != OK) { if (!shouldStop()) return status; // encode whatever is left over int available = _audio.available(); if (available == 0) { EXEC_DEBUG("End of stream. There are 0 available tokens"); shouldStop(true); _audioCtx.close(); return FINISHED; } EXEC_DEBUG("Audio frame could not be fully acquired."); EXEC_DEBUG("There are " << available << " available tokens"); _audio.setAcquireSize(available); _audio.setReleaseSize(available); return process(); } try { _audioCtx.write(_audio.tokens()); } catch (EssentiaException& e) { throw EssentiaException("MonoWriter: error writing to audio file: ", e.what()); } releaseData(); return OK; } } // namespace streaming } // namespace essentia #include "algorithmfactory.h" namespace essentia { namespace standard { const char* MonoWriter::name = "MonoWriter"; const char* MonoWriter::category = "Input/output"; const char* MonoWriter::description = DOC("This algorithm writes a mono audio stream to a file.\n\n" "The algorithm uses FFmpeg. Supported formats are wav, aiff, mp3, flac and ogg. An exception is thrown when other extensions are given. The default FFmpeg encoders are used for each format. Note that to encode in mp3 format it is mandatory that FFmpeg was configured with mp3 enabled.\n\n" "If the file specified by filename could not be opened or the header of the file omits channel's information, an exception is thrown."); void MonoWriter::createInnerNetwork() { _writer = streaming::AlgorithmFactory::create("MonoWriter"); _audiogen = new streaming::VectorInput<AudioSample, 1024>(); _audiogen->output("data") >> _writer->input("audio"); _network = new scheduler::Network(_audiogen); } void MonoWriter::configure() { _writer->configure(INHERIT("filename"), INHERIT("format"), INHERIT("sampleRate")); _configured = true; } void MonoWriter::compute() { if (!_configured) { throw EssentiaException("MonoWriter: Trying to call compute() on an MonoWriter algo which hasn't been correctly configured..."); } const vector<AudioSample>& audio = _audio.get(); _audiogen->setVector(&audio); _network->run(); // TODO: should we reset it here, same as MonoLoader to allow it to write twice in a row? } } // namespace standard } // namespace essentia <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <tlib/system.hpp> #include <tlib/errors.hpp> #include <tlib/print.hpp> #include <tlib/net.hpp> namespace { static constexpr const size_t N = 4; static constexpr const size_t timeout_ms = 2000; } // end of anonymous namespace int main(int argc, char* argv[]) { if (argc != 2) { tlib::print_line("usage: ping address_ip"); return 1; } std::string ip(argv[1]); auto ip_parts = std::split(ip, '.'); if (ip_parts.size() != 4) { tlib::print_line("Invalid address IP"); return 1; } tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::RAW, tlib::socket_protocol::ICMP); if (!sock) { tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } sock.listen(true); if (!sock) { tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } tlib::icmp::packet_descriptor desc; desc.payload_size = 0; desc.target_ip = tlib::ip::make_address(std::atoui(ip_parts[0]), std::atoui(ip_parts[1]), std::atoui(ip_parts[2]), std::atoui(ip_parts[3])); desc.type = tlib::icmp::type::ECHO_REQUEST; desc.code = 0; for (size_t i = 0; i < N; ++i) { auto packet = sock.prepare_packet(&desc); if (!sock) { if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { tlib::printf("Unable to resolve MAC address for target IP\n"); return 1; } tlib::printf("ping: prepare_packet error: %s\n", std::error_message(sock.error())); return 1; } auto* command_header = reinterpret_cast<tlib::icmp::echo_request_header*>(packet.payload + packet.index); command_header->identifier = 0x666; command_header->sequence = 0x1 + i; sock.finalize_packet(packet); if (!sock) { tlib::printf("ping: finalize_packet error: %s\n", std::error_message(sock.error())); return 1; } auto before = tlib::ms_time(); auto after = before; while (true) { // Make sure we don't wait for more than the timeout if (after > before + timeout_ms) { break; } auto remaining = timeout_ms - (after - before); bool handled = false; auto p = sock.wait_for_packet(remaining); if (!sock) { if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { tlib::printf("%s unreachable\n", ip.c_str()); handled = true; sock.clear(); } else { tlib::printf("ping: wait_for_packet error: %s\n", std::error_message(sock.error())); return 1; } } else { auto* icmp_header = reinterpret_cast<tlib::icmp::header*>(p.payload + p.index); auto command_type = static_cast<tlib::icmp::type>(icmp_header->type); if (command_type == tlib::icmp::type::ECHO_REPLY) { tlib::printf("Reply received from %s\n", ip.c_str()); handled = true; } } if (handled) { break; } after = tlib::ms_time(); } if (i < N - 1) { tlib::sleep_ms(1000); } } sock.listen(false); return 0; } <commit_msg>Resolve domain names in ping<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <tlib/system.hpp> #include <tlib/errors.hpp> #include <tlib/print.hpp> #include <tlib/net.hpp> #include <tlib/dns.hpp> namespace { static constexpr const size_t N = 4; static constexpr const size_t timeout_ms = 2000; bool is_digit(char c){ return c >= '0' && c <= '9'; } bool is_ip(const std::string& value){ auto ip_parts = std::split(value, '.'); if(ip_parts.size() != 4){ return false; } for(auto& part : ip_parts){ if(part.empty() || part.size() > 3){ return false; } for(size_t i = 0; i < part.size(); ++i){ if(!is_digit(part[i])){ return false; } } } return true; } } // end of anonymous namespace int main(int argc, char* argv[]) { if (argc != 2) { tlib::print_line("usage: ping address_ip"); return 1; } std::string query(argv[1]); std::string ip; if (is_ip(query)) { ip = query; } else { auto resolved = tlib::dns::resolve(query); if(resolved){ ip = *resolved; } else { tlib::printf("ping: failed to resolve name: %s\n", std::error_message(resolved.error())); } } auto ip_parts = std::split(ip, '.'); if (ip_parts.size() != 4) { tlib::print_line("Invalid address IP"); return 1; } tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::RAW, tlib::socket_protocol::ICMP); if (!sock) { tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } sock.listen(true); if (!sock) { tlib::printf("ls: socket error: %s\n", std::error_message(sock.error())); return 1; } tlib::icmp::packet_descriptor desc; desc.payload_size = 0; desc.target_ip = tlib::ip::make_address(std::atoui(ip_parts[0]), std::atoui(ip_parts[1]), std::atoui(ip_parts[2]), std::atoui(ip_parts[3])); desc.type = tlib::icmp::type::ECHO_REQUEST; desc.code = 0; for (size_t i = 0; i < N; ++i) { auto packet = sock.prepare_packet(&desc); if (!sock) { if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { tlib::printf("Unable to resolve MAC address for target IP\n"); return 1; } tlib::printf("ping: prepare_packet error: %s\n", std::error_message(sock.error())); return 1; } auto* command_header = reinterpret_cast<tlib::icmp::echo_request_header*>(packet.payload + packet.index); command_header->identifier = 0x666; command_header->sequence = 0x1 + i; sock.finalize_packet(packet); if (!sock) { tlib::printf("ping: finalize_packet error: %s\n", std::error_message(sock.error())); return 1; } auto before = tlib::ms_time(); auto after = before; while (true) { // Make sure we don't wait for more than the timeout if (after > before + timeout_ms) { break; } auto remaining = timeout_ms - (after - before); bool handled = false; auto p = sock.wait_for_packet(remaining); if (!sock) { if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { tlib::printf("%s unreachable\n", ip.c_str()); handled = true; sock.clear(); } else { tlib::printf("ping: wait_for_packet error: %s\n", std::error_message(sock.error())); return 1; } } else { auto* icmp_header = reinterpret_cast<tlib::icmp::header*>(p.payload + p.index); auto command_type = static_cast<tlib::icmp::type>(icmp_header->type); if (command_type == tlib::icmp::type::ECHO_REPLY) { tlib::printf("Reply received from %s\n", ip.c_str()); handled = true; } } if (handled) { break; } after = tlib::ms_time(); } if (i < N - 1) { tlib::sleep_ms(1000); } } sock.listen(false); return 0; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <tlib/system.hpp> #include <tlib/errors.hpp> #include <tlib/print.hpp> #include <tlib/net.hpp> #include <tlib/dns.hpp> namespace { int wget_http(const std::string& url){ auto parts = std::split(url, '/'); if(parts.size() < 2){ tlib::print_line("wget: Invalid url"); return 1; } if(parts[0] == "http:"){ auto& domain = parts[1]; auto ip = tlib::dns::resolve(domain); if(ip){ tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::STREAM, tlib::socket_protocol::TCP); sock.connect(*ip, 80); sock.listen(true); if (!sock) { tlib::printf("nc: socket error: %s\n", std::error_message(sock.error())); return 1; } //TODO sock.listen(false); if (!sock) { tlib::printf("nc: socket error: %s\n", std::error_message(sock.error())); return 1; } } else { tlib::print_line("wget: cannot resolve the domain"); return 1; } } else { tlib::print_line("wget: The given protocol is not support"); return 1; } return 0; } } // end of anonymous namespace int main(int argc, char* argv[]) { if (argc < 2) { tlib::print_line("usage: wget url"); return 1; } std::string url(argv[1]); return wget_http(url); } <commit_msg>Complete wget<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include <tlib/system.hpp> #include <tlib/errors.hpp> #include <tlib/print.hpp> #include <tlib/net.hpp> #include <tlib/dns.hpp> namespace { int wget_http(const std::string& url){ auto parts = std::split(url, '/'); if(parts.size() < 2){ tlib::print_line("wget: Invalid url"); return 1; } if(parts[0] == "http:"){ auto& domain = parts[1]; tlib::ip::address ip; if (tlib::dns::is_ip(domain)) { auto ip_parts = std::split(domain, '.'); ip = tlib::ip::make_address(std::atoui(ip_parts[0]), std::atoui(ip_parts[1]), std::atoui(ip_parts[2]), std::atoui(ip_parts[3])); } else { auto ip_result = tlib::dns::resolve(domain); if(!ip_result){ tlib::print_line("wget: cannot resolve the domain"); return 1; } ip = *ip_result; } tlib::socket sock(tlib::socket_domain::AF_INET, tlib::socket_type::STREAM, tlib::socket_protocol::TCP); sock.connect(ip, 80); sock.listen(true); if (!sock) { tlib::printf("nc: socket error: %s\n", std::error_message(sock.error())); return 1; } std::string message; message += "GET "; if (parts.size() < 3) { message += '/'; } else { for (size_t i = 2; i < parts.size(); ++i) { message += '/'; message += parts[i]; } } message += " HTTP/1.1\r\n"; message += "Host: "; message += domain; message += "\r\n"; message += "Accept: text/html text/plain\r\n"; message += "User-Agent: wget (Thor OS)\r\n"; message += "\r\n"; sock.send(message.c_str(), message.size()); char message_buffer[2049]; auto size = sock.receive(message_buffer, 2048, 2000); if (!sock) { if (sock.error() == std::ERROR_SOCKET_TIMEOUT) { tlib::printf("Timeout\n"); return 1; } tlib::printf("nc: receive error: %s\n", std::error_message(sock.error())); return 1; } else { message_buffer[size] = '\0'; tlib::print(message_buffer); } sock.listen(false); if (!sock) { tlib::printf("nc: socket error: %s\n", std::error_message(sock.error())); return 1; } } else { tlib::print_line("wget: The given protocol is not support"); return 1; } return 0; } } // end of anonymous namespace int main(int argc, char* argv[]) { if (argc < 2) { tlib::print_line("usage: wget url"); return 1; } std::string url(argv[1]); return wget_http(url); } <|endoftext|>
<commit_before>#include "ShaderResourceBuffer.h" #include "Director.h" using namespace Device; using namespace Rendering::Buffer; ShaderResourceBuffer::ShaderResourceBuffer() : BaseBuffer(), _srv(nullptr) { } ShaderResourceBuffer::~ShaderResourceBuffer() { SAFE_RELEASE(_srv); SAFE_RELEASE(_buffer); } void ShaderResourceBuffer::Initialize(uint stride, uint num, DXGI_FORMAT format, const void* sysMem, bool useMapWriteNoOverWrite, D3D11_USAGE usage) { D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); desc.Usage = usage; desc.ByteWidth = stride * num; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = useMapWriteNoOverWrite ? D3D11_CPU_ACCESS_WRITE : 0; D3D11_SUBRESOURCE_DATA data; data.pSysMem = sysMem; ID3D11Device* device = Director::GetInstance()->GetDirectX()->GetDevice(); HRESULT hr = device->CreateBuffer(&desc, &data, &_buffer); ASSERT_COND_MSG(SUCCEEDED( hr ), "Error!. does not create constant buffer"); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = format; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; srvDesc.Buffer.ElementOffset = 0; srvDesc.Buffer.ElementWidth = num; hr = device->CreateShaderResourceView(_buffer, &srvDesc, &_srv); ASSERT_COND_MSG(SUCCEEDED(hr), "Error!, does not create shader resource view"); }<commit_msg>format이 unknown이면, StructuredBuffer로 설정함<commit_after>#include "ShaderResourceBuffer.h" #include "Director.h" using namespace Device; using namespace Rendering::Buffer; ShaderResourceBuffer::ShaderResourceBuffer() : BaseBuffer(), _srv(nullptr) { } ShaderResourceBuffer::~ShaderResourceBuffer() { SAFE_RELEASE(_srv); SAFE_RELEASE(_buffer); } void ShaderResourceBuffer::Initialize(uint stride, uint num, DXGI_FORMAT format, const void* sysMem, bool useMapWriteNoOverWrite, D3D11_USAGE usage) { D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); desc.Usage = usage; desc.ByteWidth = stride * num; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = useMapWriteNoOverWrite ? D3D11_CPU_ACCESS_WRITE : 0; desc.StructureByteStride = stride; desc.MiscFlags = (format == DXGI_FORMAT_UNKNOWN) ? D3D11_RESOURCE_MISC_BUFFER_STRUCTURED : 0; D3D11_SUBRESOURCE_DATA data; data.pSysMem = sysMem; ID3D11Device* device = Director::GetInstance()->GetDirectX()->GetDevice(); HRESULT hr = device->CreateBuffer(&desc, &data, &_buffer); ASSERT_COND_MSG(SUCCEEDED( hr ), "Error!. does not create constant buffer"); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = format; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFER; srvDesc.Buffer.ElementOffset = 0; srvDesc.Buffer.ElementWidth = num; hr = device->CreateShaderResourceView(_buffer, &srvDesc, &_srv); ASSERT_COND_MSG(SUCCEEDED(hr), "Error!, does not create shader resource view"); }<|endoftext|>
<commit_before>/* This file is part of libkdepim. Copyright (c) 2004-2005 David Faure <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "distributionlist.h" #include <kabc/addressbook.h> static const char *s_customFieldName = "DistributionList"; KPIM::DistributionList::DistributionList() : KABC::Addressee() { // can't insert the custom entry here, we need to remain a null addressee } KPIM::DistributionList::DistributionList( const KABC::Addressee &addr ) : KABC::Addressee( addr ) { } void KPIM::DistributionList::setName( const QString &name ) { // We can't use Addressee::setName, the name isn't saved/loaded in the vcard (fixed in 3.4) Addressee::setFormattedName( name ); // Also set family name, just in case this entry appears in the // normal contacts list (e.g. old kaddressbook) Addressee::setFamilyName( name ); // We're not an empty addressee anymore // Set the custom field to non-empty, so that isDistributionList works if ( custom( "KADDRESSBOOK", s_customFieldName ).isEmpty() ) { insertCustom( "KADDRESSBOOK", s_customFieldName, ";" ); } } // Helper function, to parse the contents of the custom field // Returns a list of { uid, email } typedef QList<QPair<QString, QString> > ParseList; static ParseList parseCustom( const QString &str ) { ParseList res; const QStringList lst = str.split( ';', QString::SkipEmptyParts ); for ( QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it ) { if ( (*it).isEmpty() ) { continue; } // parse "uid,email" QStringList helpList = (*it).split( ',', QString::SkipEmptyParts ); Q_ASSERT( !helpList.isEmpty() ); if ( helpList.isEmpty() ) { continue; } const QString uid = helpList.first(); QString email; Q_ASSERT( helpList.count() < 3 ); // 1 or 2 items, but not more if ( helpList.count() == 2 ) { email = helpList.last(); } res.append( qMakePair( uid, email ) ); } return res; } QString cleanupFormattedName( const QString &_formattedName ) { QString formattedName = _formattedName; formattedName.replace( ',', ' ' ); formattedName.replace( ';', ' ' ); return formattedName; } void KPIM::DistributionList::insertEntry( const Addressee &addr, const QString &email ) { // insertEntry will removeEntry(uid), but not with formattedName removeEntry( cleanupFormattedName( addr.formattedName() ), email ); insertEntry( addr.uid(), email ); } void KPIM::DistributionList::insertEntry( const QString &uid, const QString &email ) { Q_ASSERT( !email.isEmpty() || email.isNull() ); // never call with "", would lead to confusion removeEntry( uid, email ); // avoid duplicates QString str = custom( "KADDRESSBOOK", s_customFieldName ); // Assumption: UIDs don't contain ; nor , str += ';' + uid + ',' + email; insertCustom( "KADDRESSBOOK", s_customFieldName, str ); // replace old value } void KPIM::DistributionList::removeEntry( const Addressee &addr, const QString &email ) { removeEntry( addr.uid(), email ); // Also remove entries with the full name as uid (for the kolab thing) removeEntry( cleanupFormattedName( addr.formattedName() ), email ); } void KPIM::DistributionList::removeEntry( const QString &uid, const QString &email ) { Q_ASSERT( !email.isEmpty() || email.isNull() ); // never call with "", would lead to confusion ParseList parseList = parseCustom( custom( "KADDRESSBOOK", s_customFieldName ) ); QString str; for ( ParseList::ConstIterator it = parseList.begin(); it != parseList.end(); ++it ) { const QString thisUid = (*it).first; const QString thisEmail = (*it).second; if ( thisUid == uid && thisEmail == email ) { continue; // remove that one } str += ';' + thisUid + ',' + thisEmail; } if ( str.isEmpty() ) { str = ";"; // keep something, for isDistributionList to work } insertCustom( "KADDRESSBOOK", s_customFieldName, str ); // replace old value } bool KPIM::DistributionList::isDistributionList( const KABC::Addressee &addr ) { const QString str = addr.custom( "KADDRESSBOOK", s_customFieldName ); return !str.isEmpty(); } // ###### KDE4: add findByFormattedName to KABC::AddressBook static KABC::Addressee::List findByFormattedName( KABC::AddressBook *book, const QString &name, bool caseSensitive = true ) { KABC::Addressee::List res; KABC::AddressBook::Iterator abIt; for ( abIt = book->begin(); abIt != book->end(); ++abIt ) { if ( caseSensitive && (*abIt).formattedName() == name ) { res.append( *abIt ); } if ( !caseSensitive && (*abIt).formattedName().toLower() == name.toLower() ) { res.append( *abIt ); } } return res; } KPIM::DistributionList KPIM::DistributionList::findByName( KABC::AddressBook *book, const QString &name, bool caseSensitive ) { KABC::AddressBook::Iterator abIt; for ( abIt = book->begin(); abIt != book->end(); ++abIt ) { if ( isDistributionList( *abIt ) ) { if ( caseSensitive && (*abIt).formattedName() == name ) { return *abIt; } if ( !caseSensitive && (*abIt).formattedName().toLower() == name.toLower() ) { return *abIt; } } } return DistributionList(); } static KABC::Addressee findByUidOrName( KABC::AddressBook *book, const QString &uidOrName, const QString &email ) { KABC::Addressee a = book->findByUid( uidOrName ); if ( a.isEmpty() ) { // UID not found, maybe it is a name instead. // If we have an email, let's use that for the lookup. // [This is used by e.g. the Kolab resource] if ( !email.isEmpty() ) { KABC::Addressee::List lst = book->findByEmail( email ); KABC::Addressee::List::ConstIterator listit = lst.begin(); for ( ; listit != lst.end(); ++listit ) { if ( (*listit).formattedName() == uidOrName ) { a = *listit; break; } } if ( !lst.isEmpty() && a.isEmpty() ) { // found that email, but no match on the fullname a = lst.first(); // probably the last name changed } } // If we don't have an email, or if we didn't find any match for it, look up by full name if ( a.isEmpty() ) { // (But this has to be done here, since when loading we might not have the entries yet) KABC::Addressee::List lst = findByFormattedName( book, uidOrName ); if ( !lst.isEmpty() ) { a = lst.first(); } } } return a; } KPIM::DistributionList::Entry::List KPIM::DistributionList::entries( KABC::AddressBook *book ) const { Entry::List res; const QString str = custom( "KADDRESSBOOK", s_customFieldName ); const ParseList parseList = parseCustom( str ); for ( ParseList::ConstIterator it = parseList.begin(); it != parseList.end(); ++it ) { const QString uid = (*it).first; const QString email = (*it).second; // look up contact KABC::Addressee a = findByUidOrName( book, uid, email ); if ( a.isEmpty() ) { // ## The old DistributionListManager had a "missing entries" list... kWarning() <<"Addressee not found:" << uid; } else { res.append( Entry( a, email ) ); } } return res; } QStringList KPIM::DistributionList::emails( KABC::AddressBook *book ) const { QStringList emails; const QString str = custom( "KADDRESSBOOK", s_customFieldName ); ParseList parseList = parseCustom( str ); for ( ParseList::ConstIterator it = parseList.begin(); it != parseList.end(); ++it ) { const QString thisUid = (*it).first; const QString thisEmail = (*it).second; // look up contact KABC::Addressee a = findByUidOrName( book, thisUid, thisEmail ); if ( a.isEmpty() ) { // ## The old DistributionListManager had a "missing entries" list... continue; } const QString email = thisEmail.isEmpty() ? a.fullEmail() : a.fullEmail( thisEmail ); if ( !email.isEmpty() ) { emails.append( email ); } } return emails; } QList<KPIM::DistributionList> KPIM::DistributionList::allDistributionLists( KABC::AddressBook *book ) { QList<KPIM::DistributionList> lst; KABC::AddressBook::Iterator abIt; for ( abIt = book->begin(); abIt != book->end(); ++abIt ) { if ( isDistributionList( *abIt ) ) { lst.append( KPIM::DistributionList( *abIt ) ); } } return lst; } <commit_msg>Correctly parse custom fields that have an empty uid but an email address, such as those produced by the kolab resource. Don't stumble over your own pseudo-empty list of a single ';'. Fixes kolab/issue3619. MERGE: trunk.<commit_after>/* This file is part of libkdepim. Copyright (c) 2004-2005 David Faure <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "distributionlist.h" #include <kabc/addressbook.h> static const char *s_customFieldName = "DistributionList"; KPIM::DistributionList::DistributionList() : KABC::Addressee() { // can't insert the custom entry here, we need to remain a null addressee } KPIM::DistributionList::DistributionList( const KABC::Addressee &addr ) : KABC::Addressee( addr ) { } void KPIM::DistributionList::setName( const QString &name ) { // We can't use Addressee::setName, the name isn't saved/loaded in the vcard (fixed in 3.4) Addressee::setFormattedName( name ); // Also set family name, just in case this entry appears in the // normal contacts list (e.g. old kaddressbook) Addressee::setFamilyName( name ); // We're not an empty addressee anymore // Set the custom field to non-empty, so that isDistributionList works if ( custom( "KADDRESSBOOK", s_customFieldName ).isEmpty() ) { insertCustom( "KADDRESSBOOK", s_customFieldName, ";" ); } } // Helper function, to parse the contents of the custom field // Returns a list of { uid, email } typedef QList<QPair<QString, QString> > ParseList; static ParseList parseCustom( const QString &str ) { ParseList res; const QStringList lst = str.split( ';', QString::SkipEmptyParts ); for ( QStringList::ConstIterator it = lst.begin(); it != lst.end(); ++it ) { if ( (*it).isEmpty() ) { continue; } // parse "uid,email" QStringList helpList = (*it).split( ',' ); Q_ASSERT( !helpList.isEmpty() ); if ( helpList.isEmpty() ) { continue; } Q_ASSERT( helpList.count() < 3 ); // 1 or 2 items, but not more const QString uid = helpList.first(); // if it's the only thing we have, empty UID is not ok if ( helpList.count() == 1 && uid.isEmpty() ) { continue; } QString email; if ( helpList.count() == 2 ) { email = helpList.last(); } res.append( qMakePair( uid, email ) ); } return res; } QString cleanupFormattedName( const QString &_formattedName ) { QString formattedName = _formattedName; formattedName.replace( ',', ' ' ); formattedName.replace( ';', ' ' ); return formattedName; } void KPIM::DistributionList::insertEntry( const Addressee &addr, const QString &email ) { // insertEntry will removeEntry(uid), but not with formattedName removeEntry( cleanupFormattedName( addr.formattedName() ), email ); insertEntry( addr.uid(), email ); } void KPIM::DistributionList::insertEntry( const QString &uid, const QString &email ) { Q_ASSERT( !email.isEmpty() || email.isNull() ); // never call with "", would lead to confusion removeEntry( uid, email ); // avoid duplicates QString str = custom( "KADDRESSBOOK", s_customFieldName ); // Assumption: UIDs don't contain ; nor , if ( str != ";" ) str += ';'; str += uid + ',' + email; insertCustom( "KADDRESSBOOK", s_customFieldName, str ); // replace old value } void KPIM::DistributionList::removeEntry( const Addressee &addr, const QString &email ) { removeEntry( addr.uid(), email ); // Also remove entries with the full name as uid (for the kolab thing) removeEntry( cleanupFormattedName( addr.formattedName() ), email ); } void KPIM::DistributionList::removeEntry( const QString &uid, const QString &email ) { Q_ASSERT( !email.isEmpty() || email.isNull() ); // never call with "", would lead to confusion ParseList parseList = parseCustom( custom( "KADDRESSBOOK", s_customFieldName ) ); QString str; for ( ParseList::ConstIterator it = parseList.begin(); it != parseList.end(); ++it ) { const QString thisUid = (*it).first; const QString thisEmail = (*it).second; if ( thisUid == uid && thisEmail == email ) { continue; // remove that one } str += ';' + thisUid + ',' + thisEmail; } if ( str.isEmpty() ) { str = ";"; // keep something, for isDistributionList to work } insertCustom( "KADDRESSBOOK", s_customFieldName, str ); // replace old value } bool KPIM::DistributionList::isDistributionList( const KABC::Addressee &addr ) { const QString str = addr.custom( "KADDRESSBOOK", s_customFieldName ); return !str.isEmpty(); } // ###### KDE4: add findByFormattedName to KABC::AddressBook static KABC::Addressee::List findByFormattedName( KABC::AddressBook *book, const QString &name, bool caseSensitive = true ) { KABC::Addressee::List res; KABC::AddressBook::Iterator abIt; for ( abIt = book->begin(); abIt != book->end(); ++abIt ) { if ( caseSensitive && (*abIt).formattedName() == name ) { res.append( *abIt ); } if ( !caseSensitive && (*abIt).formattedName().toLower() == name.toLower() ) { res.append( *abIt ); } } return res; } KPIM::DistributionList KPIM::DistributionList::findByName( KABC::AddressBook *book, const QString &name, bool caseSensitive ) { KABC::AddressBook::Iterator abIt; for ( abIt = book->begin(); abIt != book->end(); ++abIt ) { if ( isDistributionList( *abIt ) ) { if ( caseSensitive && (*abIt).formattedName() == name ) { return *abIt; } if ( !caseSensitive && (*abIt).formattedName().toLower() == name.toLower() ) { return *abIt; } } } return DistributionList(); } static KABC::Addressee findByUidOrName( KABC::AddressBook *book, const QString &uidOrName, const QString &email ) { KABC::Addressee a = book->findByUid( uidOrName ); if ( a.isEmpty() ) { // UID not found, maybe it is a name instead. // If we have an email, let's use that for the lookup. // [This is used by e.g. the Kolab resource] if ( !email.isEmpty() ) { KABC::Addressee::List lst = book->findByEmail( email ); KABC::Addressee::List::ConstIterator listit = lst.begin(); for ( ; listit != lst.end(); ++listit ) { if ( (*listit).formattedName() == uidOrName ) { a = *listit; break; } } if ( !lst.isEmpty() && a.isEmpty() ) { // found that email, but no match on the fullname a = lst.first(); // probably the last name changed } } // If we don't have an email, or if we didn't find any match for it, look up by full name if ( a.isEmpty() ) { // (But this has to be done here, since when loading we might not have the entries yet) KABC::Addressee::List lst = findByFormattedName( book, uidOrName ); if ( !lst.isEmpty() ) { a = lst.first(); } } } return a; } KPIM::DistributionList::Entry::List KPIM::DistributionList::entries( KABC::AddressBook *book ) const { Entry::List res; const QString str = custom( "KADDRESSBOOK", s_customFieldName ); const ParseList parseList = parseCustom( str ); for ( ParseList::ConstIterator it = parseList.begin(); it != parseList.end(); ++it ) { const QString uid = (*it).first; const QString email = (*it).second; // look up contact KABC::Addressee a = findByUidOrName( book, uid, email ); if ( a.isEmpty() ) { // ## The old DistributionListManager had a "missing entries" list... kWarning() <<"Addressee not found:" << uid; } else { res.append( Entry( a, email ) ); } } return res; } QStringList KPIM::DistributionList::emails( KABC::AddressBook *book ) const { QStringList emails; const QString str = custom( "KADDRESSBOOK", s_customFieldName ); ParseList parseList = parseCustom( str ); for ( ParseList::ConstIterator it = parseList.begin(); it != parseList.end(); ++it ) { const QString thisUid = (*it).first; const QString thisEmail = (*it).second; // look up contact KABC::Addressee a = findByUidOrName( book, thisUid, thisEmail ); if ( a.isEmpty() ) { // ## The old DistributionListManager had a "missing entries" list... continue; } const QString email = thisEmail.isEmpty() ? a.fullEmail() : a.fullEmail( thisEmail ); if ( !email.isEmpty() ) { emails.append( email ); } } return emails; } QList<KPIM::DistributionList> KPIM::DistributionList::allDistributionLists( KABC::AddressBook *book ) { QList<KPIM::DistributionList> lst; KABC::AddressBook::Iterator abIt; for ( abIt = book->begin(); abIt != book->end(); ++abIt ) { if ( isDistributionList( *abIt ) ) { lst.append( KPIM::DistributionList( *abIt ) ); } } return lst; } <|endoftext|>
<commit_before>// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #include "core/Setup.h" #if OUZEL_PLATFORM_LINUX && OUZEL_COMPILE_OPENGL #if OUZEL_SUPPORTS_X11 # include <X11/Xlib.h> # include <X11/extensions/xf86vmode.h> #endif #include "RenderDeviceOGLLinux.hpp" #include "core/linux/EngineLinux.hpp" #include "core/linux/NativeWindowLinux.hpp" #include "utils/Log.hpp" #include "utils/Utils.hpp" namespace ouzel { namespace graphics { #if OUZEL_OPENGL_INTERFACE_EGL class EGLErrorCategory: public std::error_category { public: const char* name() const noexcept override { return "EGL"; } std::string message(int condition) const override { switch (condition) { case EGL_NOT_INITIALIZED: return "EGL_NOT_INITIALIZED"; case EGL_BAD_ACCESS: return "EGL_BAD_ACCESS"; case EGL_BAD_ALLOC: return "EGL_BAD_ALLOC"; case EGL_BAD_ATTRIBUTE: return "EGL_BAD_ATTRIBUTE"; case EGL_BAD_CONTEXT: return "EGL_BAD_CONTEXT"; case EGL_BAD_CONFIG: return "EGL_BAD_CONFIG"; case EGL_BAD_CURRENT_SURFACE: return "EGL_BAD_CURRENT_SURFACE"; case EGL_BAD_DISPLAY: return "EGL_BAD_DISPLAY"; case EGL_BAD_SURFACE: return "EGL_BAD_SURFACE"; case EGL_BAD_MATCH: return "EGL_BAD_MATCH"; case EGL_BAD_PARAMETER: return "EGL_BAD_PARAMETER"; case EGL_BAD_NATIVE_PIXMAP: return "EGL_BAD_NATIVE_PIXMAP"; case EGL_BAD_NATIVE_WINDOW: return "EGL_BAD_NATIVE_WINDOW"; case EGL_CONTEXT_LOST: return "EGL_CONTEXT_LOST"; default: return "Unknown error (" + std::to_string(condition) + ")"; } } }; const EGLErrorCategory eglErrorCategory {}; #endif RenderDeviceOGLLinux::RenderDeviceOGLLinux(const std::function<void(const Event&)>& initCallback): RenderDeviceOGL(initCallback), running(false) { } RenderDeviceOGLLinux::~RenderDeviceOGLLinux() { running = false; CommandBuffer commandBuffer; commandBuffer.commands.push(std::unique_ptr<Command>(new PresentCommand())); submitCommandBuffer(std::move(commandBuffer)); if (renderThread.joinable()) renderThread.join(); #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); if (engineLinux->getDisplay() && context) { glXMakeCurrent(engineLinux->getDisplay(), None, nullptr); glXDestroyContext(engineLinux->getDisplay(), context); } #elif OUZEL_OPENGL_INTERFACE_EGL if (context) { eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(display, context); } if (surface) eglDestroySurface(display, surface); if (display) eglTerminate(display); #endif } void RenderDeviceOGLLinux::init(Window* newWindow, const Size2& newSize, uint32_t newSampleCount, Texture::Filter newTextureFilter, uint32_t newMaxAnisotropy, bool newVerticalSync, bool newDepth, bool newDebugRenderer) { NativeWindowLinux* windowLinux = static_cast<NativeWindowLinux*>(newWindow->getNativeWindow()); #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); // make sure OpenGL's GLX extension supported int dummy; if (!glXQueryExtension(engineLinux->getDisplay(), &dummy, &dummy)) throw std::runtime_error("X server has no OpenGL GLX extension"); Screen* screen = XDefaultScreenOfDisplay(engineLinux->getDisplay()); int screenIndex = XScreenNumberOfScreen(screen); int fbcount = 0; static const int attributes[] = { GLX_X_RENDERABLE, GL_TRUE, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR, GLX_DOUBLEBUFFER, GL_TRUE, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, newDepth ? 24 : 0, GLX_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0, GLX_SAMPLES, static_cast<int>(newSampleCount), 0 }; std::unique_ptr<GLXFBConfig, int(*)(void*)> frameBufferConfig(glXChooseFBConfig(engineLinux->getDisplay(), screenIndex, attributes, &fbcount), XFree); if (frameBufferConfig) { PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsProc = reinterpret_cast<PFNGLXCREATECONTEXTATTRIBSARBPROC>(glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXCreateContextAttribsARB"))); if (glXCreateContextAttribsProc) { // create an OpenGL rendering context std::vector<int> contextAttribs = { GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 2 }; if (newDebugRenderer) { contextAttribs.push_back(GL_CONTEXT_FLAGS); contextAttribs.push_back(GL_CONTEXT_FLAG_DEBUG_BIT); } contextAttribs.push_back(0); context = glXCreateContextAttribsProc(engineLinux->getDisplay(), *frameBufferConfig, nullptr, True, contextAttribs.data()); if (context) { apiMajorVersion = 3; apiMinorVersion = 2; engine->log(Log::Level::INFO) << "GLX OpenGL 3.2 context created"; } } } if (!context) { context = glXCreateContext(engineLinux->getDisplay(), windowLinux->getVisualInfo(), None, GL_TRUE); if (context) { apiMajorVersion = 2; apiMinorVersion = 0; engine->log(Log::Level::INFO) << "GLX OpenGL 2 context created"; } else throw std::runtime_error("Failed to create GLX context"); } // bind the rendering context to the window if (!glXMakeCurrent(engineLinux->getDisplay(), windowLinux->getNativeWindow(), context)) throw std::runtime_error("Failed to make GLX context current"); PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = reinterpret_cast<PFNGLXSWAPINTERVALEXTPROC>(glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXSwapIntervalEXT"))); if (glXSwapIntervalEXT) glXSwapIntervalEXT(engineLinux->getDisplay(), windowLinux->getNativeWindow(), newVerticalSync ? 1 : 0); #elif OUZEL_OPENGL_INTERFACE_EGL display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (!display) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get display"); if (!eglInitialize(display, nullptr, nullptr)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to initialize EGL"); const EGLint attributeList[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, newDepth ? 24 : 0, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0, EGL_SAMPLES, static_cast<int>(newSampleCount), EGL_NONE }; EGLConfig config; EGLint numConfig; if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to choose EGL config"); if (!eglBindAPI(EGL_OPENGL_ES_API)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to bind OpenGL ES API"); surface = eglCreateWindowSurface(display, config, reinterpret_cast<EGLNativeWindowType>(&windowLinux->getNativeWindow()), nullptr); if (surface == EGL_NO_SURFACE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to create EGL window surface"); for (EGLint version = 3; version >= 2; --version) { std::vector<EGLint> contextAttributes = { EGL_CONTEXT_CLIENT_VERSION, version }; if (newDebugRenderer) { contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR); contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR); } contextAttributes.push_back(EGL_NONE); context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data()); if (context != EGL_NO_CONTEXT) { apiMajorVersion = version; apiMinorVersion = 0; engine->log(Log::Level::INFO) << "EGL OpenGL ES " << version << " context created"; break; } } if (context == EGL_NO_CONTEXT) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to create EGL context"); if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); if (!eglSwapInterval(display, newVerticalSync ? 1 : 0)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set EGL frame interval"); #endif RenderDeviceOGL::init(newWindow, newSize, newSampleCount, newTextureFilter, newMaxAnisotropy, newVerticalSync, newDepth, newDebugRenderer); #if OUZEL_OPENGL_INTERFACE_EGL if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); #endif running = true; renderThread = std::thread(&RenderDeviceOGLLinux::main, this); } std::vector<Size2> RenderDeviceOGLLinux::getSupportedResolutions() const { std::vector<Size2> result; #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); int modeCount; XF86VidModeModeInfo** modeInfo; XF86VidModeGetAllModeLines(engineLinux->getDisplay(), 0, &modeCount, &modeInfo); for (int i = 0; i < modeCount; ++i) { result.push_back(Size2(static_cast<float>(modeInfo[i]->hdisplay), static_cast<float>(modeInfo[i]->vdisplay))); } XFree(modeInfo); #elif OUZEL_OPENGL_INTERFACE_EGL // TODO: return screen resolution #endif return result; } void RenderDeviceOGLLinux::present() { #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); NativeWindowLinux* windowLinux = static_cast<NativeWindowLinux*>(window->getNativeWindow()); glXSwapBuffers(engineLinux->getDisplay(), windowLinux->getNativeWindow()); #elif OUZEL_OPENGL_INTERFACE_EGL if (eglSwapBuffers(display, surface) != EGL_TRUE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to swap buffers"); #endif } void RenderDeviceOGLLinux::main() { setCurrentThreadName("Render"); #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); NativeWindowLinux* windowLinux = static_cast<NativeWindowLinux*>(window->getNativeWindow()); if (!glXMakeCurrent(engineLinux->getDisplay(), windowLinux->getNativeWindow(), context)) throw std::runtime_error("Failed to make GLX context current"); #elif OUZEL_OPENGL_INTERFACE_EGL if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); #endif while (running) { try { process(); #if OUZEL_OPENGL_INTERFACE_EGL if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); #endif } catch (const std::exception& e) { engine->log(Log::Level::ERR) << e.what(); } } } } // namespace graphics } // namespace ouzel #endif <commit_msg>Fix the EGL context unset<commit_after>// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #include "core/Setup.h" #if OUZEL_PLATFORM_LINUX && OUZEL_COMPILE_OPENGL #if OUZEL_SUPPORTS_X11 # include <X11/Xlib.h> # include <X11/extensions/xf86vmode.h> #endif #include "RenderDeviceOGLLinux.hpp" #include "core/linux/EngineLinux.hpp" #include "core/linux/NativeWindowLinux.hpp" #include "utils/Log.hpp" #include "utils/Utils.hpp" namespace ouzel { namespace graphics { #if OUZEL_OPENGL_INTERFACE_EGL class EGLErrorCategory: public std::error_category { public: const char* name() const noexcept override { return "EGL"; } std::string message(int condition) const override { switch (condition) { case EGL_NOT_INITIALIZED: return "EGL_NOT_INITIALIZED"; case EGL_BAD_ACCESS: return "EGL_BAD_ACCESS"; case EGL_BAD_ALLOC: return "EGL_BAD_ALLOC"; case EGL_BAD_ATTRIBUTE: return "EGL_BAD_ATTRIBUTE"; case EGL_BAD_CONTEXT: return "EGL_BAD_CONTEXT"; case EGL_BAD_CONFIG: return "EGL_BAD_CONFIG"; case EGL_BAD_CURRENT_SURFACE: return "EGL_BAD_CURRENT_SURFACE"; case EGL_BAD_DISPLAY: return "EGL_BAD_DISPLAY"; case EGL_BAD_SURFACE: return "EGL_BAD_SURFACE"; case EGL_BAD_MATCH: return "EGL_BAD_MATCH"; case EGL_BAD_PARAMETER: return "EGL_BAD_PARAMETER"; case EGL_BAD_NATIVE_PIXMAP: return "EGL_BAD_NATIVE_PIXMAP"; case EGL_BAD_NATIVE_WINDOW: return "EGL_BAD_NATIVE_WINDOW"; case EGL_CONTEXT_LOST: return "EGL_CONTEXT_LOST"; default: return "Unknown error (" + std::to_string(condition) + ")"; } } }; const EGLErrorCategory eglErrorCategory {}; #endif RenderDeviceOGLLinux::RenderDeviceOGLLinux(const std::function<void(const Event&)>& initCallback): RenderDeviceOGL(initCallback), running(false) { } RenderDeviceOGLLinux::~RenderDeviceOGLLinux() { running = false; CommandBuffer commandBuffer; commandBuffer.commands.push(std::unique_ptr<Command>(new PresentCommand())); submitCommandBuffer(std::move(commandBuffer)); if (renderThread.joinable()) renderThread.join(); #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); if (engineLinux->getDisplay() && context) { glXMakeCurrent(engineLinux->getDisplay(), None, nullptr); glXDestroyContext(engineLinux->getDisplay(), context); } #elif OUZEL_OPENGL_INTERFACE_EGL if (context) { eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(display, context); } if (surface) eglDestroySurface(display, surface); if (display) eglTerminate(display); #endif } void RenderDeviceOGLLinux::init(Window* newWindow, const Size2& newSize, uint32_t newSampleCount, Texture::Filter newTextureFilter, uint32_t newMaxAnisotropy, bool newVerticalSync, bool newDepth, bool newDebugRenderer) { NativeWindowLinux* windowLinux = static_cast<NativeWindowLinux*>(newWindow->getNativeWindow()); #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); // make sure OpenGL's GLX extension supported int dummy; if (!glXQueryExtension(engineLinux->getDisplay(), &dummy, &dummy)) throw std::runtime_error("X server has no OpenGL GLX extension"); Screen* screen = XDefaultScreenOfDisplay(engineLinux->getDisplay()); int screenIndex = XScreenNumberOfScreen(screen); int fbcount = 0; static const int attributes[] = { GLX_X_RENDERABLE, GL_TRUE, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR, GLX_DOUBLEBUFFER, GL_TRUE, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, newDepth ? 24 : 0, GLX_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0, GLX_SAMPLES, static_cast<int>(newSampleCount), 0 }; std::unique_ptr<GLXFBConfig, int(*)(void*)> frameBufferConfig(glXChooseFBConfig(engineLinux->getDisplay(), screenIndex, attributes, &fbcount), XFree); if (frameBufferConfig) { PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsProc = reinterpret_cast<PFNGLXCREATECONTEXTATTRIBSARBPROC>(glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXCreateContextAttribsARB"))); if (glXCreateContextAttribsProc) { // create an OpenGL rendering context std::vector<int> contextAttribs = { GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, GLX_CONTEXT_MAJOR_VERSION_ARB, 3, GLX_CONTEXT_MINOR_VERSION_ARB, 2 }; if (newDebugRenderer) { contextAttribs.push_back(GL_CONTEXT_FLAGS); contextAttribs.push_back(GL_CONTEXT_FLAG_DEBUG_BIT); } contextAttribs.push_back(0); context = glXCreateContextAttribsProc(engineLinux->getDisplay(), *frameBufferConfig, nullptr, True, contextAttribs.data()); if (context) { apiMajorVersion = 3; apiMinorVersion = 2; engine->log(Log::Level::INFO) << "GLX OpenGL 3.2 context created"; } } } if (!context) { context = glXCreateContext(engineLinux->getDisplay(), windowLinux->getVisualInfo(), None, GL_TRUE); if (context) { apiMajorVersion = 2; apiMinorVersion = 0; engine->log(Log::Level::INFO) << "GLX OpenGL 2 context created"; } else throw std::runtime_error("Failed to create GLX context"); } // bind the rendering context to the window if (!glXMakeCurrent(engineLinux->getDisplay(), windowLinux->getNativeWindow(), context)) throw std::runtime_error("Failed to make GLX context current"); PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = reinterpret_cast<PFNGLXSWAPINTERVALEXTPROC>(glXGetProcAddress(reinterpret_cast<const GLubyte*>("glXSwapIntervalEXT"))); if (glXSwapIntervalEXT) glXSwapIntervalEXT(engineLinux->getDisplay(), windowLinux->getNativeWindow(), newVerticalSync ? 1 : 0); #elif OUZEL_OPENGL_INTERFACE_EGL display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (!display) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to get display"); if (!eglInitialize(display, nullptr, nullptr)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to initialize EGL"); const EGLint attributeList[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, newDepth ? 24 : 0, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0, EGL_SAMPLES, static_cast<int>(newSampleCount), EGL_NONE }; EGLConfig config; EGLint numConfig; if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to choose EGL config"); if (!eglBindAPI(EGL_OPENGL_ES_API)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to bind OpenGL ES API"); surface = eglCreateWindowSurface(display, config, reinterpret_cast<EGLNativeWindowType>(&windowLinux->getNativeWindow()), nullptr); if (surface == EGL_NO_SURFACE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to create EGL window surface"); for (EGLint version = 3; version >= 2; --version) { std::vector<EGLint> contextAttributes = { EGL_CONTEXT_CLIENT_VERSION, version }; if (newDebugRenderer) { contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR); contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR); } contextAttributes.push_back(EGL_NONE); context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data()); if (context != EGL_NO_CONTEXT) { apiMajorVersion = version; apiMinorVersion = 0; engine->log(Log::Level::INFO) << "EGL OpenGL ES " << version << " context created"; break; } } if (context == EGL_NO_CONTEXT) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to create EGL context"); if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); if (!eglSwapInterval(display, newVerticalSync ? 1 : 0)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set EGL frame interval"); #endif RenderDeviceOGL::init(newWindow, newSize, newSampleCount, newTextureFilter, newMaxAnisotropy, newVerticalSync, newDepth, newDebugRenderer); #if OUZEL_OPENGL_INTERFACE_EGL if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); #endif running = true; renderThread = std::thread(&RenderDeviceOGLLinux::main, this); } std::vector<Size2> RenderDeviceOGLLinux::getSupportedResolutions() const { std::vector<Size2> result; #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); int modeCount; XF86VidModeModeInfo** modeInfo; XF86VidModeGetAllModeLines(engineLinux->getDisplay(), 0, &modeCount, &modeInfo); for (int i = 0; i < modeCount; ++i) { result.push_back(Size2(static_cast<float>(modeInfo[i]->hdisplay), static_cast<float>(modeInfo[i]->vdisplay))); } XFree(modeInfo); #elif OUZEL_OPENGL_INTERFACE_EGL // TODO: return screen resolution #endif return result; } void RenderDeviceOGLLinux::present() { #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); NativeWindowLinux* windowLinux = static_cast<NativeWindowLinux*>(window->getNativeWindow()); glXSwapBuffers(engineLinux->getDisplay(), windowLinux->getNativeWindow()); #elif OUZEL_OPENGL_INTERFACE_EGL if (eglSwapBuffers(display, surface) != EGL_TRUE) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to swap buffers"); #endif } void RenderDeviceOGLLinux::main() { setCurrentThreadName("Render"); #if OUZEL_OPENGL_INTERFACE_GLX EngineLinux* engineLinux = static_cast<EngineLinux*>(engine); NativeWindowLinux* windowLinux = static_cast<NativeWindowLinux*>(window->getNativeWindow()); if (!glXMakeCurrent(engineLinux->getDisplay(), windowLinux->getNativeWindow(), context)) throw std::runtime_error("Failed to make GLX context current"); #elif OUZEL_OPENGL_INTERFACE_EGL if (!eglMakeCurrent(display, surface, surface, context)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to set current EGL context"); #endif while (running) { try { process(); } catch (const std::exception& e) { engine->log(Log::Level::ERR) << e.what(); } } #if OUZEL_OPENGL_INTERFACE_EGL if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) throw std::system_error(eglGetError(), eglErrorCategory, "Failed to unset EGL context"); #endif } } // namespace graphics } // namespace ouzel #endif <|endoftext|>
<commit_before>// Copyright 2021 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 // // 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 "project_and_sample.h" #include <cmath> #include <random> #include <string> #include <tuple> #include <vector> // placeholder for get runfiles header. #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "include/ghc/filesystem.hpp" #include "exported_layers_test.h" #include "lyra_types.h" #include "sparse_inference_matrixvector.h" namespace chromemedia { namespace codec { namespace { static constexpr int kNumSplitBands = 4; static constexpr int kTestNumGruHiddens = 4; static constexpr int kExpandedMixesSize = 8; static constexpr char kPrefix[] = "lyra_"; // For creating typed-tests. We want to test the template class, // ProjectAndSampleTest, instantiated with different types: // 1. float: C++'s generic floating point. // 2. csrblocksparse::fixed16_type: a type that will be used in our Lyra // implementation. See the build rule for // audio/chromedia/lyra/codec:wavegru_model_impl. // Different types would require different tolerance, hence the template class // Tolerance below. template <typename WeightTypeKind> struct Tolerance { // Unspecialized Tolerance class does not define |kTolerance|, so an attempt // to test a ComputeType that is not one of // {float, csrblocksparse::fixed16_type} will result in a compile error. }; template <> struct Tolerance<float> { static constexpr float kTolerance = 1e-7f; }; template <> struct Tolerance<csrblocksparse::fixed16_type> { // Fixed-point arithmetic is less accurate than floating-point; hence a higher // tolerance. static constexpr float kTolerance = 1.5e-2f; }; // A matcher to compare a tuple (used in testing::Pointwise) and verify that // the relative error between the two elements is within a tolerance. MATCHER_P(IsRelativelyClose, relative_tolerance, absl::StrFormat("%s approximately equal (relative error <= %g)", negation ? "are not" : "are", relative_tolerance)) { const float actual = static_cast<float>(::testing::get<0>(arg)); const float expected = static_cast<float>(::testing::get<1>(arg)); return (std::abs(actual - expected) / std::abs(expected)) <= relative_tolerance; } template <typename WeightTypeKind> class ProjectAndSampleTest : public ::testing::Test { public: ProjectAndSampleTest() : project_and_sample_layer_(), gru_hiddens_(kTestNumGruHiddens, static_cast<ProjRhsType>(0.5f)), gru_hiddens_view_(gru_hiddens_.data(), kTestNumGruHiddens, 1), testdata_dir_(ghc::filesystem::current_path() / "testdata"), scratch_space_(kExpandedMixesSize) {} protected: using ProjectAndSampleType = ProjectAndSample<ProjectAndSampleTypes<WeightTypeKind, 8, 8, 8, 8, 8>>; using ScratchType = typename ProjectAndSampleType::ScratchType; using ProjRhsType = typename ProjectAndSampleType::ProjRhsType; static constexpr float kTolerance = Tolerance<WeightTypeKind>::kTolerance; ProjectAndSampleType project_and_sample_layer_; // Input to the project-and-sample layer. In Wavegru it is the hidden states // of the GRU layer. std::vector<ProjRhsType> gru_hiddens_; const csrblocksparse::MutableVectorView<ProjRhsType> gru_hiddens_view_; const ghc::filesystem::path testdata_dir_; // Scratch space for GetSample(). csrblocksparse::CacheAlignedVector<ScratchType> scratch_space_; }; using WeightTypeKinds = ::testing::Types<float, csrblocksparse::fixed16_type>; TYPED_TEST_SUITE(ProjectAndSampleTest, WeightTypeKinds); TYPED_TEST(ProjectAndSampleTest, LoadAndPrepareSucceed) { this->project_and_sample_layer_.LoadRaw(this->testdata_dir_.string(), kPrefix, /*zipped=*/true); EXPECT_EQ(this->project_and_sample_layer_.expanded_mixes_size(), kExpandedMixesSize); EXPECT_GT(this->project_and_sample_layer_.ModelSize(), 0); for (const int num_threads : {1, 2, 4}) { EXPECT_EQ(this->project_and_sample_layer_.PrepareForThreads(num_threads), num_threads); } } TYPED_TEST(ProjectAndSampleTest, GetSamplesReturnGoldenValues) { this->project_and_sample_layer_.LoadRaw(this->testdata_dir_.string(), kPrefix, /*zipped=*/true); // The result should match the golden values regardless of number of threads. const std::vector<int> expected_samples = {-104, -1387, 238, -220}; for (const int num_threads : {1, 2, 4}) { this->project_and_sample_layer_.PrepareForThreads(num_threads); // Make sampling deterministic. const std::minstd_rand::result_type kSeed = 42; std::vector<std::minstd_rand> gen(num_threads, std::minstd_rand(kSeed)); std::vector<int> actual_samples(kNumSplitBands); auto f = [&](csrblocksparse::SpinBarrier* barrier, int tid) { this->project_and_sample_layer_.GetSamples( this->gru_hiddens_view_, /*tid=*/tid, &gen[tid], &this->scratch_space_, kNumSplitBands, actual_samples.data()); barrier->barrier(); }; LaunchOnThreadsWithBarrier(num_threads, f); EXPECT_THAT(actual_samples, testing::Pointwise(IsRelativelyClose(TestFixture::kTolerance), expected_samples)); } } TYPED_TEST(ProjectAndSampleTest, ReportTiming) { this->project_and_sample_layer_.LoadRaw(this->testdata_dir_.string(), kPrefix, /*zipped=*/true); this->project_and_sample_layer_.set_time_components(true); this->project_and_sample_layer_.PrepareForThreads(1); std::minstd_rand gen; std::vector<int> actual_samples(kNumSplitBands); this->project_and_sample_layer_.GetSamples( this->gru_hiddens_view_, /*tid=*/0, &gen, &this->scratch_space_, kNumSplitBands, actual_samples.data()); // Verify that the timing is non-empty. We do not care about the content. const std::string timing = this->project_and_sample_layer_.ReportTiming(); EXPECT_FALSE(timing.empty()); } // Test that exported layers with fixed-point and float weights produce // matching results. using csrblocksparse::fixed16_type; using FixedProjectAndSampleType = ProjectAndSample<ProjectAndSampleTypes<fixed16_type>>; static constexpr int kNumGruHiddens = 1024; static constexpr int kProjSize = 512; LayerParams ProjectionLayerParams(int num_input_channels, int num_filters, bool relu, const std::string& model_path, const std::string& prefix) { return LayerParams{ .num_input_channels = num_input_channels, .num_filters = num_filters, .length = 1, .kernel_size = 1, .dilation = 1, .stride = 1, .relu = relu, .skip_connection = false, .type = LayerType::kConv1D, .num_threads = 1, .per_column_barrier = false, .from = LayerParams::FromDisk{.path = model_path, .zipped = true}, .prefix = prefix}; } struct ProjLayerTypes { using FloatLayerType = LayerWrapper<float, float, float, float>; using FixedLayerType = LayerWrapper<FixedProjectAndSampleType::ProjWeightType, FixedProjectAndSampleType::ProjRhsType, FixedProjectAndSampleType::ProjMatMulOutType, FixedProjectAndSampleType::DiskWeightType>; static LayerParams Params(const std::string& model_path) { return ProjectionLayerParams(kNumGruHiddens, kProjSize, true, model_path, "lyra_16khz_proj_"); } }; struct ScaleLayerTypes { using FloatLayerType = LayerWrapper<float, float, float, float>; using FixedLayerType = LayerWrapper<FixedProjectAndSampleType::ScaleWeightType, FixedProjectAndSampleType::ProjMatMulOutType, FixedProjectAndSampleType::ScaleMatMulOutType, FixedProjectAndSampleType::DiskWeightType>; static LayerParams Params(const std::string& model_path) { return ProjectionLayerParams(kProjSize, kNumSplitBands * kExpandedMixesSize, false, model_path, "lyra_16khz_scales_"); } }; struct MeanLayerTypes { using FloatLayerType = LayerWrapper<float, float, float, float>; using FixedLayerType = LayerWrapper<FixedProjectAndSampleType::MeanWeightType, FixedProjectAndSampleType::ProjMatMulOutType, FixedProjectAndSampleType::MeanMatMulOutType, FixedProjectAndSampleType::DiskWeightType>; static LayerParams Params(const std::string& model_path) { return ProjectionLayerParams(kProjSize, kNumSplitBands * kExpandedMixesSize, false, model_path, "lyra_16khz_means_"); } }; struct MixLayerTypes { using FloatLayerType = LayerWrapper<float, float, float, float>; using FixedLayerType = LayerWrapper<FixedProjectAndSampleType::MixWeightType, FixedProjectAndSampleType::ProjMatMulOutType, FixedProjectAndSampleType::MixMatMulOutType, FixedProjectAndSampleType::DiskWeightType>; static LayerParams Params(const std::string& model_path) { return ProjectionLayerParams(kProjSize, kNumSplitBands * kExpandedMixesSize, false, model_path, "lyra_16khz_mix_"); } }; using LayerTypesList = testing::Types<ProjLayerTypes, ScaleLayerTypes, MeanLayerTypes, MixLayerTypes>; INSTANTIATE_TYPED_TEST_SUITE_P(ProjectAndSample, ExportedLayersTest, LayerTypesList); } // namespace } // namespace codec } // namespace chromemedia <commit_msg>spelling: chromemedia<commit_after>// Copyright 2021 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 // // 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 "project_and_sample.h" #include <cmath> #include <random> #include <string> #include <tuple> #include <vector> // placeholder for get runfiles header. #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "include/ghc/filesystem.hpp" #include "exported_layers_test.h" #include "lyra_types.h" #include "sparse_inference_matrixvector.h" namespace chromemedia { namespace codec { namespace { static constexpr int kNumSplitBands = 4; static constexpr int kTestNumGruHiddens = 4; static constexpr int kExpandedMixesSize = 8; static constexpr char kPrefix[] = "lyra_"; // For creating typed-tests. We want to test the template class, // ProjectAndSampleTest, instantiated with different types: // 1. float: C++'s generic floating point. // 2. csrblocksparse::fixed16_type: a type that will be used in our Lyra // implementation. See the build rule for // audio/chromemedia/lyra/codec:wavegru_model_impl. // Different types would require different tolerance, hence the template class // Tolerance below. template <typename WeightTypeKind> struct Tolerance { // Unspecialized Tolerance class does not define |kTolerance|, so an attempt // to test a ComputeType that is not one of // {float, csrblocksparse::fixed16_type} will result in a compile error. }; template <> struct Tolerance<float> { static constexpr float kTolerance = 1e-7f; }; template <> struct Tolerance<csrblocksparse::fixed16_type> { // Fixed-point arithmetic is less accurate than floating-point; hence a higher // tolerance. static constexpr float kTolerance = 1.5e-2f; }; // A matcher to compare a tuple (used in testing::Pointwise) and verify that // the relative error between the two elements is within a tolerance. MATCHER_P(IsRelativelyClose, relative_tolerance, absl::StrFormat("%s approximately equal (relative error <= %g)", negation ? "are not" : "are", relative_tolerance)) { const float actual = static_cast<float>(::testing::get<0>(arg)); const float expected = static_cast<float>(::testing::get<1>(arg)); return (std::abs(actual - expected) / std::abs(expected)) <= relative_tolerance; } template <typename WeightTypeKind> class ProjectAndSampleTest : public ::testing::Test { public: ProjectAndSampleTest() : project_and_sample_layer_(), gru_hiddens_(kTestNumGruHiddens, static_cast<ProjRhsType>(0.5f)), gru_hiddens_view_(gru_hiddens_.data(), kTestNumGruHiddens, 1), testdata_dir_(ghc::filesystem::current_path() / "testdata"), scratch_space_(kExpandedMixesSize) {} protected: using ProjectAndSampleType = ProjectAndSample<ProjectAndSampleTypes<WeightTypeKind, 8, 8, 8, 8, 8>>; using ScratchType = typename ProjectAndSampleType::ScratchType; using ProjRhsType = typename ProjectAndSampleType::ProjRhsType; static constexpr float kTolerance = Tolerance<WeightTypeKind>::kTolerance; ProjectAndSampleType project_and_sample_layer_; // Input to the project-and-sample layer. In Wavegru it is the hidden states // of the GRU layer. std::vector<ProjRhsType> gru_hiddens_; const csrblocksparse::MutableVectorView<ProjRhsType> gru_hiddens_view_; const ghc::filesystem::path testdata_dir_; // Scratch space for GetSample(). csrblocksparse::CacheAlignedVector<ScratchType> scratch_space_; }; using WeightTypeKinds = ::testing::Types<float, csrblocksparse::fixed16_type>; TYPED_TEST_SUITE(ProjectAndSampleTest, WeightTypeKinds); TYPED_TEST(ProjectAndSampleTest, LoadAndPrepareSucceed) { this->project_and_sample_layer_.LoadRaw(this->testdata_dir_.string(), kPrefix, /*zipped=*/true); EXPECT_EQ(this->project_and_sample_layer_.expanded_mixes_size(), kExpandedMixesSize); EXPECT_GT(this->project_and_sample_layer_.ModelSize(), 0); for (const int num_threads : {1, 2, 4}) { EXPECT_EQ(this->project_and_sample_layer_.PrepareForThreads(num_threads), num_threads); } } TYPED_TEST(ProjectAndSampleTest, GetSamplesReturnGoldenValues) { this->project_and_sample_layer_.LoadRaw(this->testdata_dir_.string(), kPrefix, /*zipped=*/true); // The result should match the golden values regardless of number of threads. const std::vector<int> expected_samples = {-104, -1387, 238, -220}; for (const int num_threads : {1, 2, 4}) { this->project_and_sample_layer_.PrepareForThreads(num_threads); // Make sampling deterministic. const std::minstd_rand::result_type kSeed = 42; std::vector<std::minstd_rand> gen(num_threads, std::minstd_rand(kSeed)); std::vector<int> actual_samples(kNumSplitBands); auto f = [&](csrblocksparse::SpinBarrier* barrier, int tid) { this->project_and_sample_layer_.GetSamples( this->gru_hiddens_view_, /*tid=*/tid, &gen[tid], &this->scratch_space_, kNumSplitBands, actual_samples.data()); barrier->barrier(); }; LaunchOnThreadsWithBarrier(num_threads, f); EXPECT_THAT(actual_samples, testing::Pointwise(IsRelativelyClose(TestFixture::kTolerance), expected_samples)); } } TYPED_TEST(ProjectAndSampleTest, ReportTiming) { this->project_and_sample_layer_.LoadRaw(this->testdata_dir_.string(), kPrefix, /*zipped=*/true); this->project_and_sample_layer_.set_time_components(true); this->project_and_sample_layer_.PrepareForThreads(1); std::minstd_rand gen; std::vector<int> actual_samples(kNumSplitBands); this->project_and_sample_layer_.GetSamples( this->gru_hiddens_view_, /*tid=*/0, &gen, &this->scratch_space_, kNumSplitBands, actual_samples.data()); // Verify that the timing is non-empty. We do not care about the content. const std::string timing = this->project_and_sample_layer_.ReportTiming(); EXPECT_FALSE(timing.empty()); } // Test that exported layers with fixed-point and float weights produce // matching results. using csrblocksparse::fixed16_type; using FixedProjectAndSampleType = ProjectAndSample<ProjectAndSampleTypes<fixed16_type>>; static constexpr int kNumGruHiddens = 1024; static constexpr int kProjSize = 512; LayerParams ProjectionLayerParams(int num_input_channels, int num_filters, bool relu, const std::string& model_path, const std::string& prefix) { return LayerParams{ .num_input_channels = num_input_channels, .num_filters = num_filters, .length = 1, .kernel_size = 1, .dilation = 1, .stride = 1, .relu = relu, .skip_connection = false, .type = LayerType::kConv1D, .num_threads = 1, .per_column_barrier = false, .from = LayerParams::FromDisk{.path = model_path, .zipped = true}, .prefix = prefix}; } struct ProjLayerTypes { using FloatLayerType = LayerWrapper<float, float, float, float>; using FixedLayerType = LayerWrapper<FixedProjectAndSampleType::ProjWeightType, FixedProjectAndSampleType::ProjRhsType, FixedProjectAndSampleType::ProjMatMulOutType, FixedProjectAndSampleType::DiskWeightType>; static LayerParams Params(const std::string& model_path) { return ProjectionLayerParams(kNumGruHiddens, kProjSize, true, model_path, "lyra_16khz_proj_"); } }; struct ScaleLayerTypes { using FloatLayerType = LayerWrapper<float, float, float, float>; using FixedLayerType = LayerWrapper<FixedProjectAndSampleType::ScaleWeightType, FixedProjectAndSampleType::ProjMatMulOutType, FixedProjectAndSampleType::ScaleMatMulOutType, FixedProjectAndSampleType::DiskWeightType>; static LayerParams Params(const std::string& model_path) { return ProjectionLayerParams(kProjSize, kNumSplitBands * kExpandedMixesSize, false, model_path, "lyra_16khz_scales_"); } }; struct MeanLayerTypes { using FloatLayerType = LayerWrapper<float, float, float, float>; using FixedLayerType = LayerWrapper<FixedProjectAndSampleType::MeanWeightType, FixedProjectAndSampleType::ProjMatMulOutType, FixedProjectAndSampleType::MeanMatMulOutType, FixedProjectAndSampleType::DiskWeightType>; static LayerParams Params(const std::string& model_path) { return ProjectionLayerParams(kProjSize, kNumSplitBands * kExpandedMixesSize, false, model_path, "lyra_16khz_means_"); } }; struct MixLayerTypes { using FloatLayerType = LayerWrapper<float, float, float, float>; using FixedLayerType = LayerWrapper<FixedProjectAndSampleType::MixWeightType, FixedProjectAndSampleType::ProjMatMulOutType, FixedProjectAndSampleType::MixMatMulOutType, FixedProjectAndSampleType::DiskWeightType>; static LayerParams Params(const std::string& model_path) { return ProjectionLayerParams(kProjSize, kNumSplitBands * kExpandedMixesSize, false, model_path, "lyra_16khz_mix_"); } }; using LayerTypesList = testing::Types<ProjLayerTypes, ScaleLayerTypes, MeanLayerTypes, MixLayerTypes>; INSTANTIATE_TYPED_TEST_SUITE_P(ProjectAndSample, ExportedLayersTest, LayerTypesList); } // namespace } // namespace codec } // namespace chromemedia <|endoftext|>
<commit_before>// // StaticAnalyser.cpp // Clock Signal // // Created by Thomas Harte on 23/08/2016. // Copyright 2016 Thomas Harte. All rights reserved. // #include "StaticAnalyser.hpp" #include <algorithm> #include <cstdlib> #include <cstring> #include <iterator> // Analysers #include "Acorn/StaticAnalyser.hpp" #include "AmstradCPC/StaticAnalyser.hpp" #include "AppleII/StaticAnalyser.hpp" #include "AppleIIgs/StaticAnalyser.hpp" #include "Atari2600/StaticAnalyser.hpp" #include "AtariST/StaticAnalyser.hpp" #include "Coleco/StaticAnalyser.hpp" #include "Commodore/StaticAnalyser.hpp" #include "DiskII/StaticAnalyser.hpp" #include "Macintosh/StaticAnalyser.hpp" #include "MSX/StaticAnalyser.hpp" #include "Oric/StaticAnalyser.hpp" #include "Sega/StaticAnalyser.hpp" #include "ZX8081/StaticAnalyser.hpp" #include "ZXSpectrum/StaticAnalyser.hpp" // Cartridges #include "../../Storage/Cartridge/Formats/BinaryDump.hpp" #include "../../Storage/Cartridge/Formats/PRG.hpp" // Disks #include "../../Storage/Disk/DiskImage/Formats/2MG.hpp" #include "../../Storage/Disk/DiskImage/Formats/AcornADF.hpp" #include "../../Storage/Disk/DiskImage/Formats/AppleDSK.hpp" #include "../../Storage/Disk/DiskImage/Formats/CPCDSK.hpp" #include "../../Storage/Disk/DiskImage/Formats/D64.hpp" #include "../../Storage/Disk/DiskImage/Formats/MacintoshIMG.hpp" #include "../../Storage/Disk/DiskImage/Formats/G64.hpp" #include "../../Storage/Disk/DiskImage/Formats/DMK.hpp" #include "../../Storage/Disk/DiskImage/Formats/HFE.hpp" #include "../../Storage/Disk/DiskImage/Formats/MSA.hpp" #include "../../Storage/Disk/DiskImage/Formats/MSXDSK.hpp" #include "../../Storage/Disk/DiskImage/Formats/NIB.hpp" #include "../../Storage/Disk/DiskImage/Formats/OricMFMDSK.hpp" #include "../../Storage/Disk/DiskImage/Formats/SSD.hpp" #include "../../Storage/Disk/DiskImage/Formats/ST.hpp" #include "../../Storage/Disk/DiskImage/Formats/STX.hpp" #include "../../Storage/Disk/DiskImage/Formats/WOZ.hpp" // Mass Storage Devices (i.e. usually, hard disks) #include "../../Storage/MassStorage/Formats/DAT.hpp" #include "../../Storage/MassStorage/Formats/HFV.hpp" // Tapes #include "../../Storage/Tape/Formats/CAS.hpp" #include "../../Storage/Tape/Formats/CommodoreTAP.hpp" #include "../../Storage/Tape/Formats/CSW.hpp" #include "../../Storage/Tape/Formats/OricTAP.hpp" #include "../../Storage/Tape/Formats/TapePRG.hpp" #include "../../Storage/Tape/Formats/TapeUEF.hpp" #include "../../Storage/Tape/Formats/TZX.hpp" #include "../../Storage/Tape/Formats/ZX80O81P.hpp" #include "../../Storage/Tape/Formats/ZXSpectrumTAP.hpp" // Target Platform Types #include "../../Storage/TargetPlatforms.hpp" using namespace Analyser::Static; static Media GetMediaAndPlatforms(const std::string &file_name, TargetPlatform::IntType &potential_platforms) { Media result; // Get the extension, if any; it will be assumed that extensions are reliable, so an extension is a broad-phase // test as to file format. std::string::size_type final_dot = file_name.find_last_of("."); if(final_dot == std::string::npos) return result; std::string extension = file_name.substr(final_dot + 1); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); #define InsertInstance(list, instance, platforms) \ list.emplace_back(instance);\ potential_platforms |= platforms;\ TargetPlatform::TypeDistinguisher *distinguisher = dynamic_cast<TargetPlatform::TypeDistinguisher *>(list.back().get());\ if(distinguisher) potential_platforms &= distinguisher->target_platform_type(); \ #define Insert(list, class, platforms, ...) \ InsertInstance(list, new Storage::class(__VA_ARGS__), platforms); #define TryInsert(list, class, platforms, ...) \ try {\ Insert(list, class, platforms, __VA_ARGS__) \ } catch(...) {} #define Format(ext, list, class, platforms) \ if(extension == ext) { \ TryInsert(list, class, platforms, file_name) \ } // 2MG if(extension == "2mg") { // 2MG uses a factory method; defer to it. try { InsertInstance(result.disks, Storage::Disk::Disk2MG::open(file_name), TargetPlatform::DiskII) } catch(...) {} } Format("80", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // 80 Format("81", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // 81 Format("a26", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Atari2600) // A26 Format("adf", result.disks, Disk::DiskImageHolder<Storage::Disk::AcornADF>, TargetPlatform::Acorn) // ADF Format("adl", result.disks, Disk::DiskImageHolder<Storage::Disk::AcornADF>, TargetPlatform::Acorn) // ADL Format("bin", result.cartridges, Cartridge::BinaryDump, TargetPlatform::AllCartridge) // BIN (cartridge dump) Format("cas", result.tapes, Tape::CAS, TargetPlatform::MSX) // CAS Format("cdt", result.tapes, Tape::TZX, TargetPlatform::AmstradCPC) // CDT Format("col", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Coleco) // COL Format("csw", result.tapes, Tape::CSW, TargetPlatform::AllTape) // CSW Format("d64", result.disks, Disk::DiskImageHolder<Storage::Disk::D64>, TargetPlatform::Commodore) // D64 Format("dat", result.mass_storage_devices, MassStorage::DAT, TargetPlatform::Acorn) // DAT Format("dmk", result.disks, Disk::DiskImageHolder<Storage::Disk::DMK>, TargetPlatform::MSX) // DMK Format("do", result.disks, Disk::DiskImageHolder<Storage::Disk::AppleDSK>, TargetPlatform::DiskII) // DO Format("dsd", result.disks, Disk::DiskImageHolder<Storage::Disk::SSD>, TargetPlatform::Acorn) // DSD Format( "dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::CPCDSK>, TargetPlatform::AmstradCPC | TargetPlatform::Oric | TargetPlatform::ZXSpectrum) // DSK (Amstrad CPC, etc) Format("dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::AppleDSK>, TargetPlatform::DiskII) // DSK (Apple II) Format("dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::MacintoshIMG>, TargetPlatform::Macintosh) // DSK (Macintosh, floppy disk) Format("dsk", result.mass_storage_devices, MassStorage::HFV, TargetPlatform::Macintosh) // DSK (Macintosh, hard disk) Format("dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::MSXDSK>, TargetPlatform::MSX) // DSK (MSX) Format("dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::OricMFMDSK>, TargetPlatform::Oric) // DSK (Oric) Format("g64", result.disks, Disk::DiskImageHolder<Storage::Disk::G64>, TargetPlatform::Commodore) // G64 Format( "hfe", result.disks, Disk::DiskImageHolder<Storage::Disk::HFE>, TargetPlatform::Acorn | TargetPlatform::AmstradCPC | TargetPlatform::Commodore | TargetPlatform::Oric) // HFE (TODO: switch to AllDisk once the MSX stops being so greedy) Format("img", result.disks, Disk::DiskImageHolder<Storage::Disk::MacintoshIMG>, TargetPlatform::Macintosh) // IMG (DiskCopy 4.2) Format("image", result.disks, Disk::DiskImageHolder<Storage::Disk::MacintoshIMG>, TargetPlatform::Macintosh) // IMG (DiskCopy 4.2) Format("msa", result.disks, Disk::DiskImageHolder<Storage::Disk::MSA>, TargetPlatform::AtariST) // MSA Format("nib", result.disks, Disk::DiskImageHolder<Storage::Disk::NIB>, TargetPlatform::DiskII) // NIB Format("o", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // O Format("p", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // P Format("po", result.disks, Disk::DiskImageHolder<Storage::Disk::AppleDSK>, TargetPlatform::DiskII) // PO (original Apple II kind) // PO (Apple IIgs kind) if(extension == "po") { TryInsert(result.disks, Disk::DiskImageHolder<Storage::Disk::MacintoshIMG>, TargetPlatform::AppleIIgs, file_name, Storage::Disk::MacintoshIMG::FixedType::GCR) } Format("p81", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // P81 // PRG if(extension == "prg") { // try instantiating as a ROM; failing that accept as a tape try { Insert(result.cartridges, Cartridge::PRG, TargetPlatform::Commodore, file_name) } catch(...) { try { Insert(result.tapes, Tape::PRG, TargetPlatform::Commodore, file_name) } catch(...) {} } } Format( "rom", result.cartridges, Cartridge::BinaryDump, TargetPlatform::AcornElectron | TargetPlatform::Coleco | TargetPlatform::MSX) // ROM Format("sg", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Sega) // SG Format("sms", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Sega) // SMS Format("ssd", result.disks, Disk::DiskImageHolder<Storage::Disk::SSD>, TargetPlatform::Acorn) // SSD Format("st", result.disks, Disk::DiskImageHolder<Storage::Disk::ST>, TargetPlatform::AtariST) // ST Format("stx", result.disks, Disk::DiskImageHolder<Storage::Disk::STX>, TargetPlatform::AtariST) // STX Format("tap", result.tapes, Tape::CommodoreTAP, TargetPlatform::Commodore) // TAP (Commodore) Format("tap", result.tapes, Tape::OricTAP, TargetPlatform::Oric) // TAP (Oric) Format("tap", result.tapes, Tape::ZXSpectrumTAP, TargetPlatform::ZXSpectrum) // TAP (ZX Spectrum) Format("tsx", result.tapes, Tape::TZX, TargetPlatform::MSX) // TSX Format("tzx", result.tapes, Tape::TZX, TargetPlatform::ZX8081 | TargetPlatform::ZXSpectrum) // TZX Format("uef", result.tapes, Tape::UEF, TargetPlatform::Acorn) // UEF (tape) Format("woz", result.disks, Disk::DiskImageHolder<Storage::Disk::WOZ>, TargetPlatform::DiskII) // WOZ #undef Format #undef Insert #undef TryInsert #undef InsertInstance return result; } Media Analyser::Static::GetMedia(const std::string &file_name) { TargetPlatform::IntType throwaway; return GetMediaAndPlatforms(file_name, throwaway); } TargetList Analyser::Static::GetTargets(const std::string &file_name) { TargetList targets; // Collect all disks, tapes ROMs, etc as can be extrapolated from this file, forming the // union of all platforms this file might be a target for. TargetPlatform::IntType potential_platforms = 0; Media media = GetMediaAndPlatforms(file_name, potential_platforms); // Hand off to platform-specific determination of whether these things are actually compatible and, // if so, how to load them. #define Append(x) if(potential_platforms & TargetPlatform::x) {\ auto new_targets = x::GetTargets(media, file_name, potential_platforms);\ std::move(new_targets.begin(), new_targets.end(), std::back_inserter(targets));\ } Append(Acorn); Append(AmstradCPC); Append(AppleII); Append(AppleIIgs); Append(Atari2600); Append(AtariST); Append(Coleco); Append(Commodore); Append(DiskII); Append(Macintosh); Append(MSX); Append(Oric); Append(Sega); Append(ZX8081); Append(ZXSpectrum); #undef Append // Reset any tapes to their initial position. for(const auto &target : targets) { for(auto &tape : target->media.tapes) { tape->reset(); } } // Sort by initial confidence. Use a stable sort in case any of the machine-specific analysers // picked their insertion order carefully. std::stable_sort(targets.begin(), targets.end(), [] (const std::unique_ptr<Target> &a, const std::unique_ptr<Target> &b) { return a->confidence > b->confidence; }); return targets; } <commit_msg>Maps HFE files to the Spectrum.<commit_after>// // StaticAnalyser.cpp // Clock Signal // // Created by Thomas Harte on 23/08/2016. // Copyright 2016 Thomas Harte. All rights reserved. // #include "StaticAnalyser.hpp" #include <algorithm> #include <cstdlib> #include <cstring> #include <iterator> // Analysers #include "Acorn/StaticAnalyser.hpp" #include "AmstradCPC/StaticAnalyser.hpp" #include "AppleII/StaticAnalyser.hpp" #include "AppleIIgs/StaticAnalyser.hpp" #include "Atari2600/StaticAnalyser.hpp" #include "AtariST/StaticAnalyser.hpp" #include "Coleco/StaticAnalyser.hpp" #include "Commodore/StaticAnalyser.hpp" #include "DiskII/StaticAnalyser.hpp" #include "Macintosh/StaticAnalyser.hpp" #include "MSX/StaticAnalyser.hpp" #include "Oric/StaticAnalyser.hpp" #include "Sega/StaticAnalyser.hpp" #include "ZX8081/StaticAnalyser.hpp" #include "ZXSpectrum/StaticAnalyser.hpp" // Cartridges #include "../../Storage/Cartridge/Formats/BinaryDump.hpp" #include "../../Storage/Cartridge/Formats/PRG.hpp" // Disks #include "../../Storage/Disk/DiskImage/Formats/2MG.hpp" #include "../../Storage/Disk/DiskImage/Formats/AcornADF.hpp" #include "../../Storage/Disk/DiskImage/Formats/AppleDSK.hpp" #include "../../Storage/Disk/DiskImage/Formats/CPCDSK.hpp" #include "../../Storage/Disk/DiskImage/Formats/D64.hpp" #include "../../Storage/Disk/DiskImage/Formats/MacintoshIMG.hpp" #include "../../Storage/Disk/DiskImage/Formats/G64.hpp" #include "../../Storage/Disk/DiskImage/Formats/DMK.hpp" #include "../../Storage/Disk/DiskImage/Formats/HFE.hpp" #include "../../Storage/Disk/DiskImage/Formats/MSA.hpp" #include "../../Storage/Disk/DiskImage/Formats/MSXDSK.hpp" #include "../../Storage/Disk/DiskImage/Formats/NIB.hpp" #include "../../Storage/Disk/DiskImage/Formats/OricMFMDSK.hpp" #include "../../Storage/Disk/DiskImage/Formats/SSD.hpp" #include "../../Storage/Disk/DiskImage/Formats/ST.hpp" #include "../../Storage/Disk/DiskImage/Formats/STX.hpp" #include "../../Storage/Disk/DiskImage/Formats/WOZ.hpp" // Mass Storage Devices (i.e. usually, hard disks) #include "../../Storage/MassStorage/Formats/DAT.hpp" #include "../../Storage/MassStorage/Formats/HFV.hpp" // Tapes #include "../../Storage/Tape/Formats/CAS.hpp" #include "../../Storage/Tape/Formats/CommodoreTAP.hpp" #include "../../Storage/Tape/Formats/CSW.hpp" #include "../../Storage/Tape/Formats/OricTAP.hpp" #include "../../Storage/Tape/Formats/TapePRG.hpp" #include "../../Storage/Tape/Formats/TapeUEF.hpp" #include "../../Storage/Tape/Formats/TZX.hpp" #include "../../Storage/Tape/Formats/ZX80O81P.hpp" #include "../../Storage/Tape/Formats/ZXSpectrumTAP.hpp" // Target Platform Types #include "../../Storage/TargetPlatforms.hpp" using namespace Analyser::Static; static Media GetMediaAndPlatforms(const std::string &file_name, TargetPlatform::IntType &potential_platforms) { Media result; // Get the extension, if any; it will be assumed that extensions are reliable, so an extension is a broad-phase // test as to file format. std::string::size_type final_dot = file_name.find_last_of("."); if(final_dot == std::string::npos) return result; std::string extension = file_name.substr(final_dot + 1); std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); #define InsertInstance(list, instance, platforms) \ list.emplace_back(instance);\ potential_platforms |= platforms;\ TargetPlatform::TypeDistinguisher *distinguisher = dynamic_cast<TargetPlatform::TypeDistinguisher *>(list.back().get());\ if(distinguisher) potential_platforms &= distinguisher->target_platform_type(); \ #define Insert(list, class, platforms, ...) \ InsertInstance(list, new Storage::class(__VA_ARGS__), platforms); #define TryInsert(list, class, platforms, ...) \ try {\ Insert(list, class, platforms, __VA_ARGS__) \ } catch(...) {} #define Format(ext, list, class, platforms) \ if(extension == ext) { \ TryInsert(list, class, platforms, file_name) \ } // 2MG if(extension == "2mg") { // 2MG uses a factory method; defer to it. try { InsertInstance(result.disks, Storage::Disk::Disk2MG::open(file_name), TargetPlatform::DiskII) } catch(...) {} } Format("80", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // 80 Format("81", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // 81 Format("a26", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Atari2600) // A26 Format("adf", result.disks, Disk::DiskImageHolder<Storage::Disk::AcornADF>, TargetPlatform::Acorn) // ADF Format("adl", result.disks, Disk::DiskImageHolder<Storage::Disk::AcornADF>, TargetPlatform::Acorn) // ADL Format("bin", result.cartridges, Cartridge::BinaryDump, TargetPlatform::AllCartridge) // BIN (cartridge dump) Format("cas", result.tapes, Tape::CAS, TargetPlatform::MSX) // CAS Format("cdt", result.tapes, Tape::TZX, TargetPlatform::AmstradCPC) // CDT Format("col", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Coleco) // COL Format("csw", result.tapes, Tape::CSW, TargetPlatform::AllTape) // CSW Format("d64", result.disks, Disk::DiskImageHolder<Storage::Disk::D64>, TargetPlatform::Commodore) // D64 Format("dat", result.mass_storage_devices, MassStorage::DAT, TargetPlatform::Acorn) // DAT Format("dmk", result.disks, Disk::DiskImageHolder<Storage::Disk::DMK>, TargetPlatform::MSX) // DMK Format("do", result.disks, Disk::DiskImageHolder<Storage::Disk::AppleDSK>, TargetPlatform::DiskII) // DO Format("dsd", result.disks, Disk::DiskImageHolder<Storage::Disk::SSD>, TargetPlatform::Acorn) // DSD Format( "dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::CPCDSK>, TargetPlatform::AmstradCPC | TargetPlatform::Oric | TargetPlatform::ZXSpectrum) // DSK (Amstrad CPC, etc) Format("dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::AppleDSK>, TargetPlatform::DiskII) // DSK (Apple II) Format("dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::MacintoshIMG>, TargetPlatform::Macintosh) // DSK (Macintosh, floppy disk) Format("dsk", result.mass_storage_devices, MassStorage::HFV, TargetPlatform::Macintosh) // DSK (Macintosh, hard disk) Format("dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::MSXDSK>, TargetPlatform::MSX) // DSK (MSX) Format("dsk", result.disks, Disk::DiskImageHolder<Storage::Disk::OricMFMDSK>, TargetPlatform::Oric) // DSK (Oric) Format("g64", result.disks, Disk::DiskImageHolder<Storage::Disk::G64>, TargetPlatform::Commodore) // G64 Format( "hfe", result.disks, Disk::DiskImageHolder<Storage::Disk::HFE>, TargetPlatform::Acorn | TargetPlatform::AmstradCPC | TargetPlatform::Commodore | TargetPlatform::Oric | TargetPlatform::ZXSpectrum) // HFE (TODO: switch to AllDisk once the MSX stops being so greedy) Format("img", result.disks, Disk::DiskImageHolder<Storage::Disk::MacintoshIMG>, TargetPlatform::Macintosh) // IMG (DiskCopy 4.2) Format("image", result.disks, Disk::DiskImageHolder<Storage::Disk::MacintoshIMG>, TargetPlatform::Macintosh) // IMG (DiskCopy 4.2) Format("msa", result.disks, Disk::DiskImageHolder<Storage::Disk::MSA>, TargetPlatform::AtariST) // MSA Format("nib", result.disks, Disk::DiskImageHolder<Storage::Disk::NIB>, TargetPlatform::DiskII) // NIB Format("o", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // O Format("p", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // P Format("po", result.disks, Disk::DiskImageHolder<Storage::Disk::AppleDSK>, TargetPlatform::DiskII) // PO (original Apple II kind) // PO (Apple IIgs kind) if(extension == "po") { TryInsert(result.disks, Disk::DiskImageHolder<Storage::Disk::MacintoshIMG>, TargetPlatform::AppleIIgs, file_name, Storage::Disk::MacintoshIMG::FixedType::GCR) } Format("p81", result.tapes, Tape::ZX80O81P, TargetPlatform::ZX8081) // P81 // PRG if(extension == "prg") { // try instantiating as a ROM; failing that accept as a tape try { Insert(result.cartridges, Cartridge::PRG, TargetPlatform::Commodore, file_name) } catch(...) { try { Insert(result.tapes, Tape::PRG, TargetPlatform::Commodore, file_name) } catch(...) {} } } Format( "rom", result.cartridges, Cartridge::BinaryDump, TargetPlatform::AcornElectron | TargetPlatform::Coleco | TargetPlatform::MSX) // ROM Format("sg", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Sega) // SG Format("sms", result.cartridges, Cartridge::BinaryDump, TargetPlatform::Sega) // SMS Format("ssd", result.disks, Disk::DiskImageHolder<Storage::Disk::SSD>, TargetPlatform::Acorn) // SSD Format("st", result.disks, Disk::DiskImageHolder<Storage::Disk::ST>, TargetPlatform::AtariST) // ST Format("stx", result.disks, Disk::DiskImageHolder<Storage::Disk::STX>, TargetPlatform::AtariST) // STX Format("tap", result.tapes, Tape::CommodoreTAP, TargetPlatform::Commodore) // TAP (Commodore) Format("tap", result.tapes, Tape::OricTAP, TargetPlatform::Oric) // TAP (Oric) Format("tap", result.tapes, Tape::ZXSpectrumTAP, TargetPlatform::ZXSpectrum) // TAP (ZX Spectrum) Format("tsx", result.tapes, Tape::TZX, TargetPlatform::MSX) // TSX Format("tzx", result.tapes, Tape::TZX, TargetPlatform::ZX8081 | TargetPlatform::ZXSpectrum) // TZX Format("uef", result.tapes, Tape::UEF, TargetPlatform::Acorn) // UEF (tape) Format("woz", result.disks, Disk::DiskImageHolder<Storage::Disk::WOZ>, TargetPlatform::DiskII) // WOZ #undef Format #undef Insert #undef TryInsert #undef InsertInstance return result; } Media Analyser::Static::GetMedia(const std::string &file_name) { TargetPlatform::IntType throwaway; return GetMediaAndPlatforms(file_name, throwaway); } TargetList Analyser::Static::GetTargets(const std::string &file_name) { TargetList targets; // Collect all disks, tapes ROMs, etc as can be extrapolated from this file, forming the // union of all platforms this file might be a target for. TargetPlatform::IntType potential_platforms = 0; Media media = GetMediaAndPlatforms(file_name, potential_platforms); // Hand off to platform-specific determination of whether these things are actually compatible and, // if so, how to load them. #define Append(x) if(potential_platforms & TargetPlatform::x) {\ auto new_targets = x::GetTargets(media, file_name, potential_platforms);\ std::move(new_targets.begin(), new_targets.end(), std::back_inserter(targets));\ } Append(Acorn); Append(AmstradCPC); Append(AppleII); Append(AppleIIgs); Append(Atari2600); Append(AtariST); Append(Coleco); Append(Commodore); Append(DiskII); Append(Macintosh); Append(MSX); Append(Oric); Append(Sega); Append(ZX8081); Append(ZXSpectrum); #undef Append // Reset any tapes to their initial position. for(const auto &target : targets) { for(auto &tape : target->media.tapes) { tape->reset(); } } // Sort by initial confidence. Use a stable sort in case any of the machine-specific analysers // picked their insertion order carefully. std::stable_sort(targets.begin(), targets.end(), [] (const std::unique_ptr<Target> &a, const std::unique_ptr<Target> &b) { return a->confidence > b->confidence; }); return targets; } <|endoftext|>
<commit_before><commit_msg>catch pathnotfound, which is basically the same as file not found<commit_after><|endoftext|>
<commit_before>/** * @file Euler.hpp * * All rotations and axis systems follow the right-hand rule * * An instance of this class defines a rotation from coordinate frame 1 to coordinate frame 2. * It follows the convention of an intrinsic tait-bryan 3-2-1 sequence. * In order to go from frame 1 to frame 2 we apply the following rotations consecutively. * 1) We rotate about our initial Z axis by an angle of _psi. * 2) We rotate about the newly created Y' axis by an angle of _theta. * 3) We rotate about the newly created X'' axis by an angle of _phi. * * @author James Goppert <[email protected]> */ #pragma once #include "math.hpp" #ifndef M_PI #define M_PI (3.14159265358979323846f) #endif namespace matrix { template <typename Type> class Dcm; template <typename Type> class Quaternion; /** * Euler angles class * * This class describes the transformation from the body fixed frame * to the inertial frame via 3-2-1 tait brian euler angles. */ template<typename Type> class Euler : public Vector<Type, 3> { public: virtual ~Euler() {}; /** * Standard constructor */ Euler() : Vector<Type, 3>() { } /** * Copy constructor * * @param other vector to copy */ Euler(const Vector<Type, 3> & other) : Vector<Type, 3>(other) { } /** * Constructor from Matrix31 * * @param other Matrix31 to copy */ Euler(const Matrix<Type, 3, 1> & other) : Vector<Type, 3>(other) { } /** * Constructor from euler angles * * Instance is initialized from angle tripplet (3,2,1) * representing transformation from body frame to inertial frame. * * @param phi_ rotation angle about X axis * @param theta_ rotation angle about Y axis * @param psi_ rotation angle about Z axis */ Euler(Type phi_, Type theta_, Type psi_) : Vector<Type, 3>() { set_from_euler(phi_, theta_, psi_); } /** * Constructor from DCM matrix * * Instance is set from Dcm representing * transformation from frame 2 to frame 1. * This instance will hold the angles defining the rotation * from frame 1 to frame 2. * * @param dcm Direction cosine matrix */ Euler(const Dcm<Type> & dcm) : Vector<Type, 3>() { set_from_dcm(dcm); } /** * Constructor from quaternion instance. * * Instance is set from a quaternion representing * transformation from frame 2 to frame 1. * This instance will hold the angles defining the rotation * from frame 1 to frame 2. * * @param q quaternion */ Euler(const Quaternion<Type> & q) : Vector<Type, 3>() { set_from_quaternion(q); } /** * Set from euler angles * * Instance is set from angle tripplet (3,2,1) representing * rotation from frame 1 to frame 2. * * @param phi_ roll * @param theta_ pitch * @param psi_ yaw */ void set_from_euler(Type phi_, Type theta_, Type psi_) { phi() = phi_; theta() = theta_; psi() = psi_; } /** * Set from dcm * * Instance is set from dcm representing transformation * from frame 2 to frame 1. * * @param dcm Direction cosine matrix instance to convert from. */ void set_from_dcm(const Dcm<Type> & dcm) { Type phi_val = Type(atan2(dcm(2,1), dcm(2,2))); Type theta_val = Type(asin(-dcm(2,0))); Type psi_val = Type(atan2(dcm(1,0), dcm(0,0))); Type pi = Type(M_PI); if (fabs(theta_val - pi/2) < 1.0e-3) { phi_val = Type(0.0); psi_val = Type(atan2(dcm(1,2), dcm(0,2))); } else if (Type(fabs(theta_val + pi/2)) < Type(1.0e-3)) { phi_val = Type(0.0); psi_val = Type(atan2(-dcm(1,2), -dcm(0,2))); } phi() = phi_val; theta() = theta_val; psi() = psi_val; } /** * Set from dcm * * Instance is set from quaternion representing * transformation from body frame to inertial frame. * * @param q quaternion to set angles to */ void set_from_quaternion(const Quaternion<Type> & q) { *this = Euler(Dcm<Type>(q)); } inline Type phi() const { return (*this)(0); } inline Type theta() const { return (*this)(1); } inline Type psi() const { return (*this)(2); } inline Type & phi() { return (*this)(0); } inline Type & theta() { return (*this)(1); } inline Type & psi() { return (*this)(2); } }; typedef Euler<float> Eulerf; } // namespace matrix /* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */ <commit_msg>removing body and intertial frame expressions and establishing consistency<commit_after>/** * @file Euler.hpp * * All rotations and axis systems follow the right-hand rule * * An instance of this class defines a rotation from coordinate frame 1 to coordinate frame 2. * It follows the convention of a 3-2-1 intrinsic Tait-Bryan rotation sequence. * In order to go from frame 1 to frame 2 we apply the following rotations consecutively. * 1) We rotate about our initial Z axis by an angle of _psi. * 2) We rotate about the newly created Y' axis by an angle of _theta. * 3) We rotate about the newly created X'' axis by an angle of _phi. * * @author James Goppert <[email protected]> */ #pragma once #include "math.hpp" #ifndef M_PI #define M_PI (3.14159265358979323846f) #endif namespace matrix { template <typename Type> class Dcm; template <typename Type> class Quaternion; /** * Euler angles class * * This class describes the rotation from frame 1 * to frame 2 via 3-2-1 intrinsic Tait-Bryan rotation sequence. */ template<typename Type> class Euler : public Vector<Type, 3> { public: virtual ~Euler() {}; /** * Standard constructor */ Euler() : Vector<Type, 3>() { } /** * Copy constructor * * @param other vector to copy */ Euler(const Vector<Type, 3> & other) : Vector<Type, 3>(other) { } /** * Constructor from Matrix31 * * @param other Matrix31 to copy */ Euler(const Matrix<Type, 3, 1> & other) : Vector<Type, 3>(other) { } /** * Constructor from euler angles * * Instance is initialized from an 3-2-1 intrinsic Tait-Bryan * rotation sequence representing transformation from frame 1 * to frame 2. * * @param phi_ rotation angle about X axis * @param theta_ rotation angle about Y axis * @param psi_ rotation angle about Z axis */ Euler(Type phi_, Type theta_, Type psi_) : Vector<Type, 3>() { set_from_euler(phi_, theta_, psi_); } /** * Constructor from DCM matrix * * Instance is set from Dcm representing transformation from * frame 2 to frame 1. * This instance will hold the angles defining the 3-2-1 intrinsic * Tait-Bryan rotation sequence from frame 1 to frame 2. * * @param dcm Direction cosine matrix */ Euler(const Dcm<Type> & dcm) : Vector<Type, 3>() { set_from_dcm(dcm); } /** * Constructor from quaternion instance. * * Instance is set from a quaternion representing transformation * from frame 2 to frame 1. * This instance will hold the angles defining the 3-2-1 intrinsic * Tait-Bryan rotation sequence from frame 1 to frame 2. * * @param q quaternion */ Euler(const Quaternion<Type> & q) : Vector<Type, 3>() { set_from_quaternion(q); } /** * Set from euler angles * * Instance is set from an 3-2-1 intrinsic Tait-Bryan rotation * sequence representing transformation from frame 1 to frame 2. * * @param phi_ rotation angle about X axis * @param theta_ rotation angle about Y axis * @param psi_ rotation angle about Z axis */ void set_from_euler(Type phi_, Type theta_, Type psi_) { phi() = phi_; theta() = theta_; psi() = psi_; } /** * Set from DCM matrix * * Instance is set from Dcm representing transformation from * frame 2 to frame 1. * This instance will hold the angles defining the 3-2-1 intrinsic * Tait-Bryan rotation sequence from frame 1 to frame 2. * * @param dcm Direction cosine matrix */ void set_from_dcm(const Dcm<Type> & dcm) { Type phi_val = Type(atan2(dcm(2,1), dcm(2,2))); Type theta_val = Type(asin(-dcm(2,0))); Type psi_val = Type(atan2(dcm(1,0), dcm(0,0))); Type pi = Type(M_PI); if (fabs(theta_val - pi/2) < 1.0e-3) { phi_val = Type(0.0); psi_val = Type(atan2(dcm(1,2), dcm(0,2))); } else if (Type(fabs(theta_val + pi/2)) < Type(1.0e-3)) { phi_val = Type(0.0); psi_val = Type(atan2(-dcm(1,2), -dcm(0,2))); } phi() = phi_val; theta() = theta_val; psi() = psi_val; } /** * Set from quaternion instance. * * Instance is set from a quaternion representing transformation * from frame 2 to frame 1. * This instance will hold the angles defining the 3-2-1 intrinsic * Tait-Bryan rotation sequence from frame 1 to frame 2. * * @param q quaternion */ void set_from_quaternion(const Quaternion<Type> & q) { *this = Euler(Dcm<Type>(q)); } inline Type phi() const { return (*this)(0); } inline Type theta() const { return (*this)(1); } inline Type psi() const { return (*this)(2); } inline Type & phi() { return (*this)(0); } inline Type & theta() { return (*this)(1); } inline Type & psi() { return (*this)(2); } }; typedef Euler<float> Eulerf; } // namespace matrix /* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */ <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "AssetEvents.h" #include "AssetManager.h" #include "AssetModule.h" #include "RexAsset.h" #include "RexTypes.h" #include "LocalAssetProvider.h" #include "AssetServiceInterface.h" #include "Framework.h" #include "EventManager.h" #include "ServiceManager.h" #include "ConfigurationManager.h" #include "LocalAssetStorage.h" #include "IAssetUploadTransfer.h" #include <QByteArray> #include <QFile> #include <QFileSystemWatcher> namespace Asset { LocalAssetProvider::LocalAssetProvider(Foundation::Framework* framework) : framework_(framework) { EventManagerPtr event_manager = framework_->GetEventManager(); event_category_ = event_manager->QueryEventCategory("Asset"); } LocalAssetProvider::~LocalAssetProvider() { } const std::string& LocalAssetProvider::Name() { static const std::string name("Local"); return name; } bool LocalAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type) { return (asset_id.find("file://") == 0); } bool LocalAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag) { if (!IsValidId(asset_id, asset_type)) return false; ServiceManagerPtr service_manager = framework_->GetServiceManager(); boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = service_manager->GetService<Foundation::AssetServiceInterface>(Service::ST_Asset).lock(); if (!asset_service) return false; AssetModule::LogDebug("New local asset request: " + asset_id); // Strip file: trims asset provider id (f.ex. 'file://') and potential mesh name inside the file (everything after last slash) std::string filename = asset_id.substr(7); size_t lastSlash = filename.find_last_of('/'); if (lastSlash != std::string::npos) filename = filename.substr(0, lastSlash); std::string assetpath = GetPathForAsset(filename); // Look up all known local file asset storages for this asset. if (assetpath.empty()) { AssetModule::LogInfo("Failed to load local asset " + filename); return true; } boost::filesystem::path file_path(assetpath + "/" + filename); std::ifstream filestr(file_path.native_directory_string().c_str(), std::ios::in | std::ios::binary); if (filestr.good()) { filestr.seekg(0, std::ios::end); uint length = filestr.tellg(); filestr.seekg(0, std::ios::beg); if (length > 0) { RexAsset* new_asset = new RexAsset(asset_id, asset_type); Foundation::AssetPtr asset_ptr(new_asset); RexAsset::AssetDataVector& data = new_asset->GetDataInternal(); data.resize(length); filestr.read((char *)&data[0], length); filestr.close(); // Store to memory cache only asset_service->StoreAsset(asset_ptr, false); // Send asset_ready event as delayed Events::AssetReady* event_data = new Events::AssetReady(asset_ptr->GetId(), asset_ptr->GetType(), asset_ptr, tag); framework_->GetEventManager()->SendDelayedEvent(event_category_, Events::ASSET_READY, EventDataPtr(event_data)); return true; } else filestr.close(); } AssetModule::LogInfo("Failed to load local asset " + filename); return true; } std::string LocalAssetProvider::GetPathForAsset(const std::string& assetname) { // Check first all subdirs without recursion, because recursion is potentially slow for(size_t i = 0; i < storages.size(); ++i) { std::string path = storages[i]->GetFullPathForAsset(assetname, false); if (path != "") return path; } for(size_t i = 0; i < storages.size(); ++i) { std::string path = storages[i]->GetFullPathForAsset(assetname, true); if (path != "") return path; } return ""; } bool LocalAssetProvider::InProgress(const std::string& asset_id) { return false; } Foundation::AssetPtr LocalAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received) { // Not supported return Foundation::AssetPtr(); } bool LocalAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous) { // Not supported return false; } void LocalAssetProvider::Update(f64 frametime) { CompletePendingFileUploads(); } void LocalAssetProvider::AddStorageDirectory(const std::string &directory, const std::string &storageName, bool recursive) { ///\todo Check first if the given directory exists as a storage, and don't add it as a duplicate if so. LocalAssetStoragePtr storage = LocalAssetStoragePtr(new LocalAssetStorage()); storage->directory = directory; storage->name = storageName; storage->recursive = recursive; storage->provider = shared_from_this(); storage->SetupWatcher(); // Start listening on file change notifications. // connect(storage->changeWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(FileChanged(QString))); connect(storage->changeWatcher, SIGNAL(fileChanged(QString)), this, SLOT(FileChanged(QString))); storages.push_back(storage); } std::vector<AssetStoragePtr> LocalAssetProvider::GetStorages() const { std::vector<AssetStoragePtr> stores; for(size_t i = 0; i < storages.size(); ++i) stores.push_back(storages[i]); return stores; } IAssetUploadTransfer *LocalAssetProvider::UploadAssetFromFile(const char *filename, AssetStoragePtr destination, const char *assetName) { LocalAssetStorage *storage = dynamic_cast<LocalAssetStorage*>(destination.get()); if (!storage) { AssetModule::LogError("LocalAssetProvider::UploadAssetFromFile: Invalid destination asset storage type! Was not of type LocalAssetStorage!"); return 0; } AssetUploadTransferPtr transfer = AssetUploadTransferPtr(new IAssetUploadTransfer()); transfer->sourceFilename = filename; transfer->destinationName = assetName; transfer->destinationStorage = destination; pendingUploads.push_back(transfer); return transfer.get(); } IAssetUploadTransfer *LocalAssetProvider::UploadAssetFromFileInMemory(const u8 *data, size_t numBytes, AssetStoragePtr destination, const char *assetName) { assert(data); if (!data) { AssetModule::LogError("LocalAssetProvider::UploadAssetFromFileInMemory: Null source data pointer passed to function!"); return 0; } LocalAssetStorage *storage = dynamic_cast<LocalAssetStorage*>(destination.get()); if (!storage) { AssetModule::LogError("LocalAssetProvider::UploadAssetFromFileInMemory: Invalid destination asset storage type! Was not of type LocalAssetStorage!"); return 0; } AssetUploadTransferPtr transfer = AssetUploadTransferPtr(new IAssetUploadTransfer()); transfer->sourceFilename = ""; transfer->destinationName = assetName; transfer->destinationStorage = destination; transfer->assetData.insert(transfer->assetData.end(), data, data + numBytes); pendingUploads.push_back(transfer); return transfer.get(); } namespace { bool CopyAsset(const char *sourceFile, const char *destFile) { assert(sourceFile); assert(destFile); QFile asset_in(sourceFile); if (!asset_in.open(QFile::ReadOnly)) { AssetModule::LogError("Could not open input asset file " + std::string(sourceFile)); return false; } QByteArray bytes = asset_in.readAll(); asset_in.close(); QFile asset_out(destFile); if (!asset_out.open(QFile::WriteOnly)) { AssetModule::LogError("Could not open output asset file " + std::string(destFile)); return false; } asset_out.write(bytes); asset_out.close(); return true; } bool SaveAssetFromMemoryToFile(const u8 *data, size_t numBytes, const char *destFile) { assert(data); assert(destFile); QFile asset_out(destFile); if (!asset_out.open(QFile::WriteOnly)) { AssetModule::LogError("Could not open output asset file " + std::string(destFile)); return false; } asset_out.write((const char *)data, numBytes); asset_out.close(); return true; } } // ~unnamed namespace void LocalAssetProvider::CompletePendingFileUploads() { while(pendingUploads.size() > 0) { AssetUploadTransferPtr transfer = pendingUploads.back(); pendingUploads.pop_back(); LocalAssetStorage *storage = dynamic_cast<LocalAssetStorage *>(transfer->destinationStorage.lock().get()); if (!storage) { AssetModule::LogError("Invalid IAssetStorage specified for file upload in LocalAssetProvider!"); transfer->EmitTransferFailed(); continue; } if (transfer->sourceFilename.length() == 0 && transfer->assetData.size() == 0) { AssetModule::LogError("No source data present when trying to upload asset to LocalAssetProvider!"); continue; } std::string fromFile = transfer->sourceFilename.toStdString(); std::string toFile = storage->directory + transfer->destinationName.toStdString(); bool success; if (fromFile.length() == 0) success = SaveAssetFromMemoryToFile(&transfer->assetData[0], transfer->assetData.size(), toFile.c_str()); else success = CopyAsset(fromFile.c_str(), toFile.c_str()); if (!success) { AssetModule::LogError("Asset upload failed in LocalAssetProvider: CopyAsset from \"" + fromFile + "\" to \"" + toFile + "\" failed!"); transfer->EmitTransferFailed(); } else transfer->EmitTransferCompleted(); } } void LocalAssetProvider::FileChanged(const QString &path) { AssetModule::LogInfo(("File " + path + " changed.").toStdString()); } } // ~Asset <commit_msg>Fixed a missing trailing slash from a directory specifier.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "AssetEvents.h" #include "AssetManager.h" #include "AssetModule.h" #include "RexAsset.h" #include "RexTypes.h" #include "LocalAssetProvider.h" #include "AssetServiceInterface.h" #include "Framework.h" #include "EventManager.h" #include "ServiceManager.h" #include "ConfigurationManager.h" #include "LocalAssetStorage.h" #include "IAssetUploadTransfer.h" #include <QByteArray> #include <QFile> #include <QFileSystemWatcher> namespace Asset { LocalAssetProvider::LocalAssetProvider(Foundation::Framework* framework) : framework_(framework) { EventManagerPtr event_manager = framework_->GetEventManager(); event_category_ = event_manager->QueryEventCategory("Asset"); } LocalAssetProvider::~LocalAssetProvider() { } const std::string& LocalAssetProvider::Name() { static const std::string name("Local"); return name; } bool LocalAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type) { return (asset_id.find("file://") == 0); } bool LocalAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag) { if (!IsValidId(asset_id, asset_type)) return false; ServiceManagerPtr service_manager = framework_->GetServiceManager(); boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = service_manager->GetService<Foundation::AssetServiceInterface>(Service::ST_Asset).lock(); if (!asset_service) return false; AssetModule::LogDebug("New local asset request: " + asset_id); // Strip file: trims asset provider id (f.ex. 'file://') and potential mesh name inside the file (everything after last slash) std::string filename = asset_id.substr(7); size_t lastSlash = filename.find_last_of('/'); if (lastSlash != std::string::npos) filename = filename.substr(0, lastSlash); std::string assetpath = GetPathForAsset(filename); // Look up all known local file asset storages for this asset. if (assetpath.empty()) { AssetModule::LogInfo("Failed to load local asset " + filename); return true; } boost::filesystem::path file_path(assetpath + "/" + filename); std::ifstream filestr(file_path.native_directory_string().c_str(), std::ios::in | std::ios::binary); if (filestr.good()) { filestr.seekg(0, std::ios::end); uint length = filestr.tellg(); filestr.seekg(0, std::ios::beg); if (length > 0) { RexAsset* new_asset = new RexAsset(asset_id, asset_type); Foundation::AssetPtr asset_ptr(new_asset); RexAsset::AssetDataVector& data = new_asset->GetDataInternal(); data.resize(length); filestr.read((char *)&data[0], length); filestr.close(); // Store to memory cache only asset_service->StoreAsset(asset_ptr, false); // Send asset_ready event as delayed Events::AssetReady* event_data = new Events::AssetReady(asset_ptr->GetId(), asset_ptr->GetType(), asset_ptr, tag); framework_->GetEventManager()->SendDelayedEvent(event_category_, Events::ASSET_READY, EventDataPtr(event_data)); return true; } else filestr.close(); } AssetModule::LogInfo("Failed to load local asset " + filename); return true; } std::string LocalAssetProvider::GetPathForAsset(const std::string& assetname) { // Check first all subdirs without recursion, because recursion is potentially slow for(size_t i = 0; i < storages.size(); ++i) { std::string path = storages[i]->GetFullPathForAsset(assetname, false); if (path != "") return path; } for(size_t i = 0; i < storages.size(); ++i) { std::string path = storages[i]->GetFullPathForAsset(assetname, true); if (path != "") return path; } return ""; } bool LocalAssetProvider::InProgress(const std::string& asset_id) { return false; } Foundation::AssetPtr LocalAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received) { // Not supported return Foundation::AssetPtr(); } bool LocalAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous) { // Not supported return false; } void LocalAssetProvider::Update(f64 frametime) { CompletePendingFileUploads(); } void LocalAssetProvider::AddStorageDirectory(const std::string &directory, const std::string &storageName, bool recursive) { ///\todo Check first if the given directory exists as a storage, and don't add it as a duplicate if so. LocalAssetStoragePtr storage = LocalAssetStoragePtr(new LocalAssetStorage()); storage->directory = directory; storage->name = storageName; storage->recursive = recursive; storage->provider = shared_from_this(); storage->SetupWatcher(); // Start listening on file change notifications. // connect(storage->changeWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(FileChanged(QString))); connect(storage->changeWatcher, SIGNAL(fileChanged(QString)), this, SLOT(FileChanged(QString))); storages.push_back(storage); } std::vector<AssetStoragePtr> LocalAssetProvider::GetStorages() const { std::vector<AssetStoragePtr> stores; for(size_t i = 0; i < storages.size(); ++i) stores.push_back(storages[i]); return stores; } IAssetUploadTransfer *LocalAssetProvider::UploadAssetFromFile(const char *filename, AssetStoragePtr destination, const char *assetName) { LocalAssetStorage *storage = dynamic_cast<LocalAssetStorage*>(destination.get()); if (!storage) { AssetModule::LogError("LocalAssetProvider::UploadAssetFromFile: Invalid destination asset storage type! Was not of type LocalAssetStorage!"); return 0; } AssetUploadTransferPtr transfer = AssetUploadTransferPtr(new IAssetUploadTransfer()); transfer->sourceFilename = filename; transfer->destinationName = assetName; transfer->destinationStorage = destination; pendingUploads.push_back(transfer); return transfer.get(); } IAssetUploadTransfer *LocalAssetProvider::UploadAssetFromFileInMemory(const u8 *data, size_t numBytes, AssetStoragePtr destination, const char *assetName) { assert(data); if (!data) { AssetModule::LogError("LocalAssetProvider::UploadAssetFromFileInMemory: Null source data pointer passed to function!"); return 0; } LocalAssetStorage *storage = dynamic_cast<LocalAssetStorage*>(destination.get()); if (!storage) { AssetModule::LogError("LocalAssetProvider::UploadAssetFromFileInMemory: Invalid destination asset storage type! Was not of type LocalAssetStorage!"); return 0; } AssetUploadTransferPtr transfer = AssetUploadTransferPtr(new IAssetUploadTransfer()); transfer->sourceFilename = ""; transfer->destinationName = assetName; transfer->destinationStorage = destination; transfer->assetData.insert(transfer->assetData.end(), data, data + numBytes); pendingUploads.push_back(transfer); return transfer.get(); } namespace { bool CopyAsset(const char *sourceFile, const char *destFile) { assert(sourceFile); assert(destFile); QFile asset_in(sourceFile); if (!asset_in.open(QFile::ReadOnly)) { AssetModule::LogError("Could not open input asset file " + std::string(sourceFile)); return false; } QByteArray bytes = asset_in.readAll(); asset_in.close(); QFile asset_out(destFile); if (!asset_out.open(QFile::WriteOnly)) { AssetModule::LogError("Could not open output asset file " + std::string(destFile)); return false; } asset_out.write(bytes); asset_out.close(); return true; } bool SaveAssetFromMemoryToFile(const u8 *data, size_t numBytes, const char *destFile) { assert(data); assert(destFile); QFile asset_out(destFile); if (!asset_out.open(QFile::WriteOnly)) { AssetModule::LogError("Could not open output asset file " + std::string(destFile)); return false; } asset_out.write((const char *)data, numBytes); asset_out.close(); return true; } } // ~unnamed namespace /// Adds a trailing slash to the given string representing a directory path if it doesn't have one at the end already. QString GuaranteeTrailingSlash(const QString &source) { QString s = source.trimmed(); if (s[s.length()-1] != '/' && s[s.length()-1] != '\\') s = s + "/"; return s; } void LocalAssetProvider::CompletePendingFileUploads() { while(pendingUploads.size() > 0) { AssetUploadTransferPtr transfer = pendingUploads.back(); pendingUploads.pop_back(); LocalAssetStorage *storage = dynamic_cast<LocalAssetStorage *>(transfer->destinationStorage.lock().get()); if (!storage) { AssetModule::LogError("Invalid IAssetStorage specified for file upload in LocalAssetProvider!"); transfer->EmitTransferFailed(); continue; } if (transfer->sourceFilename.length() == 0 && transfer->assetData.size() == 0) { AssetModule::LogError("No source data present when trying to upload asset to LocalAssetProvider!"); continue; } QString fromFile = transfer->sourceFilename; QString toFile = GuaranteeTrailingSlash(storage->directory.c_str()) + transfer->destinationName; bool success; if (fromFile.length() == 0) success = SaveAssetFromMemoryToFile(&transfer->assetData[0], transfer->assetData.size(), toFile.toStdString().c_str()); else success = CopyAsset(fromFile.toStdString().c_str(), toFile.toStdString().c_str()); if (!success) { AssetModule::LogError(("Asset upload failed in LocalAssetProvider: CopyAsset from \"" + fromFile + "\" to \"" + toFile + "\" failed!").toStdString()); transfer->EmitTransferFailed(); } else transfer->EmitTransferCompleted(); } } void LocalAssetProvider::FileChanged(const QString &path) { AssetModule::LogInfo(("File " + path + " changed.").toStdString()); } } // ~Asset <|endoftext|>
<commit_before>#include "vga/rast/text_10x16.h" #include "vga/arena.h" #include "vga/timing.h" #include "vga/font_10x16.h" #include "vga/rast/unpack_text_10p_attributed.h" namespace vga { namespace rast { static constexpr unsigned glyph_cols = 10, glyph_rows = 16; static constexpr unsigned chars_in_font = 256; Text_10x16::Text_10x16(unsigned width, unsigned height, unsigned top_line) : _cols((width + (glyph_cols - 1)) / glyph_cols), _rows((height + (glyph_rows - 1)) / glyph_rows), _fb(nullptr), _font(nullptr), _top_line(top_line), _x_adj(0) {} void Text_10x16::activate(Timing const &timing) { _font = arena_new_array<unsigned char>(chars_in_font * glyph_rows); _fb = arena_new_array<unsigned>(_cols * _rows); for (unsigned i = 0; i < chars_in_font * glyph_rows; ++i) { _font[i] = font_10x16[i]; } } __attribute__((section(".ramcode"))) Rasterizer::LineShape Text_10x16::rasterize(unsigned line_number, Pixel *raster_target) { line_number -= _top_line; unsigned text_row = line_number / glyph_rows; unsigned row_in_glyph = line_number % glyph_rows; if (text_row >= _rows) return { 0, 0 }; unsigned const *src = _fb + _cols * text_row; unsigned char const *font = _font + row_in_glyph * chars_in_font; unpack_text_10p_attributed_impl(src, font, raster_target + _x_adj, _cols); return { 0, _cols * glyph_cols }; } void Text_10x16::deactivate() { _font = nullptr; _fb = nullptr; _cols = 0; } void Text_10x16::clear_framebuffer(Pixel bg) { unsigned word = bg << 8 | ' '; for (unsigned i = 0; i < _cols * _rows; ++i) { _fb[i] = word; } } void Text_10x16::put_char(unsigned col, unsigned row, Pixel fore, Pixel back, char c) { put_packed(col, row, (fore << 16) | (back << 8) | c); } void Text_10x16::put_packed(unsigned col, unsigned row, unsigned p) { _fb[row * _cols + col] = p; } } // namespace rast } // namespace vga <commit_msg>rast/text_10x16: tiny cleanup.<commit_after>#include "vga/rast/text_10x16.h" #include "vga/arena.h" #include "vga/timing.h" #include "vga/font_10x16.h" #include "vga/rast/unpack_text_10p_attributed.h" namespace vga { namespace rast { static constexpr unsigned glyph_cols = 10, glyph_rows = 16; static constexpr unsigned chars_in_font = 256; Text_10x16::Text_10x16(unsigned width, unsigned height, unsigned top_line) : _cols((width + (glyph_cols - 1)) / glyph_cols), _rows((height + (glyph_rows - 1)) / glyph_rows), _fb(nullptr), _font(nullptr), _top_line(top_line), _x_adj(0) {} void Text_10x16::activate(Timing const &) { _font = arena_new_array<unsigned char>(chars_in_font * glyph_rows); _fb = arena_new_array<unsigned>(_cols * _rows); for (unsigned i = 0; i < chars_in_font * glyph_rows; ++i) { _font[i] = font_10x16[i]; } } __attribute__((section(".ramcode"))) Rasterizer::LineShape Text_10x16::rasterize(unsigned line_number, Pixel *raster_target) { line_number -= _top_line; unsigned text_row = line_number / glyph_rows; unsigned row_in_glyph = line_number % glyph_rows; if (text_row >= _rows) return { 0, 0 }; unsigned const *src = _fb + _cols * text_row; unsigned char const *font = _font + row_in_glyph * chars_in_font; unpack_text_10p_attributed_impl(src, font, raster_target + _x_adj, _cols); return { 0, _cols * glyph_cols }; } void Text_10x16::deactivate() { _font = nullptr; _fb = nullptr; _cols = 0; } void Text_10x16::clear_framebuffer(Pixel bg) { unsigned word = bg << 8 | ' '; for (unsigned i = 0; i < _cols * _rows; ++i) { _fb[i] = word; } } void Text_10x16::put_char(unsigned col, unsigned row, Pixel fore, Pixel back, char c) { put_packed(col, row, (fore << 16) | (back << 8) | c); } void Text_10x16::put_packed(unsigned col, unsigned row, unsigned p) { _fb[row * _cols + col] = p; } } // namespace rast } // namespace vga <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "volumebutton.h" #include "volumepopup.h" #include "audiodevice.h" #include <QtGui/QSlider> #include <QtGui/QMouseEvent> #include <QtCore/QProcess> #include <qtxdg/xdgicon.h> #include "../panel/razorpanel.h" VolumeButton::VolumeButton(RazorPanel *panel, QWidget* parent): QToolButton(parent), m_panel(panel), m_popupHideTimerDuration(1000), m_showOnClick(true), m_muteOnMiddleClick(true) { m_volumePopup = new VolumePopup(); connect(this, SIGNAL(clicked()), this, SLOT(toggleVolumeSlider())); connect(m_panel, SIGNAL(positionChanged()), this, SLOT(hideVolumeSlider())); connect(&m_popupHideTimer, SIGNAL(timeout()), this, SLOT(handlePopupHideTimeout())); connect(m_volumePopup, SIGNAL(mouseEntered()), this, SLOT(popupHideTimerStop())); connect(m_volumePopup, SIGNAL(mouseLeft()), this, SLOT(popupHideTimerStart())); connect(m_volumePopup, SIGNAL(deviceChanged()), this, SLOT(handleDeviceChanged())); connect(m_volumePopup, SIGNAL(launchMixer()), this, SLOT(handleMixerLaunch())); connect(m_volumePopup, SIGNAL(stockIconChanged(QString)), this, SLOT(handleStockIconChanged(QString))); } VolumeButton::~VolumeButton() { if (m_volumePopup) delete m_volumePopup; } void VolumeButton::setShowOnClicked(bool state) { if (m_showOnClick == state) return; m_showOnClick = state; } void VolumeButton::setMuteOnMiddleClick(bool state) { m_muteOnMiddleClick = state; } void VolumeButton::setMixerCommand(const QString &command) { m_mixerCommand = command; } void VolumeButton::enterEvent(QEvent *event) { if (!m_showOnClick) showVolumeSlider(); popupHideTimerStop(); } void VolumeButton::leaveEvent(QEvent *event) { popupHideTimerStart(); } void VolumeButton::wheelEvent(QWheelEvent *event) { m_volumePopup->handleWheelEvent(event); } void VolumeButton::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::MidButton && m_muteOnMiddleClick) { if (m_volumePopup->device()) { m_volumePopup->device()->toggleMute(); return; } } QToolButton::mouseReleaseEvent(event); } void VolumeButton::toggleVolumeSlider() { if (m_volumePopup->isVisible()) { popupHideTimerStop(); handlePopupHideTimeout(); } else { showVolumeSlider(); } } void VolumeButton::showVolumeSlider() { if (m_volumePopup->isVisible()) return; popupHideTimerStop(); m_volumePopup->updateGeometry(); if (isLeftToRight()) { switch (m_panel->position()) { case RazorPanel::PositionTop: m_volumePopup->open(mapToGlobal(geometry().bottomLeft()), Qt::TopLeftCorner); break; case RazorPanel::PositionBottom: m_volumePopup->open(mapToGlobal(geometry().topLeft()), Qt::BottomLeftCorner); break; case RazorPanel::PositionLeft: m_volumePopup->open(mapToGlobal(geometry().topRight()), Qt::TopLeftCorner); break; case RazorPanel::PositionRight: m_volumePopup->open(mapToGlobal(geometry().topLeft()), Qt::TopLeftCorner); break; } } else { switch (m_panel->position()) { case RazorPanel::PositionTop: m_volumePopup->open(mapToGlobal(geometry().bottomRight()), Qt::TopRightCorner); break; case RazorPanel::PositionBottom: m_volumePopup->open(mapToGlobal(geometry().topRight()), Qt::BottomRightCorner); break; case RazorPanel::PositionLeft: m_volumePopup->open(mapToGlobal(geometry().topRight()), Qt::TopLeftCorner); break; case RazorPanel::PositionRight: m_volumePopup->open(mapToGlobal(geometry().topLeft()), Qt::TopLeftCorner); break; } } } void VolumeButton::hideVolumeSlider() { popupHideTimerStart(); } void VolumeButton::handlePopupHideTimeout() { m_volumePopup->hide(); } void VolumeButton::popupHideTimerStart() { m_popupHideTimer.start(m_popupHideTimerDuration); } void VolumeButton::popupHideTimerStop() { m_popupHideTimer.stop(); } void VolumeButton::handleMixerLaunch() { QProcess::startDetached(m_mixerCommand); } void VolumeButton::handleStockIconChanged(const QString &iconName) { setIcon(XdgIcon::fromTheme(iconName)); } <commit_msg>panel volume: show some icon when there is no device<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2012 Razor team * Authors: * Johannes Zellner <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "volumebutton.h" #include "volumepopup.h" #include "audiodevice.h" #include <QtGui/QSlider> #include <QtGui/QMouseEvent> #include <QtCore/QProcess> #include <qtxdg/xdgicon.h> #include "../panel/razorpanel.h" VolumeButton::VolumeButton(RazorPanel *panel, QWidget* parent): QToolButton(parent), m_panel(panel), m_popupHideTimerDuration(1000), m_showOnClick(true), m_muteOnMiddleClick(true) { // initial icon for button. It will be replaced after devices scan. // In the worst case - no soundcard/pulse - is found it remains // in the button but at least the button is not blank ("invisible") handleStockIconChanged("dialog-error"); m_volumePopup = new VolumePopup(); connect(this, SIGNAL(clicked()), this, SLOT(toggleVolumeSlider())); connect(m_panel, SIGNAL(positionChanged()), this, SLOT(hideVolumeSlider())); connect(&m_popupHideTimer, SIGNAL(timeout()), this, SLOT(handlePopupHideTimeout())); connect(m_volumePopup, SIGNAL(mouseEntered()), this, SLOT(popupHideTimerStop())); connect(m_volumePopup, SIGNAL(mouseLeft()), this, SLOT(popupHideTimerStart())); connect(m_volumePopup, SIGNAL(deviceChanged()), this, SLOT(handleDeviceChanged())); connect(m_volumePopup, SIGNAL(launchMixer()), this, SLOT(handleMixerLaunch())); connect(m_volumePopup, SIGNAL(stockIconChanged(QString)), this, SLOT(handleStockIconChanged(QString))); } VolumeButton::~VolumeButton() { if (m_volumePopup) delete m_volumePopup; } void VolumeButton::setShowOnClicked(bool state) { if (m_showOnClick == state) return; m_showOnClick = state; } void VolumeButton::setMuteOnMiddleClick(bool state) { m_muteOnMiddleClick = state; } void VolumeButton::setMixerCommand(const QString &command) { m_mixerCommand = command; } void VolumeButton::enterEvent(QEvent *event) { if (!m_showOnClick) showVolumeSlider(); popupHideTimerStop(); } void VolumeButton::leaveEvent(QEvent *event) { popupHideTimerStart(); } void VolumeButton::wheelEvent(QWheelEvent *event) { m_volumePopup->handleWheelEvent(event); } void VolumeButton::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::MidButton && m_muteOnMiddleClick) { if (m_volumePopup->device()) { m_volumePopup->device()->toggleMute(); return; } } QToolButton::mouseReleaseEvent(event); } void VolumeButton::toggleVolumeSlider() { if (m_volumePopup->isVisible()) { popupHideTimerStop(); handlePopupHideTimeout(); } else { showVolumeSlider(); } } void VolumeButton::showVolumeSlider() { if (m_volumePopup->isVisible()) return; popupHideTimerStop(); m_volumePopup->updateGeometry(); if (isLeftToRight()) { switch (m_panel->position()) { case RazorPanel::PositionTop: m_volumePopup->open(mapToGlobal(geometry().bottomLeft()), Qt::TopLeftCorner); break; case RazorPanel::PositionBottom: m_volumePopup->open(mapToGlobal(geometry().topLeft()), Qt::BottomLeftCorner); break; case RazorPanel::PositionLeft: m_volumePopup->open(mapToGlobal(geometry().topRight()), Qt::TopLeftCorner); break; case RazorPanel::PositionRight: m_volumePopup->open(mapToGlobal(geometry().topLeft()), Qt::TopLeftCorner); break; } } else { switch (m_panel->position()) { case RazorPanel::PositionTop: m_volumePopup->open(mapToGlobal(geometry().bottomRight()), Qt::TopRightCorner); break; case RazorPanel::PositionBottom: m_volumePopup->open(mapToGlobal(geometry().topRight()), Qt::BottomRightCorner); break; case RazorPanel::PositionLeft: m_volumePopup->open(mapToGlobal(geometry().topRight()), Qt::TopLeftCorner); break; case RazorPanel::PositionRight: m_volumePopup->open(mapToGlobal(geometry().topLeft()), Qt::TopLeftCorner); break; } } } void VolumeButton::hideVolumeSlider() { popupHideTimerStart(); } void VolumeButton::handlePopupHideTimeout() { m_volumePopup->hide(); } void VolumeButton::popupHideTimerStart() { m_popupHideTimer.start(m_popupHideTimerDuration); } void VolumeButton::popupHideTimerStop() { m_popupHideTimer.stop(); } void VolumeButton::handleMixerLaunch() { QProcess::startDetached(m_mixerCommand); } void VolumeButton::handleStockIconChanged(const QString &iconName) { setIcon(XdgIcon::fromTheme(iconName)); } <|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 <windows.h> //#include "chrome/browser/platform_util.h" #include "content/nw/src/browser/browser_dialogs.h" #include "content/nw/src/browser/color_chooser_dialog.h" #include "content/public/browser/color_chooser.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "ui/views/color_chooser/color_chooser_listener.h" class ColorChooserWin : public content::ColorChooser, public views::ColorChooserListener { public: static ColorChooserWin* Open(content::WebContents* web_contents, SkColor initial_color); ColorChooserWin(content::WebContents* web_contents, SkColor initial_color); ~ColorChooserWin(); // content::ColorChooser overrides: virtual void End() OVERRIDE {} virtual void SetSelectedColor(SkColor color) OVERRIDE {} // views::ColorChooserListener overrides: virtual void OnColorChosen(SkColor color); virtual void OnColorChooserDialogClosed(); private: static ColorChooserWin* current_color_chooser_; // The web contents invoking the color chooser. No ownership. because it will // outlive this class. content::WebContents* web_contents_; // The color chooser dialog which maintains the native color chooser UI. scoped_refptr<ColorChooserDialog> color_chooser_dialog_; }; ColorChooserWin* ColorChooserWin::current_color_chooser_ = NULL; ColorChooserWin* ColorChooserWin::Open(content::WebContents* web_contents, SkColor initial_color) { if (!current_color_chooser_) current_color_chooser_ = new ColorChooserWin(web_contents, initial_color); return current_color_chooser_; } ColorChooserWin::ColorChooserWin(content::WebContents* web_contents, SkColor initial_color) : web_contents_(web_contents) { gfx::NativeWindow owning_window = platform_util::GetTopLevel( web_contents->GetRenderViewHost()->GetView()->GetNativeView()); color_chooser_dialog_ = new ColorChooserDialog(this, initial_color, owning_window); } ColorChooserWin::~ColorChooserWin() { // Always call End() before destroying. DCHECK(!color_chooser_dialog_); } void ColorChooserWin::OnColorChosen(SkColor color) { if (web_contents_) web_contents_->DidChooseColorInColorChooser(color); } void ColorChooserWin::OnColorChooserDialogClosed() { if (color_chooser_dialog_.get()) { color_chooser_dialog_->ListenerDestroyed(); color_chooser_dialog_ = NULL; } DCHECK(current_color_chooser_ == this); current_color_chooser_ = NULL; if (web_contents_) web_contents_->DidEndColorChooser(); } namespace chrome { content::ColorChooser* ShowColorChooser(content::WebContents* web_contents, SkColor initial_color) { return ColorChooserWin::Open(web_contents, initial_color); } } // namespace chrome <commit_msg>fix color chooser for windows<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 <windows.h> //#include "chrome/browser/platform_util.h" #include "content/nw/src/browser/browser_dialogs.h" #include "content/nw/src/browser/color_chooser_dialog.h" #include "content/public/browser/color_chooser.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "ui/views/color_chooser/color_chooser_listener.h" class ColorChooserWin : public content::ColorChooser, public views::ColorChooserListener { public: static ColorChooserWin* Open(content::WebContents* web_contents, SkColor initial_color); ColorChooserWin(content::WebContents* web_contents, SkColor initial_color); ~ColorChooserWin(); // content::ColorChooser overrides: virtual void End() OVERRIDE {} virtual void SetSelectedColor(SkColor color) OVERRIDE {} // views::ColorChooserListener overrides: virtual void OnColorChosen(SkColor color); virtual void OnColorChooserDialogClosed(); private: static ColorChooserWin* current_color_chooser_; // The web contents invoking the color chooser. No ownership. because it will // outlive this class. content::WebContents* web_contents_; // The color chooser dialog which maintains the native color chooser UI. scoped_refptr<ColorChooserDialog> color_chooser_dialog_; }; ColorChooserWin* ColorChooserWin::current_color_chooser_ = NULL; ColorChooserWin* ColorChooserWin::Open(content::WebContents* web_contents, SkColor initial_color) { if (!current_color_chooser_) current_color_chooser_ = new ColorChooserWin(web_contents, initial_color); return current_color_chooser_; } ColorChooserWin::ColorChooserWin(content::WebContents* web_contents, SkColor initial_color) : web_contents_(web_contents) { gfx::NativeWindow owning_window = ::GetAncestor( web_contents->GetRenderViewHost()->GetView()->GetNativeView(), GA_ROOT); color_chooser_dialog_ = new ColorChooserDialog(this, initial_color, owning_window); } ColorChooserWin::~ColorChooserWin() { // Always call End() before destroying. DCHECK(!color_chooser_dialog_); } void ColorChooserWin::OnColorChosen(SkColor color) { if (web_contents_) web_contents_->DidChooseColorInColorChooser(color); } void ColorChooserWin::OnColorChooserDialogClosed() { if (color_chooser_dialog_.get()) { color_chooser_dialog_->ListenerDestroyed(); color_chooser_dialog_ = NULL; } DCHECK(current_color_chooser_ == this); current_color_chooser_ = NULL; if (web_contents_) web_contents_->DidEndColorChooser(); } namespace nw { content::ColorChooser* ShowColorChooser(content::WebContents* web_contents, SkColor initial_color) { return ColorChooserWin::Open(web_contents, initial_color); } } // namespace chrome <|endoftext|>
<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Write some debug info */ #include "mysql_priv.h" #include "sql_select.h" #include <hash.h> #include <thr_alarm.h> /* Intern key cache variables */ extern "C" pthread_mutex_t THR_LOCK_keycache; #ifndef DBUG_OFF void print_where(COND *cond,const char *info) { if (cond) { char buff[256]; String str(buff,(uint32) sizeof(buff), default_charset_info); str.length(0); cond->print(&str); str.append('\0'); DBUG_LOCK_FILE; (void) fprintf(DBUG_FILE,"\nWHERE:(%s) ",info); (void) fputs(str.ptr(),DBUG_FILE); (void) fputc('\n',DBUG_FILE); DBUG_UNLOCK_FILE; } } /* This is for debugging purposes */ extern HASH open_cache; extern TABLE *unused_tables; void print_cached_tables(void) { uint idx,count,unused; TABLE *start_link,*lnk; VOID(pthread_mutex_lock(&LOCK_open)); puts("DB Table Version Thread L.thread Open"); for (idx=unused=0 ; idx < open_cache.records ; idx++) { TABLE *entry=(TABLE*) hash_element(&open_cache,idx); printf("%-14.14s %-32s%6ld%8ld%10ld%6d\n", entry->table_cache_key,entry->real_name,entry->version, entry->in_use ? entry->in_use->thread_id : 0L, entry->in_use ? entry->in_use->dbug_thread_id : 0L, entry->db_stat ? 1 : 0); if (!entry->in_use) unused++; } count=0; if ((start_link=lnk=unused_tables)) { do { if (lnk != lnk->next->prev || lnk != lnk->prev->next) { printf("unused_links isn't linked properly\n"); return; } } while (count++ < open_cache.records && (lnk=lnk->next) != start_link); if (lnk != start_link) { printf("Unused_links aren't connected\n"); } } if (count != unused) printf("Unused_links (%d) doesn't match open_cache: %d\n", count,unused); printf("\nCurrent refresh version: %ld\n",refresh_version); if (hash_check(&open_cache)) printf("Error: File hash table is corrupted\n"); fflush(stdout); VOID(pthread_mutex_unlock(&LOCK_open)); return; } void TEST_filesort(SORT_FIELD *sortorder,uint s_length) { char buff[256],buff2[256]; String str(buff,sizeof(buff),default_charset_info); String out(buff2,sizeof(buff2),default_charset_info); const char *sep; DBUG_ENTER("TEST_filesort"); out.length(0); for (sep=""; s_length-- ; sortorder++, sep=" ") { out.append(sep); if (sortorder->reverse) out.append('-'); if (sortorder->field) { if (sortorder->field->table_name) { out.append(sortorder->field->table_name); out.append('.'); } out.append(sortorder->field->field_name ? sortorder->field->field_name: "tmp_table_column"); } else { str.length(0); sortorder->item->print(&str); out.append(str); } } out.append('\0'); // Purify doesn't like c_ptr() DBUG_LOCK_FILE; VOID(fputs("\nInfo about FILESORT\n",DBUG_FILE)); fprintf(DBUG_FILE,"Sortorder: %s\n",out.ptr()); DBUG_UNLOCK_FILE; DBUG_VOID_RETURN; } void TEST_join(JOIN *join) { uint i,ref; DBUG_ENTER("TEST_join"); DBUG_LOCK_FILE; VOID(fputs("\nInfo about JOIN\n",DBUG_FILE)); for (i=0 ; i < join->tables ; i++) { JOIN_TAB *tab=join->join_tab+i; TABLE *form=tab->table; fprintf(DBUG_FILE,"%-16.16s type: %-7s q_keys: %4d refs: %d key: %d len: %d\n", form->table_name, join_type_str[tab->type], tab->keys, tab->ref.key_parts, tab->ref.key, tab->ref.key_length); if (tab->select) { if (tab->use_quick == 2) fprintf(DBUG_FILE, " quick select checked for each record (keys: %d)\n", (int) tab->select->quick_keys); else if (tab->select->quick) fprintf(DBUG_FILE," quick select used on key %s, length: %d\n", form->key_info[tab->select->quick->index].name, tab->select->quick->max_used_key_length); else VOID(fputs(" select used\n",DBUG_FILE)); } if (tab->ref.key_parts) { VOID(fputs(" refs: ",DBUG_FILE)); for (ref=0 ; ref < tab->ref.key_parts ; ref++) { Item *item=tab->ref.items[ref]; fprintf(DBUG_FILE,"%s ", item->full_name()); } VOID(fputc('\n',DBUG_FILE)); } } DBUG_UNLOCK_FILE; DBUG_VOID_RETURN; } #endif void mysql_print_status(THD *thd) { char current_dir[FN_REFLEN]; printf("\nStatus information:\n\n"); my_getwd(current_dir, sizeof(current_dir),MYF(0)); printf("Current dir: %s\n", current_dir); if (thd) thd->proc_info="locks"; thr_print_locks(); // Write some debug info #ifndef DBUG_OFF if (thd) thd->proc_info="table cache"; print_cached_tables(); #endif /* Print key cache status */ if (thd) thd->proc_info="key cache"; pthread_mutex_lock(&THR_LOCK_keycache); printf("key_cache status:\n\ blocks used:%10lu\n\ not flushed:%10lu\n\ w_requests: %10lu\n\ writes: %10lu\n\ r_requests: %10lu\n\ reads: %10lu\n", _my_blocks_used,_my_blocks_changed,_my_cache_w_requests, _my_cache_write,_my_cache_r_requests,_my_cache_read); pthread_mutex_unlock(&THR_LOCK_keycache); if (thd) thd->proc_info="status"; pthread_mutex_lock(&LOCK_status); printf("\nhandler status:\n\ read_key: %10lu\n\ read_next: %10lu\n\ read_rnd %10lu\n\ read_first: %10lu\n\ write: %10lu\n\ delete %10lu\n\ update: %10lu\n", ha_read_key_count, ha_read_next_count, ha_read_rnd_count, ha_read_first_count, ha_write_count, ha_delete_count, ha_update_count); pthread_mutex_unlock(&LOCK_status); printf("\nTable status:\n\ Opened tables: %10lu\n\ Open tables: %10lu\n\ Open files: %10lu\n\ Open streams: %10lu\n", opened_tables, (ulong) cached_tables(), (ulong) my_file_opened, (ulong) my_stream_opened); ALARM_INFO alarm_info; #ifndef DONT_USE_THR_ALARM thr_alarm_info(&alarm_info); printf("\nAlarm status:\n\ Active alarms: %u\n\ Max used alarms: %u\n\ Next alarm time: %lu\n", alarm_info.active_alarms, alarm_info.max_used_alarms, alarm_info.next_alarm_time); #endif fflush(stdout); if (thd) thd->proc_info="malloc"; my_checkmalloc(); TERMINATE(stdout); // Write malloc information if (thd) thd->proc_info=0; } <commit_msg>Small addition to COM_DEBUG<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Write some debug info */ #include "mysql_priv.h" #include "sql_select.h" #include <hash.h> #include <thr_alarm.h> /* Intern key cache variables */ extern "C" pthread_mutex_t THR_LOCK_keycache; #ifndef DBUG_OFF void print_where(COND *cond,const char *info) { if (cond) { char buff[256]; String str(buff,(uint32) sizeof(buff), default_charset_info); str.length(0); cond->print(&str); str.append('\0'); DBUG_LOCK_FILE; (void) fprintf(DBUG_FILE,"\nWHERE:(%s) ",info); (void) fputs(str.ptr(),DBUG_FILE); (void) fputc('\n',DBUG_FILE); DBUG_UNLOCK_FILE; } } /* This is for debugging purposes */ extern HASH open_cache; extern TABLE *unused_tables; static const char *lock_descriptions[] = { "No lock", "Low priority read lock", "Shared Read lock", "High priority read lock", "Read lock without concurrent inserts", "Write lock that allows other writers", "Write lock, but allow reading", "Concurrent insert lock", "Lock Used by delayed insert", "Low priority write lock", "High priority write lock", "Highest priority write lock" }; void print_cached_tables(void) { uint idx,count,unused; TABLE *start_link,*lnk; VOID(pthread_mutex_lock(&LOCK_open)); puts("DB Table Version Thread L.thread Open Lock"); for (idx=unused=0 ; idx < open_cache.records ; idx++) { TABLE *entry=(TABLE*) hash_element(&open_cache,idx); printf("%-14.14s %-32s%6ld%8ld%10ld%6d %s\n", entry->table_cache_key,entry->real_name,entry->version, entry->in_use ? entry->in_use->thread_id : 0L, entry->in_use ? entry->in_use->dbug_thread_id : 0L, entry->db_stat ? 1 : 0, entry->in_use ? lock_descriptions[(int)entry->reginfo.lock_type] : "Not in use"); if (!entry->in_use) unused++; } count=0; if ((start_link=lnk=unused_tables)) { do { if (lnk != lnk->next->prev || lnk != lnk->prev->next) { printf("unused_links isn't linked properly\n"); return; } } while (count++ < open_cache.records && (lnk=lnk->next) != start_link); if (lnk != start_link) { printf("Unused_links aren't connected\n"); } } if (count != unused) printf("Unused_links (%d) doesn't match open_cache: %d\n", count,unused); printf("\nCurrent refresh version: %ld\n",refresh_version); if (hash_check(&open_cache)) printf("Error: File hash table is corrupted\n"); fflush(stdout); VOID(pthread_mutex_unlock(&LOCK_open)); return; } void TEST_filesort(SORT_FIELD *sortorder,uint s_length) { char buff[256],buff2[256]; String str(buff,sizeof(buff),default_charset_info); String out(buff2,sizeof(buff2),default_charset_info); const char *sep; DBUG_ENTER("TEST_filesort"); out.length(0); for (sep=""; s_length-- ; sortorder++, sep=" ") { out.append(sep); if (sortorder->reverse) out.append('-'); if (sortorder->field) { if (sortorder->field->table_name) { out.append(sortorder->field->table_name); out.append('.'); } out.append(sortorder->field->field_name ? sortorder->field->field_name: "tmp_table_column"); } else { str.length(0); sortorder->item->print(&str); out.append(str); } } out.append('\0'); // Purify doesn't like c_ptr() DBUG_LOCK_FILE; VOID(fputs("\nInfo about FILESORT\n",DBUG_FILE)); fprintf(DBUG_FILE,"Sortorder: %s\n",out.ptr()); DBUG_UNLOCK_FILE; DBUG_VOID_RETURN; } void TEST_join(JOIN *join) { uint i,ref; DBUG_ENTER("TEST_join"); DBUG_LOCK_FILE; VOID(fputs("\nInfo about JOIN\n",DBUG_FILE)); for (i=0 ; i < join->tables ; i++) { JOIN_TAB *tab=join->join_tab+i; TABLE *form=tab->table; fprintf(DBUG_FILE,"%-16.16s type: %-7s q_keys: %4d refs: %d key: %d len: %d\n", form->table_name, join_type_str[tab->type], tab->keys, tab->ref.key_parts, tab->ref.key, tab->ref.key_length); if (tab->select) { if (tab->use_quick == 2) fprintf(DBUG_FILE, " quick select checked for each record (keys: %d)\n", (int) tab->select->quick_keys); else if (tab->select->quick) fprintf(DBUG_FILE," quick select used on key %s, length: %d\n", form->key_info[tab->select->quick->index].name, tab->select->quick->max_used_key_length); else VOID(fputs(" select used\n",DBUG_FILE)); } if (tab->ref.key_parts) { VOID(fputs(" refs: ",DBUG_FILE)); for (ref=0 ; ref < tab->ref.key_parts ; ref++) { Item *item=tab->ref.items[ref]; fprintf(DBUG_FILE,"%s ", item->full_name()); } VOID(fputc('\n',DBUG_FILE)); } } DBUG_UNLOCK_FILE; DBUG_VOID_RETURN; } #endif void mysql_print_status(THD *thd) { char current_dir[FN_REFLEN]; printf("\nStatus information:\n\n"); my_getwd(current_dir, sizeof(current_dir),MYF(0)); printf("Current dir: %s\n", current_dir); if (thd) thd->proc_info="locks"; thr_print_locks(); // Write some debug info #ifndef DBUG_OFF if (thd) thd->proc_info="table cache"; print_cached_tables(); #endif /* Print key cache status */ if (thd) thd->proc_info="key cache"; pthread_mutex_lock(&THR_LOCK_keycache); printf("key_cache status:\n\ blocks used:%10lu\n\ not flushed:%10lu\n\ w_requests: %10lu\n\ writes: %10lu\n\ r_requests: %10lu\n\ reads: %10lu\n", _my_blocks_used,_my_blocks_changed,_my_cache_w_requests, _my_cache_write,_my_cache_r_requests,_my_cache_read); pthread_mutex_unlock(&THR_LOCK_keycache); if (thd) thd->proc_info="status"; pthread_mutex_lock(&LOCK_status); printf("\nhandler status:\n\ read_key: %10lu\n\ read_next: %10lu\n\ read_rnd %10lu\n\ read_first: %10lu\n\ write: %10lu\n\ delete %10lu\n\ update: %10lu\n", ha_read_key_count, ha_read_next_count, ha_read_rnd_count, ha_read_first_count, ha_write_count, ha_delete_count, ha_update_count); pthread_mutex_unlock(&LOCK_status); printf("\nTable status:\n\ Opened tables: %10lu\n\ Open tables: %10lu\n\ Open files: %10lu\n\ Open streams: %10lu\n", opened_tables, (ulong) cached_tables(), (ulong) my_file_opened, (ulong) my_stream_opened); ALARM_INFO alarm_info; #ifndef DONT_USE_THR_ALARM thr_alarm_info(&alarm_info); printf("\nAlarm status:\n\ Active alarms: %u\n\ Max used alarms: %u\n\ Next alarm time: %lu\n", alarm_info.active_alarms, alarm_info.max_used_alarms, alarm_info.next_alarm_time); #endif fflush(stdout); if (thd) thd->proc_info="malloc"; my_checkmalloc(); TERMINATE(stdout); // Write malloc information if (thd) thd->proc_info=0; } <|endoftext|>
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2016/09/14 // Author: Mike Ovsiannikov // // Copyright 2016 Quantcast Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // Restart process by issuing exec with saved args, environment, and working // directory. // //---------------------------------------------------------------------------- #include "ProcessRestarter.h" #include "common/Properties.h" #include "qcdio/QCUtils.h" #include <signal.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <sys/resource.h> #include <string> extern char **environ; namespace KFS { using std::string; class ProcessRestarter::Impl { public: Impl( bool inCloseFdsAtInitFlag, bool inSaveRestoreEnvFlag, bool inExitOnRestartFlag, bool inCloseFdsBeforeExecFlag, int inMaxGracefulRestartSeconds) : mCwd(0), mArgs(0), mEnv(0), mMaxGracefulRestartSeconds(inMaxGracefulRestartSeconds), mExitOnRestartFlag(inExitOnRestartFlag), mCloseFdsAtInitFlag(inCloseFdsAtInitFlag), mCloseFdsBeforeExecFlag(inCloseFdsBeforeExecFlag), mSaveRestoreEnvFlag(inSaveRestoreEnvFlag) {} ~Impl() { Cleanup(); } int Init( int inArgCnt, char** inArgsPtr) { ::alarm(0); if (::signal(SIGALRM, &Impl::SigAlrmHandler) == SIG_ERR) { QCUtils::FatalError("signal(SIGALRM)", errno); } Cleanup(); if (inArgCnt < 1 || ! inArgsPtr) { return EINVAL; } int theErr = 0; for (int theLen = 4 << 10; theLen < (128 << 10); theLen += theLen) { mCwd = (char*)::malloc(theLen); if (! mCwd || ::getcwd(mCwd, theLen)) { break; } theErr = errno; ::free(mCwd); mCwd = 0; if (theErr != ERANGE) { break; } } if (! mCwd) { return (0 == theErr ? EINVAL : theErr); } mArgs = new char*[inArgCnt + 1]; int i; for (i = 0; i < inArgCnt; i++) { if (! (mArgs[i] = ::strdup(inArgsPtr[i]))) { theErr = errno; Cleanup(); return (0 == theErr ? ENOMEM : theErr); } } mArgs[i] = 0; if (mSaveRestoreEnvFlag) { if (environ) { char** thePtr = environ; for (i = 0; *thePtr; i++, thePtr++) {} mEnv = new char*[i + 1]; for (i = 0, thePtr = environ; *thePtr; ) { if (! (mEnv[i++] = ::strdup(*thePtr++))) { theErr = errno; Cleanup(); return (0 == theErr ? ENOMEM : theErr); } } } else { i = 0; mEnv = new char*[i + 1]; } mEnv[i] = 0; } if (mCloseFdsAtInitFlag) { CloseFds(); } return 0; } void SetParameters( const char* inPrefixPtr, const Properties& inProps) { Properties::String theName(inPrefixPtr ? inPrefixPtr : ""); const size_t theLen = theName.GetSize(); mMaxGracefulRestartSeconds = inProps.getValue( theName.Truncate(theLen).Append("maxGracefulRestartSeconds"), mMaxGracefulRestartSeconds ); // Prior name for backward compatibility. mExitOnRestartFlag = inProps.getValue( theName.Truncate(theLen).Append("exitOnRestartFlag"), mExitOnRestartFlag ? 1 : 0 ) != 0; mExitOnRestartFlag = inProps.getValue( theName.Truncate(theLen).Append("exitOnRestart"), mExitOnRestartFlag ? 1 : 0 ) != 0; mCloseFdsAtInitFlag = inProps.getValue( theName.Truncate(theLen).Append("closeFdsAtInit"), mCloseFdsAtInitFlag ? 1 : 0 ) != 0; mCloseFdsBeforeExecFlag = inProps.getValue( theName.Truncate(theLen).Append("closeFdsBeforeExec"), mCloseFdsBeforeExecFlag ? 1 : 0 ) != 0; } string Restart() { if (! mCwd || ! mArgs || ! mArgs[0] || ! mArgs[0][0] || (! mEnv && mSaveRestoreEnvFlag)) { return string("not initialized"); } if (! mExitOnRestartFlag) { struct stat theRes = {0}; if (::stat(mCwd, &theRes) != 0) { return QCUtils::SysError(errno, mCwd); } if (! S_ISDIR(theRes.st_mode)) { return (mCwd + string(": not a directory")); } string theExecpath(mArgs[0][0] == '/' ? mArgs[0] : mCwd); if (mArgs[0][0] != '/') { if (! theExecpath.empty() && theExecpath.at(theExecpath.length() - 1) != '/') { theExecpath += "/"; } theExecpath += mArgs[0]; } if (::stat(theExecpath.c_str(), &theRes) != 0) { return QCUtils::SysError(errno, theExecpath.c_str()); } if (! S_ISREG(theRes.st_mode)) { return (theExecpath + string(": not a file")); } } if (::signal(SIGALRM, &Impl::SigAlrmHandler) == SIG_ERR) { QCUtils::FatalError("signal(SIGALRM)", errno); } if (0 < mMaxGracefulRestartSeconds) { if (sInstancePtr) { return string("restart in progress"); } sInstancePtr = this; if (::atexit(&Impl::RestartSelf)) { sInstancePtr = 0; return QCUtils::SysError(errno, "atexit"); } ::alarm((unsigned int)mMaxGracefulRestartSeconds); } else { ::alarm((unsigned int)-mMaxGracefulRestartSeconds); Exec(); } return string(); } static void CloseFds( int inFrstFd = 3) { int theMaxFds = 16 << 10; struct rlimit theLimt = { 0 }; if (0 == getrlimit(RLIMIT_NOFILE, &theLimt)) { if (0 < theLimt.rlim_cur) { theMaxFds = (int)theLimt.rlim_cur; } } for (int i = inFrstFd; i < theMaxFds; i++) { close(i); } } private: char* mCwd; char** mArgs; char** mEnv; int mMaxGracefulRestartSeconds; bool mExitOnRestartFlag; bool mCloseFdsAtInitFlag; bool mCloseFdsBeforeExecFlag; bool mSaveRestoreEnvFlag; static Impl* sInstancePtr; static void FreeArgs( char** inArgsPtr) { if (! inArgsPtr) { return; } char** thePtr = inArgsPtr; while (*thePtr) { ::free(*thePtr++); } delete [] inArgsPtr; } void Cleanup() { free(mCwd); mCwd = 0; FreeArgs(mArgs); mArgs = 0; FreeArgs(mEnv); mEnv = 0; } void Exec() { if (mExitOnRestartFlag) { _exit(0); } if (mEnv && mSaveRestoreEnvFlag) { #ifdef KFS_OS_NAME_LINUX ::clearenv(); #else environ = 0; #endif for (char** thePtr = mEnv; *thePtr; thePtr++) { if (::putenv(*thePtr)) { QCUtils::FatalError("putenv", errno); } } } if (::chdir(mCwd) != 0) { QCUtils::FatalError(mCwd, errno); } if (mCloseFdsBeforeExecFlag) { CloseFds(); } execvp(mArgs[0], mArgs); QCUtils::FatalError(mArgs[0], errno); } static void RestartSelf() { if (! sInstancePtr) { ::abort(); } sInstancePtr->Exec(); } static void SigAlrmHandler( int /* inSig */) { if (write(2, "SIGALRM\n", 8) < 0) { QCUtils::SetLastIgnoredError(errno); } ::abort(); } }; ProcessRestarter::Impl* ProcessRestarter::Impl::sInstancePtr = 0; ProcessRestarter::ProcessRestarter( bool inCloseFdsAtInitFlag, bool inSaveRestoreEnvFlag, bool inExitOnRestartFlag, bool inCloseFdsBeforeExecFlag, int inMaxGracefulRestartSeconds) : mImpl(*(new Impl( inCloseFdsAtInitFlag, inSaveRestoreEnvFlag, inExitOnRestartFlag, inCloseFdsBeforeExecFlag, inMaxGracefulRestartSeconds))) {} ProcessRestarter::~ProcessRestarter() { delete &mImpl; } int ProcessRestarter::Init( int inArgCnt, char** inArgsPtr) { return mImpl.Init(inArgCnt, inArgsPtr); } void ProcessRestarter::SetParameters( const char* inPrefixPtr, const Properties& inProps) { mImpl.SetParameters(inPrefixPtr, inProps); } string ProcessRestarter::Restart() { return mImpl.Restart(); } /* static */ void ProcessRestarter::CloseFds( int inFrstFd) { Impl::CloseFds(inFrstFd); } } // namespace KFS <commit_msg>IO library: fix process restarter parameter name.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2016/09/14 // Author: Mike Ovsiannikov // // Copyright 2016 Quantcast Corp. // // This file is part of Kosmos File System (KFS). // // 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. // // Restart process by issuing exec with saved args, environment, and working // directory. // //---------------------------------------------------------------------------- #include "ProcessRestarter.h" #include "common/Properties.h" #include "qcdio/QCUtils.h" #include <signal.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <sys/resource.h> #include <string> extern char **environ; namespace KFS { using std::string; class ProcessRestarter::Impl { public: Impl( bool inCloseFdsAtInitFlag, bool inSaveRestoreEnvFlag, bool inExitOnRestartFlag, bool inCloseFdsBeforeExecFlag, int inMaxGracefulRestartSeconds) : mCwd(0), mArgs(0), mEnv(0), mMaxGracefulRestartSeconds(inMaxGracefulRestartSeconds), mExitOnRestartFlag(inExitOnRestartFlag), mCloseFdsAtInitFlag(inCloseFdsAtInitFlag), mCloseFdsBeforeExecFlag(inCloseFdsBeforeExecFlag), mSaveRestoreEnvFlag(inSaveRestoreEnvFlag) {} ~Impl() { Cleanup(); } int Init( int inArgCnt, char** inArgsPtr) { ::alarm(0); if (::signal(SIGALRM, &Impl::SigAlrmHandler) == SIG_ERR) { QCUtils::FatalError("signal(SIGALRM)", errno); } Cleanup(); if (inArgCnt < 1 || ! inArgsPtr) { return EINVAL; } int theErr = 0; for (int theLen = 4 << 10; theLen < (128 << 10); theLen += theLen) { mCwd = (char*)::malloc(theLen); if (! mCwd || ::getcwd(mCwd, theLen)) { break; } theErr = errno; ::free(mCwd); mCwd = 0; if (theErr != ERANGE) { break; } } if (! mCwd) { return (0 == theErr ? EINVAL : theErr); } mArgs = new char*[inArgCnt + 1]; int i; for (i = 0; i < inArgCnt; i++) { if (! (mArgs[i] = ::strdup(inArgsPtr[i]))) { theErr = errno; Cleanup(); return (0 == theErr ? ENOMEM : theErr); } } mArgs[i] = 0; if (mSaveRestoreEnvFlag) { if (environ) { char** thePtr = environ; for (i = 0; *thePtr; i++, thePtr++) {} mEnv = new char*[i + 1]; for (i = 0, thePtr = environ; *thePtr; ) { if (! (mEnv[i++] = ::strdup(*thePtr++))) { theErr = errno; Cleanup(); return (0 == theErr ? ENOMEM : theErr); } } } else { i = 0; mEnv = new char*[i + 1]; } mEnv[i] = 0; } if (mCloseFdsAtInitFlag) { CloseFds(); } return 0; } void SetParameters( const char* inPrefixPtr, const Properties& inProps) { Properties::String theName(inPrefixPtr ? inPrefixPtr : ""); const size_t theLen = theName.GetSize(); mMaxGracefulRestartSeconds = inProps.getValue( theName.Truncate(theLen).Append("maxGracefulRestartSeconds"), mMaxGracefulRestartSeconds ); // Prior name for backward compatibility. mExitOnRestartFlag = inProps.getValue( theName.Truncate(theLen).Append("exitOnRestart"), mExitOnRestartFlag ? 1 : 0 ) != 0; mExitOnRestartFlag = inProps.getValue( theName.Truncate(theLen).Append("exitOnRestart"), mExitOnRestartFlag ? 1 : 0 ) != 0; mCloseFdsAtInitFlag = inProps.getValue( theName.Truncate(theLen).Append("closeFdsAtInit"), mCloseFdsAtInitFlag ? 1 : 0 ) != 0; mCloseFdsBeforeExecFlag = inProps.getValue( theName.Truncate(theLen).Append("closeFdsBeforeExec"), mCloseFdsBeforeExecFlag ? 1 : 0 ) != 0; } string Restart() { if (! mCwd || ! mArgs || ! mArgs[0] || ! mArgs[0][0] || (! mEnv && mSaveRestoreEnvFlag)) { return string("not initialized"); } if (! mExitOnRestartFlag) { struct stat theRes = {0}; if (::stat(mCwd, &theRes) != 0) { return QCUtils::SysError(errno, mCwd); } if (! S_ISDIR(theRes.st_mode)) { return (mCwd + string(": not a directory")); } string theExecpath(mArgs[0][0] == '/' ? mArgs[0] : mCwd); if (mArgs[0][0] != '/') { if (! theExecpath.empty() && theExecpath.at(theExecpath.length() - 1) != '/') { theExecpath += "/"; } theExecpath += mArgs[0]; } if (::stat(theExecpath.c_str(), &theRes) != 0) { return QCUtils::SysError(errno, theExecpath.c_str()); } if (! S_ISREG(theRes.st_mode)) { return (theExecpath + string(": not a file")); } } if (::signal(SIGALRM, &Impl::SigAlrmHandler) == SIG_ERR) { QCUtils::FatalError("signal(SIGALRM)", errno); } if (0 < mMaxGracefulRestartSeconds) { if (sInstancePtr) { return string("restart in progress"); } sInstancePtr = this; if (::atexit(&Impl::RestartSelf)) { sInstancePtr = 0; return QCUtils::SysError(errno, "atexit"); } ::alarm((unsigned int)mMaxGracefulRestartSeconds); } else { ::alarm((unsigned int)-mMaxGracefulRestartSeconds); Exec(); } return string(); } static void CloseFds( int inFrstFd = 3) { int theMaxFds = 16 << 10; struct rlimit theLimt = { 0 }; if (0 == getrlimit(RLIMIT_NOFILE, &theLimt)) { if (0 < theLimt.rlim_cur) { theMaxFds = (int)theLimt.rlim_cur; } } for (int i = inFrstFd; i < theMaxFds; i++) { close(i); } } private: char* mCwd; char** mArgs; char** mEnv; int mMaxGracefulRestartSeconds; bool mExitOnRestartFlag; bool mCloseFdsAtInitFlag; bool mCloseFdsBeforeExecFlag; bool mSaveRestoreEnvFlag; static Impl* sInstancePtr; static void FreeArgs( char** inArgsPtr) { if (! inArgsPtr) { return; } char** thePtr = inArgsPtr; while (*thePtr) { ::free(*thePtr++); } delete [] inArgsPtr; } void Cleanup() { free(mCwd); mCwd = 0; FreeArgs(mArgs); mArgs = 0; FreeArgs(mEnv); mEnv = 0; } void Exec() { if (mExitOnRestartFlag) { _exit(0); } if (mEnv && mSaveRestoreEnvFlag) { #ifdef KFS_OS_NAME_LINUX ::clearenv(); #else environ = 0; #endif for (char** thePtr = mEnv; *thePtr; thePtr++) { if (::putenv(*thePtr)) { QCUtils::FatalError("putenv", errno); } } } if (::chdir(mCwd) != 0) { QCUtils::FatalError(mCwd, errno); } if (mCloseFdsBeforeExecFlag) { CloseFds(); } execvp(mArgs[0], mArgs); QCUtils::FatalError(mArgs[0], errno); } static void RestartSelf() { if (! sInstancePtr) { ::abort(); } sInstancePtr->Exec(); } static void SigAlrmHandler( int /* inSig */) { if (write(2, "SIGALRM\n", 8) < 0) { QCUtils::SetLastIgnoredError(errno); } ::abort(); } }; ProcessRestarter::Impl* ProcessRestarter::Impl::sInstancePtr = 0; ProcessRestarter::ProcessRestarter( bool inCloseFdsAtInitFlag, bool inSaveRestoreEnvFlag, bool inExitOnRestartFlag, bool inCloseFdsBeforeExecFlag, int inMaxGracefulRestartSeconds) : mImpl(*(new Impl( inCloseFdsAtInitFlag, inSaveRestoreEnvFlag, inExitOnRestartFlag, inCloseFdsBeforeExecFlag, inMaxGracefulRestartSeconds))) {} ProcessRestarter::~ProcessRestarter() { delete &mImpl; } int ProcessRestarter::Init( int inArgCnt, char** inArgsPtr) { return mImpl.Init(inArgCnt, inArgsPtr); } void ProcessRestarter::SetParameters( const char* inPrefixPtr, const Properties& inProps) { mImpl.SetParameters(inPrefixPtr, inProps); } string ProcessRestarter::Restart() { return mImpl.Restart(); } /* static */ void ProcessRestarter::CloseFds( int inFrstFd) { Impl::CloseFds(inFrstFd); } } // namespace KFS <|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/yosys.h" #include "kernel/sigtools.h" #include "kernel/celltypes.h" #include "kernel/utils.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct CheckPass : public Pass { CheckPass() : Pass("check", "check for obvious problems in the design") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" check [selection]\n"); log("\n"); log("This pass identifies the following problems in the current design:\n"); log("\n"); log(" - combinatorical loops\n"); log("\n"); log(" - two or more conflicting drivers for one wire\n"); log("\n"); log(" - used wires that do not have a driver\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { int counter = 0; log_header("Executing CHECK pass (checking for obvious problems).\n"); extra_args(args, 1, design); for (auto module : design->selected_whole_modules_warn()) { if (module->has_processes_warn()) continue; log("checking module %s..\n", log_id(module)); SigMap sigmap(module); dict<SigBit, vector<string>> wire_drivers; pool<SigBit> used_wires; TopoSort<string> topo; for (auto cell : module->cells()) for (auto &conn : cell->connections()) { SigSpec sig = sigmap(conn.second); bool logic_cell = yosys_celltypes.cell_evaluable(cell->type); if (cell->input(conn.first)) for (auto bit : sig) if (bit.wire) { if (logic_cell) topo.edge(stringf("wire %s", log_signal(bit)), stringf("cell %s (%s)", log_id(cell), log_id(cell->type))); used_wires.insert(bit); } if (cell->output(conn.first)) for (int i = 0; i < GetSize(sig); i++) { if (logic_cell) topo.edge(stringf("cell %s (%s)", log_id(cell), log_id(cell->type)), stringf("wire %s", log_signal(sig[i]))); wire_drivers[sig[i]].push_back(stringf("port %s[%d] of cell %s (%s)", log_id(conn.first), i, log_id(cell), log_id(cell->type))); } } for (auto wire : module->wires()) { if (wire->port_input) { SigSpec sig = sigmap(wire); for (int i = 0; i < GetSize(sig); i++) wire_drivers[sig[i]].push_back(stringf("module input %s[%d]", log_id(wire), i)); } if (wire->port_output) for (auto bit : sigmap(wire)) used_wires.insert(bit); } for (auto it : wire_drivers) if (GetSize(it.second) > 1) { string message = stringf("multiple conflicting drivers for %s.%s:\n", log_id(module), log_signal(it.first)); for (auto str : it.second) message += stringf(" %s\n", str.c_str()); log_warning("%s", message.c_str()); counter++; } for (auto bit : used_wires) if (!wire_drivers.count(bit)) { log_warning("Wire %s.%s is used but has no driver.\n", log_id(module), log_signal(bit)); counter++; } topo.sort(); for (auto &loop : topo.loops) { string message = stringf("found logic loop in module %s:\n", log_id(module)); for (auto &str : loop) message += stringf(" %s\n", str.c_str()); log_warning("%s", message.c_str()); counter++; } } log("found and reported %d problems.\n", counter); } } CheckPass; PRIVATE_NAMESPACE_END <commit_msg>hotfix in "check" command<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/yosys.h" #include "kernel/sigtools.h" #include "kernel/celltypes.h" #include "kernel/utils.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct CheckPass : public Pass { CheckPass() : Pass("check", "check for obvious problems in the design") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" check [selection]\n"); log("\n"); log("This pass identifies the following problems in the current design:\n"); log("\n"); log(" - combinatorical loops\n"); log("\n"); log(" - two or more conflicting drivers for one wire\n"); log("\n"); log(" - used wires that do not have a driver\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { int counter = 0; log_header("Executing CHECK pass (checking for obvious problems).\n"); extra_args(args, 1, design); for (auto module : design->selected_whole_modules_warn()) { if (module->has_processes_warn()) continue; log("checking module %s..\n", log_id(module)); SigMap sigmap(module); dict<SigBit, vector<string>> wire_drivers; pool<SigBit> used_wires; TopoSort<string> topo; for (auto cell : module->cells()) for (auto &conn : cell->connections()) { SigSpec sig = sigmap(conn.second); bool logic_cell = yosys_celltypes.cell_evaluable(cell->type); if (cell->input(conn.first)) for (auto bit : sig) if (bit.wire) { if (logic_cell) topo.edge(stringf("wire %s", log_signal(bit)), stringf("cell %s (%s)", log_id(cell), log_id(cell->type))); used_wires.insert(bit); } if (cell->output(conn.first)) for (int i = 0; i < GetSize(sig); i++) { if (logic_cell) topo.edge(stringf("cell %s (%s)", log_id(cell), log_id(cell->type)), stringf("wire %s", log_signal(sig[i]))); wire_drivers[sig[i]].push_back(stringf("port %s[%d] of cell %s (%s)", log_id(conn.first), i, log_id(cell), log_id(cell->type))); } } for (auto wire : module->wires()) { if (wire->port_input) { SigSpec sig = sigmap(wire); for (int i = 0; i < GetSize(sig); i++) wire_drivers[sig[i]].push_back(stringf("module input %s[%d]", log_id(wire), i)); } if (wire->port_output) for (auto bit : sigmap(wire)) if (bit.wire) used_wires.insert(bit); } for (auto it : wire_drivers) if (GetSize(it.second) > 1) { string message = stringf("multiple conflicting drivers for %s.%s:\n", log_id(module), log_signal(it.first)); for (auto str : it.second) message += stringf(" %s\n", str.c_str()); log_warning("%s", message.c_str()); counter++; } for (auto bit : used_wires) if (!wire_drivers.count(bit)) { log_warning("Wire %s.%s is used but has no driver.\n", log_id(module), log_signal(bit)); counter++; } topo.sort(); for (auto &loop : topo.loops) { string message = stringf("found logic loop in module %s:\n", log_id(module)); for (auto &str : loop) message += stringf(" %s\n", str.c_str()); log_warning("%s", message.c_str()); counter++; } } log("found and reported %d problems.\n", counter); } } CheckPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/aec3/subtractor.h" #include <algorithm> #include <numeric> #include "api/array_view.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_minmax.h" #include "system_wrappers/include/field_trial.h" namespace webrtc { namespace { bool EnableAgcGainChangeResponse() { return !field_trial::IsEnabled("WebRTC-Aec3AgcGainChangeResponseKillSwitch"); } bool EnableAdaptationDuringSaturation() { return !field_trial::IsEnabled("WebRTC-Aec3RapidAgcGainRecoveryKillSwitch"); } bool EnableMisadjustmentEstimator() { return !field_trial::IsEnabled("WebRTC-Aec3MisadjustmentEstimatorKillSwitch"); } bool EnableShadowFilterJumpstart() { return !field_trial::IsEnabled("WebRTC-Aec3ShadowFilterJumpstartKillSwitch"); } void PredictionError(const Aec3Fft& fft, const FftData& S, rtc::ArrayView<const float> y, std::array<float, kBlockSize>* e, std::array<float, kBlockSize>* s, bool adaptation_during_saturation, bool* saturation) { std::array<float, kFftLength> tmp; fft.Ifft(S, &tmp); constexpr float kScale = 1.0f / kFftLengthBy2; std::transform(y.begin(), y.end(), tmp.begin() + kFftLengthBy2, e->begin(), [&](float a, float b) { return a - b * kScale; }); *saturation = false; if (s) { for (size_t k = 0; k < s->size(); ++k) { (*s)[k] = kScale * tmp[k + kFftLengthBy2]; } auto result = std::minmax_element(s->begin(), s->end()); *saturation = *result.first <= -32768 || *result.first >= 32767; } if (!(*saturation)) { auto result = std::minmax_element(e->begin(), e->end()); *saturation = *result.first <= -32768 || *result.first >= 32767; } if (!adaptation_during_saturation) { std::for_each(e->begin(), e->end(), [](float& a) { a = rtc::SafeClamp(a, -32768.f, 32767.f); }); } else { *saturation = false; } } void ScaleFilterOutput(rtc::ArrayView<const float> y, float factor, rtc::ArrayView<float> e, rtc::ArrayView<float> s) { RTC_DCHECK_EQ(y.size(), e.size()); RTC_DCHECK_EQ(y.size(), s.size()); for (size_t k = 0; k < y.size(); ++k) { s[k] *= factor; e[k] = y[k] - s[k]; } } } // namespace Subtractor::Subtractor(const EchoCanceller3Config& config, ApmDataDumper* data_dumper, Aec3Optimization optimization) : fft_(), data_dumper_(data_dumper), optimization_(optimization), config_(config), adaptation_during_saturation_(EnableAdaptationDuringSaturation()), enable_misadjustment_estimator_(EnableMisadjustmentEstimator()), enable_agc_gain_change_response_(EnableAgcGainChangeResponse()), enable_shadow_filter_jumpstart_(EnableShadowFilterJumpstart()), main_filter_(config_.filter.main.length_blocks, config_.filter.main_initial.length_blocks, config.filter.config_change_duration_blocks, optimization, data_dumper_), shadow_filter_(config_.filter.shadow.length_blocks, config_.filter.shadow_initial.length_blocks, config.filter.config_change_duration_blocks, optimization, data_dumper_), G_main_(config_.filter.main_initial, config_.filter.config_change_duration_blocks), G_shadow_(config_.filter.shadow_initial, config.filter.config_change_duration_blocks) { RTC_DCHECK(data_dumper_); // Currently, the rest of AEC3 requires the main and shadow filter lengths to // be identical. RTC_DCHECK_EQ(config_.filter.main.length_blocks, config_.filter.shadow.length_blocks); RTC_DCHECK_EQ(config_.filter.main_initial.length_blocks, config_.filter.shadow_initial.length_blocks); } Subtractor::~Subtractor() = default; void Subtractor::HandleEchoPathChange( const EchoPathVariability& echo_path_variability) { const auto full_reset = [&]() { main_filter_.HandleEchoPathChange(); shadow_filter_.HandleEchoPathChange(); G_main_.HandleEchoPathChange(echo_path_variability); G_shadow_.HandleEchoPathChange(); G_main_.SetConfig(config_.filter.main_initial, true); G_shadow_.SetConfig(config_.filter.shadow_initial, true); main_filter_.SetSizePartitions(config_.filter.main_initial.length_blocks, true); shadow_filter_.SetSizePartitions( config_.filter.shadow_initial.length_blocks, true); }; if (echo_path_variability.delay_change != EchoPathVariability::DelayAdjustment::kNone) { full_reset(); } if (echo_path_variability.gain_change && enable_agc_gain_change_response_) { RTC_LOG(LS_WARNING) << "Resetting main filter adaptation speed due to " "microphone gain change"; G_main_.HandleEchoPathChange(echo_path_variability); } } void Subtractor::ExitInitialState() { G_main_.SetConfig(config_.filter.main, false); G_shadow_.SetConfig(config_.filter.shadow, false); main_filter_.SetSizePartitions(config_.filter.main.length_blocks, false); shadow_filter_.SetSizePartitions(config_.filter.shadow.length_blocks, false); } void Subtractor::Process(const RenderBuffer& render_buffer, const rtc::ArrayView<const float> capture, const RenderSignalAnalyzer& render_signal_analyzer, const AecState& aec_state, SubtractorOutput* output) { RTC_DCHECK_EQ(kBlockSize, capture.size()); rtc::ArrayView<const float> y = capture; FftData& E_main = output->E_main; FftData E_shadow; std::array<float, kBlockSize>& e_main = output->e_main; std::array<float, kBlockSize>& e_shadow = output->e_shadow; FftData S; FftData& G = S; // Form the outputs of the main and shadow filters. main_filter_.Filter(render_buffer, &S); bool main_saturation = false; PredictionError(fft_, S, y, &e_main, &output->s_main, adaptation_during_saturation_, &main_saturation); shadow_filter_.Filter(render_buffer, &S); bool shadow_saturation = false; PredictionError(fft_, S, y, &e_shadow, &output->s_shadow, adaptation_during_saturation_, &shadow_saturation); // Compute the signal powers in the subtractor output. output->UpdatePowers(y); // Adjust the filter if needed. bool main_filter_adjusted = false; if (enable_misadjustment_estimator_) { filter_misadjustment_estimator_.Update(*output); if (filter_misadjustment_estimator_.IsAdjustmentNeeded()) { float scale = filter_misadjustment_estimator_.GetMisadjustment(); main_filter_.ScaleFilter(scale); ScaleFilterOutput(y, scale, e_main, output->s_main); filter_misadjustment_estimator_.Reset(); main_filter_adjusted = true; } } // Compute the FFts of the main and shadow filter outputs. fft_.ZeroPaddedFft(e_main, Aec3Fft::Window::kHanning, &E_main); fft_.ZeroPaddedFft(e_shadow, Aec3Fft::Window::kHanning, &E_shadow); // Compute spectra for future use. E_shadow.Spectrum(optimization_, output->E2_shadow); E_main.Spectrum(optimization_, output->E2_main); // Update the main filter. std::array<float, kFftLengthBy2Plus1> X2; render_buffer.SpectralSum(main_filter_.SizePartitions(), &X2); if (!main_filter_adjusted) { G_main_.Compute(X2, render_signal_analyzer, *output, main_filter_, aec_state.SaturatedCapture() || main_saturation, &G); } else { G.re.fill(0.f); G.im.fill(0.f); } main_filter_.Adapt(render_buffer, G); data_dumper_->DumpRaw("aec3_subtractor_G_main", G.re); data_dumper_->DumpRaw("aec3_subtractor_G_main", G.im); // Update the shadow filter. poor_shadow_filter_counter_ = output->e2_main < output->e2_shadow ? poor_shadow_filter_counter_ + 1 : 0; if (poor_shadow_filter_counter_ < 10 || !enable_shadow_filter_jumpstart_) { if (shadow_filter_.SizePartitions() != main_filter_.SizePartitions()) { render_buffer.SpectralSum(shadow_filter_.SizePartitions(), &X2); } G_shadow_.Compute(X2, render_signal_analyzer, E_shadow, shadow_filter_.SizePartitions(), aec_state.SaturatedCapture() || shadow_saturation, &G); shadow_filter_.Adapt(render_buffer, G); } else { G.re.fill(0.f); G.im.fill(0.f); poor_shadow_filter_counter_ = 0; shadow_filter_.SetFilter(main_filter_.GetFilter()); } data_dumper_->DumpRaw("aec3_subtractor_G_shadow", G.re); data_dumper_->DumpRaw("aec3_subtractor_G_shadow", G.im); filter_misadjustment_estimator_.Dump(data_dumper_); DumpFilters(); if (adaptation_during_saturation_) { std::for_each(e_main.begin(), e_main.end(), [](float& a) { a = rtc::SafeClamp(a, -32768.f, 32767.f); }); } data_dumper_->DumpWav("aec3_main_filter_output", kBlockSize, &e_main[0], 16000, 1); data_dumper_->DumpWav("aec3_shadow_filter_output", kBlockSize, &e_shadow[0], 16000, 1); } void Subtractor::FilterMisadjustmentEstimator::Update( const SubtractorOutput& output) { e2_acum_ += output.e2_main; y2_acum_ += output.y2; if (++n_blocks_acum_ == n_blocks_) { if (y2_acum_ > n_blocks_ * 200.f * 200.f * kBlockSize) { float update = (e2_acum_ / y2_acum_); if (e2_acum_ > n_blocks_ * 7500.f * 7500.f * kBlockSize) { // Duration equal to blockSizeMs * n_blocks_ * 4. overhang_ = 4; } else { overhang_ = std::max(overhang_ - 1, 0); } if ((update < inv_misadjustment_) || (overhang_ > 0)) { inv_misadjustment_ += 0.1f * (update - inv_misadjustment_); } } e2_acum_ = 0.f; y2_acum_ = 0.f; n_blocks_acum_ = 0; } } void Subtractor::FilterMisadjustmentEstimator::Reset() { e2_acum_ = 0.f; y2_acum_ = 0.f; n_blocks_acum_ = 0; inv_misadjustment_ = 0.f; overhang_ = 0.f; } void Subtractor::FilterMisadjustmentEstimator::Dump( ApmDataDumper* data_dumper) const { data_dumper->DumpRaw("aec3_inv_misadjustment_factor", inv_misadjustment_); } } // namespace webrtc <commit_msg>AEC3: Ensure that the shadow filter is adapted at each block<commit_after>/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/aec3/subtractor.h" #include <algorithm> #include <numeric> #include "api/array_view.h" #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_minmax.h" #include "system_wrappers/include/field_trial.h" namespace webrtc { namespace { bool EnableAgcGainChangeResponse() { return !field_trial::IsEnabled("WebRTC-Aec3AgcGainChangeResponseKillSwitch"); } bool EnableAdaptationDuringSaturation() { return !field_trial::IsEnabled("WebRTC-Aec3RapidAgcGainRecoveryKillSwitch"); } bool EnableMisadjustmentEstimator() { return !field_trial::IsEnabled("WebRTC-Aec3MisadjustmentEstimatorKillSwitch"); } bool EnableShadowFilterJumpstart() { return !field_trial::IsEnabled("WebRTC-Aec3ShadowFilterJumpstartKillSwitch"); } void PredictionError(const Aec3Fft& fft, const FftData& S, rtc::ArrayView<const float> y, std::array<float, kBlockSize>* e, std::array<float, kBlockSize>* s, bool adaptation_during_saturation, bool* saturation) { std::array<float, kFftLength> tmp; fft.Ifft(S, &tmp); constexpr float kScale = 1.0f / kFftLengthBy2; std::transform(y.begin(), y.end(), tmp.begin() + kFftLengthBy2, e->begin(), [&](float a, float b) { return a - b * kScale; }); *saturation = false; if (s) { for (size_t k = 0; k < s->size(); ++k) { (*s)[k] = kScale * tmp[k + kFftLengthBy2]; } auto result = std::minmax_element(s->begin(), s->end()); *saturation = *result.first <= -32768 || *result.first >= 32767; } if (!(*saturation)) { auto result = std::minmax_element(e->begin(), e->end()); *saturation = *result.first <= -32768 || *result.first >= 32767; } if (!adaptation_during_saturation) { std::for_each(e->begin(), e->end(), [](float& a) { a = rtc::SafeClamp(a, -32768.f, 32767.f); }); } else { *saturation = false; } } void ScaleFilterOutput(rtc::ArrayView<const float> y, float factor, rtc::ArrayView<float> e, rtc::ArrayView<float> s) { RTC_DCHECK_EQ(y.size(), e.size()); RTC_DCHECK_EQ(y.size(), s.size()); for (size_t k = 0; k < y.size(); ++k) { s[k] *= factor; e[k] = y[k] - s[k]; } } } // namespace Subtractor::Subtractor(const EchoCanceller3Config& config, ApmDataDumper* data_dumper, Aec3Optimization optimization) : fft_(), data_dumper_(data_dumper), optimization_(optimization), config_(config), adaptation_during_saturation_(EnableAdaptationDuringSaturation()), enable_misadjustment_estimator_(EnableMisadjustmentEstimator()), enable_agc_gain_change_response_(EnableAgcGainChangeResponse()), enable_shadow_filter_jumpstart_(EnableShadowFilterJumpstart()), main_filter_(config_.filter.main.length_blocks, config_.filter.main_initial.length_blocks, config.filter.config_change_duration_blocks, optimization, data_dumper_), shadow_filter_(config_.filter.shadow.length_blocks, config_.filter.shadow_initial.length_blocks, config.filter.config_change_duration_blocks, optimization, data_dumper_), G_main_(config_.filter.main_initial, config_.filter.config_change_duration_blocks), G_shadow_(config_.filter.shadow_initial, config.filter.config_change_duration_blocks) { RTC_DCHECK(data_dumper_); // Currently, the rest of AEC3 requires the main and shadow filter lengths to // be identical. RTC_DCHECK_EQ(config_.filter.main.length_blocks, config_.filter.shadow.length_blocks); RTC_DCHECK_EQ(config_.filter.main_initial.length_blocks, config_.filter.shadow_initial.length_blocks); } Subtractor::~Subtractor() = default; void Subtractor::HandleEchoPathChange( const EchoPathVariability& echo_path_variability) { const auto full_reset = [&]() { main_filter_.HandleEchoPathChange(); shadow_filter_.HandleEchoPathChange(); G_main_.HandleEchoPathChange(echo_path_variability); G_shadow_.HandleEchoPathChange(); G_main_.SetConfig(config_.filter.main_initial, true); G_shadow_.SetConfig(config_.filter.shadow_initial, true); main_filter_.SetSizePartitions(config_.filter.main_initial.length_blocks, true); shadow_filter_.SetSizePartitions( config_.filter.shadow_initial.length_blocks, true); }; if (echo_path_variability.delay_change != EchoPathVariability::DelayAdjustment::kNone) { full_reset(); } if (echo_path_variability.gain_change && enable_agc_gain_change_response_) { RTC_LOG(LS_WARNING) << "Resetting main filter adaptation speed due to " "microphone gain change"; G_main_.HandleEchoPathChange(echo_path_variability); } } void Subtractor::ExitInitialState() { G_main_.SetConfig(config_.filter.main, false); G_shadow_.SetConfig(config_.filter.shadow, false); main_filter_.SetSizePartitions(config_.filter.main.length_blocks, false); shadow_filter_.SetSizePartitions(config_.filter.shadow.length_blocks, false); } void Subtractor::Process(const RenderBuffer& render_buffer, const rtc::ArrayView<const float> capture, const RenderSignalAnalyzer& render_signal_analyzer, const AecState& aec_state, SubtractorOutput* output) { RTC_DCHECK_EQ(kBlockSize, capture.size()); rtc::ArrayView<const float> y = capture; FftData& E_main = output->E_main; FftData E_shadow; std::array<float, kBlockSize>& e_main = output->e_main; std::array<float, kBlockSize>& e_shadow = output->e_shadow; FftData S; FftData& G = S; // Form the outputs of the main and shadow filters. main_filter_.Filter(render_buffer, &S); bool main_saturation = false; PredictionError(fft_, S, y, &e_main, &output->s_main, adaptation_during_saturation_, &main_saturation); shadow_filter_.Filter(render_buffer, &S); bool shadow_saturation = false; PredictionError(fft_, S, y, &e_shadow, &output->s_shadow, adaptation_during_saturation_, &shadow_saturation); // Compute the signal powers in the subtractor output. output->UpdatePowers(y); // Adjust the filter if needed. bool main_filter_adjusted = false; if (enable_misadjustment_estimator_) { filter_misadjustment_estimator_.Update(*output); if (filter_misadjustment_estimator_.IsAdjustmentNeeded()) { float scale = filter_misadjustment_estimator_.GetMisadjustment(); main_filter_.ScaleFilter(scale); ScaleFilterOutput(y, scale, e_main, output->s_main); filter_misadjustment_estimator_.Reset(); main_filter_adjusted = true; } } // Compute the FFts of the main and shadow filter outputs. fft_.ZeroPaddedFft(e_main, Aec3Fft::Window::kHanning, &E_main); fft_.ZeroPaddedFft(e_shadow, Aec3Fft::Window::kHanning, &E_shadow); // Compute spectra for future use. E_shadow.Spectrum(optimization_, output->E2_shadow); E_main.Spectrum(optimization_, output->E2_main); // Update the main filter. std::array<float, kFftLengthBy2Plus1> X2; render_buffer.SpectralSum(main_filter_.SizePartitions(), &X2); if (!main_filter_adjusted) { G_main_.Compute(X2, render_signal_analyzer, *output, main_filter_, aec_state.SaturatedCapture() || main_saturation, &G); } else { G.re.fill(0.f); G.im.fill(0.f); } main_filter_.Adapt(render_buffer, G); data_dumper_->DumpRaw("aec3_subtractor_G_main", G.re); data_dumper_->DumpRaw("aec3_subtractor_G_main", G.im); // Update the shadow filter. poor_shadow_filter_counter_ = output->e2_main < output->e2_shadow ? poor_shadow_filter_counter_ + 1 : 0; if (poor_shadow_filter_counter_ < 10 || !enable_shadow_filter_jumpstart_) { if (shadow_filter_.SizePartitions() != main_filter_.SizePartitions()) { render_buffer.SpectralSum(shadow_filter_.SizePartitions(), &X2); } G_shadow_.Compute(X2, render_signal_analyzer, E_shadow, shadow_filter_.SizePartitions(), aec_state.SaturatedCapture() || shadow_saturation, &G); shadow_filter_.Adapt(render_buffer, G); } else { G.re.fill(0.f); G.im.fill(0.f); poor_shadow_filter_counter_ = 0; shadow_filter_.Adapt(render_buffer, G); shadow_filter_.SetFilter(main_filter_.GetFilter()); } data_dumper_->DumpRaw("aec3_subtractor_G_shadow", G.re); data_dumper_->DumpRaw("aec3_subtractor_G_shadow", G.im); filter_misadjustment_estimator_.Dump(data_dumper_); DumpFilters(); if (adaptation_during_saturation_) { std::for_each(e_main.begin(), e_main.end(), [](float& a) { a = rtc::SafeClamp(a, -32768.f, 32767.f); }); } data_dumper_->DumpWav("aec3_main_filter_output", kBlockSize, &e_main[0], 16000, 1); data_dumper_->DumpWav("aec3_shadow_filter_output", kBlockSize, &e_shadow[0], 16000, 1); } void Subtractor::FilterMisadjustmentEstimator::Update( const SubtractorOutput& output) { e2_acum_ += output.e2_main; y2_acum_ += output.y2; if (++n_blocks_acum_ == n_blocks_) { if (y2_acum_ > n_blocks_ * 200.f * 200.f * kBlockSize) { float update = (e2_acum_ / y2_acum_); if (e2_acum_ > n_blocks_ * 7500.f * 7500.f * kBlockSize) { // Duration equal to blockSizeMs * n_blocks_ * 4. overhang_ = 4; } else { overhang_ = std::max(overhang_ - 1, 0); } if ((update < inv_misadjustment_) || (overhang_ > 0)) { inv_misadjustment_ += 0.1f * (update - inv_misadjustment_); } } e2_acum_ = 0.f; y2_acum_ = 0.f; n_blocks_acum_ = 0; } } void Subtractor::FilterMisadjustmentEstimator::Reset() { e2_acum_ = 0.f; y2_acum_ = 0.f; n_blocks_acum_ = 0; inv_misadjustment_ = 0.f; overhang_ = 0.f; } void Subtractor::FilterMisadjustmentEstimator::Dump( ApmDataDumper* data_dumper) const { data_dumper->DumpRaw("aec3_inv_misadjustment_factor", inv_misadjustment_); } } // namespace webrtc <|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/map/relative_map/navigation_lane.h" #include <algorithm> #include <limits> #include "modules/map/proto/map_lane.pb.h" #include "modules/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/relative_map/common/relative_map_gflags.h" namespace apollo { namespace relative_map { using apollo::common::VehicleStateProvider; using apollo::common::math::Vec2d; using apollo::common::util::DistanceXY; using apollo::hdmap::Lane; using apollo::common::util::operator+; using apollo::perception::PerceptionObstacles; NavigationLane::NavigationLane(const NavigationLaneConfig &config) : config_(config) {} void NavigationLane::SetConfig(const NavigationLaneConfig &config) { config_ = config; } bool NavigationLane::GeneratePath() { // original_pose is in world coordination: ENU original_pose_ = VehicleStateProvider::instance()->original_pose(); navigation_path_.Clear(); auto *path = navigation_path_.mutable_path(); const auto &lane_marker = perception_obstacles_.lane_marker(); // priority: merge > navigation line > perception lane marker if (FLAGS_enable_navigation_line && navigation_info_.navigation_path_size() > 0) { ConvertNavigationLineToPath(path); if (path->path_point().size() <= 0) { ConvertLaneMarkerToPath(lane_marker, path); } } else { ConvertLaneMarkerToPath(lane_marker, path); } return true; } double NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1, const double c2, const double c3, const double z) const { return ((c3 * z + c2) * z + c1) * z + c0; } void NavigationLane::MergeNavigationLineAndLaneMarker( const perception::LaneMarkers &lane_marker, common::Path *path) { CHECK_NOTNULL(path); common::Path navigation_path; ConvertNavigationLineToPath(&navigation_path); common::Path lane_marker_path; ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(), &lane_marker_path); const double len = std::fmin( navigation_path.path_point(navigation_path.path_point_size() - 1).s(), lane_marker_path.path_point(lane_marker_path.path_point_size() - 1).s()); const double ds = 1.0; int navigation_index = 0; int lane_marker_index = 0; for (double s = 0.0; s < len; s += ds) { auto p1 = GetPathPointByS(navigation_path, navigation_index, s, &navigation_index); auto p2 = GetPathPointByS(lane_marker_path, lane_marker_index, s, &lane_marker_index); auto *p = path->add_path_point(); const double kWeight = 0.9; *p = common::util::GetWeightedAverageOfTwoPathPoints(p1, p2, kWeight, 1 - kWeight); } } common::PathPoint NavigationLane::GetPathPointByS(const common::Path &path, const int start_index, const double s, int *matched_index) { CHECK_NOTNULL(matched_index); constexpr double kEpsilon = 1e-9; if (std::fabs(path.path_point(start_index).s() - s) < kEpsilon) { *matched_index = start_index; return path.path_point(start_index); } int i = start_index; while (i + 1 < path.path_point_size() && path.path_point(i + 1).s() < s) { ++i; } *matched_index = i; // x, y, z, theta, kappa, s, dkappa, ddkappa const double r = (s - path.path_point(i).s()) / (path.path_point(i + 1).s() - path.path_point(i).s()); auto p = common::util::GetWeightedAverageOfTwoPathPoints( path.path_point(i), path.path_point(i + 1), 1 - r, r); return p; } void NavigationLane::ConvertNavigationLineToPath(common::Path *path) { CHECK_NOTNULL(path); if (navigation_info_.navigation_path_size() == 0 || !navigation_info_.navigation_path(0).has_path() || navigation_info_.navigation_path(0).path().path_point_size() == 0) { // path is empty return; } path->set_name("Path from navigation."); UpdateProjectionIndex(); // TODO(All): support multiple navigation path // currently, only 1 navigation path is supported const auto &navigation_path = navigation_info_.navigation_path(0).path(); int curr_project_index = last_project_index_; double dist = navigation_path.path_point(navigation_path.path_point_size() - 1).s() - navigation_path.path_point(curr_project_index).s(); if (dist < 20) { return; } // offset between the current vehicle state and navigation line const double dx = -original_pose_.position().x(); const double dy = -original_pose_.position().y(); const double ref_s = navigation_path.path_point(curr_project_index).s(); for (int i = std::max(0, curr_project_index - 3); i < navigation_path.path_point_size(); ++i) { auto *point = path->add_path_point(); point->CopyFrom(navigation_path.path_point(i)); // shift to (0, 0) double emu_x = point->x() + dx; double emu_y = point->y() + dy; double flu_x = 0.0; double flu_y = 0.0; common::math::RotateAxis(original_pose_.heading(), emu_x, emu_y, &flu_x, &flu_y); point->set_x(flu_x); point->set_y(flu_y); point->set_theta(point->theta() - original_pose_.heading()); const double accumulated_s = navigation_path.path_point(i).s() - ref_s; point->set_s(accumulated_s); if (accumulated_s > FLAGS_max_len_from_navigation_line) { break; } } const perception::LaneMarkers &lane_marker = perception_obstacles_.lane_marker(); const auto &left_lane = lane_marker.left_lane_marker(); const auto &right_lane = lane_marker.right_lane_marker(); left_width_ = (std::fabs(left_lane.c0_position()) + std::fabs(right_lane.c0_position())) / 2.0; right_width_ = left_width_; } // project adc_state_ onto path void NavigationLane::UpdateProjectionIndex() { // TODO(All): support multiple navigation path // currently, only 1 navigation path is supported const auto &path = navigation_info_.navigation_path(0).path(); int index = 0; double min_d = std::numeric_limits<double>::max(); for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) { const double d = DistanceXY(original_pose_.position(), path.path_point(i)); if (d < min_d) { min_d = d; index = i; } const double kMaxDistance = 50.0; if (last_project_index_ != 0 && d > kMaxDistance) { break; } } last_project_index_ = index; } void NavigationLane::ConvertLaneMarkerToPath( const perception::LaneMarkers &lane_marker, common::Path *path) { CHECK_NOTNULL(path); path->set_name("Path from lane markers."); const auto &left_lane = lane_marker.left_lane_marker(); const auto &right_lane = lane_marker.right_lane_marker(); double path_c0 = (left_lane.c0_position() + right_lane.c0_position()) / 2.0; double left_quality = left_lane.quality() + 0.001; double right_quality = right_lane.quality() + 0.001; double quality_divider = left_quality + right_quality; double path_c1 = (left_lane.c1_heading_angle() * left_quality + right_lane.c1_heading_angle() * right_quality) / quality_divider; double path_c2 = (left_lane.c2_curvature() * left_quality + right_lane.c2_curvature() * right_quality) / quality_divider; double path_c3 = (left_lane.c3_curvature_derivative() * left_lane.quality() + right_lane.c3_curvature_derivative() * left_lane.quality()) / quality_divider; const double current_speed = VehicleStateProvider::instance()->vehicle_state().linear_velocity(); double path_range = current_speed * FLAGS_ratio_navigation_lane_len_to_speed; if (path_range <= FLAGS_min_len_for_navigation_lane) { path_range = FLAGS_min_len_for_navigation_lane; } else { path_range = FLAGS_max_len_for_navigation_lane; } const double unit_z = 1.0; const double start_s = -2.0; double accumulated_s = start_s; for (double z = start_s; z <= path_range; z += unit_z) { double x_l = EvaluateCubicPolynomial(path_c0, path_c1, path_c2, path_c3, z); double x1 = z; double y1 = x_l; auto *point = path->add_path_point(); point->set_x(x1); point->set_y(y1); if (path->path_point_size() > 1) { auto &pre_point = path->path_point(path->path_point_size() - 2); accumulated_s += std::hypot(x1 - pre_point.x(), y1 - pre_point.y()); } point->set_s(accumulated_s); } left_width_ = (std::fabs(left_lane.c0_position()) + std::fabs(right_lane.c0_position())) / 2.0; right_width_ = left_width_; } bool NavigationLane::CreateMap(const MapGenerationParam &map_config, MapMsg *map_msg) const { auto *navigation_info = map_msg->mutable_navigation_path(); auto *hdmap = map_msg->mutable_hdmap(); auto *lane_marker = map_msg->mutable_lane_marker(); lane_marker->CopyFrom(perception_obstacles_.lane_marker()); const auto &path = navigation_path_.path(); if (path.path_point_size() < 2) { AERROR << "The path length is invalid"; return false; } auto *lane = hdmap->add_lane(); lane->mutable_id()->set_id(std::to_string(navigation_path_.path_priority()) + "_" + path.name()); (*navigation_info)[lane->id().id()] = navigation_path_; // lane types lane->set_type(Lane::CITY_DRIVING); lane->set_turn(Lane::NO_TURN); // speed limit lane->set_speed_limit(map_config.default_speed_limit()); // center line auto *curve_segment = lane->mutable_central_curve()->add_segment(); curve_segment->set_heading(path.path_point(0).theta()); auto *line_segment = curve_segment->mutable_line_segment(); // left boundary auto *left_boundary = lane->mutable_left_boundary(); auto *left_boundary_type = left_boundary->add_boundary_type(); left_boundary->set_virtual_(false); left_boundary_type->set_s(0.0); left_boundary_type->add_types( perception_obstacles_.lane_marker().left_lane_marker().lane_type()); auto *left_segment = left_boundary->mutable_curve()->add_segment()->mutable_line_segment(); // right boundary auto *right_boundary = lane->mutable_right_boundary(); auto *right_boundary_type = right_boundary->add_boundary_type(); right_boundary->set_virtual_(false); right_boundary_type->set_s(0.0); right_boundary_type->add_types( perception_obstacles_.lane_marker().right_lane_marker().lane_type()); auto *right_segment = right_boundary->mutable_curve()->add_segment()->mutable_line_segment(); const double lane_left_width = left_width_ > 0 ? left_width_ : map_config.default_left_width(); const double lane_right_width = right_width_ > 0 ? right_width_ : map_config.default_right_width(); for (const auto &path_point : path.path_point()) { auto *point = line_segment->add_point(); point->set_x(path_point.x()); point->set_y(path_point.y()); point->set_z(path_point.z()); auto *left_sample = lane->add_left_sample(); left_sample->set_s(path_point.s()); left_sample->set_width(lane_left_width); left_segment->add_point()->CopyFrom( *point + lane_left_width * Vec2d::CreateUnitVec2d(path_point.theta() + M_PI_2)); auto *right_sample = lane->add_right_sample(); right_sample->set_s(path_point.s()); right_sample->set_width(lane_right_width); right_segment->add_point()->CopyFrom( *point + lane_right_width * Vec2d::CreateUnitVec2d(path_point.theta() - M_PI_2)); } return true; } } // namespace relative_map } // namespace apollo <commit_msg>navi: fixed bug for converting lane markers to ref line (#3186)<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/map/relative_map/navigation_lane.h" #include <algorithm> #include <limits> #include "modules/map/proto/map_lane.pb.h" #include "modules/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/relative_map/common/relative_map_gflags.h" namespace apollo { namespace relative_map { using apollo::common::VehicleStateProvider; using apollo::common::math::Vec2d; using apollo::common::util::DistanceXY; using apollo::hdmap::Lane; using apollo::common::util::operator+; using apollo::perception::PerceptionObstacles; NavigationLane::NavigationLane(const NavigationLaneConfig &config) : config_(config) {} void NavigationLane::SetConfig(const NavigationLaneConfig &config) { config_ = config; } bool NavigationLane::GeneratePath() { // original_pose is in world coordination: ENU original_pose_ = VehicleStateProvider::instance()->original_pose(); navigation_path_.Clear(); auto *path = navigation_path_.mutable_path(); const auto &lane_marker = perception_obstacles_.lane_marker(); // priority: merge > navigation line > perception lane marker if (FLAGS_enable_navigation_line && navigation_info_.navigation_path_size() > 0) { ConvertNavigationLineToPath(path); if (path->path_point().size() <= 0) { ConvertLaneMarkerToPath(lane_marker, path); } } else { ConvertLaneMarkerToPath(lane_marker, path); } return true; } double NavigationLane::EvaluateCubicPolynomial(const double c0, const double c1, const double c2, const double c3, const double z) const { return ((c3 * z + c2) * z + c1) * z + c0; } void NavigationLane::MergeNavigationLineAndLaneMarker( const perception::LaneMarkers &lane_marker, common::Path *path) { CHECK_NOTNULL(path); common::Path navigation_path; ConvertNavigationLineToPath(&navigation_path); common::Path lane_marker_path; ConvertLaneMarkerToPath(perception_obstacles_.lane_marker(), &lane_marker_path); const double len = std::fmin( navigation_path.path_point(navigation_path.path_point_size() - 1).s(), lane_marker_path.path_point(lane_marker_path.path_point_size() - 1).s()); const double ds = 1.0; int navigation_index = 0; int lane_marker_index = 0; for (double s = 0.0; s < len; s += ds) { auto p1 = GetPathPointByS(navigation_path, navigation_index, s, &navigation_index); auto p2 = GetPathPointByS(lane_marker_path, lane_marker_index, s, &lane_marker_index); auto *p = path->add_path_point(); const double kWeight = 0.9; *p = common::util::GetWeightedAverageOfTwoPathPoints(p1, p2, kWeight, 1 - kWeight); } } common::PathPoint NavigationLane::GetPathPointByS(const common::Path &path, const int start_index, const double s, int *matched_index) { CHECK_NOTNULL(matched_index); constexpr double kEpsilon = 1e-9; if (std::fabs(path.path_point(start_index).s() - s) < kEpsilon) { *matched_index = start_index; return path.path_point(start_index); } int i = start_index; while (i + 1 < path.path_point_size() && path.path_point(i + 1).s() < s) { ++i; } *matched_index = i; // x, y, z, theta, kappa, s, dkappa, ddkappa const double r = (s - path.path_point(i).s()) / (path.path_point(i + 1).s() - path.path_point(i).s()); auto p = common::util::GetWeightedAverageOfTwoPathPoints( path.path_point(i), path.path_point(i + 1), 1 - r, r); return p; } void NavigationLane::ConvertNavigationLineToPath(common::Path *path) { CHECK_NOTNULL(path); if (navigation_info_.navigation_path_size() == 0 || !navigation_info_.navigation_path(0).has_path() || navigation_info_.navigation_path(0).path().path_point_size() == 0) { // path is empty return; } path->set_name("Path from navigation."); UpdateProjectionIndex(); // TODO(All): support multiple navigation path // currently, only 1 navigation path is supported const auto &navigation_path = navigation_info_.navigation_path(0).path(); int curr_project_index = last_project_index_; double dist = navigation_path.path_point(navigation_path.path_point_size() - 1).s() - navigation_path.path_point(curr_project_index).s(); if (dist < 20) { return; } // offset between the current vehicle state and navigation line const double dx = -original_pose_.position().x(); const double dy = -original_pose_.position().y(); const double ref_s = navigation_path.path_point(curr_project_index).s(); for (int i = std::max(0, curr_project_index - 3); i < navigation_path.path_point_size(); ++i) { auto *point = path->add_path_point(); point->CopyFrom(navigation_path.path_point(i)); // shift to (0, 0) double emu_x = point->x() + dx; double emu_y = point->y() + dy; double flu_x = 0.0; double flu_y = 0.0; common::math::RotateAxis(original_pose_.heading(), emu_x, emu_y, &flu_x, &flu_y); point->set_x(flu_x); point->set_y(flu_y); point->set_theta(point->theta() - original_pose_.heading()); const double accumulated_s = navigation_path.path_point(i).s() - ref_s; point->set_s(accumulated_s); if (accumulated_s > FLAGS_max_len_from_navigation_line) { break; } } const perception::LaneMarkers &lane_marker = perception_obstacles_.lane_marker(); const auto &left_lane = lane_marker.left_lane_marker(); const auto &right_lane = lane_marker.right_lane_marker(); left_width_ = (std::fabs(left_lane.c0_position()) + std::fabs(right_lane.c0_position())) / 2.0; right_width_ = left_width_; } // project adc_state_ onto path void NavigationLane::UpdateProjectionIndex() { // TODO(All): support multiple navigation path // currently, only 1 navigation path is supported const auto &path = navigation_info_.navigation_path(0).path(); int index = 0; double min_d = std::numeric_limits<double>::max(); for (int i = last_project_index_; i + 1 < path.path_point_size(); ++i) { const double d = DistanceXY(original_pose_.position(), path.path_point(i)); if (d < min_d) { min_d = d; index = i; } const double kMaxDistance = 50.0; if (last_project_index_ != 0 && d > kMaxDistance) { break; } } last_project_index_ = index; } void NavigationLane::ConvertLaneMarkerToPath( const perception::LaneMarkers &lane_marker, common::Path *path) { CHECK_NOTNULL(path); path->set_name("Path from lane markers."); const auto &left_lane = lane_marker.left_lane_marker(); const auto &right_lane = lane_marker.right_lane_marker(); double path_c0 = (left_lane.c0_position() + right_lane.c0_position()) / 2.0; double left_quality = left_lane.quality() + 0.001; double right_quality = right_lane.quality() + 0.001; double quality_divider = left_quality + right_quality; double path_c1 = (left_lane.c1_heading_angle() * left_quality + right_lane.c1_heading_angle() * right_quality) / quality_divider; double path_c2 = (left_lane.c2_curvature() * left_quality + right_lane.c2_curvature() * right_quality) / quality_divider; double path_c3 = (left_lane.c3_curvature_derivative() * left_quality + right_lane.c3_curvature_derivative() * right_quality) / quality_divider; const double current_speed = VehicleStateProvider::instance()->vehicle_state().linear_velocity(); double path_range = current_speed * FLAGS_ratio_navigation_lane_len_to_speed; if (path_range <= FLAGS_min_len_for_navigation_lane) { path_range = FLAGS_min_len_for_navigation_lane; } else { path_range = FLAGS_max_len_for_navigation_lane; } const double unit_z = 1.0; const double start_s = -2.0; double accumulated_s = start_s; for (double z = start_s; z <= path_range; z += unit_z) { double x_l = EvaluateCubicPolynomial(path_c0, path_c1, path_c2, path_c3, z); double x1 = z; double y1 = x_l; auto *point = path->add_path_point(); point->set_x(x1); point->set_y(y1); if (path->path_point_size() > 1) { auto &pre_point = path->path_point(path->path_point_size() - 2); accumulated_s += std::hypot(x1 - pre_point.x(), y1 - pre_point.y()); } point->set_s(accumulated_s); } left_width_ = (std::fabs(left_lane.c0_position()) + std::fabs(right_lane.c0_position())) / 2.0; right_width_ = left_width_; } bool NavigationLane::CreateMap(const MapGenerationParam &map_config, MapMsg *map_msg) const { auto *navigation_info = map_msg->mutable_navigation_path(); auto *hdmap = map_msg->mutable_hdmap(); auto *lane_marker = map_msg->mutable_lane_marker(); lane_marker->CopyFrom(perception_obstacles_.lane_marker()); const auto &path = navigation_path_.path(); if (path.path_point_size() < 2) { AERROR << "The path length is invalid"; return false; } auto *lane = hdmap->add_lane(); lane->mutable_id()->set_id(std::to_string(navigation_path_.path_priority()) + "_" + path.name()); (*navigation_info)[lane->id().id()] = navigation_path_; // lane types lane->set_type(Lane::CITY_DRIVING); lane->set_turn(Lane::NO_TURN); // speed limit lane->set_speed_limit(map_config.default_speed_limit()); // center line auto *curve_segment = lane->mutable_central_curve()->add_segment(); curve_segment->set_heading(path.path_point(0).theta()); auto *line_segment = curve_segment->mutable_line_segment(); // left boundary auto *left_boundary = lane->mutable_left_boundary(); auto *left_boundary_type = left_boundary->add_boundary_type(); left_boundary->set_virtual_(false); left_boundary_type->set_s(0.0); left_boundary_type->add_types( perception_obstacles_.lane_marker().left_lane_marker().lane_type()); auto *left_segment = left_boundary->mutable_curve()->add_segment()->mutable_line_segment(); // right boundary auto *right_boundary = lane->mutable_right_boundary(); auto *right_boundary_type = right_boundary->add_boundary_type(); right_boundary->set_virtual_(false); right_boundary_type->set_s(0.0); right_boundary_type->add_types( perception_obstacles_.lane_marker().right_lane_marker().lane_type()); auto *right_segment = right_boundary->mutable_curve()->add_segment()->mutable_line_segment(); const double lane_left_width = left_width_ > 0 ? left_width_ : map_config.default_left_width(); const double lane_right_width = right_width_ > 0 ? right_width_ : map_config.default_right_width(); for (const auto &path_point : path.path_point()) { auto *point = line_segment->add_point(); point->set_x(path_point.x()); point->set_y(path_point.y()); point->set_z(path_point.z()); auto *left_sample = lane->add_left_sample(); left_sample->set_s(path_point.s()); left_sample->set_width(lane_left_width); left_segment->add_point()->CopyFrom( *point + lane_left_width * Vec2d::CreateUnitVec2d(path_point.theta() + M_PI_2)); auto *right_sample = lane->add_right_sample(); right_sample->set_s(path_point.s()); right_sample->set_width(lane_right_width); right_segment->add_point()->CopyFrom( *point + lane_right_width * Vec2d::CreateUnitVec2d(path_point.theta() - M_PI_2)); } return true; } } // namespace relative_map } // namespace apollo <|endoftext|>
<commit_before>#ifndef MRR_CHILD_PROCESS_HXX_ #define MRR_CHILD_PROCESS_HXX_ #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- namespace mrr { namespace posix { //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- struct fork_failed { }; //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- template <typename Function> struct child_process { using function_type = Function; using pid_type = pid_t; using status_type = int; child_process(function_type const& func) : func_(func), pid_(-1), status_(-1), waited_for(false) { } child_process(child_process const& cp) : child_process(cp.func_) { } ~child_process() { this->wait(); } child_process& operator =(child_process const& cp) { func_ = cp.func_; pid_= -1; status_ = -1; waited_for = false; } template <typename... FuncArgs> void fork(FuncArgs&&... args) { pid_ = ::fork(); if(pid_ == 0) { func_(std::forward<FuncArgs>(args)...); std::exit(0); } } void wait(int options = 0) { if(pid_ != 0 && !waited_for) { ::waitpid(pid_, &status_, options); waited_for = true; } } pid_type pid() const { return pid_; } status_type status() const { return status_; } private: function_type func_; pid_type pid_; status_type status_; bool waited_for; }; // struct child_process<Function> template <typename Function> inline child_process<Function> make_child_process(Function&& func) { return child_process<Function>(std::forward<Function>(func)); } // child_process<Function> make_child_process() //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- } // namespace posix } // namespace mrr //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #endif // #ifndef MRR_CHILD_PROCESS_HXX_ <commit_msg>Added move constructor and move assignment to child_process<commit_after>#ifndef MRR_CHILD_PROCESS_HXX_ #define MRR_CHILD_PROCESS_HXX_ #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- namespace mrr { namespace posix { //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- struct fork_failed { }; //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- template <typename Function> struct child_process { using function_type = Function; using pid_type = pid_t; using status_type = int; child_process(function_type const& func) : func_(func), pid_(), status_(-1), waited_for(false) { } child_process(child_process const& cp) : child_process(cp.func_) { } child_process(child_process&& cp) : func_(cp.func_), pid_(cp.pid_), status_(cp.status_), waited_for(cp.waited_for) { cp.pid_ = 0; cp.status_ = -1; cp.waited_for = false; } ~child_process() { this->wait(); } child_process& operator =(child_process const& cp) { this->wait(); func_ = cp.func_; pid_= 0; status_ = -1; waited_for = false; return *this; } child_process& operator =(child_process&& cp) { func_ = cp.func_; pid_= cp.pid_; status_ = cp.statu_; waited_for = cp.waited_for; cp.pid_= 0; cp.status_ = -1; cp.waited_for = false; return *this; } template <typename... FuncArgs> void fork(FuncArgs&&... args) { pid_ = ::fork(); if(pid_ == 0) { func_(std::forward<FuncArgs>(args)...); std::exit(0); } } void wait(int options = 0) { if(pid_ != 0 && !waited_for) { ::waitpid(pid_, &status_, options); waited_for = true; } } pid_type pid() const { return pid_; } status_type status() const { return status_; } private: function_type func_; pid_type pid_; status_type status_; bool waited_for; }; // struct child_process<Function> template <typename Function> inline child_process<Function> make_child_process(Function&& func) { return child_process<Function>(std::forward<Function>(func)); } // child_process<Function> make_child_process() //m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- } // namespace posix } // namespace mrr //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #endif // #ifndef MRR_CHILD_PROCESS_HXX_ <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2007 by Jeroen Broekhuizen * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This 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 Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "linuxfilesystem.h" #include <sys/stat.h> #include <dirent.h> #include <stdio.h> #include <fnmatch.h> #include "core/string/string.h" #include "core/defines.h" LinuxFileSystem::LinuxFileSystem(): FileSystem() { } LinuxFileSystem::~LinuxFileSystem() { } int LinuxFileSystem::mkdir(const String& path) { C2D_UNUSED(path); return NO_ERR; } bool LinuxFileSystem::copyFile(const String& from, const String& to) { C2D_UNUSED(from); C2D_UNUSED(to); return true; } bool LinuxFileSystem::moveFile(const String&, const String&) { return true; } bool LinuxFileSystem::deleteFile(const String& filename) { return true; } UChar LinuxFileSystem::getSeparator() const { return L'/'; } bool LinuxFileSystem::doRecurseDirectory(const String& dir, const String& mask, std::vector<String>& result, bool recursive) { std::string path = dir.toUtf8(); std::string searchmask = mask.toUtf8(); const char* pdir = path.c_str(); const char* pmask = searchmask.c_str(); dirent** pentries = NULL; int count = scandir(pdir, &pentries, NULL, alphasort); struct stat s; for ( int index = 0; index < count; index++ ) { dirent& entry = *pentries[index]; String path = dir + L'/' + String::fromUtf8(entry.d_name); stat(path.toUtf8().c_str(), &s); if ( S_ISDIR(s.st_mode) ) { if ( recursive && path != UTEXT(".") && path != UTEXT("..") ) { doRecurseDirectory(path, mask, result, recursive); } } else { if ( fnmatch(pmask, entry.d_name, FNM_PATHNAME) == 0 ) { result.push_back(path); } } } return true; } bool LinuxFileSystem::find(const String& mask, std::vector<String>& result, bool recursive) { String dir; String pattern; int index = mask.lastIndexOf('/'); if ( index != -1 ) { dir = mask.subStr(0, index); pattern = mask.subStr(index+1, mask.length() - index - 1); } else { dir = '.'; pattern = mask; } return doRecurseDirectory(dir, pattern, result, recursive); } <commit_msg>Cov 58174 - check return value of stat<commit_after>/*************************************************************************** * Copyright (C) 2007 by Jeroen Broekhuizen * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This 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 Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "linuxfilesystem.h" #include <sys/stat.h> #include <dirent.h> #include <stdio.h> #include <fnmatch.h> #include "core/log/log.h" #include "core/string/string.h" #include "core/defines.h" LinuxFileSystem::LinuxFileSystem(): FileSystem() { } LinuxFileSystem::~LinuxFileSystem() { } int LinuxFileSystem::mkdir(const String& path) { C2D_UNUSED(path); return NO_ERR; } bool LinuxFileSystem::copyFile(const String& from, const String& to) { C2D_UNUSED(from); C2D_UNUSED(to); return true; } bool LinuxFileSystem::moveFile(const String&, const String&) { return true; } bool LinuxFileSystem::deleteFile(const String& filename) { return true; } UChar LinuxFileSystem::getSeparator() const { return L'/'; } bool LinuxFileSystem::doRecurseDirectory(const String& dir, const String& mask, std::vector<String>& result, bool recursive) { std::string path = dir.toUtf8(); std::string searchmask = mask.toUtf8(); const char* pdir = path.c_str(); const char* pmask = searchmask.c_str(); dirent** pentries = NULL; int count = scandir(pdir, &pentries, NULL, alphasort); struct stat s; for ( int index = 0; index < count; index++ ) { dirent& entry = *pentries[index]; String path = dir + L'/' + String::fromUtf8(entry.d_name); int r = stat(path.toUtf8().c_str(), &s); if ( r == 0 ) { if ( S_ISDIR(s.st_mode) ) { if ( recursive && path != UTEXT(".") && path != UTEXT("..") ) { doRecurseDirectory(path, mask, result, recursive); } } else { if ( fnmatch(pmask, entry.d_name, FNM_PATHNAME) == 0 ) { result.push_back(path); } } } else { Log::getInstance().info("Error getting directory entry stats %s : %d", path.c_str(), errno); } } return true; } bool LinuxFileSystem::find(const String& mask, std::vector<String>& result, bool recursive) { String dir; String pattern; int index = mask.lastIndexOf('/'); if ( index != -1 ) { dir = mask.subStr(0, index); pattern = mask.subStr(index+1, mask.length() - index - 1); } else { dir = '.'; pattern = mask; } return doRecurseDirectory(dir, pattern, result, recursive); } <|endoftext|>
<commit_before>/* * * Copyright 2015-2016 gRPC authors. * * 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 <grpcpp/server_builder.h> #include <grpc/support/cpu.h> #include <grpc/support/log.h> #include <grpcpp/impl/service_type.h> #include <grpcpp/resource_quota.h> #include <grpcpp/server.h> #include <utility> #include "src/core/lib/gpr/useful.h" #include "src/cpp/server/thread_pool_interface.h" namespace grpc { static std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>* g_plugin_factory_list; static gpr_once once_init_plugin_list = GPR_ONCE_INIT; static void do_plugin_list_init(void) { g_plugin_factory_list = new std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>(); } ServerBuilder::ServerBuilder() : max_receive_message_size_(INT_MIN), max_send_message_size_(INT_MIN), sync_server_settings_(SyncServerSettings()), resource_quota_(nullptr), generic_service_(nullptr) { gpr_once_init(&once_init_plugin_list, do_plugin_list_init); for (auto it = g_plugin_factory_list->begin(); it != g_plugin_factory_list->end(); it++) { auto& factory = *it; plugins_.emplace_back(factory()); } // all compression algorithms enabled by default. enabled_compression_algorithms_bitset_ = (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1; memset(&maybe_default_compression_level_, 0, sizeof(maybe_default_compression_level_)); memset(&maybe_default_compression_algorithm_, 0, sizeof(maybe_default_compression_algorithm_)); } ServerBuilder::~ServerBuilder() { if (resource_quota_ != nullptr) { grpc_resource_quota_unref(resource_quota_); } } std::unique_ptr<ServerCompletionQueue> ServerBuilder::AddCompletionQueue( bool is_frequently_polled) { ServerCompletionQueue* cq = new ServerCompletionQueue( GRPC_CQ_NEXT, is_frequently_polled ? GRPC_CQ_DEFAULT_POLLING : GRPC_CQ_NON_LISTENING, nullptr); cqs_.push_back(cq); return std::unique_ptr<ServerCompletionQueue>(cq); } ServerBuilder& ServerBuilder::RegisterService(Service* service) { services_.emplace_back(new NamedService(service)); return *this; } ServerBuilder& ServerBuilder::RegisterService(const grpc::string& addr, Service* service) { services_.emplace_back(new NamedService(addr, service)); return *this; } ServerBuilder& ServerBuilder::RegisterAsyncGenericService( AsyncGenericService* service) { if (generic_service_) { gpr_log(GPR_ERROR, "Adding multiple AsyncGenericService is unsupported for now. " "Dropping the service %p", (void*)service); } else { generic_service_ = service; } return *this; } ServerBuilder& ServerBuilder::SetOption( std::unique_ptr<ServerBuilderOption> option) { options_.push_back(std::move(option)); return *this; } ServerBuilder& ServerBuilder::SetSyncServerOption( ServerBuilder::SyncServerOption option, int val) { switch (option) { case NUM_CQS: sync_server_settings_.num_cqs = val; break; case MIN_POLLERS: sync_server_settings_.min_pollers = val; break; case MAX_POLLERS: sync_server_settings_.max_pollers = val; break; case CQ_TIMEOUT_MSEC: sync_server_settings_.cq_timeout_msec = val; break; } return *this; } ServerBuilder& ServerBuilder::SetCompressionAlgorithmSupportStatus( grpc_compression_algorithm algorithm, bool enabled) { if (enabled) { GPR_BITSET(&enabled_compression_algorithms_bitset_, algorithm); } else { GPR_BITCLEAR(&enabled_compression_algorithms_bitset_, algorithm); } return *this; } ServerBuilder& ServerBuilder::SetDefaultCompressionLevel( grpc_compression_level level) { maybe_default_compression_level_.level = level; return *this; } ServerBuilder& ServerBuilder::SetDefaultCompressionAlgorithm( grpc_compression_algorithm algorithm) { maybe_default_compression_algorithm_.is_set = true; maybe_default_compression_algorithm_.algorithm = algorithm; return *this; } ServerBuilder& ServerBuilder::SetResourceQuota( const grpc::ResourceQuota& resource_quota) { if (resource_quota_ != nullptr) { grpc_resource_quota_unref(resource_quota_); } resource_quota_ = resource_quota.c_resource_quota(); grpc_resource_quota_ref(resource_quota_); return *this; } ServerBuilder& ServerBuilder::AddListeningPort( const grpc::string& addr_uri, std::shared_ptr<ServerCredentials> creds, int* selected_port) { const grpc::string uri_scheme = "dns:"; grpc::string addr = addr_uri; if (addr_uri.compare(0, uri_scheme.size(), uri_scheme) == 0) { size_t pos = uri_scheme.size(); while (addr_uri[pos] == '/') ++pos; // Skip slashes. addr = addr_uri.substr(pos); } Port port = {addr, std::move(creds), selected_port}; ports_.push_back(port); return *this; } std::unique_ptr<Server> ServerBuilder::BuildAndStart() { ChannelArguments args; for (auto option = options_.begin(); option != options_.end(); ++option) { (*option)->UpdateArguments(&args); (*option)->UpdatePlugins(&plugins_); } for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin)->UpdateServerBuilder(this); (*plugin)->UpdateChannelArguments(&args); } if (max_receive_message_size_ >= -1) { args.SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, max_receive_message_size_); } // The default message size is -1 (max), so no need to explicitly set it for // -1. if (max_send_message_size_ >= 0) { args.SetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH, max_send_message_size_); } args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET, enabled_compression_algorithms_bitset_); if (maybe_default_compression_level_.is_set) { args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL, maybe_default_compression_level_.level); } if (maybe_default_compression_algorithm_.is_set) { args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, maybe_default_compression_algorithm_.algorithm); } if (resource_quota_ != nullptr) { args.SetPointerWithVtable(GRPC_ARG_RESOURCE_QUOTA, resource_quota_, grpc_resource_quota_arg_vtable()); } // == Determine if the server has any syncrhonous methods == bool has_sync_methods = false; for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_synchronous_methods()) { has_sync_methods = true; break; } } if (!has_sync_methods) { for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { if ((*plugin)->has_sync_methods()) { has_sync_methods = true; break; } } } // If this is a Sync server, i.e a server expositing sync API, then the server // needs to create some completion queues to listen for incoming requests. // 'sync_server_cqs' are those internal completion queues. // // This is different from the completion queues added to the server via // ServerBuilder's AddCompletionQueue() method (those completion queues // are in 'cqs_' member variable of ServerBuilder object) std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>> sync_server_cqs(std::make_shared< std::vector<std::unique_ptr<ServerCompletionQueue>>>()); int num_frequently_polled_cqs = 0; for (auto it = cqs_.begin(); it != cqs_.end(); ++it) { if ((*it)->IsFrequentlyPolled()) { num_frequently_polled_cqs++; } } const bool is_hybrid_server = has_sync_methods && num_frequently_polled_cqs > 0; if (has_sync_methods) { grpc_cq_polling_type polling_type = is_hybrid_server ? GRPC_CQ_NON_POLLING : GRPC_CQ_DEFAULT_POLLING; // Create completion queues to listen to incoming rpc requests for (int i = 0; i < sync_server_settings_.num_cqs; i++) { sync_server_cqs->emplace_back( new ServerCompletionQueue(GRPC_CQ_NEXT, polling_type, nullptr)); } } // == Determine if the server has any callback methods == bool has_callback_methods = false; for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_callback_methods()) { has_callback_methods = true; break; } } // TODO(vjpai): Add a section here for plugins once they can support callback // methods if (has_sync_methods) { // This is a Sync server gpr_log(GPR_INFO, "Synchronous server. Num CQs: %d, Min pollers: %d, Max Pollers: " "%d, CQ timeout (msec): %d", sync_server_settings_.num_cqs, sync_server_settings_.min_pollers, sync_server_settings_.max_pollers, sync_server_settings_.cq_timeout_msec); } if (has_callback_methods) { gpr_log(GPR_INFO, "Callback server."); } std::unique_ptr<Server> server(new Server( max_receive_message_size_, &args, sync_server_cqs, sync_server_settings_.min_pollers, sync_server_settings_.max_pollers, sync_server_settings_.cq_timeout_msec, resource_quota_, std::move(interceptor_creators_))); ServerInitializer* initializer = server->initializer(); // Register all the completion queues with the server. i.e // 1. sync_server_cqs: internal completion queues created IF this is a sync // server // 2. cqs_: Completion queues added via AddCompletionQueue() call for (auto it = sync_server_cqs->begin(); it != sync_server_cqs->end(); ++it) { grpc_server_register_completion_queue(server->server_, (*it)->cq(), nullptr); num_frequently_polled_cqs++; } if (has_callback_methods) { auto* cq = server->CallbackCQ(); grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr); num_frequently_polled_cqs++; } // cqs_ contains the completion queue added by calling the ServerBuilder's // AddCompletionQueue() API. Some of them may not be frequently polled (i.e by // calling Next() or AsyncNext()) and hence are not safe to be used for // listening to incoming channels. Such completion queues must be registered // as non-listening queues for (auto it = cqs_.begin(); it != cqs_.end(); ++it) { grpc_server_register_completion_queue(server->server_, (*it)->cq(), nullptr); } if (num_frequently_polled_cqs == 0) { gpr_log(GPR_ERROR, "At least one of the completion queues must be frequently polled"); return nullptr; } for (auto service = services_.begin(); service != services_.end(); service++) { if (!server->RegisterService((*service)->host.get(), (*service)->service)) { return nullptr; } } for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin)->InitServer(initializer); } if (generic_service_) { server->RegisterAsyncGenericService(generic_service_); } else { for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_generic_methods()) { gpr_log(GPR_ERROR, "Some methods were marked generic but there is no " "generic service registered."); return nullptr; } } } bool added_port = false; for (auto port = ports_.begin(); port != ports_.end(); port++) { int r = server->AddListeningPort(port->addr, port->creds.get()); if (!r) { if (added_port) server->Shutdown(); return nullptr; } added_port = true; if (port->selected_port != nullptr) { *port->selected_port = r; } } auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0]; server->Start(cqs_data, cqs_.size()); for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin)->Finish(initializer); } return server; } void ServerBuilder::InternalAddPluginFactory( std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)()) { gpr_once_init(&once_init_plugin_list, do_plugin_list_init); (*g_plugin_factory_list).push_back(CreatePlugin); } ServerBuilder& ServerBuilder::EnableWorkaround(grpc_workaround_list id) { switch (id) { case GRPC_WORKAROUND_ID_CRONET_COMPRESSION: return AddChannelArgument(GRPC_ARG_WORKAROUND_CRONET_COMPRESSION, 1); default: gpr_log(GPR_ERROR, "Workaround %u does not exist or is obsolete.", id); return *this; } } } // namespace grpc <commit_msg>Default compression level quick fix<commit_after>/* * * Copyright 2015-2016 gRPC authors. * * 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 <grpcpp/server_builder.h> #include <grpc/support/cpu.h> #include <grpc/support/log.h> #include <grpcpp/impl/service_type.h> #include <grpcpp/resource_quota.h> #include <grpcpp/server.h> #include <utility> #include "src/core/lib/gpr/useful.h" #include "src/cpp/server/thread_pool_interface.h" namespace grpc { static std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>* g_plugin_factory_list; static gpr_once once_init_plugin_list = GPR_ONCE_INIT; static void do_plugin_list_init(void) { g_plugin_factory_list = new std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>(); } ServerBuilder::ServerBuilder() : max_receive_message_size_(INT_MIN), max_send_message_size_(INT_MIN), sync_server_settings_(SyncServerSettings()), resource_quota_(nullptr), generic_service_(nullptr) { gpr_once_init(&once_init_plugin_list, do_plugin_list_init); for (auto it = g_plugin_factory_list->begin(); it != g_plugin_factory_list->end(); it++) { auto& factory = *it; plugins_.emplace_back(factory()); } // all compression algorithms enabled by default. enabled_compression_algorithms_bitset_ = (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1; memset(&maybe_default_compression_level_, 0, sizeof(maybe_default_compression_level_)); memset(&maybe_default_compression_algorithm_, 0, sizeof(maybe_default_compression_algorithm_)); } ServerBuilder::~ServerBuilder() { if (resource_quota_ != nullptr) { grpc_resource_quota_unref(resource_quota_); } } std::unique_ptr<ServerCompletionQueue> ServerBuilder::AddCompletionQueue( bool is_frequently_polled) { ServerCompletionQueue* cq = new ServerCompletionQueue( GRPC_CQ_NEXT, is_frequently_polled ? GRPC_CQ_DEFAULT_POLLING : GRPC_CQ_NON_LISTENING, nullptr); cqs_.push_back(cq); return std::unique_ptr<ServerCompletionQueue>(cq); } ServerBuilder& ServerBuilder::RegisterService(Service* service) { services_.emplace_back(new NamedService(service)); return *this; } ServerBuilder& ServerBuilder::RegisterService(const grpc::string& addr, Service* service) { services_.emplace_back(new NamedService(addr, service)); return *this; } ServerBuilder& ServerBuilder::RegisterAsyncGenericService( AsyncGenericService* service) { if (generic_service_) { gpr_log(GPR_ERROR, "Adding multiple AsyncGenericService is unsupported for now. " "Dropping the service %p", (void*)service); } else { generic_service_ = service; } return *this; } ServerBuilder& ServerBuilder::SetOption( std::unique_ptr<ServerBuilderOption> option) { options_.push_back(std::move(option)); return *this; } ServerBuilder& ServerBuilder::SetSyncServerOption( ServerBuilder::SyncServerOption option, int val) { switch (option) { case NUM_CQS: sync_server_settings_.num_cqs = val; break; case MIN_POLLERS: sync_server_settings_.min_pollers = val; break; case MAX_POLLERS: sync_server_settings_.max_pollers = val; break; case CQ_TIMEOUT_MSEC: sync_server_settings_.cq_timeout_msec = val; break; } return *this; } ServerBuilder& ServerBuilder::SetCompressionAlgorithmSupportStatus( grpc_compression_algorithm algorithm, bool enabled) { if (enabled) { GPR_BITSET(&enabled_compression_algorithms_bitset_, algorithm); } else { GPR_BITCLEAR(&enabled_compression_algorithms_bitset_, algorithm); } return *this; } ServerBuilder& ServerBuilder::SetDefaultCompressionLevel( grpc_compression_level level) { maybe_default_compression_level_.is_set = true; maybe_default_compression_level_.level = level; return *this; } ServerBuilder& ServerBuilder::SetDefaultCompressionAlgorithm( grpc_compression_algorithm algorithm) { maybe_default_compression_algorithm_.is_set = true; maybe_default_compression_algorithm_.algorithm = algorithm; return *this; } ServerBuilder& ServerBuilder::SetResourceQuota( const grpc::ResourceQuota& resource_quota) { if (resource_quota_ != nullptr) { grpc_resource_quota_unref(resource_quota_); } resource_quota_ = resource_quota.c_resource_quota(); grpc_resource_quota_ref(resource_quota_); return *this; } ServerBuilder& ServerBuilder::AddListeningPort( const grpc::string& addr_uri, std::shared_ptr<ServerCredentials> creds, int* selected_port) { const grpc::string uri_scheme = "dns:"; grpc::string addr = addr_uri; if (addr_uri.compare(0, uri_scheme.size(), uri_scheme) == 0) { size_t pos = uri_scheme.size(); while (addr_uri[pos] == '/') ++pos; // Skip slashes. addr = addr_uri.substr(pos); } Port port = {addr, std::move(creds), selected_port}; ports_.push_back(port); return *this; } std::unique_ptr<Server> ServerBuilder::BuildAndStart() { ChannelArguments args; for (auto option = options_.begin(); option != options_.end(); ++option) { (*option)->UpdateArguments(&args); (*option)->UpdatePlugins(&plugins_); } for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin)->UpdateServerBuilder(this); (*plugin)->UpdateChannelArguments(&args); } if (max_receive_message_size_ >= -1) { args.SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, max_receive_message_size_); } // The default message size is -1 (max), so no need to explicitly set it for // -1. if (max_send_message_size_ >= 0) { args.SetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH, max_send_message_size_); } args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET, enabled_compression_algorithms_bitset_); if (maybe_default_compression_level_.is_set) { args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL, maybe_default_compression_level_.level); } if (maybe_default_compression_algorithm_.is_set) { args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, maybe_default_compression_algorithm_.algorithm); } if (resource_quota_ != nullptr) { args.SetPointerWithVtable(GRPC_ARG_RESOURCE_QUOTA, resource_quota_, grpc_resource_quota_arg_vtable()); } // == Determine if the server has any syncrhonous methods == bool has_sync_methods = false; for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_synchronous_methods()) { has_sync_methods = true; break; } } if (!has_sync_methods) { for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { if ((*plugin)->has_sync_methods()) { has_sync_methods = true; break; } } } // If this is a Sync server, i.e a server expositing sync API, then the server // needs to create some completion queues to listen for incoming requests. // 'sync_server_cqs' are those internal completion queues. // // This is different from the completion queues added to the server via // ServerBuilder's AddCompletionQueue() method (those completion queues // are in 'cqs_' member variable of ServerBuilder object) std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>> sync_server_cqs(std::make_shared< std::vector<std::unique_ptr<ServerCompletionQueue>>>()); int num_frequently_polled_cqs = 0; for (auto it = cqs_.begin(); it != cqs_.end(); ++it) { if ((*it)->IsFrequentlyPolled()) { num_frequently_polled_cqs++; } } const bool is_hybrid_server = has_sync_methods && num_frequently_polled_cqs > 0; if (has_sync_methods) { grpc_cq_polling_type polling_type = is_hybrid_server ? GRPC_CQ_NON_POLLING : GRPC_CQ_DEFAULT_POLLING; // Create completion queues to listen to incoming rpc requests for (int i = 0; i < sync_server_settings_.num_cqs; i++) { sync_server_cqs->emplace_back( new ServerCompletionQueue(GRPC_CQ_NEXT, polling_type, nullptr)); } } // == Determine if the server has any callback methods == bool has_callback_methods = false; for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_callback_methods()) { has_callback_methods = true; break; } } // TODO(vjpai): Add a section here for plugins once they can support callback // methods if (has_sync_methods) { // This is a Sync server gpr_log(GPR_INFO, "Synchronous server. Num CQs: %d, Min pollers: %d, Max Pollers: " "%d, CQ timeout (msec): %d", sync_server_settings_.num_cqs, sync_server_settings_.min_pollers, sync_server_settings_.max_pollers, sync_server_settings_.cq_timeout_msec); } if (has_callback_methods) { gpr_log(GPR_INFO, "Callback server."); } std::unique_ptr<Server> server(new Server( max_receive_message_size_, &args, sync_server_cqs, sync_server_settings_.min_pollers, sync_server_settings_.max_pollers, sync_server_settings_.cq_timeout_msec, resource_quota_, std::move(interceptor_creators_))); ServerInitializer* initializer = server->initializer(); // Register all the completion queues with the server. i.e // 1. sync_server_cqs: internal completion queues created IF this is a sync // server // 2. cqs_: Completion queues added via AddCompletionQueue() call for (auto it = sync_server_cqs->begin(); it != sync_server_cqs->end(); ++it) { grpc_server_register_completion_queue(server->server_, (*it)->cq(), nullptr); num_frequently_polled_cqs++; } if (has_callback_methods) { auto* cq = server->CallbackCQ(); grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr); num_frequently_polled_cqs++; } // cqs_ contains the completion queue added by calling the ServerBuilder's // AddCompletionQueue() API. Some of them may not be frequently polled (i.e by // calling Next() or AsyncNext()) and hence are not safe to be used for // listening to incoming channels. Such completion queues must be registered // as non-listening queues for (auto it = cqs_.begin(); it != cqs_.end(); ++it) { grpc_server_register_completion_queue(server->server_, (*it)->cq(), nullptr); } if (num_frequently_polled_cqs == 0) { gpr_log(GPR_ERROR, "At least one of the completion queues must be frequently polled"); return nullptr; } for (auto service = services_.begin(); service != services_.end(); service++) { if (!server->RegisterService((*service)->host.get(), (*service)->service)) { return nullptr; } } for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin)->InitServer(initializer); } if (generic_service_) { server->RegisterAsyncGenericService(generic_service_); } else { for (auto it = services_.begin(); it != services_.end(); ++it) { if ((*it)->service->has_generic_methods()) { gpr_log(GPR_ERROR, "Some methods were marked generic but there is no " "generic service registered."); return nullptr; } } } bool added_port = false; for (auto port = ports_.begin(); port != ports_.end(); port++) { int r = server->AddListeningPort(port->addr, port->creds.get()); if (!r) { if (added_port) server->Shutdown(); return nullptr; } added_port = true; if (port->selected_port != nullptr) { *port->selected_port = r; } } auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0]; server->Start(cqs_data, cqs_.size()); for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin)->Finish(initializer); } return server; } void ServerBuilder::InternalAddPluginFactory( std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)()) { gpr_once_init(&once_init_plugin_list, do_plugin_list_init); (*g_plugin_factory_list).push_back(CreatePlugin); } ServerBuilder& ServerBuilder::EnableWorkaround(grpc_workaround_list id) { switch (id) { case GRPC_WORKAROUND_ID_CRONET_COMPRESSION: return AddChannelArgument(GRPC_ARG_WORKAROUND_CRONET_COMPRESSION, 1); default: gpr_log(GPR_ERROR, "Workaround %u does not exist or is obsolete.", id); return *this; } } } // namespace grpc <|endoftext|>
<commit_before>/* * OSPRayNHSphereGeometry.cpp * Copyright (C) 2009-2017 by MegaMol Team * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "OSPRayNHSphereGeometry.h" #include "vislib/forceinline.h" #include "mmcore/moldyn/MultiParticleDataCall.h" #include "mmcore/param/FloatParam.h" #include "mmcore/param/IntParam.h" #include "mmcore/param/Vector3fParam.h" #include "mmcore/param/EnumParam.h" #include "vislib/sys/Log.h" #include "mmcore/Call.h" #include "mmcore/view/CallGetTransferFunction.h" #include "mmcore/view/CallClipPlane.h" using namespace megamol::ospray; typedef float(*floatFromArrayFunc)(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index); typedef unsigned char(*byteFromArrayFunc)(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index); OSPRayNHSphereGeometry::OSPRayNHSphereGeometry(void) : AbstractOSPRayStructure(), getDataSlot("getdata", "Connects to the data source"), particleList("ParticleList", "Switches between particle lists") { this->getDataSlot.SetCompatibleCall<core::moldyn::MultiParticleDataCallDescription>(); this->MakeSlotAvailable(&this->getDataSlot); this->particleList << new core::param::IntParam(0); this->MakeSlotAvailable(&this->particleList); } bool OSPRayNHSphereGeometry::readData(megamol::core::Call &call) { // fill material container this->processMaterial(); // read Data, calculate shape parameters, fill data vectors CallOSPRayStructure *os = dynamic_cast<CallOSPRayStructure*>(&call); megamol::core::moldyn::MultiParticleDataCall *cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>(); this->structureContainer.dataChanged = false; if (cd == NULL) return false; cd->SetTimeStamp(os->getTime()); cd->SetFrameID(os->getTime(), true); // isTimeForced flag set to true if (this->datahash != cd->DataHash() || this->time != os->getTime() || this->InterfaceIsDirty()) { this->datahash = cd->DataHash(); this->time = os->getTime(); this->structureContainer.dataChanged = true; } else { return true; } if (this->particleList.Param<core::param::IntParam>()->Value() >(cd->GetParticleListCount() - 1)) { this->particleList.Param<core::param::IntParam>()->SetValue(0); } if (!(*cd)(1)) return false; if (!(*cd)(0)) return false; core::moldyn::MultiParticleDataCall::Particles &parts = cd->AccessParticles(this->particleList.Param<core::param::IntParam>()->Value()); unsigned int partCount = parts.GetCount(); float globalRadius = parts.GetGlobalRadius(); size_t vertexLength; size_t colorLength; // Vertex data type check if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZ) { vertexLength = 3; } else if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR) { vertexLength = 4; } // Color data type check if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_RGBA) { colorLength = 4; } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_I) { colorLength = 1; } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_RGB) { colorLength = 3; } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_UINT8_RGBA) { colorLength = 4; } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_NONE) { colorLength = 0; } int vstride; if (parts.GetVertexDataStride() == 0) { vstride = core::moldyn::MultiParticleDataCall::Particles::VertexDataSize[parts.GetVertexDataType()]; } if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_NONE || parts.GetColourDataType() != core::moldyn::MultiParticleDataCall::Particles::COLDATA_NONE) { vislib::sys::Log::DefaultLog.WriteError("Only color data is not allowed."); } // Write stuff into the structureContainer this->structureContainer.type = structureTypeEnum::GEOMETRY; this->structureContainer.geometryType = geometryTypeEnum::NHSPHERES; this->structureContainer.raw = std::make_shared<const void*>(std::move(parts.GetVertexData())); this->structureContainer.vertexLength = vertexLength; this->structureContainer.vertexStride = vstride; this->structureContainer.colorLength = colorLength; this->structureContainer.colorStride = parts.GetColourDataStride(); this->structureContainer.partCount = partCount; this->structureContainer.globalRadius = globalRadius; this->structureContainer.mmpldColor = parts.GetColourDataType(); return true; } OSPRayNHSphereGeometry::~OSPRayNHSphereGeometry() { this->Release(); } bool OSPRayNHSphereGeometry::create() { return true; } void OSPRayNHSphereGeometry::release() { } /* ospray::OSPRayNHSphereGeometry::InterfaceIsDirty() */ bool OSPRayNHSphereGeometry::InterfaceIsDirty() { if ( this->particleList.IsDirty() ) { this->particleList.ResetDirty(); return true; } else { return false; } } bool OSPRayNHSphereGeometry::getExtends(megamol::core::Call &call) { CallOSPRayStructure *os = dynamic_cast<CallOSPRayStructure*>(&call); megamol::core::moldyn::MultiParticleDataCall *cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>(); if (cd == NULL) return false; cd->SetFrameID(os->getTime(), true); // isTimeForced flag set to true // if (!(*cd)(1)) return false; // floattable returns flase at first attempt and breaks everything (*cd)(1); this->extendContainer.boundingBox = std::make_shared<megamol::core::BoundingBoxes>(cd->AccessBoundingBoxes()); this->extendContainer.timeFramesCount = cd->FrameCount(); this->extendContainer.isValid = true; return true; }<commit_msg>There I fixed it<commit_after>/* * OSPRayNHSphereGeometry.cpp * Copyright (C) 2009-2017 by MegaMol Team * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "OSPRayNHSphereGeometry.h" #include "vislib/forceinline.h" #include "mmcore/moldyn/MultiParticleDataCall.h" #include "mmcore/param/FloatParam.h" #include "mmcore/param/IntParam.h" #include "mmcore/param/Vector3fParam.h" #include "mmcore/param/EnumParam.h" #include "vislib/sys/Log.h" #include "mmcore/Call.h" #include "mmcore/view/CallGetTransferFunction.h" #include "mmcore/view/CallClipPlane.h" using namespace megamol::ospray; typedef float(*floatFromArrayFunc)(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index); typedef unsigned char(*byteFromArrayFunc)(const megamol::core::moldyn::MultiParticleDataCall::Particles& p, size_t index); OSPRayNHSphereGeometry::OSPRayNHSphereGeometry(void) : AbstractOSPRayStructure(), getDataSlot("getdata", "Connects to the data source"), particleList("ParticleList", "Switches between particle lists") { this->getDataSlot.SetCompatibleCall<core::moldyn::MultiParticleDataCallDescription>(); this->MakeSlotAvailable(&this->getDataSlot); this->particleList << new core::param::IntParam(0); this->MakeSlotAvailable(&this->particleList); } bool OSPRayNHSphereGeometry::readData(megamol::core::Call &call) { // fill material container this->processMaterial(); // read Data, calculate shape parameters, fill data vectors CallOSPRayStructure *os = dynamic_cast<CallOSPRayStructure*>(&call); megamol::core::moldyn::MultiParticleDataCall *cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>(); this->structureContainer.dataChanged = false; if (cd == NULL) return false; cd->SetTimeStamp(os->getTime()); cd->SetFrameID(os->getTime(), true); // isTimeForced flag set to true if (this->datahash != cd->DataHash() || this->time != os->getTime() || this->InterfaceIsDirty()) { this->datahash = cd->DataHash(); this->time = os->getTime(); this->structureContainer.dataChanged = true; } else { return true; } if (!(*cd)(1)) return false; if (!(*cd)(0)) return false; if (cd->GetParticleListCount() == 0) return false; if (this->particleList.Param<core::param::IntParam>()->Value() > (cd->GetParticleListCount() - 1)) { this->particleList.Param<core::param::IntParam>()->SetValue(0); } core::moldyn::MultiParticleDataCall::Particles &parts = cd->AccessParticles(this->particleList.Param<core::param::IntParam>()->Value()); unsigned int partCount = parts.GetCount(); float globalRadius = parts.GetGlobalRadius(); size_t vertexLength; size_t colorLength; // Vertex data type check if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZ) { vertexLength = 3; } else if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR) { vertexLength = 4; } // Color data type check if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_RGBA) { colorLength = 4; } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_I) { colorLength = 1; } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_FLOAT_RGB) { colorLength = 3; } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_UINT8_RGBA) { colorLength = 4; } else if (parts.GetColourDataType() == core::moldyn::MultiParticleDataCall::Particles::COLDATA_NONE) { colorLength = 0; } int vstride; if (parts.GetVertexDataStride() == 0) { vstride = core::moldyn::MultiParticleDataCall::Particles::VertexDataSize[parts.GetVertexDataType()]; } if (parts.GetVertexDataType() == core::moldyn::MultiParticleDataCall::Particles::VERTDATA_NONE || parts.GetColourDataType() != core::moldyn::MultiParticleDataCall::Particles::COLDATA_NONE) { vislib::sys::Log::DefaultLog.WriteError("Only color data is not allowed."); } // Write stuff into the structureContainer this->structureContainer.type = structureTypeEnum::GEOMETRY; this->structureContainer.geometryType = geometryTypeEnum::NHSPHERES; this->structureContainer.raw = std::make_shared<const void*>(std::move(parts.GetVertexData())); this->structureContainer.vertexLength = vertexLength; this->structureContainer.vertexStride = vstride; this->structureContainer.colorLength = colorLength; this->structureContainer.colorStride = parts.GetColourDataStride(); this->structureContainer.partCount = partCount; this->structureContainer.globalRadius = globalRadius; this->structureContainer.mmpldColor = parts.GetColourDataType(); return true; } OSPRayNHSphereGeometry::~OSPRayNHSphereGeometry() { this->Release(); } bool OSPRayNHSphereGeometry::create() { return true; } void OSPRayNHSphereGeometry::release() { } /* ospray::OSPRayNHSphereGeometry::InterfaceIsDirty() */ bool OSPRayNHSphereGeometry::InterfaceIsDirty() { if ( this->particleList.IsDirty() ) { this->particleList.ResetDirty(); return true; } else { return false; } } bool OSPRayNHSphereGeometry::getExtends(megamol::core::Call &call) { CallOSPRayStructure *os = dynamic_cast<CallOSPRayStructure*>(&call); megamol::core::moldyn::MultiParticleDataCall *cd = this->getDataSlot.CallAs<megamol::core::moldyn::MultiParticleDataCall>(); if (cd == NULL) return false; cd->SetFrameID(os->getTime(), true); // isTimeForced flag set to true // if (!(*cd)(1)) return false; // floattable returns flase at first attempt and breaks everything (*cd)(1); this->extendContainer.boundingBox = std::make_shared<megamol::core::BoundingBoxes>(cd->AccessBoundingBoxes()); this->extendContainer.timeFramesCount = cd->FrameCount(); this->extendContainer.isValid = true; return true; }<|endoftext|>
<commit_before>/** * \file CMaster.cpp * \date Apr 1, 2010 * \author samael */ #include <sys/time.h> #include <unistd.h> #include <cstdlib> #include "CMutex.h" #include "CUdpSocket.h" #include "CThread.h" #include "CSingletonAutoDestructor.h" #include "CTlvUint32.h" #include "CMaster.h" #include "CTlvCommand.h" #include "IManagerActor.h" #include "internal/CMasterSideConnectionListener.h" #include "internal/CMasterSideCommandListener.h" #include "internal/CMasterSideCommandSender.h" #include "internal/CMasterSideFinishedWorkerProcessor.h" using namespace std; namespace wolf { struct PData { PData(): rsocks(), rsocksmx(), cmdsdr(), clis(), pfwpsr(NULL), mgrq(), mgrqmx(), fwq(), fwqmx(), nfinwrks(0), bcastaddr(CHostAddress::BroadcastAddress), stime(), exetime() {} // Runner related resources. vector<CTcpSocket *> rsocks; // Runner sockets. CMutex rsocksmx; // Runner sockets mutex. CMasterSideCommandSender cmdsdr; // Command sender. vector<CMasterSideCommandListener *> clis; // Command listeners. CMasterSideFinishedWorkerProcessor *pfwpsr; // Finished worker processor. // Others. map<uint32_t, IManagerActor *> mgrq; // Manager queue. CMutex mgrqmx; // Manager queue mutex. deque<pair<uint32_t, AWorkerActor *> > fwq; // Finished worker queue. CMutex fwqmx; // Finished worker queue mutex. unsigned nfinwrks; // # finished workers. CHostAddress bcastaddr; // Broadcast address. wolf::CTime stime; // Time when started. wolf::CTime exetime; // Execution time. private: PData(const PData &UNUSED(o)): rsocks(), rsocksmx(), cmdsdr(), clis(), pfwpsr(NULL), mgrq(), mgrqmx(), fwq(), fwqmx(), nfinwrks(0), bcastaddr(CHostAddress::BroadcastAddress), stime(), exetime() {} PData& operator=(const PData &UNUSED(o)) { return *this; } }; SINGLETON_REGISTRATION(CMaster); SINGLETON_DEPENDS_SOCKET(CMaster); SINGLETON_REGISTRATION_END(); const string CMaster::StateString[] = { "Not Ready", "Ready", "End" }; CMaster::CMaster(): SINGLETON_MEMBER_INITLST, _state(NOT_READY), _mserver(), _defdisp(), _activedisp(&_defdisp), _d(new PData) { } CMaster::~CMaster() { for (unsigned i = 0; i < _d->clis.size(); i++) delete _d->clis[i]; delete _d->pfwpsr; delete _d; } /** * Initial master with program parameters. */ void CMaster::init(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "b:h")) != -1) { switch (opt) { case 'b': _d->bcastaddr = CHostAddress(optarg); break; case 'h': cerr << "Usage: " << argv[0] << " [-b broadcast_address]" << endl; exit(EXIT_FAILURE); } } } /** * Setup the master. It must be called before other operations. */ bool CMaster::setup(in_port_t master_port, in_port_t runner_port, const string &appname, unsigned int timeout) { if (_state != NOT_READY) return false; // Start waiting runner connections. CMasterSideConnectionListener listener(this, &_mserver, master_port); listener.start(); // Join D2MCE group and broadcast hello message. _d->cmdsdr.joinD2MCE(appname); _d->cmdsdr.hello(runner_port, _d->bcastaddr); // Check the runners. sleep(timeout); listener.stop(); if (_d->rsocks.size() == 0) { PERR("No runner found."); return false; } PINF_1("Totally " << _d->rsocks.size() << " runners connected."); // Start finished worker processor. _d->pfwpsr = new CMasterSideFinishedWorkerProcessor(this); _d->pfwpsr->start(); // Bind command listeners to each runner, and start all runners. for (unsigned i = 0; i < _d->rsocks.size(); i++) { CMasterSideCommandListener *cl = new CMasterSideCommandListener(this, _d->rsocks[i]); cl->start(); _d->clis.push_back(cl); _d->cmdsdr.startRunner(_d->rsocks[i]); } _state = READY; _d->stime = CTime::now(); return true; } /** * Send a worker out to run. */ void CMaster::runWorker(AWorkerActor *worker, IManagerActor *mgr) { if (!worker || !mgr) return; #ifdef __D2MCE__ /* DSM mode */ _d->mgrqmx.lock(); for (unsigned i = 0; i < _d->rsocks.size(); i++) { uint32_t seq = _d->cmdsdr.runWorker(_d->rsocks[i], worker); _d->mgrq[seq] = mgr; } _d->mgrqmx.unlock(); #else /* Normal mode */ _d->rsocksmx.lock(); CTcpSocket *runner = dispatcher()->choose(_d->rsocks); _d->rsocksmx.unlock(); if (runner) { _d->mgrqmx.lock(); uint32_t seq = _d->cmdsdr.runWorker(runner, worker); _d->mgrq[seq] = mgr; PINF_2("Worker " << seq << " has been sent to runner " << runner->peerAddress().toString()); _d->mgrqmx.unlock(); } #endif /* __D2MCE__ */ } /** * Tell the runners to shutdown. It should be perform before program exits. */ void CMaster::shutdown() { _d->exetime = CTime::now() - _d->stime; PINF_1("Execution time = " << _d->exetime); PINF_1(_d->nfinwrks << " runners finished."); // Stop finished worker processor. _d->pfwpsr->setDone(); _d->pfwpsr->join(); // Shutdown all runners and stop all command listeners. for (unsigned i = 0; i < _d->rsocks.size(); i++) { _d->clis[i]->setDone(); _d->clis[i]->join(); } for (unsigned i = 0; i < _d->rsocks.size(); i++) _d->cmdsdr.shutdown(_d->rsocks[i]); _state = END; } /** * Used by RunnerCommandListener to notify that a runner is got. */ void CMaster::runnerConnected(wolf::CTcpSocket *runnersock) { vector<CHostAddress> addrs; _d->rsocksmx.lock(); for (unsigned i = 0; i < _d->rsocks.size(); i++) { addrs.push_back(_d->rsocks[i]->peerAddress()); } _d->cmdsdr.addRunner(runnersock, addrs); _d->rsocks.push_back(runnersock); _d->rsocksmx.unlock(); } /** * Put a finished worker into waiting to for processing. */ void CMaster::putFinishWorker(uint32_t wseq, AWorkerActor *worker) { _d->fwqmx.lock(); _d->nfinwrks++; _d->fwq.push_back(pair<uint32_t, AWorkerActor *>(wseq, worker)); _d->fwqmx.unlock(); } /** * Process a finished worker from queue. It's called by a different thread from * who put workers to queue. */ void CMaster::processFinishedWorker() { uint32_t wseq; AWorkerActor *worker = NULL; // Take a finished worker. _d->fwqmx.lock(); if (!_d->fwq.empty()) { pair<uint32_t, AWorkerActor *> p = _d->fwq.front(); wseq = p.first; worker = p.second; _d->fwq.pop_front(); } _d->fwqmx.unlock(); if (!worker) { usleep(10000); } else { // Find the belonging manager. map<uint32_t, IManagerActor *>::iterator iter; _d->mgrqmx.lock(); if ((iter = _d->mgrq.find(wseq)) == _d->mgrq.end()) { PERR("No manager found owning worker with sequence = " << wseq); delete worker; return; } // Take the value and remove the manager from the queue. IManagerActor *mgr = iter->second; _d->mgrq.erase(iter); _d->mgrqmx.unlock(); #ifdef __D2MCE__ /* DSM mode */ // Check if it's the last worker owned by that manager. map<uint32_t, IManagerActor *>::iterator tmpiter; bool lastone = true; _d->mgrqmx.lock(); for (tmpiter = _d->mgrq.begin(); tmpiter != _d->mgrq.end(); ++tmpiter) { if (tmpiter->second == mgr) { lastone = false; break; } } _d->mgrqmx.unlock(); // Notify manager only if it's the last worker. if (lastone) { mgr->processFinishedWorker(worker); } #else /* Normal mode */ mgr->workerFinished(worker); #endif /* DISABLE_D2MCE */ delete worker; } } /** * Get the number of runners. */ unsigned CMaster::numberOfRunners() { _d->rsocksmx.lock(); unsigned n = _d->rsocks.size(); _d->rsocksmx.unlock(); return n; } CTime CMaster::executionTime() const { return _d->exetime; } } <commit_msg><commit_after>/** * \file CMaster.cpp * \date Apr 1, 2010 * \author samael */ #include <sys/time.h> #include <unistd.h> #include <cstdlib> #include "CMutex.h" #include "CUdpSocket.h" #include "CThread.h" #include "CSingletonAutoDestructor.h" #include "CTlvUint32.h" #include "CMaster.h" #include "CTlvCommand.h" #include "IManagerActor.h" #include "internal/CMasterSideConnectionListener.h" #include "internal/CMasterSideCommandListener.h" #include "internal/CMasterSideCommandSender.h" #include "internal/CMasterSideFinishedWorkerProcessor.h" using namespace std; namespace wolf { struct PData { PData(): rsocks(), rsocksmx(), cmdsdr(), clis(), pfwpsr(NULL), mgrq(), mgrqmx(), fwq(), fwqmx(), nfinwrks(0), bcastaddr(CHostAddress::BroadcastAddress), stime(), exetime() {} // Runner related resources. vector<CTcpSocket *> rsocks; // Runner sockets. CMutex rsocksmx; // Runner sockets mutex. CMasterSideCommandSender cmdsdr; // Command sender. vector<CMasterSideCommandListener *> clis; // Command listeners. CMasterSideFinishedWorkerProcessor *pfwpsr; // Finished worker processor. // Others. map<uint32_t, IManagerActor *> mgrq; // Manager queue. CMutex mgrqmx; // Manager queue mutex. deque<pair<uint32_t, AWorkerActor *> > fwq; // Finished worker queue. CMutex fwqmx; // Finished worker queue mutex. unsigned nfinwrks; // # finished workers. CHostAddress bcastaddr; // Broadcast address. wolf::CTime stime; // Time when started. wolf::CTime exetime; // Execution time. private: PData(const PData &UNUSED(o)): rsocks(), rsocksmx(), cmdsdr(), clis(), pfwpsr(NULL), mgrq(), mgrqmx(), fwq(), fwqmx(), nfinwrks(0), bcastaddr(CHostAddress::BroadcastAddress), stime(), exetime() {} PData& operator=(const PData &UNUSED(o)) { return *this; } }; SINGLETON_REGISTRATION(CMaster); SINGLETON_DEPENDS_SOCKET(CMaster); SINGLETON_REGISTRATION_END(); const string CMaster::StateString[] = { "Not Ready", "Ready", "End" }; CMaster::CMaster(): SINGLETON_MEMBER_INITLST, _state(NOT_READY), _mserver(), _defdisp(), _activedisp(&_defdisp), _d(new PData) { } CMaster::~CMaster() { for (unsigned i = 0; i < _d->clis.size(); i++) delete _d->clis[i]; delete _d->pfwpsr; delete _d; } /** * Initial master with program parameters. */ void CMaster::init(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "b:h")) != -1) { switch (opt) { case 'b': _d->bcastaddr = CHostAddress(optarg); break; case 'h': cerr << "Usage: " << argv[0] << " [-b broadcast_address]" << endl; exit(EXIT_FAILURE); } } } /** * Setup the master. It must be called before other operations. */ bool CMaster::setup(in_port_t master_port, in_port_t runner_port, const string &appname, unsigned int timeout) { if (_state != NOT_READY) return false; // Start waiting runner connections. CMasterSideConnectionListener listener(this, &_mserver, master_port); listener.start(); // Join D2MCE group and broadcast hello message. _d->cmdsdr.joinD2MCE(appname); _d->cmdsdr.hello(runner_port, _d->bcastaddr); // Check the runners. sleep(timeout); listener.stop(); if (_d->rsocks.size() == 0) { PERR("No runner found."); return false; } PINF_1("Totally " << _d->rsocks.size() << " runners connected."); // Start finished worker processor. _d->pfwpsr = new CMasterSideFinishedWorkerProcessor(this); _d->pfwpsr->start(); // Bind command listeners to each runner, and start all runners. for (unsigned i = 0; i < _d->rsocks.size(); i++) { CMasterSideCommandListener *cl = new CMasterSideCommandListener(this, _d->rsocks[i]); cl->start(); _d->clis.push_back(cl); _d->cmdsdr.startRunner(_d->rsocks[i]); } _state = READY; _d->stime = CTime::now(); return true; } /** * Send a worker out to run. */ void CMaster::runWorker(AWorkerActor *worker, IManagerActor *mgr) { if (!worker || !mgr) return; #ifdef __D2MCE__ /* DSM mode */ _d->mgrqmx.lock(); for (unsigned i = 0; i < _d->rsocks.size(); i++) { uint32_t seq = _d->cmdsdr.runWorker(_d->rsocks[i], worker); _d->mgrq[seq] = mgr; } _d->mgrqmx.unlock(); #else /* Normal mode */ _d->rsocksmx.lock(); CTcpSocket *runner = dispatcher()->choose(_d->rsocks); _d->rsocksmx.unlock(); if (runner) { _d->mgrqmx.lock(); uint32_t seq = _d->cmdsdr.runWorker(runner, worker); _d->mgrq[seq] = mgr; PINF_2("Worker " << seq << " has been sent to runner " << runner->peerAddress().toString()); _d->mgrqmx.unlock(); } #endif /* __D2MCE__ */ } /** * Tell the runners to shutdown. It should be perform before program exits. */ void CMaster::shutdown() { _d->exetime = CTime::now() - _d->stime; PINF_1("Execution time = " << _d->exetime); PINF_1(_d->nfinwrks << " runners finished."); // Stop finished worker processor. _d->pfwpsr->setDone(); _d->pfwpsr->join(); // Shutdown all runners and stop all command listeners. for (unsigned i = 0; i < _d->rsocks.size(); i++) { _d->clis[i]->setDone(); _d->cmdsdr.shutdown(_d->rsocks[i]); } for (unsigned i = 0; i < _d->rsocks.size(); i++) _d->clis[i]->join(); _state = END; } /** * Used by RunnerCommandListener to notify that a runner is got. */ void CMaster::runnerConnected(wolf::CTcpSocket *runnersock) { vector<CHostAddress> addrs; _d->rsocksmx.lock(); for (unsigned i = 0; i < _d->rsocks.size(); i++) { addrs.push_back(_d->rsocks[i]->peerAddress()); } _d->cmdsdr.addRunner(runnersock, addrs); _d->rsocks.push_back(runnersock); _d->rsocksmx.unlock(); } /** * Put a finished worker into waiting to for processing. */ void CMaster::putFinishWorker(uint32_t wseq, AWorkerActor *worker) { _d->fwqmx.lock(); _d->nfinwrks++; _d->fwq.push_back(pair<uint32_t, AWorkerActor *>(wseq, worker)); _d->fwqmx.unlock(); } /** * Process a finished worker from queue. It's called by a different thread from * who put workers to queue. */ void CMaster::processFinishedWorker() { uint32_t wseq; AWorkerActor *worker = NULL; // Take a finished worker. _d->fwqmx.lock(); if (!_d->fwq.empty()) { pair<uint32_t, AWorkerActor *> p = _d->fwq.front(); wseq = p.first; worker = p.second; _d->fwq.pop_front(); } _d->fwqmx.unlock(); if (!worker) { usleep(10000); } else { // Find the belonging manager. map<uint32_t, IManagerActor *>::iterator iter; _d->mgrqmx.lock(); if ((iter = _d->mgrq.find(wseq)) == _d->mgrq.end()) { PERR("No manager found owning worker with sequence = " << wseq); delete worker; return; } // Take the value and remove the manager from the queue. IManagerActor *mgr = iter->second; _d->mgrq.erase(iter); _d->mgrqmx.unlock(); #ifdef __D2MCE__ /* DSM mode */ // Check if it's the last worker owned by that manager. map<uint32_t, IManagerActor *>::iterator tmpiter; bool lastone = true; _d->mgrqmx.lock(); for (tmpiter = _d->mgrq.begin(); tmpiter != _d->mgrq.end(); ++tmpiter) { if (tmpiter->second == mgr) { lastone = false; break; } } _d->mgrqmx.unlock(); // Notify manager only if it's the last worker. if (lastone) { mgr->processFinishedWorker(worker); } #else /* Normal mode */ mgr->workerFinished(worker); #endif /* DISABLE_D2MCE */ delete worker; } } /** * Get the number of runners. */ unsigned CMaster::numberOfRunners() { _d->rsocksmx.lock(); unsigned n = _d->rsocks.size(); _d->rsocksmx.unlock(); return n; } CTime CMaster::executionTime() const { return _d->exetime; } } <|endoftext|>
<commit_before>{% extends 'scan.cpp' %} {% block initializer %}{{ super() }}, {{mapping_var_name}}{% endblock %} <commit_msg>oops again<commit_after>{% extends 'scan.cpp' %} {% block initializer %}{{ super() }}, {{mapping_var_name}}.second{% endblock %} <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2018-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <[email protected]> * * 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.1 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 Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "Chapter.h" #include "database/SqliteTools.h" #include "database/SqliteQuery.h" #include "Media.h" namespace medialibrary { const std::string Chapter::Table::Name = "Chapter"; const std::string Chapter::Table::PrimaryKeyColumn = "id_chapter"; int64_t Chapter::* const Chapter::Table::PrimaryKey = &Chapter::m_id; void Chapter::createTable( sqlite::Connection* dbConn ) { sqlite::Tools::executeRequest( dbConn, schema( Table::Name, Settings::DbModelVersion ) ); } std::string Chapter::schema( const std::string& tableName, uint32_t ) { UNUSED_IN_RELEASE( tableName ); assert( tableName == Table::Name ); return "CREATE TABLE " + Table::Name + "(" + Table::PrimaryKeyColumn + " INTEGER PRIMARY KEY AUTOINCREMENT," "offset INTEGER NOT NULL," "duration INTEGER NOT NULL," "name TEXT," "media_id INTEGER," "FOREIGN KEY(media_id) REFERENCES " + Media::Table::Name + "(" + Media::Table::PrimaryKeyColumn + ")" " ON DELETE CASCADE" ")"; } bool Chapter::checkDbModel( MediaLibraryPtr ml ) { return sqlite::Tools::checkTableSchema( ml->getConn(), schema( Table::Name, Settings::DbModelVersion ), Table::Name ); } std::shared_ptr<Chapter> Chapter::create( MediaLibraryPtr ml, int64_t offset, int64_t duration, std::string name, int64_t mediaId ) { static const std::string req = "INSERT INTO " + Table::Name + "(offset, duration, name, media_id) VALUES(?, ?, ?, ?)"; auto self = std::make_shared<Chapter>( ml, offset, duration, std::move( name ) ); if ( insert( ml, self, req, offset, duration, self->m_name, mediaId ) == false ) return nullptr; return self; } Query<IChapter> Chapter::fromMedia( MediaLibraryPtr ml, int64_t mediaId, const QueryParameters* params ) { std::string req = "FROM " + Table::Name + " WHERE media_id = ?"; std::string orderBy = "ORDER BY "; auto desc = params != nullptr ? params->desc : false; auto sort = params != nullptr ? params->sort : SortingCriteria::Default; switch ( sort ) { case SortingCriteria::Alpha: orderBy += "name"; break; case SortingCriteria::Duration: orderBy += "duration"; desc = !desc; break; default: LOG_WARN( "Unsupported sorting criteria ", static_cast<std::underlying_type<SortingCriteria>::type>( sort ), " falling back to default (by offset)" ); /* fall-through */ case SortingCriteria::Default: orderBy += "offset"; break; } if ( desc == true ) orderBy += " DESC"; return make_query<Chapter, IChapter>( ml, "*", req, orderBy, mediaId ); } Chapter::Chapter( MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) , m_id( row.extract<decltype(m_id)>() ) , m_offset( row.extract<decltype(m_offset)>() ) , m_duration( row.extract<decltype(m_offset)>() ) , m_name( row.extract<decltype(m_name)>() ) { // Simply check that the media_id row is present, until we eventually store it assert( row.extract<int64_t>() ); assert( row.hasRemainingColumns() == false ); } Chapter::Chapter( MediaLibraryPtr ml, int64_t offset, int64_t duration, std::string name ) : m_ml( ml ) , m_id( 0 ) , m_offset( offset ) , m_duration( duration ) , m_name( std::move( name ) ) { } const std::string& Chapter::name() const { return m_name; } int64_t Chapter::offset() const { return m_offset; } int64_t Chapter::duration() const { return m_duration; } } <commit_msg>Chapter: Use enum_to_string<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2018-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <[email protected]> * * 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.1 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 Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "Chapter.h" #include "database/SqliteTools.h" #include "database/SqliteQuery.h" #include "Media.h" #include "utils/Enums.h" namespace medialibrary { const std::string Chapter::Table::Name = "Chapter"; const std::string Chapter::Table::PrimaryKeyColumn = "id_chapter"; int64_t Chapter::* const Chapter::Table::PrimaryKey = &Chapter::m_id; void Chapter::createTable( sqlite::Connection* dbConn ) { sqlite::Tools::executeRequest( dbConn, schema( Table::Name, Settings::DbModelVersion ) ); } std::string Chapter::schema( const std::string& tableName, uint32_t ) { UNUSED_IN_RELEASE( tableName ); assert( tableName == Table::Name ); return "CREATE TABLE " + Table::Name + "(" + Table::PrimaryKeyColumn + " INTEGER PRIMARY KEY AUTOINCREMENT," "offset INTEGER NOT NULL," "duration INTEGER NOT NULL," "name TEXT," "media_id INTEGER," "FOREIGN KEY(media_id) REFERENCES " + Media::Table::Name + "(" + Media::Table::PrimaryKeyColumn + ")" " ON DELETE CASCADE" ")"; } bool Chapter::checkDbModel( MediaLibraryPtr ml ) { return sqlite::Tools::checkTableSchema( ml->getConn(), schema( Table::Name, Settings::DbModelVersion ), Table::Name ); } std::shared_ptr<Chapter> Chapter::create( MediaLibraryPtr ml, int64_t offset, int64_t duration, std::string name, int64_t mediaId ) { static const std::string req = "INSERT INTO " + Table::Name + "(offset, duration, name, media_id) VALUES(?, ?, ?, ?)"; auto self = std::make_shared<Chapter>( ml, offset, duration, std::move( name ) ); if ( insert( ml, self, req, offset, duration, self->m_name, mediaId ) == false ) return nullptr; return self; } Query<IChapter> Chapter::fromMedia( MediaLibraryPtr ml, int64_t mediaId, const QueryParameters* params ) { std::string req = "FROM " + Table::Name + " WHERE media_id = ?"; std::string orderBy = "ORDER BY "; auto desc = params != nullptr ? params->desc : false; auto sort = params != nullptr ? params->sort : SortingCriteria::Default; switch ( sort ) { case SortingCriteria::Alpha: orderBy += "name"; break; case SortingCriteria::Duration: orderBy += "duration"; desc = !desc; break; default: LOG_WARN( "Unsupported sorting criteria ", utils::enum_to_string( sort ), " falling back to default (by offset)" ); /* fall-through */ case SortingCriteria::Default: orderBy += "offset"; break; } if ( desc == true ) orderBy += " DESC"; return make_query<Chapter, IChapter>( ml, "*", req, orderBy, mediaId ); } Chapter::Chapter( MediaLibraryPtr ml, sqlite::Row& row ) : m_ml( ml ) , m_id( row.extract<decltype(m_id)>() ) , m_offset( row.extract<decltype(m_offset)>() ) , m_duration( row.extract<decltype(m_offset)>() ) , m_name( row.extract<decltype(m_name)>() ) { // Simply check that the media_id row is present, until we eventually store it assert( row.extract<int64_t>() ); assert( row.hasRemainingColumns() == false ); } Chapter::Chapter( MediaLibraryPtr ml, int64_t offset, int64_t duration, std::string name ) : m_ml( ml ) , m_id( 0 ) , m_offset( offset ) , m_duration( duration ) , m_name( std::move( name ) ) { } const std::string& Chapter::name() const { return m_name; } int64_t Chapter::offset() const { return m_offset; } int64_t Chapter::duration() const { return m_duration; } } <|endoftext|>
<commit_before>// // Clutter.cpp // Clutter // // Created by PM Bult on 24-01-2016 // Copyright (c) P.M. Bult. All rights reserved. // // Version 1.0 // #include "Clutter.h" #include "Utils.h" namespace Clutter { // // Constructor // Clutter::Clutter( int argc, const char* argv[] ) { // Initialize processing variables string flag; string tag; std::vector<string> values; // Loop over all tags in the command line for (int i = 1; i < argc; ++i) { // Convert the current entry to a tag string flag = string( argv[i] ); // Ensure the tag is a flag-type if ( Utils::isValue( flag ) ) throw "error: parsing error"; // Ensure the flag does not alread exist if ( mCommandMap.count( flag ) > 0 ) throw "error: duplicate flag"; // Find the next flag (or the end of list) for (i++; i < argc; i++) { // Load the next tag tag = string( argv[i] ); // Test of tag type if ( Utils::isFlag( tag ) ) { i--; break; } // flag found: block is complete else values.push_back( tag ); // value found: add to current block } // Store the tag & values as a block mCommandMap.emplace( flag, CommandBlock(values) ); // Clear the processing memory values.clear(); // Continue with next block // ... } // Set help flag if ( this->has_flag("-h") || this->has_flag("--help") ) { mHelpFlag = true; } } // // Support function // bool Clutter::has_flag( string flag ) { if ( mCommandMap.count( flag ) == 1 ) return true; else return false; } // // Parse templace specializations // // -> Boolian specialization template <> void Clutter::parse( bool& value, CommandBlock &block ) { // Test block size if ( block.size() > 0 ) printf( "warning: orhpan value\n" ); // Flip value value = !value; // Mark as processed block.processed = true; } // -> String specialization template <> void Clutter::parse( string& value, CommandBlock &block ) { // Test block size if ( block.size() > 1 ) printf( "warning: orhpan value\n" ); // Flip value value = block.values[0]; // Mark as processed block.processed = true; } // // Parse termination function // void Clutter::end_parse() { // Check the help flag if ( mHelpFlag ) { printf( "Required arguments:\n" ); for ( auto& block : mHelpTree_required ) block.print(); printf( "Optional arguments:\n" ); for ( auto& block : mHelpTree_requested ) block.print(); exit(0); } // Check orphan options for ( auto& map : mCommandMap ) { if ( !map.second.processed ) { throw "error: orphan options"; } } } } <commit_msg>Add print_help() function for HelpTable formatting<commit_after>// // Clutter.cpp // Clutter // // Created by PM Bult on 24-01-2016 // Copyright (c) P.M. Bult. All rights reserved. // // Version 1.0 // #include "Clutter.h" #include "Utils.h" namespace Clutter { // // Constructor // Clutter::Clutter( int argc, const char* argv[] ) { // Initialize processing variables string flag; string tag; std::vector<string> values; // Loop over all tags in the command line for (int i = 1; i < argc; ++i) { // Convert the current entry to a tag string flag = string( argv[i] ); // Ensure the tag is a flag-type if ( Utils::isValue( flag ) ) throw "error: parsing error"; // Ensure the flag does not alread exist if ( mCommandMap.count( flag ) > 0 ) throw "error: duplicate flag"; // Find the next flag (or the end of list) for (i++; i < argc; i++) { // Load the next tag tag = string( argv[i] ); // Test of tag type if ( Utils::isFlag( tag ) ) { i--; break; } // flag found: block is complete else values.push_back( tag ); // value found: add to current block } // Store the tag & values as a block mCommandMap.emplace( flag, CommandBlock(values) ); // Clear the processing memory values.clear(); // Continue with next block // ... } // Set help flag if ( this->has_flag("-h") || this->has_flag("--help") ) { mHelpFlag = true; } } // // Support function // bool Clutter::has_flag( string flag ) { if ( mCommandMap.count( flag ) == 1 ) return true; else return false; } // // Parse templace specializations // // -> Boolian specialization template <> void Clutter::parse( bool& value, CommandBlock &block ) { // Test block size if ( block.size() > 0 ) printf( "warning: orhpan value\n" ); // Flip value value = !value; // Mark as processed block.processed = true; } // -> String specialization template <> void Clutter::parse( string& value, CommandBlock &block ) { // Test block size if ( block.size() > 1 ) printf( "warning: orhpan value\n" ); // Flip value value = block.values[0]; // Mark as processed block.processed = true; } // // Parse termination function // void Clutter::end_parse() { // Check the help flag if ( mHelpFlag ) { // Print the help table print_help(); // Terminate program exit(0); } // Check orphan options for ( auto& map : mCommandMap ) { if ( !map.second.processed ) { throw "error: orphan options"; } } } // // Print help table // void Clutter::print_help() { // Resolve label width int max_width = 0; // Search the required tree for ( auto& block : mHelpTree_required ) max_width = std::max( max_width, block.label.size() ) // Search the requested tree for ( auto& block : mHelpTree_requested ) max_width = std::max( max_width, block.label.size() ) // Add two characters max_width = std::max( 16, max_width+2 ); // Print the help table printf( "Required arguments:\n" ); for ( auto& block : mHelpTree_required ) block.print( 6, max_width ); printf( "Optional arguments:\n" ); for ( auto& block : mHelpTree_requested ) block.print( 6, max_width ); } } <|endoftext|>
<commit_before>#include <string.h> #include "base/logging.h" #include "gfx_es2/fbo.h" #include "gfx/gl_common.h" #include "gfx_es2/gl_state.h" #if defined(USING_GLES2) #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER #define GL_RGBA8 GL_RGBA #ifndef GL_DEPTH_COMPONENT24 #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES #endif #ifndef GL_DEPTH24_STENCIL8_OES #define GL_DEPTH24_STENCIL8_OES 0x88F0 #endif #endif struct FBO { GLuint handle; GLuint color_texture; GLuint z_stencil_buffer; // Either this is set, or the two below. GLuint z_buffer; GLuint stencil_buffer; int width; int height; FBOColorDepth colorDepth; }; // On PC, we always use GL_DEPTH24_STENCIL8. // On Android, we try to use what's available. FBO *fbo_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { CheckGLExtensions(); FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffers(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #ifdef USING_GLES2 if (gl_extensions.OES_packed_depth_stencil) { ILOG("Creating %i x %i FBO using DEPTH24_STENCIL8", width, height); // Standard method fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil combined glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); } else { ILOG("Creating %i x %i FBO using separate stencil", width, height); // TEGRA fbo->z_stencil_buffer = 0; // 16/24-bit Z, separate 8-bit stencil glGenRenderbuffers(1, &fbo->z_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_buffer); glRenderbufferStorage(GL_RENDERBUFFER, gl_extensions.OES_depth24 ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT16, width, height); // 8-bit stencil buffer glGenRenderbuffers(1, &fbo->stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->stencil_buffer); } #else fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); #endif GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); switch(status) { case GL_FRAMEBUFFER_COMPLETE: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } void fbo_unbind() { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); } void fbo_bind_as_render_target(FBO *fbo) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); } void fbo_bind_for_read(FBO *fbo) { glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo->handle); } void fbo_bind_color_as_texture(FBO *fbo, int color) { glBindTexture(GL_TEXTURE_2D, fbo->color_texture); } void fbo_destroy(FBO *fbo) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glDeleteFramebuffers(1, &fbo->handle); glDeleteTextures(1, &fbo->color_texture); glDeleteRenderbuffers(1, &fbo->z_stencil_buffer); } void fbo_get_dimensions(FBO *fbo, int *w, int *h) { *w = fbo->width; *h = fbo->height; }<commit_msg>Delete FBOs in fbo_destroy().<commit_after>#include <string.h> #include "base/logging.h" #include "gfx_es2/fbo.h" #include "gfx/gl_common.h" #include "gfx_es2/gl_state.h" #if defined(USING_GLES2) #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER #define GL_RGBA8 GL_RGBA #ifndef GL_DEPTH_COMPONENT24 #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES #endif #ifndef GL_DEPTH24_STENCIL8_OES #define GL_DEPTH24_STENCIL8_OES 0x88F0 #endif #endif struct FBO { GLuint handle; GLuint color_texture; GLuint z_stencil_buffer; // Either this is set, or the two below. GLuint z_buffer; GLuint stencil_buffer; int width; int height; FBOColorDepth colorDepth; }; // On PC, we always use GL_DEPTH24_STENCIL8. // On Android, we try to use what's available. FBO *fbo_create(int width, int height, int num_color_textures, bool z_stencil, FBOColorDepth colorDepth) { CheckGLExtensions(); FBO *fbo = new FBO(); fbo->width = width; fbo->height = height; fbo->colorDepth = colorDepth; // Color texture is same everywhere glGenFramebuffers(1, &fbo->handle); glGenTextures(1, &fbo->color_texture); // Create the surfaces. glBindTexture(GL_TEXTURE_2D, fbo->color_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: We could opt to only create 16-bit render targets on slow devices. For later. switch (colorDepth) { case FBO_8888: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); break; case FBO_4444: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, NULL); break; case FBO_5551: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, NULL); break; case FBO_565: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); break; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); #ifdef USING_GLES2 if (gl_extensions.OES_packed_depth_stencil) { ILOG("Creating %i x %i FBO using DEPTH24_STENCIL8", width, height); // Standard method fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil combined glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); } else { ILOG("Creating %i x %i FBO using separate stencil", width, height); // TEGRA fbo->z_stencil_buffer = 0; // 16/24-bit Z, separate 8-bit stencil glGenRenderbuffers(1, &fbo->z_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_buffer); glRenderbufferStorage(GL_RENDERBUFFER, gl_extensions.OES_depth24 ? GL_DEPTH_COMPONENT24 : GL_DEPTH_COMPONENT16, width, height); // 8-bit stencil buffer glGenRenderbuffers(1, &fbo->stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->stencil_buffer); } #else fbo->stencil_buffer = 0; fbo->z_buffer = 0; // 24-bit Z, 8-bit stencil glGenRenderbuffers(1, &fbo->z_stencil_buffer); glBindRenderbuffer(GL_RENDERBUFFER, fbo->z_stencil_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); // Bind it all together glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo->color_texture, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo->z_stencil_buffer); #endif GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); switch(status) { case GL_FRAMEBUFFER_COMPLETE: // ILOG("Framebuffer verified complete."); break; case GL_FRAMEBUFFER_UNSUPPORTED: ELOG("GL_FRAMEBUFFER_UNSUPPORTED"); break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: ELOG("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT "); break; default: FLOG("Other framebuffer error: %i", status); break; } // Unbind state we don't need glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindTexture(GL_TEXTURE_2D, 0); return fbo; } void fbo_unbind() { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); } void fbo_bind_as_render_target(FBO *fbo) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); } void fbo_bind_for_read(FBO *fbo) { glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo->handle); } void fbo_bind_color_as_texture(FBO *fbo, int color) { glBindTexture(GL_TEXTURE_2D, fbo->color_texture); } void fbo_destroy(FBO *fbo) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo->handle); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glDeleteFramebuffers(1, &fbo->handle); glDeleteTextures(1, &fbo->color_texture); glDeleteRenderbuffers(1, &fbo->z_stencil_buffer); delete fbo; } void fbo_get_dimensions(FBO *fbo, int *w, int *h) { *w = fbo->width; *h = fbo->height; }<|endoftext|>
<commit_before>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include <iostream> #include <string> #include <type_traits> #include <typeinfo> #include <vector> #include <tao/pegtl.hpp> using namespace tao::TAOCPP_PEGTL_NAMESPACE; namespace parse_tree { template< typename > struct store_simple : std::false_type { }; template< typename > struct store_content : std::false_type { }; struct node { std::vector< std::unique_ptr< node > > children; const std::type_info* id = nullptr; const char* begin = nullptr; const char* end = nullptr; }; struct state { std::vector< std::unique_ptr< node > > stack; state() { emplace_back(); } const node& root() const { return *stack.front(); } void emplace_back() { std::unique_ptr< node > r( new node ); stack.emplace_back( std::move( r ) ); } }; template< typename Rule, bool = store_simple< Rule >::value, bool = store_content< Rule >::value > struct builder_impl; template< typename Rule > struct builder : builder_impl< Rule > { }; template< typename Rule > struct builder_impl< Rule, false, false > : normal< Rule > { }; template< typename Rule > struct builder_impl< Rule, true, true > : normal< Rule > { static_assert( sizeof( Rule ) == 0, "error: both store_simple and store_content are set" ); }; template< typename Rule > struct builder_impl< Rule, true, false > : normal< Rule > { template< typename Input > static void start( const Input&, state& s ) { s.emplace_back(); } template< typename Input > static void success( const Input&, state& s ) { auto n = std::move( s.stack.back() ); n->id = &typeid( Rule ); s.stack.pop_back(); s.stack.back()->children.emplace_back( std::move( n ) ); } template< typename Input > static void failure( const Input&, state& s ) { s.stack.pop_back(); } }; template< typename Rule > struct action : nothing< Rule > { }; template< typename Rule > struct builder_impl< Rule, false, true > : normal< Rule > { template< typename Input > static void start( const Input& in, state& s ) { s.emplace_back(); s.stack.back()->begin = in.current(); } template< typename Input > static void success( const Input& in, state& s ) { auto n = std::move( s.stack.back() ); n->id = &typeid( Rule ); n->end = in.current(); s.stack.pop_back(); s.stack.back()->children.emplace_back( std::move( n ) ); } template< typename Input > static void failure( const Input&, state& s ) { s.stack.pop_back(); } }; void print_node( const node& n, const std::string& s = "" ) { if( n.id ) { if( n.begin ) { std::cout << s << internal::demangle( n.id->name() ) << " \"" << std::string( n.begin, n.end ) << '"' << std::endl; } else { std::cout << s << internal::demangle( n.id->name() ) << std::endl; } } else { std::cout << "ROOT" << std::endl; } if( !n.children.empty() ) { const auto s2 = s + " "; for( auto& up : n.children ) { print_node( *up, s2 ); } } } // clang-format off struct integer : plus< digit > {}; struct variable : identifier {}; struct plus : pad< one< '+' >, space > {}; struct minus : pad< one< '-' >, space > {}; struct multiply : pad< one< '*' >, space > {}; struct divide : pad< one< '/' >, space > {}; struct open_bracket : seq< one< '(' >, star< space > > {}; struct close_bracket : seq< star< space >, one< ')' > > {}; struct expression; struct bracketed : seq< open_bracket, expression, close_bracket > {}; struct value : sor< integer, variable, bracketed > {}; struct product : list< value, sor< multiply, divide > > {}; struct expression : list< product, sor< plus, minus > > {}; struct grammar : must< expression, eof > {}; // select which rules in the grammar will produce parse tree nodes: template<> struct store_content< integer > : std::true_type {}; template<> struct store_content< variable > : std::true_type {}; template<> struct store_simple< plus > : std::true_type {}; template<> struct store_simple< minus > : std::true_type {}; template<> struct store_simple< multiply > : std::true_type {}; template<> struct store_simple< divide > : std::true_type {}; template<> struct store_simple< product > : std::true_type {}; template<> struct store_simple< expression > : std::true_type {}; // clang-format on // use actions to transform the parse tree: template<> struct action< product > { static void rearrange( std::unique_ptr< node >& n ) { auto& c = n->children; if( c.size() == 1 ) { n = std::move( c.back() ); } else { auto r = std::move( c.back() ); c.pop_back(); auto o = std::move( c.back() ); c.pop_back(); o->children.emplace_back( std::move( n ) ); o->children.emplace_back( std::move( r ) ); n = std::move( o ); rearrange( n->children.front() ); } } template< typename Input > static void apply( const Input&, state& s ) { rearrange( s.stack.back()->children.back() ); } }; template<> struct action< expression > : action< product > { }; } // namespace parse_tree int main( int argc, char** argv ) { for( int i = 1; i < argc; ++i ) { argv_input<> in( argv, i ); parse_tree::state s; parse< parse_tree::grammar, parse_tree::action, parse_tree::builder >( in, s ); print_node( s.root() ); } return 0; } <commit_msg>Simplify<commit_after>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include <iostream> #include <string> #include <type_traits> #include <typeinfo> #include <vector> #include <tao/pegtl.hpp> using namespace tao::TAOCPP_PEGTL_NAMESPACE; namespace parse_tree { template< typename > struct store_simple : std::false_type { }; template< typename > struct store_content : std::false_type { }; struct node { std::vector< std::unique_ptr< node > > children; const std::type_info* id = nullptr; const char* begin = nullptr; const char* end = nullptr; }; struct state { std::vector< std::unique_ptr< node > > stack; state() { emplace_back(); } const node& root() const { return *stack.front(); } void emplace_back() { stack.emplace_back( new node ); } }; template< typename Rule, bool = store_simple< Rule >::value, bool = store_content< Rule >::value > struct builder_impl; template< typename Rule > struct builder : builder_impl< Rule > { }; template< typename Rule > struct builder_impl< Rule, false, false > : normal< Rule > { }; template< typename Rule > struct builder_impl< Rule, true, true > : normal< Rule > { static_assert( sizeof( Rule ) == 0, "error: both store_simple and store_content are set" ); }; template< typename Rule > struct builder_impl< Rule, true, false > : normal< Rule > { template< typename Input > static void start( const Input&, state& s ) { s.emplace_back(); } template< typename Input > static void success( const Input&, state& s ) { auto n = std::move( s.stack.back() ); n->id = &typeid( Rule ); s.stack.pop_back(); s.stack.back()->children.emplace_back( std::move( n ) ); } template< typename Input > static void failure( const Input&, state& s ) { s.stack.pop_back(); } }; template< typename Rule > struct action : nothing< Rule > { }; template< typename Rule > struct builder_impl< Rule, false, true > : normal< Rule > { template< typename Input > static void start( const Input& in, state& s ) { s.emplace_back(); s.stack.back()->begin = in.current(); } template< typename Input > static void success( const Input& in, state& s ) { auto n = std::move( s.stack.back() ); n->id = &typeid( Rule ); n->end = in.current(); s.stack.pop_back(); s.stack.back()->children.emplace_back( std::move( n ) ); } template< typename Input > static void failure( const Input&, state& s ) { s.stack.pop_back(); } }; void print_node( const node& n, const std::string& s = "" ) { if( n.id ) { if( n.begin ) { std::cout << s << internal::demangle( n.id->name() ) << " \"" << std::string( n.begin, n.end ) << '"' << std::endl; } else { std::cout << s << internal::demangle( n.id->name() ) << std::endl; } } else { std::cout << "ROOT" << std::endl; } if( !n.children.empty() ) { const auto s2 = s + " "; for( auto& up : n.children ) { print_node( *up, s2 ); } } } // clang-format off struct integer : plus< digit > {}; struct variable : identifier {}; struct plus : pad< one< '+' >, space > {}; struct minus : pad< one< '-' >, space > {}; struct multiply : pad< one< '*' >, space > {}; struct divide : pad< one< '/' >, space > {}; struct open_bracket : seq< one< '(' >, star< space > > {}; struct close_bracket : seq< star< space >, one< ')' > > {}; struct expression; struct bracketed : seq< open_bracket, expression, close_bracket > {}; struct value : sor< integer, variable, bracketed > {}; struct product : list< value, sor< multiply, divide > > {}; struct expression : list< product, sor< plus, minus > > {}; struct grammar : must< expression, eof > {}; // select which rules in the grammar will produce parse tree nodes: template<> struct store_content< integer > : std::true_type {}; template<> struct store_content< variable > : std::true_type {}; template<> struct store_simple< plus > : std::true_type {}; template<> struct store_simple< minus > : std::true_type {}; template<> struct store_simple< multiply > : std::true_type {}; template<> struct store_simple< divide > : std::true_type {}; template<> struct store_simple< product > : std::true_type {}; template<> struct store_simple< expression > : std::true_type {}; // clang-format on // use actions to transform the parse tree: template<> struct action< product > { static void rearrange( std::unique_ptr< node >& n ) { auto& c = n->children; if( c.size() == 1 ) { n = std::move( c.back() ); } else { auto r = std::move( c.back() ); c.pop_back(); auto o = std::move( c.back() ); c.pop_back(); o->children.emplace_back( std::move( n ) ); o->children.emplace_back( std::move( r ) ); n = std::move( o ); rearrange( n->children.front() ); } } template< typename Input > static void apply( const Input&, state& s ) { rearrange( s.stack.back()->children.back() ); } }; template<> struct action< expression > : action< product > { }; } // namespace parse_tree int main( int argc, char** argv ) { for( int i = 1; i < argc; ++i ) { argv_input<> in( argv, i ); parse_tree::state s; parse< parse_tree::grammar, parse_tree::action, parse_tree::builder >( in, s ); print_node( s.root() ); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Implements the Chrome Extensions Cookies API. #include "chrome/browser/extensions/extension_cookies_api.h" #include "base/json/json_writer.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/extensions/extension_cookies_api_constants.h" #include "chrome/browser/extensions/extension_cookies_helpers.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/profile.h" #include "chrome/common/extensions/extension_error_utils.h" #include "chrome/common/net/url_request_context_getter.h" #include "chrome/common/notification_type.h" #include "chrome/common/notification_service.h" #include "net/base/cookie_monster.h" namespace keys = extension_cookies_api_constants; // static ExtensionCookiesEventRouter* ExtensionCookiesEventRouter::GetInstance() { return Singleton<ExtensionCookiesEventRouter>::get(); } void ExtensionCookiesEventRouter::Init() { if (registrar_.IsEmpty()) { registrar_.Add(this, NotificationType::COOKIE_CHANGED, NotificationService::AllSources()); } } void ExtensionCookiesEventRouter::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::COOKIE_CHANGED: CookieChanged( Source<Profile>(source).ptr(), Details<ChromeCookieDetails>(details).ptr()); break; default: NOTREACHED(); } } void ExtensionCookiesEventRouter::CookieChanged( Profile* profile, ChromeCookieDetails* details) { ListValue args; DictionaryValue* dict = new DictionaryValue(); dict->SetBoolean(keys::kRemovedKey, details->removed); dict->Set( keys::kCookieKey, extension_cookies_helpers::CreateCookieValue(*details->cookie_pair, extension_cookies_helpers::GetStoreIdFromProfile(profile))); args.Append(dict); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); GURL cookie_domain = extension_cookies_helpers::GetURLFromCookiePair(*details->cookie_pair); LOG(WARNING) << "Sending cookie " << json_args; DispatchEvent(profile, keys::kOnChanged, json_args, cookie_domain); } void ExtensionCookiesEventRouter::DispatchEvent(Profile* profile, const char* event_name, const std::string& json_args, GURL& cookie_domain) { if (profile && profile->GetExtensionMessageService()) { profile->GetExtensionMessageService()->DispatchEventToRenderers( event_name, json_args, profile->IsOffTheRecord(), cookie_domain); } } bool CookiesFunction::ParseUrl(const DictionaryValue* details, GURL* url, bool check_host_permissions) { DCHECK(details && url); std::string url_string; // Get the URL string or return false. EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kUrlKey, &url_string)); *url = GURL(url_string); if (!url->is_valid()) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kInvalidUrlError, url_string); return false; } // Check against host permissions if needed. if (check_host_permissions && !GetExtension()->HasHostPermission(*url)) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoHostPermissionsError, url->spec()); return false; } return true; } bool CookiesFunction::ParseCookieStore(const DictionaryValue* details, net::CookieStore** store, std::string* store_id) { DCHECK(details && (store || store_id)); Profile* store_profile = NULL; if (details->HasKey(keys::kStoreIdKey)) { // The store ID was explicitly specified in the details dictionary. // Retrieve its corresponding cookie store. std::string store_id_value; // Get the store ID string or return false. EXTENSION_FUNCTION_VALIDATE( details->GetString(keys::kStoreIdKey, &store_id_value)); store_profile = extension_cookies_helpers::ChooseProfileFromStoreId( store_id_value, profile(), include_incognito()); if (!store_profile) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kInvalidStoreIdError, store_id_value); return false; } } else { // The store ID was not specified; use the current execution context's // cookie store by default. // GetCurrentBrowser() already takes into account incognito settings. Browser* current_browser = GetCurrentBrowser(); if (!current_browser) { error_ = keys::kNoCookieStoreFoundError; return false; } store_profile = current_browser->profile(); } DCHECK(store_profile); if (store) *store = store_profile->GetRequestContext()->GetCookieStore(); if (store_id) *store_id = extension_cookies_helpers::GetStoreIdFromProfile(store_profile); return true; } bool GetCookieFunction::RunImpl() { // Return false if the arguments are malformed. DictionaryValue* details; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); DCHECK(details); // Read/validate input parameters. GURL url; if (!ParseUrl(details, &url, true)) return false; std::string name; // Get the cookie name string or return false. EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kNameKey, &name)); net::CookieStore* cookie_store; std::string store_id; if (!ParseCookieStore(details, &cookie_store, &store_id)) return false; DCHECK(cookie_store && !store_id.empty()); net::CookieMonster::CookieList cookie_list = extension_cookies_helpers::GetCookieListFromStore(cookie_store, url); net::CookieMonster::CookieList::iterator it; for (it = cookie_list.begin(); it != cookie_list.end(); ++it) { // Return the first matching cookie. Relies on the fact that the // CookieMonster retrieves them in reverse domain-length order. const net::CookieMonster::CanonicalCookie& cookie = it->second; if (cookie.Name() == name) { result_.reset( extension_cookies_helpers::CreateCookieValue(*it, store_id)); return true; } } // The cookie doesn't exist; return null. result_.reset(Value::CreateNullValue()); return true; } bool GetAllCookiesFunction::RunImpl() { // Return false if the arguments are malformed. DictionaryValue* details; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); DCHECK(details); // Read/validate input parameters. GURL url; if (details->HasKey(keys::kUrlKey) && !ParseUrl(details, &url, false)) return false; net::CookieStore* cookie_store; std::string store_id; if (!ParseCookieStore(details, &cookie_store, &store_id)) return false; DCHECK(cookie_store); ListValue* matching_list = new ListValue(); extension_cookies_helpers::AppendMatchingCookiesToList( cookie_store, store_id, url, details, GetExtension(), matching_list); result_.reset(matching_list); return true; } bool SetCookieFunction::RunImpl() { // Return false if the arguments are malformed. DictionaryValue* details; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); DCHECK(details); // Read/validate input parameters. GURL url; if (!ParseUrl(details, &url, true)) return false; // The macros below return false if argument types are not as expected. std::string name; if (details->HasKey(keys::kNameKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kNameKey, &name)); } std::string value; if (details->HasKey(keys::kValueKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kValueKey, &value)); } std::string domain; if (details->HasKey(keys::kDomainKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kDomainKey, &domain)); } std::string path; if (details->HasKey(keys::kPathKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kPathKey, &path)); } bool secure = false; if (details->HasKey(keys::kSecureKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetBoolean(keys::kSecureKey, &secure)); } bool http_only = false; if (details->HasKey(keys::kHttpOnlyKey)) { EXTENSION_FUNCTION_VALIDATE( details->GetBoolean(keys::kHttpOnlyKey, &http_only)); } base::Time expiration_time; if (details->HasKey(keys::kExpirationDateKey)) { Value* expiration_date_value; EXTENSION_FUNCTION_VALIDATE(details->Get(keys::kExpirationDateKey, &expiration_date_value)); double expiration_date; if (expiration_date_value->IsType(Value::TYPE_INTEGER)) { int expiration_date_int; EXTENSION_FUNCTION_VALIDATE( expiration_date_value->GetAsInteger(&expiration_date_int)); expiration_date = static_cast<double>(expiration_date_int); } else { EXTENSION_FUNCTION_VALIDATE( expiration_date_value->GetAsReal(&expiration_date)); } expiration_time = base::Time::FromDoubleT(expiration_date); } net::CookieStore* cookie_store; if (!ParseCookieStore(details, &cookie_store, NULL)) return false; DCHECK(cookie_store); if (!cookie_store->GetCookieMonster()->SetCookieWithDetails( url, name, value, domain, path, expiration_time, secure, http_only)) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kCookieSetFailedError, name); return false; } return true; } bool RemoveCookieFunction::RunImpl() { // Return false if the arguments are malformed. DictionaryValue* details; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); DCHECK(details); // Read/validate input parameters. GURL url; if (!ParseUrl(details, &url, true)) return false; std::string name; // Get the cookie name string or return false. EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kNameKey, &name)); net::CookieStore* cookie_store; if (!ParseCookieStore(details, &cookie_store, NULL)) return false; DCHECK(cookie_store); cookie_store->DeleteCookie(url, name); return true; } bool GetAllCookieStoresFunction::RunImpl() { Profile* original_profile = profile()->GetOriginalProfile(); DCHECK(original_profile); scoped_ptr<ListValue> original_tab_ids(new ListValue()); Profile* incognito_profile = NULL; scoped_ptr<ListValue> incognito_tab_ids; if (include_incognito()) { incognito_profile = profile()->GetOffTheRecordProfile(); if (incognito_profile) incognito_tab_ids.reset(new ListValue()); } // Iterate through all browser instances, and for each browser, // add its tab IDs to either the regular or incognito tab ID list depending // whether the browser is regular or incognito. for (BrowserList::const_iterator iter = BrowserList::begin(); iter != BrowserList::end(); ++iter) { Browser* browser = *iter; if (browser->profile() == original_profile) { extension_cookies_helpers::AppendToTabIdList(browser, original_tab_ids.get()); } else if (incognito_tab_ids.get() && browser->profile() == incognito_profile) { extension_cookies_helpers::AppendToTabIdList(browser, incognito_tab_ids.get()); } } // Return a list of all cookie stores with at least one open tab. ListValue* cookie_store_list = new ListValue(); if (original_tab_ids->GetSize() > 0) { cookie_store_list->Append( extension_cookies_helpers::CreateCookieStoreValue( original_profile, original_tab_ids.release())); } if (incognito_tab_ids.get() && incognito_tab_ids->GetSize() > 0) { cookie_store_list->Append( extension_cookies_helpers::CreateCookieStoreValue( incognito_profile, incognito_tab_ids.release())); } result_.reset(cookie_store_list); return true; } <commit_msg>Reduce console spam from unneeded LOG().<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. // Implements the Chrome Extensions Cookies API. #include "chrome/browser/extensions/extension_cookies_api.h" #include "base/json/json_writer.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/extensions/extension_cookies_api_constants.h" #include "chrome/browser/extensions/extension_cookies_helpers.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/profile.h" #include "chrome/common/extensions/extension_error_utils.h" #include "chrome/common/net/url_request_context_getter.h" #include "chrome/common/notification_type.h" #include "chrome/common/notification_service.h" #include "net/base/cookie_monster.h" namespace keys = extension_cookies_api_constants; // static ExtensionCookiesEventRouter* ExtensionCookiesEventRouter::GetInstance() { return Singleton<ExtensionCookiesEventRouter>::get(); } void ExtensionCookiesEventRouter::Init() { if (registrar_.IsEmpty()) { registrar_.Add(this, NotificationType::COOKIE_CHANGED, NotificationService::AllSources()); } } void ExtensionCookiesEventRouter::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::COOKIE_CHANGED: CookieChanged( Source<Profile>(source).ptr(), Details<ChromeCookieDetails>(details).ptr()); break; default: NOTREACHED(); } } void ExtensionCookiesEventRouter::CookieChanged( Profile* profile, ChromeCookieDetails* details) { ListValue args; DictionaryValue* dict = new DictionaryValue(); dict->SetBoolean(keys::kRemovedKey, details->removed); dict->Set( keys::kCookieKey, extension_cookies_helpers::CreateCookieValue(*details->cookie_pair, extension_cookies_helpers::GetStoreIdFromProfile(profile))); args.Append(dict); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); GURL cookie_domain = extension_cookies_helpers::GetURLFromCookiePair(*details->cookie_pair); DispatchEvent(profile, keys::kOnChanged, json_args, cookie_domain); } void ExtensionCookiesEventRouter::DispatchEvent(Profile* profile, const char* event_name, const std::string& json_args, GURL& cookie_domain) { if (profile && profile->GetExtensionMessageService()) { profile->GetExtensionMessageService()->DispatchEventToRenderers( event_name, json_args, profile->IsOffTheRecord(), cookie_domain); } } bool CookiesFunction::ParseUrl(const DictionaryValue* details, GURL* url, bool check_host_permissions) { DCHECK(details && url); std::string url_string; // Get the URL string or return false. EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kUrlKey, &url_string)); *url = GURL(url_string); if (!url->is_valid()) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kInvalidUrlError, url_string); return false; } // Check against host permissions if needed. if (check_host_permissions && !GetExtension()->HasHostPermission(*url)) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoHostPermissionsError, url->spec()); return false; } return true; } bool CookiesFunction::ParseCookieStore(const DictionaryValue* details, net::CookieStore** store, std::string* store_id) { DCHECK(details && (store || store_id)); Profile* store_profile = NULL; if (details->HasKey(keys::kStoreIdKey)) { // The store ID was explicitly specified in the details dictionary. // Retrieve its corresponding cookie store. std::string store_id_value; // Get the store ID string or return false. EXTENSION_FUNCTION_VALIDATE( details->GetString(keys::kStoreIdKey, &store_id_value)); store_profile = extension_cookies_helpers::ChooseProfileFromStoreId( store_id_value, profile(), include_incognito()); if (!store_profile) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kInvalidStoreIdError, store_id_value); return false; } } else { // The store ID was not specified; use the current execution context's // cookie store by default. // GetCurrentBrowser() already takes into account incognito settings. Browser* current_browser = GetCurrentBrowser(); if (!current_browser) { error_ = keys::kNoCookieStoreFoundError; return false; } store_profile = current_browser->profile(); } DCHECK(store_profile); if (store) *store = store_profile->GetRequestContext()->GetCookieStore(); if (store_id) *store_id = extension_cookies_helpers::GetStoreIdFromProfile(store_profile); return true; } bool GetCookieFunction::RunImpl() { // Return false if the arguments are malformed. DictionaryValue* details; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); DCHECK(details); // Read/validate input parameters. GURL url; if (!ParseUrl(details, &url, true)) return false; std::string name; // Get the cookie name string or return false. EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kNameKey, &name)); net::CookieStore* cookie_store; std::string store_id; if (!ParseCookieStore(details, &cookie_store, &store_id)) return false; DCHECK(cookie_store && !store_id.empty()); net::CookieMonster::CookieList cookie_list = extension_cookies_helpers::GetCookieListFromStore(cookie_store, url); net::CookieMonster::CookieList::iterator it; for (it = cookie_list.begin(); it != cookie_list.end(); ++it) { // Return the first matching cookie. Relies on the fact that the // CookieMonster retrieves them in reverse domain-length order. const net::CookieMonster::CanonicalCookie& cookie = it->second; if (cookie.Name() == name) { result_.reset( extension_cookies_helpers::CreateCookieValue(*it, store_id)); return true; } } // The cookie doesn't exist; return null. result_.reset(Value::CreateNullValue()); return true; } bool GetAllCookiesFunction::RunImpl() { // Return false if the arguments are malformed. DictionaryValue* details; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); DCHECK(details); // Read/validate input parameters. GURL url; if (details->HasKey(keys::kUrlKey) && !ParseUrl(details, &url, false)) return false; net::CookieStore* cookie_store; std::string store_id; if (!ParseCookieStore(details, &cookie_store, &store_id)) return false; DCHECK(cookie_store); ListValue* matching_list = new ListValue(); extension_cookies_helpers::AppendMatchingCookiesToList( cookie_store, store_id, url, details, GetExtension(), matching_list); result_.reset(matching_list); return true; } bool SetCookieFunction::RunImpl() { // Return false if the arguments are malformed. DictionaryValue* details; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); DCHECK(details); // Read/validate input parameters. GURL url; if (!ParseUrl(details, &url, true)) return false; // The macros below return false if argument types are not as expected. std::string name; if (details->HasKey(keys::kNameKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kNameKey, &name)); } std::string value; if (details->HasKey(keys::kValueKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kValueKey, &value)); } std::string domain; if (details->HasKey(keys::kDomainKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kDomainKey, &domain)); } std::string path; if (details->HasKey(keys::kPathKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kPathKey, &path)); } bool secure = false; if (details->HasKey(keys::kSecureKey)) { EXTENSION_FUNCTION_VALIDATE(details->GetBoolean(keys::kSecureKey, &secure)); } bool http_only = false; if (details->HasKey(keys::kHttpOnlyKey)) { EXTENSION_FUNCTION_VALIDATE( details->GetBoolean(keys::kHttpOnlyKey, &http_only)); } base::Time expiration_time; if (details->HasKey(keys::kExpirationDateKey)) { Value* expiration_date_value; EXTENSION_FUNCTION_VALIDATE(details->Get(keys::kExpirationDateKey, &expiration_date_value)); double expiration_date; if (expiration_date_value->IsType(Value::TYPE_INTEGER)) { int expiration_date_int; EXTENSION_FUNCTION_VALIDATE( expiration_date_value->GetAsInteger(&expiration_date_int)); expiration_date = static_cast<double>(expiration_date_int); } else { EXTENSION_FUNCTION_VALIDATE( expiration_date_value->GetAsReal(&expiration_date)); } expiration_time = base::Time::FromDoubleT(expiration_date); } net::CookieStore* cookie_store; if (!ParseCookieStore(details, &cookie_store, NULL)) return false; DCHECK(cookie_store); if (!cookie_store->GetCookieMonster()->SetCookieWithDetails( url, name, value, domain, path, expiration_time, secure, http_only)) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kCookieSetFailedError, name); return false; } return true; } bool RemoveCookieFunction::RunImpl() { // Return false if the arguments are malformed. DictionaryValue* details; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); DCHECK(details); // Read/validate input parameters. GURL url; if (!ParseUrl(details, &url, true)) return false; std::string name; // Get the cookie name string or return false. EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kNameKey, &name)); net::CookieStore* cookie_store; if (!ParseCookieStore(details, &cookie_store, NULL)) return false; DCHECK(cookie_store); cookie_store->DeleteCookie(url, name); return true; } bool GetAllCookieStoresFunction::RunImpl() { Profile* original_profile = profile()->GetOriginalProfile(); DCHECK(original_profile); scoped_ptr<ListValue> original_tab_ids(new ListValue()); Profile* incognito_profile = NULL; scoped_ptr<ListValue> incognito_tab_ids; if (include_incognito()) { incognito_profile = profile()->GetOffTheRecordProfile(); if (incognito_profile) incognito_tab_ids.reset(new ListValue()); } // Iterate through all browser instances, and for each browser, // add its tab IDs to either the regular or incognito tab ID list depending // whether the browser is regular or incognito. for (BrowserList::const_iterator iter = BrowserList::begin(); iter != BrowserList::end(); ++iter) { Browser* browser = *iter; if (browser->profile() == original_profile) { extension_cookies_helpers::AppendToTabIdList(browser, original_tab_ids.get()); } else if (incognito_tab_ids.get() && browser->profile() == incognito_profile) { extension_cookies_helpers::AppendToTabIdList(browser, incognito_tab_ids.get()); } } // Return a list of all cookie stores with at least one open tab. ListValue* cookie_store_list = new ListValue(); if (original_tab_ids->GetSize() > 0) { cookie_store_list->Append( extension_cookies_helpers::CreateCookieStoreValue( original_profile, original_tab_ids.release())); } if (incognito_tab_ids.get() && incognito_tab_ids->GetSize() > 0) { cookie_store_list->Append( extension_cookies_helpers::CreateCookieStoreValue( incognito_profile, incognito_tab_ids.release())); } result_.reset(cookie_store_list); return true; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/command_line.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_tts_api.h" #include "chrome/browser/extensions/extension_tts_api_controller.h" #include "chrome/browser/extensions/extension_tts_api_platform.h" #include "chrome/common/chrome_switches.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" // Needed for CreateFunctor. #define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING #include "testing/gmock_mutant.h" using ::testing::AnyNumber; using ::testing::CreateFunctor; using ::testing::DoAll; using ::testing::InSequence; using ::testing::InvokeWithoutArgs; using ::testing::Return; using ::testing::StrictMock; using ::testing::_; class MockExtensionTtsPlatformImpl : public ExtensionTtsPlatformImpl { public: MockExtensionTtsPlatformImpl() : ALLOW_THIS_IN_INITIALIZER_LIST(ptr_factory_(this)) {} virtual bool PlatformImplAvailable() { return true; } virtual bool SendsEvent(TtsEventType event_type) { return (event_type == TTS_EVENT_END || event_type == TTS_EVENT_WORD); } MOCK_METHOD4(Speak, bool(int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params)); MOCK_METHOD0(StopSpeaking, bool(void)); void SetErrorToEpicFail() { set_error("epic fail"); } void SendEndEvent(int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MockExtensionTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), false, utterance_id, TTS_EVENT_END, utterance.size(), std::string()), 0); } void SendEndEventWhenQueueNotEmpty( int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MockExtensionTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), true, utterance_id, TTS_EVENT_END, utterance.size(), std::string()), 0); } void SendWordEvents(int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { for (int i = 0; i < static_cast<int>(utterance.size()); i++) { if (i == 0 || utterance[i - 1] == ' ') { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MockExtensionTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), false, utterance_id, TTS_EVENT_WORD, i, std::string()), 0); } } } void SendEvent(bool wait_for_non_empty_queue, int utterance_id, TtsEventType event_type, int char_index, const std::string& message) { ExtensionTtsController* controller = ExtensionTtsController::GetInstance(); if (wait_for_non_empty_queue && controller->QueueSize() == 0) { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MockExtensionTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), true, utterance_id, event_type, char_index, message), 100); return; } controller->OnTtsEvent(utterance_id, event_type, char_index, message); } private: base::WeakPtrFactory<MockExtensionTtsPlatformImpl> ptr_factory_; }; class TtsApiTest : public ExtensionApiTest { public: virtual void SetUpCommandLine(CommandLine* command_line) { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } virtual void SetUpInProcessBrowserTestFixture() { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); ExtensionTtsController::GetInstance()->SetPlatformImpl( &mock_platform_impl_); } protected: StrictMock<MockExtensionTtsPlatformImpl> mock_platform_impl_; }; IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakOptionalArgs) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "", _, _)) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "Alpha", _, _)) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "Bravo", _, _)) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "Charlie", _, _)) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "Echo", _, _)) .WillOnce(Return(true)); ASSERT_TRUE(RunExtensionTest("tts/optional_args")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakFinishesImmediately) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/speak_once")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakInterrupt) { // One utterance starts speaking, and then a second interrupts. InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 1", _, _)) .WillOnce(Return(true)); // Expect the second utterance and allow it to finish. EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 2", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/interrupt")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakQueueInterrupt) { // In this test, two utterances are queued, and then a third // interrupts. Speak() never gets called on the second utterance. InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 1", _, _)) .WillOnce(Return(true)); // Don't expect the second utterance, because it's queued up and the // first never finishes. // Expect the third utterance and allow it to finish successfully. EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 3", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/queue_interrupt")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakEnqueue) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 1", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEventWhenQueueNotEmpty), Return(true))); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 2", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/enqueue")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakError) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "first try", _, _)) .WillOnce(DoAll( InvokeWithoutArgs( CreateFunctor(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SetErrorToEpicFail)), Return(false))); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "second try", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/speak_error")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformWordCallbacks) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "one two three", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendWordEvents), Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/word_callbacks")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, RegisterEngine) { EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillRepeatedly(Return(true)); { InSequence s; EXPECT_CALL(mock_platform_impl_, Speak(_, "native speech", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); EXPECT_CALL(mock_platform_impl_, Speak(_, "native speech 2", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); EXPECT_CALL(mock_platform_impl_, Speak(_, "native speech 3", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); } ASSERT_TRUE(RunExtensionTest("tts_engine/register_engine")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, EngineError) { EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillRepeatedly(Return(true)); ASSERT_TRUE(RunExtensionTest("tts_engine/engine_error")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, EngineWordCallbacks) { EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillRepeatedly(Return(true)); ASSERT_TRUE(RunExtensionTest("tts_engine/engine_word_callbacks")) << message_; } <commit_msg>Get rid of experimental flag from tts apitest.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/command_line.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_tts_api.h" #include "chrome/browser/extensions/extension_tts_api_controller.h" #include "chrome/browser/extensions/extension_tts_api_platform.h" #include "chrome/common/chrome_switches.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" // Needed for CreateFunctor. #define GMOCK_MUTANT_INCLUDE_LATE_OBJECT_BINDING #include "testing/gmock_mutant.h" using ::testing::AnyNumber; using ::testing::CreateFunctor; using ::testing::DoAll; using ::testing::InSequence; using ::testing::InvokeWithoutArgs; using ::testing::Return; using ::testing::StrictMock; using ::testing::_; class MockExtensionTtsPlatformImpl : public ExtensionTtsPlatformImpl { public: MockExtensionTtsPlatformImpl() : ALLOW_THIS_IN_INITIALIZER_LIST(ptr_factory_(this)) {} virtual bool PlatformImplAvailable() { return true; } virtual bool SendsEvent(TtsEventType event_type) { return (event_type == TTS_EVENT_END || event_type == TTS_EVENT_WORD); } MOCK_METHOD4(Speak, bool(int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params)); MOCK_METHOD0(StopSpeaking, bool(void)); void SetErrorToEpicFail() { set_error("epic fail"); } void SendEndEvent(int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MockExtensionTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), false, utterance_id, TTS_EVENT_END, utterance.size(), std::string()), 0); } void SendEndEventWhenQueueNotEmpty( int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MockExtensionTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), true, utterance_id, TTS_EVENT_END, utterance.size(), std::string()), 0); } void SendWordEvents(int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { for (int i = 0; i < static_cast<int>(utterance.size()); i++) { if (i == 0 || utterance[i - 1] == ' ') { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MockExtensionTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), false, utterance_id, TTS_EVENT_WORD, i, std::string()), 0); } } } void SendEvent(bool wait_for_non_empty_queue, int utterance_id, TtsEventType event_type, int char_index, const std::string& message) { ExtensionTtsController* controller = ExtensionTtsController::GetInstance(); if (wait_for_non_empty_queue && controller->QueueSize() == 0) { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind( &MockExtensionTtsPlatformImpl::SendEvent, ptr_factory_.GetWeakPtr(), true, utterance_id, event_type, char_index, message), 100); return; } controller->OnTtsEvent(utterance_id, event_type, char_index, message); } private: base::WeakPtrFactory<MockExtensionTtsPlatformImpl> ptr_factory_; }; class TtsApiTest : public ExtensionApiTest { public: virtual void SetUpInProcessBrowserTestFixture() { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); ExtensionTtsController::GetInstance()->SetPlatformImpl( &mock_platform_impl_); } protected: StrictMock<MockExtensionTtsPlatformImpl> mock_platform_impl_; }; IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakOptionalArgs) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "", _, _)) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "Alpha", _, _)) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "Bravo", _, _)) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "Charlie", _, _)) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "Echo", _, _)) .WillOnce(Return(true)); ASSERT_TRUE(RunExtensionTest("tts/optional_args")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakFinishesImmediately) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, _, _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/speak_once")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakInterrupt) { // One utterance starts speaking, and then a second interrupts. InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 1", _, _)) .WillOnce(Return(true)); // Expect the second utterance and allow it to finish. EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 2", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/interrupt")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakQueueInterrupt) { // In this test, two utterances are queued, and then a third // interrupts. Speak() never gets called on the second utterance. InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 1", _, _)) .WillOnce(Return(true)); // Don't expect the second utterance, because it's queued up and the // first never finishes. // Expect the third utterance and allow it to finish successfully. EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 3", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/queue_interrupt")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakEnqueue) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 1", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEventWhenQueueNotEmpty), Return(true))); EXPECT_CALL(mock_platform_impl_, Speak(_, "text 2", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/enqueue")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformSpeakError) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "first try", _, _)) .WillOnce(DoAll( InvokeWithoutArgs( CreateFunctor(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SetErrorToEpicFail)), Return(false))); EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "second try", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/speak_error")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, PlatformWordCallbacks) { InSequence s; EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillOnce(Return(true)); EXPECT_CALL(mock_platform_impl_, Speak(_, "one two three", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendWordEvents), Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); ASSERT_TRUE(RunExtensionTest("tts/word_callbacks")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, RegisterEngine) { EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillRepeatedly(Return(true)); { InSequence s; EXPECT_CALL(mock_platform_impl_, Speak(_, "native speech", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); EXPECT_CALL(mock_platform_impl_, Speak(_, "native speech 2", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); EXPECT_CALL(mock_platform_impl_, Speak(_, "native speech 3", _, _)) .WillOnce(DoAll( Invoke(&mock_platform_impl_, &MockExtensionTtsPlatformImpl::SendEndEvent), Return(true))); } ASSERT_TRUE(RunExtensionTest("tts_engine/register_engine")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, EngineError) { EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillRepeatedly(Return(true)); ASSERT_TRUE(RunExtensionTest("tts_engine/engine_error")) << message_; } IN_PROC_BROWSER_TEST_F(TtsApiTest, EngineWordCallbacks) { EXPECT_CALL(mock_platform_impl_, StopSpeaking()) .WillRepeatedly(Return(true)); ASSERT_TRUE(RunExtensionTest("tts_engine/engine_word_callbacks")) << message_; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/metrics/metrics_service.h" #include <string> #include "base/base64.h" #include "testing/gtest/include/gtest/gtest.h" class MetricsServiceTest : public ::testing::Test { }; // Ensure the ClientId is formatted as expected. TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) { std::string clientid = MetricsService::GenerateClientID(); EXPECT_EQ(36U, clientid.length()); std::string hexchars = "0123456789ABCDEF"; for (uint32 i = 0; i < clientid.length(); i++) { char current = clientid.at(i); if (i == 8 || i == 13 || i == 18 || i == 23) { EXPECT_EQ('-', current); } else { EXPECT_TRUE(std::string::npos != hexchars.find(current)); } } } TEST(MetricsServiceTest, IsPluginProcess) { EXPECT_TRUE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN)); EXPECT_TRUE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN)); EXPECT_FALSE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU)); } <commit_msg>Clean up MetricsService unit test.<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 <ctype.h> #include <string> #include "chrome/browser/metrics/metrics_service.h" #include "testing/gtest/include/gtest/gtest.h" // Ensure the ClientId is formatted as expected. TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) { std::string clientid = MetricsService::GenerateClientID(); EXPECT_EQ(36U, clientid.length()); for (size_t i = 0; i < clientid.length(); ++i) { char current = clientid[i]; if (i == 8 || i == 13 || i == 18 || i == 23) EXPECT_EQ('-', current); else EXPECT_TRUE(isxdigit(current)); } } TEST(MetricsServiceTest, IsPluginProcess) { EXPECT_TRUE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN)); EXPECT_TRUE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN)); EXPECT_FALSE( MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU)); } <|endoftext|>
<commit_before>// #include <algorithm> #include <cassert> #include <cmath> #include <fstream> // #include <iostream> #include <sstream> // #include <string> // #include <vector> #include "Dungeon.h" /* Default constructor. * @param playerName, string with user-inputted name for player * @effects Creates a new Dungeon object. */ Dungeon::Dungeon(std::string playerName) { _currDay = new Day(); _daysPassed = 0; _player = new Player( playerName ); loadMonsterData(); // srand(time(NULL)); // generate a random seed } /* File loader. * @param inFileName, char* with file containing Monster names * @param ifstr, instream for reading file * @modifies ifstr, modified to read individual files * @effects Loads all monster information from 'inFileName'. */ void Dungeon::readFile(char* inFileName, std::ifstream &ifstr) { // search up through directory to find file (max of 20 levels up) unsigned int parentDirNum = 0; std::string dirStr = inFileName; ifstr.open(dirStr.c_str(),std::ifstream::in); while ( (!ifstr.good()) && (parentDirNum < 20) ) { dirStr = "../" + dirStr; ++parentDirNum; ifstr.open(dirStr.c_str(),std::ifstream::in); } // verify that we found the file if ( !ifstr.good() ) { // error finding file within max directory search std::cerr << "Problem opening monster name file: " << inFileName << std::endl; } } /* Load Monster attributes. * @modifies _monsterNames, _monsterTypes * @effects Pulls in data from MonsterNamesList and loads into * '_monsterNames' and '_monterTypes' */ void Dungeon::loadMonsterData() { // attempt to load in MonsterNameList.txt std::ifstream ifstr; char* file = (char*) ("MonterNameList.txt"); readFile(file, ifstr); std::string line, name, type, delim = ", "; _monsterNames = new std::string[MONSTER_ARRAY_SIZE]; _monsterTypes = new std::string[MONSTER_ARRAY_SIZE]; unsigned int i = 0; // load in names to '_monsterNames' and types to '_monsterTypes' while ( getline(ifstr, line) ) { name = line.substr(0, line.find(delim)); type = line.substr(line.find(delim) + 2, line.size()); _monsterNames[i] = name; _monsterTypes[i] = type; ++i; } // assert that monster data arrays have length 'MONSTER_ARRAY_SIZE' assert ( i == MONSTER_ARRAY_SIZE ); } /* Standard toString operation. * @param ostr, current outstream for program * @param d, Dungeon object to print * @modifies ostr * @effects Loads 'ostr' with all data available in 'd'. * @return ostr */ std::ostream& operator<<(std::ostream& ostr, const Dungeon& d) { ostr << std::endl << "PRINTING DUNGEON" << std::endl << std::endl; ostr << "Day: " << *(d._currDay) << std::endl; ostr << "daysPassed: " << d._daysPassed << std::endl; ostr << "Monsters Stored: " << std::endl; for ( unsigned int i = 0; i < d.MONSTER_ARRAY_SIZE; ++i ) { ostr << d._monsterNames[i] << " " << d._monsterTypes[i] << std::endl; } ostr << "Player: " << *(d._player) << std::endl; ostr << "END OF DUNGEON OBJECT" << std::endl; return ostr; } /* Time progression. * @modifies _daysPassed, _currDay * @effects Increments '_daysPassed' and iterates in '_currDay' */ void Dungeon::progressToNextDay(){ ++_daysPassed; generateMonster(); _currDay->moveForwardOneDay(); } /* Hour decrementing operation. * @param numHrs * @modifies _currDay->_hoursOfDay * @effects Decreases '_currDay->_hoursOfDay' by 'numHrs' */ void Dungeon::subtractHrs(int numHrs){ int& currHrs = _currDay->_hoursOfDay; if ( numHrs >= currHrs ) { int remainder = (numHrs - currHrs); //TODO: if we want to allow skipping days through activities we need to make sure a monster is generated //and then then stored(we only should need to auto store if remainder >= 24) progressToNextDay(); //make day move to the next day subtractHrs(remainder); } else { currHrs -= numHrs; } } /* Monster stats modifier. * @param name, name from Monster object * @param monsterAtt, attack from Monster object * @param monsterDef, defense from Monster object * @param monsterHp, health from Monster object * @modifies name, monsterAtt, monsterDef, monsterHp * @effects Scales passed Monter stats to '_daysPassed' */ void Dungeon::scaleStats(std::string& name, int& monsterAtt, int& monsterDef, int& monsterHp){ //based on days passed higher as more days pass. int base = 100; monsterHp = (base + _daysPassed * 2); monsterAtt = (5 + ceil( _daysPassed * 0.33 )); monsterDef = (0 + ceil( _daysPassed * 1.2 )); int minSize = ( _daysPassed < MONSTER_ARRAY_SIZE ? _daysPassed : MONSTER_ARRAY_SIZE ); int nameInd = (rand() % minSize);//std::max(daysPassed)//, Dungeon::MONSTER_ARRAY_SIZE); name = _monsterNames[nameInd]; } /* Creates new Monster object. * @modifies _currDay * @effects Assigns a new Monster to '_currDay'. */ void Dungeon::generateMonster(){ int monsterHp, monsterAtt, monsterDef; std::string name; scaleStats(name, monsterAtt, monsterDef, monsterHp); _currDay->setMonster(name, monsterAtt, monsterDef, monsterHp); _currDay->_currentMonster->getName(); } <commit_msg>Fixed linker error with 'Dungeon.cpp'<commit_after>#include <algorithm> #include <cassert> #include <cmath> #include <fstream> // #include <iostream> #include <sstream> // #include <string> // #include <vector> #include "Dungeon.h" /* Default constructor. * @param playerName, string with user-inputted name for player * @effects Creates a new Dungeon object. */ Dungeon::Dungeon(std::string playerName) { _currDay = new Day(); _daysPassed = 0; _player = new Player( playerName ); loadMonsterData(); // srand(time(NULL)); // generate a random seed } /* File loader. * @param inFileName, char* with file containing Monster names * @param ifstr, instream for reading file * @modifies ifstr, modified to read individual files * @effects Loads all monster information from 'inFileName'. */ void Dungeon::readFile(char* inFileName, std::ifstream &ifstr) { // search up through directory to find file (max of 20 levels up) unsigned int parentDirNum = 0; std::string dirStr = inFileName; ifstr.open(dirStr.c_str(),std::ifstream::in); while ( (!ifstr.good()) && (parentDirNum < 20) ) { dirStr = "../" + dirStr; ++parentDirNum; ifstr.open(dirStr.c_str(),std::ifstream::in); } // verify that we found the file if ( !ifstr.good() ) { // error finding file within max directory search std::cerr << "Problem opening monster name file: " << inFileName << std::endl; } } /* Load Monster attributes. * @modifies _monsterNames, _monsterTypes * @effects Pulls in data from MonsterNamesList and loads into * '_monsterNames' and '_monterTypes' */ void Dungeon::loadMonsterData() { // attempt to load in MonsterNameList.txt std::ifstream ifstr; char* file = (char*) ("MonterNameList.txt"); readFile(file, ifstr); std::string line, name, type, delim = ", "; _monsterNames = new std::string[MONSTER_ARRAY_SIZE]; _monsterTypes = new std::string[MONSTER_ARRAY_SIZE]; unsigned int i = 0; // load in names to '_monsterNames' and types to '_monsterTypes' while ( getline(ifstr, line) ) { name = line.substr(0, line.find(delim)); type = line.substr(line.find(delim) + 2, line.size()); _monsterNames[i] = name; _monsterTypes[i] = type; ++i; } // assert that monster data arrays have length 'MONSTER_ARRAY_SIZE' assert ( i == MONSTER_ARRAY_SIZE ); } /* Standard toString operation. * @param ostr, current outstream for program * @param d, Dungeon object to print * @modifies ostr * @effects Loads 'ostr' with all data available in 'd'. * @return ostr */ std::ostream& operator<<(std::ostream& ostr, const Dungeon& d) { ostr << std::endl << "PRINTING DUNGEON" << std::endl << std::endl; ostr << "Day: " << *(d._currDay) << std::endl; ostr << "daysPassed: " << d._daysPassed << std::endl; ostr << "Monsters Stored: " << std::endl; for ( unsigned int i = 0; i < d.MONSTER_ARRAY_SIZE; ++i ) { ostr << d._monsterNames[i] << " " << d._monsterTypes[i] << std::endl; } ostr << "Player: " << *(d._player) << std::endl; ostr << "END OF DUNGEON OBJECT" << std::endl; return ostr; } /* Time progression. * @modifies _daysPassed, _currDay * @effects Increments '_daysPassed' and iterates in '_currDay' */ void Dungeon::progressToNextDay(){ ++_daysPassed; generateMonster(); _currDay->moveForwardOneDay(); } /* Hour decrementing operation. * @param numHrs * @modifies _currDay->_hoursOfDay * @effects Decreases '_currDay->_hoursOfDay' by 'numHrs' */ void Dungeon::subtractHrs(int numHrs){ int& currHrs = _currDay->_hoursOfDay; if ( numHrs >= currHrs ) { int remainder = (numHrs - currHrs); //TODO: if we want to allow skipping days through activities we need to make sure a monster is generated //and then then stored(we only should need to auto store if remainder >= 24) progressToNextDay(); //make day move to the next day subtractHrs(remainder); } else { currHrs -= numHrs; } } /* Monster stats modifier. * @param name, name from Monster object * @param monsterAtt, attack from Monster object * @param monsterDef, defense from Monster object * @param monsterHp, health from Monster object * @modifies name, monsterAtt, monsterDef, monsterHp * @effects Scales passed Monter stats to '_daysPassed' */ void Dungeon::scaleStats(std::string& name, int& monsterAtt, int& monsterDef, int& monsterHp){ //based on days passed higher as more days pass. int base = 100; monsterHp = (base + _daysPassed * 2); monsterAtt = (5 + ceil( _daysPassed * 0.33 )); monsterDef = (0 + ceil( _daysPassed * 1.2 )); int minSize = ( _daysPassed < MONSTER_ARRAY_SIZE ? _daysPassed : MONSTER_ARRAY_SIZE ); int nameInd = (rand() % minSize);//std::max(daysPassed)//, Dungeon::MONSTER_ARRAY_SIZE); name = _monsterNames[nameInd]; } /* Creates new Monster object. * @modifies _currDay * @effects Assigns a new Monster to '_currDay'. */ void Dungeon::generateMonster(){ int monsterHp, monsterAtt, monsterDef; std::string name; scaleStats(name, monsterAtt, monsterDef, monsterHp); _currDay->setMonster(name, monsterAtt, monsterDef, monsterHp); _currDay->_currentMonster->getName(); } <|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/toolbar/action_box_menu_model.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/chrome_to_mobile_service.h" #include "chrome/browser/chrome_to_mobile_service_factory.h" #include "chrome/browser/command_updater.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/extensions/extension_toolbar_model.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/resource/resource_bundle.h" namespace { // Extensions get command IDs that are beyond the maximal valid extension ID // (0xDFFF) so that they are not confused with actual commands that appear in // the menu. For more details see: chrome/app/chrome_command_ids.h // const int kFirstExtensionCommandId = 0xE000; } // namespace //////////////////////////////////////////////////////////////////////////////// // ActionBoxMenuModel ActionBoxMenuModel::ActionBoxMenuModel(Browser* browser) : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)), browser_(browser) { ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); if (ChromeToMobileServiceFactory::GetForProfile(browser_->profile())-> HasMobiles()) { AddItemWithStringId(IDC_CHROME_TO_MOBILE_PAGE, IDS_CHROME_TO_MOBILE_BUBBLE_TOOLTIP); SetIcon(GetIndexOfCommandId(IDC_CHROME_TO_MOBILE_PAGE), rb.GetNativeImageNamed(IDR_MOBILE)); } TabContents* current_tab_contents = chrome::GetActiveTabContents(browser_); bool starred = current_tab_contents->bookmark_tab_helper()->is_starred(); AddItemWithStringId(IDC_BOOKMARK_PAGE, starred ? IDS_TOOLTIP_STARRED : IDS_TOOLTIP_STAR); SetIcon(GetIndexOfCommandId(IDC_BOOKMARK_PAGE), rb.GetNativeImageNamed(starred ? IDR_STAR_LIT : IDR_STAR)); InsertItemWithStringIdAt(2, IDC_SHARE_PAGE, IDS_SHARE_PAGE); // TODO(skare, stromme): Obtain an icon from UX. // Adds extensions to the model. int command_id = kFirstExtensionCommandId; const extensions::ExtensionList& action_box_items = GetActionBoxMenuItems(); if (!action_box_items.empty()) { AddSeparator(ui::NORMAL_SEPARATOR); for (size_t i = 0; i < action_box_items.size(); ++i) { const extensions::Extension* extension = action_box_items[i]; AddItem(command_id, UTF8ToUTF16(extension->name())); id_to_extension_id_map_[command_id++] = extension->id(); } } } ActionBoxMenuModel::~ActionBoxMenuModel() { // Ensures parent destructor does not use a partially destroyed delegate. set_delegate(NULL); } bool ActionBoxMenuModel::IsItemExtension(int index) { return GetCommandIdAt(index) >= kFirstExtensionCommandId; } const extensions::Extension* ActionBoxMenuModel::GetExtensionAt(int index) { if (!IsItemExtension(index)) return NULL; // ExtensionList is mutable, so need to get up-to-date extension. int command_id = GetCommandIdAt(index); IdToEntensionIdMap::const_iterator it = id_to_extension_id_map_.find(command_id); if (it == id_to_extension_id_map_.end()) return NULL; ExtensionService* extension_service = extensions::ExtensionSystem::Get(browser_->profile())-> extension_service(); return extension_service->GetExtensionById(it->second, false); } bool ActionBoxMenuModel::IsCommandIdChecked(int command_id) const { return false; } bool ActionBoxMenuModel::IsCommandIdEnabled(int command_id) const { return true; } bool ActionBoxMenuModel::GetAcceleratorForCommandId( int command_id, ui::Accelerator* accelerator) { return false; } void ActionBoxMenuModel::ExecuteCommand(int command_id) { if (command_id < kFirstExtensionCommandId) chrome::ExecuteCommand(browser_, command_id); } const extensions::ExtensionList& ActionBoxMenuModel::GetActionBoxMenuItems() { ExtensionService* extension_service = extensions::ExtensionSystem::Get(browser_->profile())-> extension_service(); return extension_service->toolbar_model()->action_box_menu_items(); } void ActionBoxMenuModel::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { } <commit_msg>Use InsertItem/AddItem consistently in Action box, crash fix (resolve commits 154458 and 154546)<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/toolbar/action_box_menu_model.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/chrome_to_mobile_service.h" #include "chrome/browser/chrome_to_mobile_service_factory.h" #include "chrome/browser/command_updater.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/extensions/extension_toolbar_model.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/resource/resource_bundle.h" namespace { // Extensions get command IDs that are beyond the maximal valid extension ID // (0xDFFF) so that they are not confused with actual commands that appear in // the menu. For more details see: chrome/app/chrome_command_ids.h // const int kFirstExtensionCommandId = 0xE000; } // namespace //////////////////////////////////////////////////////////////////////////////// // ActionBoxMenuModel ActionBoxMenuModel::ActionBoxMenuModel(Browser* browser) : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)), browser_(browser) { ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); if (ChromeToMobileServiceFactory::GetForProfile(browser_->profile())-> HasMobiles()) { AddItemWithStringId(IDC_CHROME_TO_MOBILE_PAGE, IDS_CHROME_TO_MOBILE_BUBBLE_TOOLTIP); SetIcon(GetIndexOfCommandId(IDC_CHROME_TO_MOBILE_PAGE), rb.GetNativeImageNamed(IDR_MOBILE)); } TabContents* current_tab_contents = chrome::GetActiveTabContents(browser_); bool starred = current_tab_contents->bookmark_tab_helper()->is_starred(); AddItemWithStringId(IDC_BOOKMARK_PAGE, starred ? IDS_TOOLTIP_STARRED : IDS_TOOLTIP_STAR); SetIcon(GetIndexOfCommandId(IDC_BOOKMARK_PAGE), rb.GetNativeImageNamed(starred ? IDR_STAR_LIT : IDR_STAR)); AddItemWithStringId(IDC_SHARE_PAGE, IDS_SHARE_PAGE); // TODO(skare, stromme): Obtain an icon from UX. // Adds extensions to the model. int command_id = kFirstExtensionCommandId; const extensions::ExtensionList& action_box_items = GetActionBoxMenuItems(); if (!action_box_items.empty()) { AddSeparator(ui::NORMAL_SEPARATOR); for (size_t i = 0; i < action_box_items.size(); ++i) { const extensions::Extension* extension = action_box_items[i]; AddItem(command_id, UTF8ToUTF16(extension->name())); id_to_extension_id_map_[command_id++] = extension->id(); } } } ActionBoxMenuModel::~ActionBoxMenuModel() { // Ensures parent destructor does not use a partially destroyed delegate. set_delegate(NULL); } bool ActionBoxMenuModel::IsItemExtension(int index) { return GetCommandIdAt(index) >= kFirstExtensionCommandId; } const extensions::Extension* ActionBoxMenuModel::GetExtensionAt(int index) { if (!IsItemExtension(index)) return NULL; // ExtensionList is mutable, so need to get up-to-date extension. int command_id = GetCommandIdAt(index); IdToEntensionIdMap::const_iterator it = id_to_extension_id_map_.find(command_id); if (it == id_to_extension_id_map_.end()) return NULL; ExtensionService* extension_service = extensions::ExtensionSystem::Get(browser_->profile())-> extension_service(); return extension_service->GetExtensionById(it->second, false); } bool ActionBoxMenuModel::IsCommandIdChecked(int command_id) const { return false; } bool ActionBoxMenuModel::IsCommandIdEnabled(int command_id) const { return true; } bool ActionBoxMenuModel::GetAcceleratorForCommandId( int command_id, ui::Accelerator* accelerator) { return false; } void ActionBoxMenuModel::ExecuteCommand(int command_id) { if (command_id < kFirstExtensionCommandId) chrome::ExecuteCommand(browser_, command_id); } const extensions::ExtensionList& ActionBoxMenuModel::GetActionBoxMenuItems() { ExtensionService* extension_service = extensions::ExtensionSystem::Get(browser_->profile())-> extension_service(); return extension_service->toolbar_model()->action_box_menu_items(); } void ActionBoxMenuModel::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "GbtMaker.h" #include <glog/logging.h> #include "bitcoin/util.h" #include "Utils.h" #include "utilities_js.hpp" // // bitcoind zmq pub msg type: "hashblock", "hashtx", "rawblock", "rawtx" // #define BITCOIND_ZMQ_HASHBLOCK "hashblock" #define BITCOIND_ZMQ_HASHTX "hashtx" /////////////////////////////////// GbtMaker ///////////////////////////////// GbtMaker::GbtMaker(const string &zmqBitcoindAddr, const string &bitcoindRpcAddr, const string &bitcoindRpcUserpass, const string &kafkaBrokers, uint32_t kRpcCallInterval, bool isCheckZmq) : running_(true), zmqContext_(1/*i/o threads*/), zmqBitcoindAddr_(zmqBitcoindAddr), bitcoindRpcAddr_(bitcoindRpcAddr), bitcoindRpcUserpass_(bitcoindRpcUserpass), lastGbtMakeTime_(0), kRpcCallInterval_(kRpcCallInterval), kafkaBrokers_(kafkaBrokers), kafkaProducer_(kafkaBrokers_.c_str(), KAFKA_TOPIC_RAWGBT, 0/* partition */), isCheckZmq_(isCheckZmq) { } GbtMaker::~GbtMaker() {} bool GbtMaker::init() { map<string, string> options; // set to 1 (0 is an illegal value here), deliver msg as soon as possible. options["queue.buffering.max.ms"] = "1"; if (!kafkaProducer_.setup(&options)) { LOG(ERROR) << "kafka producer setup failure"; return false; } // setup kafka and check if it's alive if (!kafkaProducer_.checkAlive()) { LOG(ERROR) << "kafka is NOT alive"; return false; } // check bitcoind { string response; string request = "{\"jsonrpc\":\"1.0\",\"id\":\"1\",\"method\":\"getinfo\",\"params\":[]}"; bool res = bitcoindRpcCall(bitcoindRpcAddr_.c_str(), bitcoindRpcUserpass_.c_str(), request.c_str(), response); if (!res) { LOG(ERROR) << "bitcoind rpc call failure"; return false; } LOG(INFO) << "bitcoind getinfo: " << response; JsonNode r; if (!JsonNode::parse(response.c_str(), response.c_str() + response.length(), r)) { LOG(ERROR) << "decode gbt failure"; return false; } // check fields if (r["result"].type() != Utilities::JS::type::Obj || r["result"]["connections"].type() != Utilities::JS::type::Int || r["result"]["blocks"].type() != Utilities::JS::type::Int) { LOG(ERROR) << "getinfo missing some fields"; return false; } if (r["result"]["connections"].int32() <= 0) { LOG(ERROR) << "bitcoind connections is zero"; return false; } } if (isCheckZmq_ && !checkBitcoindZMQ()) return false; return true; } bool GbtMaker::checkBitcoindZMQ() { // // bitcoind MUST with option: -zmqpubhashtx // zmq::socket_t subscriber(zmqContext_, ZMQ_SUB); subscriber.connect(zmqBitcoindAddr_); subscriber.setsockopt(ZMQ_SUBSCRIBE, BITCOIND_ZMQ_HASHTX, strlen(BITCOIND_ZMQ_HASHTX)); zmq::message_t ztype, zcontent; LOG(INFO) << "check bitcoind zmq, waiting for zmq message 'hashtx'..."; try { subscriber.recv(&ztype); subscriber.recv(&zcontent); } catch (std::exception & e) { LOG(ERROR) << "bitcoind zmq recv exception: " << e.what(); return false; } const string type = std::string(static_cast<char*>(ztype.data()), ztype.size()); const string content = std::string(static_cast<char*>(zcontent.data()), zcontent.size()); if (type == BITCOIND_ZMQ_HASHTX) { string hashHex; Bin2Hex((const uint8 *)content.data(), content.size(), hashHex); LOG(INFO) << "bitcoind zmq recv hashtx: " << hashHex; return true; } LOG(ERROR) << "unknown zmq message type from bitcoind: " << type; return false; } void GbtMaker::stop() { if (!running_) { return; } running_ = false; LOG(INFO) << "stop gbtmaker"; } void GbtMaker::kafkaProduceMsg(const void *payload, size_t len) { kafkaProducer_.produce(payload, len); } bool GbtMaker::bitcoindRpcGBT(string &response) { string request = "{\"jsonrpc\":\"1.0\",\"id\":\"1\",\"method\":\"getblocktemplate\",\"params\":[]}"; bool res = bitcoindRpcCall(bitcoindRpcAddr_.c_str(), bitcoindRpcUserpass_.c_str(), request.c_str(), response); if (!res) { LOG(ERROR) << "bitcoind rpc failure"; return false; } return true; } string GbtMaker::makeRawGbtMsg() { string gbt; if (!bitcoindRpcGBT(gbt)) { return ""; } JsonNode r; if (!JsonNode::parse(gbt.c_str(), gbt.c_str() + gbt.length(), r)) { LOG(ERROR) << "decode gbt failure: " << gbt; return ""; } // check fields if (r["result"].type() != Utilities::JS::type::Obj || r["result"]["previousblockhash"].type() != Utilities::JS::type::Str || r["result"]["height"].type() != Utilities::JS::type::Int || r["result"]["coinbasevalue"].type() != Utilities::JS::type::Int || r["result"]["bits"].type() != Utilities::JS::type::Str || r["result"]["mintime"].type() != Utilities::JS::type::Int || r["result"]["version"].type() != Utilities::JS::type::Int) { LOG(ERROR) << "gbt check fields failure"; return ""; } const uint256 gbtHash = Hash(gbt.begin(), gbt.end()); LOG(INFO) << "gbt height: " << r["result"]["height"].uint32() << ", prev_hash: " << r["result"]["previousblockhash"].str() << ", coinbase_value: " << r["result"]["coinbasevalue"].uint64() << ", bits: " << r["result"]["bits"].str() << ", mintime: " << r["result"]["mintime"].uint32() << ", version: " << r["result"]["version"].uint32() << "|0x" << Strings::Format("%08x", r["result"]["version"].uint32()) << ", gbthash: " << gbtHash.ToString(); return Strings::Format("{\"created_at_ts\":%u," "\"block_template_base64\":\"%s\"," "\"gbthash\":\"%s\"}", (uint32_t)time(nullptr), EncodeBase64(gbt).c_str(), gbtHash.ToString().c_str()); // return Strings::Format("{\"created_at_ts\":%u," // "\"gbthash\":\"%s\"}", // (uint32_t)time(nullptr), // gbtHash.ToString().c_str()); } void GbtMaker::submitRawGbtMsg(bool checkTime) { ScopeLock sl(lock_); if (checkTime && lastGbtMakeTime_ + kRpcCallInterval_ > time(nullptr)) { return; } const string rawGbtMsg = makeRawGbtMsg(); if (rawGbtMsg.length() == 0) { LOG(ERROR) << "get rawgbt failure"; return; } lastGbtMakeTime_ = (uint32_t)time(nullptr); // submit to Kafka LOG(INFO) << "sumbit to Kafka, msg len: " << rawGbtMsg.length(); kafkaProduceMsg(rawGbtMsg.c_str(), rawGbtMsg.length()); } void GbtMaker::threadListenBitcoind() { zmq::socket_t subscriber(zmqContext_, ZMQ_SUB); subscriber.connect(zmqBitcoindAddr_); subscriber.setsockopt(ZMQ_SUBSCRIBE, BITCOIND_ZMQ_HASHBLOCK, strlen(BITCOIND_ZMQ_HASHBLOCK)); while (running_) { zmq::message_t ztype, zcontent; try { if (subscriber.recv(&ztype, ZMQ_DONTWAIT) == false) { if (!running_) { break; } usleep(50000); // so we sleep and try again continue; } subscriber.recv(&zcontent); } catch (std::exception & e) { LOG(ERROR) << "bitcoind zmq recv exception: " << e.what(); break; // break big while } const string type = std::string(static_cast<char*>(ztype.data()), ztype.size()); const string content = std::string(static_cast<char*>(zcontent.data()), zcontent.size()); if (type == BITCOIND_ZMQ_HASHBLOCK) { string hashHex; Bin2Hex((const uint8 *)content.data(), content.size(), hashHex); LOG(INFO) << ">>>> bitcoind recv hashblock: " << hashHex << " <<<<"; submitRawGbtMsg(false); } else { LOG(ERROR) << "unknown message type from bitcoind: " << type; } } /* /while */ subscriber.close(); LOG(INFO) << "stop thread listen to bitcoind"; } void GbtMaker::run() { thread threadListenBitcoind = thread(&GbtMaker::threadListenBitcoind, this); while (running_) { sleep(1); submitRawGbtMsg(true); } if (threadListenBitcoind.joinable()) threadListenBitcoind.join(); } <commit_msg>add check filed: curtime<commit_after>/* The MIT License (MIT) Copyright (c) [2016] [BTC.COM] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "GbtMaker.h" #include <glog/logging.h> #include "bitcoin/util.h" #include "Utils.h" #include "utilities_js.hpp" // // bitcoind zmq pub msg type: "hashblock", "hashtx", "rawblock", "rawtx" // #define BITCOIND_ZMQ_HASHBLOCK "hashblock" #define BITCOIND_ZMQ_HASHTX "hashtx" /////////////////////////////////// GbtMaker ///////////////////////////////// GbtMaker::GbtMaker(const string &zmqBitcoindAddr, const string &bitcoindRpcAddr, const string &bitcoindRpcUserpass, const string &kafkaBrokers, uint32_t kRpcCallInterval, bool isCheckZmq) : running_(true), zmqContext_(1/*i/o threads*/), zmqBitcoindAddr_(zmqBitcoindAddr), bitcoindRpcAddr_(bitcoindRpcAddr), bitcoindRpcUserpass_(bitcoindRpcUserpass), lastGbtMakeTime_(0), kRpcCallInterval_(kRpcCallInterval), kafkaBrokers_(kafkaBrokers), kafkaProducer_(kafkaBrokers_.c_str(), KAFKA_TOPIC_RAWGBT, 0/* partition */), isCheckZmq_(isCheckZmq) { } GbtMaker::~GbtMaker() {} bool GbtMaker::init() { map<string, string> options; // set to 1 (0 is an illegal value here), deliver msg as soon as possible. options["queue.buffering.max.ms"] = "1"; if (!kafkaProducer_.setup(&options)) { LOG(ERROR) << "kafka producer setup failure"; return false; } // setup kafka and check if it's alive if (!kafkaProducer_.checkAlive()) { LOG(ERROR) << "kafka is NOT alive"; return false; } // check bitcoind { string response; string request = "{\"jsonrpc\":\"1.0\",\"id\":\"1\",\"method\":\"getinfo\",\"params\":[]}"; bool res = bitcoindRpcCall(bitcoindRpcAddr_.c_str(), bitcoindRpcUserpass_.c_str(), request.c_str(), response); if (!res) { LOG(ERROR) << "bitcoind rpc call failure"; return false; } LOG(INFO) << "bitcoind getinfo: " << response; JsonNode r; if (!JsonNode::parse(response.c_str(), response.c_str() + response.length(), r)) { LOG(ERROR) << "decode gbt failure"; return false; } // check fields if (r["result"].type() != Utilities::JS::type::Obj || r["result"]["connections"].type() != Utilities::JS::type::Int || r["result"]["blocks"].type() != Utilities::JS::type::Int) { LOG(ERROR) << "getinfo missing some fields"; return false; } if (r["result"]["connections"].int32() <= 0) { LOG(ERROR) << "bitcoind connections is zero"; return false; } } if (isCheckZmq_ && !checkBitcoindZMQ()) return false; return true; } bool GbtMaker::checkBitcoindZMQ() { // // bitcoind MUST with option: -zmqpubhashtx // zmq::socket_t subscriber(zmqContext_, ZMQ_SUB); subscriber.connect(zmqBitcoindAddr_); subscriber.setsockopt(ZMQ_SUBSCRIBE, BITCOIND_ZMQ_HASHTX, strlen(BITCOIND_ZMQ_HASHTX)); zmq::message_t ztype, zcontent; LOG(INFO) << "check bitcoind zmq, waiting for zmq message 'hashtx'..."; try { subscriber.recv(&ztype); subscriber.recv(&zcontent); } catch (std::exception & e) { LOG(ERROR) << "bitcoind zmq recv exception: " << e.what(); return false; } const string type = std::string(static_cast<char*>(ztype.data()), ztype.size()); const string content = std::string(static_cast<char*>(zcontent.data()), zcontent.size()); if (type == BITCOIND_ZMQ_HASHTX) { string hashHex; Bin2Hex((const uint8 *)content.data(), content.size(), hashHex); LOG(INFO) << "bitcoind zmq recv hashtx: " << hashHex; return true; } LOG(ERROR) << "unknown zmq message type from bitcoind: " << type; return false; } void GbtMaker::stop() { if (!running_) { return; } running_ = false; LOG(INFO) << "stop gbtmaker"; } void GbtMaker::kafkaProduceMsg(const void *payload, size_t len) { kafkaProducer_.produce(payload, len); } bool GbtMaker::bitcoindRpcGBT(string &response) { string request = "{\"jsonrpc\":\"1.0\",\"id\":\"1\",\"method\":\"getblocktemplate\",\"params\":[]}"; bool res = bitcoindRpcCall(bitcoindRpcAddr_.c_str(), bitcoindRpcUserpass_.c_str(), request.c_str(), response); if (!res) { LOG(ERROR) << "bitcoind rpc failure"; return false; } return true; } string GbtMaker::makeRawGbtMsg() { string gbt; if (!bitcoindRpcGBT(gbt)) { return ""; } JsonNode r; if (!JsonNode::parse(gbt.c_str(), gbt.c_str() + gbt.length(), r)) { LOG(ERROR) << "decode gbt failure: " << gbt; return ""; } // check fields if (r["result"].type() != Utilities::JS::type::Obj || r["result"]["previousblockhash"].type() != Utilities::JS::type::Str || r["result"]["height"].type() != Utilities::JS::type::Int || r["result"]["coinbasevalue"].type() != Utilities::JS::type::Int || r["result"]["bits"].type() != Utilities::JS::type::Str || r["result"]["mintime"].type() != Utilities::JS::type::Int || r["result"]["curtime"].type() != Utilities::JS::type::Int || r["result"]["version"].type() != Utilities::JS::type::Int) { LOG(ERROR) << "gbt check fields failure"; return ""; } const uint256 gbtHash = Hash(gbt.begin(), gbt.end()); LOG(INFO) << "gbt height: " << r["result"]["height"].uint32() << ", prev_hash: " << r["result"]["previousblockhash"].str() << ", coinbase_value: " << r["result"]["coinbasevalue"].uint64() << ", bits: " << r["result"]["bits"].str() << ", mintime: " << r["result"]["mintime"].uint32() << ", version: " << r["result"]["version"].uint32() << "|0x" << Strings::Format("%08x", r["result"]["version"].uint32()) << ", gbthash: " << gbtHash.ToString(); return Strings::Format("{\"created_at_ts\":%u," "\"block_template_base64\":\"%s\"," "\"gbthash\":\"%s\"}", (uint32_t)time(nullptr), EncodeBase64(gbt).c_str(), gbtHash.ToString().c_str()); // return Strings::Format("{\"created_at_ts\":%u," // "\"gbthash\":\"%s\"}", // (uint32_t)time(nullptr), // gbtHash.ToString().c_str()); } void GbtMaker::submitRawGbtMsg(bool checkTime) { ScopeLock sl(lock_); if (checkTime && lastGbtMakeTime_ + kRpcCallInterval_ > time(nullptr)) { return; } const string rawGbtMsg = makeRawGbtMsg(); if (rawGbtMsg.length() == 0) { LOG(ERROR) << "get rawgbt failure"; return; } lastGbtMakeTime_ = (uint32_t)time(nullptr); // submit to Kafka LOG(INFO) << "sumbit to Kafka, msg len: " << rawGbtMsg.length(); kafkaProduceMsg(rawGbtMsg.c_str(), rawGbtMsg.length()); } void GbtMaker::threadListenBitcoind() { zmq::socket_t subscriber(zmqContext_, ZMQ_SUB); subscriber.connect(zmqBitcoindAddr_); subscriber.setsockopt(ZMQ_SUBSCRIBE, BITCOIND_ZMQ_HASHBLOCK, strlen(BITCOIND_ZMQ_HASHBLOCK)); while (running_) { zmq::message_t ztype, zcontent; try { if (subscriber.recv(&ztype, ZMQ_DONTWAIT) == false) { if (!running_) { break; } usleep(50000); // so we sleep and try again continue; } subscriber.recv(&zcontent); } catch (std::exception & e) { LOG(ERROR) << "bitcoind zmq recv exception: " << e.what(); break; // break big while } const string type = std::string(static_cast<char*>(ztype.data()), ztype.size()); const string content = std::string(static_cast<char*>(zcontent.data()), zcontent.size()); if (type == BITCOIND_ZMQ_HASHBLOCK) { string hashHex; Bin2Hex((const uint8 *)content.data(), content.size(), hashHex); LOG(INFO) << ">>>> bitcoind recv hashblock: " << hashHex << " <<<<"; submitRawGbtMsg(false); } else { LOG(ERROR) << "unknown message type from bitcoind: " << type; } } /* /while */ subscriber.close(); LOG(INFO) << "stop thread listen to bitcoind"; } void GbtMaker::run() { thread threadListenBitcoind = thread(&GbtMaker::threadListenBitcoind, this); while (running_) { sleep(1); submitRawGbtMsg(true); } if (threadListenBitcoind.joinable()) threadListenBitcoind.join(); } <|endoftext|>
<commit_before>#include "ns3/log.h" #include "ns3/address.h" #include "ns3/node.h" #include "ns3/nstime.h" #include "ns3/socket.h" #include "ns3/simulator.h" #include "ns3/socket-factory.h" #include "ns3/packet.h" #include "ns3/uinteger.h" #include "ns3/trace-source-accessor.h" #include "ns3/tcp-socket-factory.h" #include "HttpGeneratorClient.h" NS_LOG_COMPONENT_DEFINE ("HttpGeneratorClient"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (HttpGeneratorClient); TypeId HttpGeneratorClient::GetTypeId (void) { static TypeId tid = TypeId ("ns3::HttpGeneratorClien") .SetParent<Application> () .AddConstructor<HttpGeneratorClien> () .AddAttribute ("SendSize", "The amount of data to send each time.", UintegerValue (512), MakeUintegerAccessor (&HttpGeneratorClient::m_sendSize), MakeUintegerChecker<uint32_t> (1)) .AddAttribute ("Remote", "The address of the destination", AddressValue (), MakeAddressAccessor (&HttpGeneratorClient::m_peer), MakeAddressChecker ()) .AddAttribute ("MaxBytes", "The total number of bytes to send. " "Once these bytes are sent, " "no data is sent again. The value zero means " "that there is no limit.", UintegerValue (0), MakeUintegerAccessor (&HttpGeneratorClient::m_maxBytes), MakeUintegerChecker<uint32_t> ()) .AddAttribute ("Protocol", "The type of protocol to use.", TypeIdValue (TcpSocketFactory::GetTypeId ()), MakeTypeIdAccessor (&HttpGeneratorClient::m_tid), MakeTypeIdChecker ()) .AddTraceSource ("Tx", "A new packet is created and is sent", MakeTraceSourceAccessor (&HttpGeneratorClient::m_txTrace)) ; return tid; } HttpGeneratorClient::HttpGeneratorClient () : m_socket (0), m_connected (false), m_totBytes (0) { NS_LOG_FUNCTION (this); } HttpGeneratorClient::~HttpGeneratorClient () { NS_LOG_FUNCTION (this); } void HttpGeneratorClient::SetMaxBytes (uint32_t maxBytes) { NS_LOG_FUNCTION (this << maxBytes); m_maxBytes = maxBytes; } Ptr<Socket> HttpGeneratorClient::GetSocket (void) const { NS_LOG_FUNCTION (this); return m_socket; } void HttpGeneratorClient::DoDispose (void) { NS_LOG_FUNCTION (this); m_socket = 0; // chain up Application::DoDispose (); } // Application Methods void HttpGeneratorClient::StartApplication (void) // Called at time specified by Start { NS_LOG_FUNCTION (this); // Create the socket if not already if (!m_socket) { m_socket = Socket::CreateSocket (GetNode (), m_tid); // Fatal error if socket type is not NS3_SOCK_STREAM or NS3_SOCK_SEQPACKET if (m_socket->GetSocketType () != Socket::NS3_SOCK_STREAM && m_socket->GetSocketType () != Socket::NS3_SOCK_SEQPACKET) { NS_FATAL_ERROR ("Using HttpGeneratorClient with an incompatible socket type. " "HttpGeneratorClient requires SOCK_STREAM or SOCK_SEQPACKET. " "In other words, use TCP instead of UDP."); } if (Inet6SocketAddress::IsMatchingType (m_peer)) { m_socket->Bind6 (); } else if (InetSocketAddress::IsMatchingType (m_peer)) { m_socket->Bind (); } m_socket->Connect (m_peer); m_socket->ShutdownRecv (); m_socket->SetConnectCallback ( MakeCallback (&HttpGeneratorClient::ConnectionSucceeded, this), MakeCallback (&HttpGeneratorClient::ConnectionFailed, this)); m_socket->SetSendCallback ( MakeCallback (&HttpGeneratorClient::DataSend, this)); } if (m_connected) { SendData (); } } void HttpGeneratorClient::StopApplication (void) // Called at time specified by Stop { NS_LOG_FUNCTION (this); if (m_socket != 0) { m_socket->Close (); m_connected = false; } else { NS_LOG_WARN ("HttpGeneratorClient found null socket to close in StopApplication"); } } // Private helpers void HttpGeneratorClient::SendData (void) { NS_LOG_FUNCTION (this); while (m_maxBytes == 0 || m_totBytes < m_maxBytes) { // Time to send more uint32_t toSend = m_sendSize; // Make sure we don't send too many if (m_maxBytes > 0) { toSend = std::min (m_sendSize, m_maxBytes - m_totBytes); } NS_LOG_LOGIC ("sending packet at " << Simulator::Now ()); Ptr<Packet> packet = Create<Packet> (toSend); m_txTrace (packet); int actual = m_socket->Send (packet); if (actual > 0) { m_totBytes += actual; } // We exit this loop when actual < toSend as the send side // buffer is full. The "DataSent" callback will pop when // some buffer space has freed ip. if ((unsigned)actual != toSend) { break; } } // Check if time to close (all sent) if (m_totBytes == m_maxBytes && m_connected) { m_socket->Close (); m_connected = false; } } void HttpGeneratorClient::ConnectionSucceeded (Ptr<Socket> socket) { NS_LOG_FUNCTION (this << socket); NS_LOG_LOGIC ("HttpGeneratorClient Connection succeeded"); m_connected = true; SendData (); } void HttpGeneratorClient::ConnectionFailed (Ptr<Socket> socket) { NS_LOG_FUNCTION (this << socket); NS_LOG_LOGIC ("HttpGeneratorClient, Connection Failed"); } void HttpGeneratorClient::DataSend (Ptr<Socket>, uint32_t) { NS_LOG_FUNCTION (this); if (m_connected) { // Only send new data if the connection has completed Simulator::ScheduleNow (&HttpGeneratorClient::SendData, this); } } } // Namespace ns3 <commit_msg>Fixed syntax problem<commit_after>#include "ns3/log.h" #include "ns3/address.h" #include "ns3/node.h" #include "ns3/nstime.h" #include "ns3/socket.h" #include "ns3/simulator.h" #include "ns3/socket-factory.h" #include "ns3/packet.h" #include "ns3/uinteger.h" #include "ns3/trace-source-accessor.h" #include "ns3/tcp-socket-factory.h" #include "HttpGeneratorClient.h" NS_LOG_COMPONENT_DEFINE ("HttpGeneratorClient"); namespace ns3 { NS_OBJECT_ENSURE_REGISTERED (HttpGeneratorClient); TypeId HttpGeneratorClient::GetTypeId (void) { static TypeId tid = TypeId ("ns3::HttpGeneratorClient") .SetParent<Application> () .AddConstructor<HttpGeneratorClient> () .AddAttribute ("SendSize", "The amount of data to send each time.", UintegerValue (512), MakeUintegerAccessor (&HttpGeneratorClient::m_sendSize), MakeUintegerChecker<uint32_t> (1)) .AddAttribute ("Remote", "The address of the destination", AddressValue (), MakeAddressAccessor (&HttpGeneratorClient::m_peer), MakeAddressChecker ()) .AddAttribute ("MaxBytes", "The total number of bytes to send. " "Once these bytes are sent, " "no data is sent again. The value zero means " "that there is no limit.", UintegerValue (0), MakeUintegerAccessor (&HttpGeneratorClient::m_maxBytes), MakeUintegerChecker<uint32_t> ()) .AddAttribute ("Protocol", "The type of protocol to use.", TypeIdValue (TcpSocketFactory::GetTypeId ()), MakeTypeIdAccessor (&HttpGeneratorClient::m_tid), MakeTypeIdChecker ()) .AddTraceSource ("Tx", "A new packet is created and is sent", MakeTraceSourceAccessor (&HttpGeneratorClient::m_txTrace)) ; return tid; } HttpGeneratorClient::HttpGeneratorClient () : m_socket (0), m_connected (false), m_totBytes (0) { NS_LOG_FUNCTION (this); } HttpGeneratorClient::~HttpGeneratorClient () { NS_LOG_FUNCTION (this); } void HttpGeneratorClient::SetMaxBytes (uint32_t maxBytes) { NS_LOG_FUNCTION (this << maxBytes); m_maxBytes = maxBytes; } Ptr<Socket> HttpGeneratorClient::GetSocket (void) const { NS_LOG_FUNCTION (this); return m_socket; } void HttpGeneratorClient::DoDispose (void) { NS_LOG_FUNCTION (this); m_socket = 0; // chain up Application::DoDispose (); } // Application Methods void HttpGeneratorClient::StartApplication (void) // Called at time specified by Start { NS_LOG_FUNCTION (this); // Create the socket if not already if (!m_socket) { m_socket = Socket::CreateSocket (GetNode (), m_tid); // Fatal error if socket type is not NS3_SOCK_STREAM or NS3_SOCK_SEQPACKET if (m_socket->GetSocketType () != Socket::NS3_SOCK_STREAM && m_socket->GetSocketType () != Socket::NS3_SOCK_SEQPACKET) { NS_FATAL_ERROR ("Using HttpGeneratorClient with an incompatible socket type. " "HttpGeneratorClient requires SOCK_STREAM or SOCK_SEQPACKET. " "In other words, use TCP instead of UDP."); } if (Inet6SocketAddress::IsMatchingType (m_peer)) { m_socket->Bind6 (); } else if (InetSocketAddress::IsMatchingType (m_peer)) { m_socket->Bind (); } m_socket->Connect (m_peer); m_socket->ShutdownRecv (); m_socket->SetConnectCallback ( MakeCallback (&HttpGeneratorClient::ConnectionSucceeded, this), MakeCallback (&HttpGeneratorClient::ConnectionFailed, this)); m_socket->SetSendCallback ( MakeCallback (&HttpGeneratorClient::DataSend, this)); } if (m_connected) { SendData (); } } void HttpGeneratorClient::StopApplication (void) // Called at time specified by Stop { NS_LOG_FUNCTION (this); if (m_socket != 0) { m_socket->Close (); m_connected = false; } else { NS_LOG_WARN ("HttpGeneratorClient found null socket to close in StopApplication"); } } // Private helpers void HttpGeneratorClient::SendData (void) { NS_LOG_FUNCTION (this); while (m_maxBytes == 0 || m_totBytes < m_maxBytes) { // Time to send more uint32_t toSend = m_sendSize; // Make sure we don't send too many if (m_maxBytes > 0) { toSend = std::min (m_sendSize, m_maxBytes - m_totBytes); } NS_LOG_LOGIC ("sending packet at " << Simulator::Now ()); Ptr<Packet> packet = Create<Packet> (toSend); m_txTrace (packet); int actual = m_socket->Send (packet); if (actual > 0) { m_totBytes += actual; } // We exit this loop when actual < toSend as the send side // buffer is full. The "DataSent" callback will pop when // some buffer space has freed ip. if ((unsigned)actual != toSend) { break; } } // Check if time to close (all sent) if (m_totBytes == m_maxBytes && m_connected) { m_socket->Close (); m_connected = false; } } void HttpGeneratorClient::ConnectionSucceeded (Ptr<Socket> socket) { NS_LOG_FUNCTION (this << socket); NS_LOG_LOGIC ("HttpGeneratorClient Connection succeeded"); m_connected = true; SendData (); } void HttpGeneratorClient::ConnectionFailed (Ptr<Socket> socket) { NS_LOG_FUNCTION (this << socket); NS_LOG_LOGIC ("HttpGeneratorClient, Connection Failed"); } void HttpGeneratorClient::DataSend (Ptr<Socket>, uint32_t) { NS_LOG_FUNCTION (this); if (m_connected) { // Only send new data if the connection has completed Simulator::ScheduleNow (&HttpGeneratorClient::SendData, this); } } } // Namespace ns3 <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $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 either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** 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.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qstylefactory.h" #include "qstyleplugin.h" #include "private/qfactoryloader_p.h" #include "qmutex.h" #include "qapplication.h" #include "qwindowsstyle.h" #include "qmotifstyle.h" #include "qcdestyle.h" #ifndef QT_NO_STYLE_PLASTIQUE #include "qplastiquestyle.h" #endif #ifndef QT_NO_STYLE_CLEANLOOKS #include "qcleanlooksstyle.h" #endif #ifndef QT_NO_STYLE_GTK #include "qgtkstyle.h" #endif #ifndef QT_NO_STYLE_WINDOWSXP #include "qwindowsxpstyle.h" #endif #ifndef QT_NO_STYLE_WINDOWSVISTA #include "qwindowsvistastyle.h" #endif #ifndef QT_NO_STYLE_WINDOWSCE #include "qwindowscestyle.h" #endif #ifndef QT_NO_STYLE_WINDOWSMOBILE #include "qwindowsmobilestyle.h" #endif QT_BEGIN_NAMESPACE #if !defined(QT_NO_STYLE_MAC) && defined(Q_WS_MAC) QT_BEGIN_INCLUDE_NAMESPACE # include "qmacstyle_mac.h" QT_END_INCLUDE_NAMESPACE #endif #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QStyleFactoryInterface_iid, QLatin1String("/styles"), Qt::CaseInsensitive)) #endif /*! \class QStyleFactory \brief The QStyleFactory class creates QStyle objects. \ingroup appearance The QStyle class is an abstract base class that encapsulates the look and feel of a GUI. QStyleFactory creates a QStyle object using the create() function and a key identifying the style. The styles are either built-in or dynamically loaded from a style plugin (see QStylePlugin). The valid keys can be retrieved using the keys() function. Typically they include "windows", "motif", "cde", "plastique" and "cleanlooks". Depending on the platform, "windowsxp", "windowsvista" and "macintosh" may be available. Note that keys are case insensitive. \sa QStyle */ /*! Creates and returns a QStyle object that matches the given \a key, or returns 0 if no matching style is found. Both built-in styles and styles from style plugins are queried for a matching style. \note The keys used are case insensitive. \sa keys() */ QStyle *QStyleFactory::create(const QString& key) { QStyle *ret = 0; QString style = key.toLower(); #ifndef QT_NO_STYLE_WINDOWS if (style == QLatin1String("windows")) ret = new QWindowsStyle; else #endif #ifndef QT_NO_STYLE_WINDOWSCE if (style == QLatin1String("windowsce")) ret = new QWindowsCEStyle; else #endif #ifndef QT_NO_STYLE_WINDOWSMOBILE if (style == QLatin1String("windowsmobile")) ret = new QWindowsMobileStyle; else #endif #ifndef QT_NO_STYLE_WINDOWSXP if (style == QLatin1String("windowsxp")) ret = new QWindowsXPStyle; else #endif #ifndef QT_NO_STYLE_WINDOWSVISTA if (style == QLatin1String("windowsvista")) ret = new QWindowsVistaStyle; else #endif #ifndef QT_NO_STYLE_MOTIF if (style == QLatin1String("motif")) ret = new QMotifStyle; else #endif #ifndef QT_NO_STYLE_CDE if (style == QLatin1String("cde")) ret = new QCDEStyle; else #endif #ifndef QT_NO_STYLE_PLASTIQUE if (style == QLatin1String("plastique")) ret = new QPlastiqueStyle; else #endif #ifndef QT_NO_STYLE_CLEANLOOKS if (style == QLatin1String("cleanlooks")) ret = new QCleanlooksStyle; else #endif #ifndef QT_NO_STYLE_GTK if (style == QLatin1String("gtk") || style == QLatin1String("gtk+")) ret = new QGtkStyle; else #endif #ifndef QT_NO_STYLE_MAC if (style.left(9) == QLatin1String("macintosh")) { ret = new QMacStyle; # ifdef Q_WS_MAC if (style == QLatin1String("macintosh")) style += QLatin1String(" (aqua)"); # endif } else #endif { } // Keep these here - they make the #ifdefery above work #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if(!ret) { if (QStyleFactoryInterface *factory = qobject_cast<QStyleFactoryInterface*>(loader()->instance(style))) ret = factory->create(style); } #endif if(ret) ret->setObjectName(style); return ret; } /*! Returns the list of valid keys, i.e. the keys this factory can create styles for. \sa create() */ QStringList QStyleFactory::keys() { #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) QStringList list = loader()->keys(); #else QStringList list; #endif #ifndef QT_NO_STYLE_WINDOWS if (!list.contains(QLatin1String("Windows"))) list << QLatin1String("Windows"); #endif #ifndef QT_NO_STYLE_WINDOWSCE if (!list.contains(QLatin1String("WindowsCE"))) list << QLatin1String("WindowsCE"); #endif #ifndef QT_NO_STYLE_WINDOWSMOBILE if (!list.contains(QLatin1String("WindowsMobile"))) list << QLatin1String("WindowsMobile"); #endif #ifndef QT_NO_STYLE_WINDOWSXP if (!list.contains(QLatin1String("WindowsXP")) && (QSysInfo::WindowsVersion >= QSysInfo::WV_XP && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) list << QLatin1String("WindowsXP"); #endif #ifndef QT_NO_STYLE_WINDOWSVISTA if (!list.contains(QLatin1String("WindowsVista")) && (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) list << QLatin1String("WindowsVista"); #endif #ifndef QT_NO_STYLE_MOTIF if (!list.contains(QLatin1String("Motif"))) list << QLatin1String("Motif"); #endif #ifndef QT_NO_STYLE_CDE if (!list.contains(QLatin1String("CDE"))) list << QLatin1String("CDE"); #endif #ifndef QT_NO_STYLE_PLASTIQUE if (!list.contains(QLatin1String("Plastique"))) list << QLatin1String("Plastique"); #endif #ifndef QT_NO_STYLE_GTK if (!list.contains(QLatin1String("GTK+"))) list << QLatin1String("GTK+"); #endif #ifndef QT_NO_STYLE_CLEANLOOKS if (!list.contains(QLatin1String("Cleanlooks"))) list << QLatin1String("Cleanlooks"); #endif #ifndef QT_NO_STYLE_MAC QString mstyle = QLatin1String("Macintosh"); # ifdef Q_WS_MAC mstyle += QLatin1String(" (aqua)"); # endif if (!list.contains(mstyle)) list << mstyle; #endif return list; } QT_END_NAMESPACE <commit_msg>small change in a string, using startsWith<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $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 either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** 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.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qstylefactory.h" #include "qstyleplugin.h" #include "private/qfactoryloader_p.h" #include "qmutex.h" #include "qapplication.h" #include "qwindowsstyle.h" #include "qmotifstyle.h" #include "qcdestyle.h" #ifndef QT_NO_STYLE_PLASTIQUE #include "qplastiquestyle.h" #endif #ifndef QT_NO_STYLE_CLEANLOOKS #include "qcleanlooksstyle.h" #endif #ifndef QT_NO_STYLE_GTK #include "qgtkstyle.h" #endif #ifndef QT_NO_STYLE_WINDOWSXP #include "qwindowsxpstyle.h" #endif #ifndef QT_NO_STYLE_WINDOWSVISTA #include "qwindowsvistastyle.h" #endif #ifndef QT_NO_STYLE_WINDOWSCE #include "qwindowscestyle.h" #endif #ifndef QT_NO_STYLE_WINDOWSMOBILE #include "qwindowsmobilestyle.h" #endif QT_BEGIN_NAMESPACE #if !defined(QT_NO_STYLE_MAC) && defined(Q_WS_MAC) QT_BEGIN_INCLUDE_NAMESPACE # include "qmacstyle_mac.h" QT_END_INCLUDE_NAMESPACE #endif #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QStyleFactoryInterface_iid, QLatin1String("/styles"), Qt::CaseInsensitive)) #endif /*! \class QStyleFactory \brief The QStyleFactory class creates QStyle objects. \ingroup appearance The QStyle class is an abstract base class that encapsulates the look and feel of a GUI. QStyleFactory creates a QStyle object using the create() function and a key identifying the style. The styles are either built-in or dynamically loaded from a style plugin (see QStylePlugin). The valid keys can be retrieved using the keys() function. Typically they include "windows", "motif", "cde", "plastique" and "cleanlooks". Depending on the platform, "windowsxp", "windowsvista" and "macintosh" may be available. Note that keys are case insensitive. \sa QStyle */ /*! Creates and returns a QStyle object that matches the given \a key, or returns 0 if no matching style is found. Both built-in styles and styles from style plugins are queried for a matching style. \note The keys used are case insensitive. \sa keys() */ QStyle *QStyleFactory::create(const QString& key) { QStyle *ret = 0; QString style = key.toLower(); #ifndef QT_NO_STYLE_WINDOWS if (style == QLatin1String("windows")) ret = new QWindowsStyle; else #endif #ifndef QT_NO_STYLE_WINDOWSCE if (style == QLatin1String("windowsce")) ret = new QWindowsCEStyle; else #endif #ifndef QT_NO_STYLE_WINDOWSMOBILE if (style == QLatin1String("windowsmobile")) ret = new QWindowsMobileStyle; else #endif #ifndef QT_NO_STYLE_WINDOWSXP if (style == QLatin1String("windowsxp")) ret = new QWindowsXPStyle; else #endif #ifndef QT_NO_STYLE_WINDOWSVISTA if (style == QLatin1String("windowsvista")) ret = new QWindowsVistaStyle; else #endif #ifndef QT_NO_STYLE_MOTIF if (style == QLatin1String("motif")) ret = new QMotifStyle; else #endif #ifndef QT_NO_STYLE_CDE if (style == QLatin1String("cde")) ret = new QCDEStyle; else #endif #ifndef QT_NO_STYLE_PLASTIQUE if (style == QLatin1String("plastique")) ret = new QPlastiqueStyle; else #endif #ifndef QT_NO_STYLE_CLEANLOOKS if (style == QLatin1String("cleanlooks")) ret = new QCleanlooksStyle; else #endif #ifndef QT_NO_STYLE_GTK if (style == QLatin1String("gtk") || style == QLatin1String("gtk+")) ret = new QGtkStyle; else #endif #ifndef QT_NO_STYLE_MAC if (style.startsWith(QLatin1String("macintosh"))) { ret = new QMacStyle; # ifdef Q_WS_MAC if (style == QLatin1String("macintosh")) style += QLatin1String(" (aqua)"); # endif } else #endif { } // Keep these here - they make the #ifdefery above work #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) if(!ret) { if (QStyleFactoryInterface *factory = qobject_cast<QStyleFactoryInterface*>(loader()->instance(style))) ret = factory->create(style); } #endif if(ret) ret->setObjectName(style); return ret; } /*! Returns the list of valid keys, i.e. the keys this factory can create styles for. \sa create() */ QStringList QStyleFactory::keys() { #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS) QStringList list = loader()->keys(); #else QStringList list; #endif #ifndef QT_NO_STYLE_WINDOWS if (!list.contains(QLatin1String("Windows"))) list << QLatin1String("Windows"); #endif #ifndef QT_NO_STYLE_WINDOWSCE if (!list.contains(QLatin1String("WindowsCE"))) list << QLatin1String("WindowsCE"); #endif #ifndef QT_NO_STYLE_WINDOWSMOBILE if (!list.contains(QLatin1String("WindowsMobile"))) list << QLatin1String("WindowsMobile"); #endif #ifndef QT_NO_STYLE_WINDOWSXP if (!list.contains(QLatin1String("WindowsXP")) && (QSysInfo::WindowsVersion >= QSysInfo::WV_XP && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) list << QLatin1String("WindowsXP"); #endif #ifndef QT_NO_STYLE_WINDOWSVISTA if (!list.contains(QLatin1String("WindowsVista")) && (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)) list << QLatin1String("WindowsVista"); #endif #ifndef QT_NO_STYLE_MOTIF if (!list.contains(QLatin1String("Motif"))) list << QLatin1String("Motif"); #endif #ifndef QT_NO_STYLE_CDE if (!list.contains(QLatin1String("CDE"))) list << QLatin1String("CDE"); #endif #ifndef QT_NO_STYLE_PLASTIQUE if (!list.contains(QLatin1String("Plastique"))) list << QLatin1String("Plastique"); #endif #ifndef QT_NO_STYLE_GTK if (!list.contains(QLatin1String("GTK+"))) list << QLatin1String("GTK+"); #endif #ifndef QT_NO_STYLE_CLEANLOOKS if (!list.contains(QLatin1String("Cleanlooks"))) list << QLatin1String("Cleanlooks"); #endif #ifndef QT_NO_STYLE_MAC QString mstyle = QLatin1String("Macintosh"); # ifdef Q_WS_MAC mstyle += QLatin1String(" (aqua)"); # endif if (!list.contains(mstyle)) list << mstyle; #endif return list; } QT_END_NAMESPACE <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <string> #include <iostream> #include <vector> #include <atomic> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "assert.hpp" #include "Options.hpp" using namespace eddic; namespace po = boost::program_options; namespace { std::pair<std::string, std::string> numeric_parser(const std::string& s){ if (s.find("-32") == 0) { return make_pair("32", std::string("true")); } else if (s.find("-64") == 0) { return make_pair("64", std::string("true")); } else { return make_pair(std::string(), std::string()); } } std::atomic<bool> description_flag; po::options_description visible("Usage : eddic [options] source.eddi"); po::options_description all("Usage : eddic [options] source.eddi"); std::unordered_map<std::string, std::vector<std::string>> triggers; void add_trigger(const std::string& option, const std::vector<std::string>& childs){ triggers[option] = childs; } void init_descriptions(){ po::options_description general("General options"); general.add_options() ("help,h", "Generate this help message") ("assembly,S", "Generate only the assembly") ("keep,k", "Keep the assembly file") ("version", "Print the version of eddic") ("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable") ("debug,g", "Add debugging symbols") ("template-depth", po::value<int>()->default_value(100), "Define the maximum template depth") ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ; po::options_description display("Display options"); display.add_options() ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; po::options_description optimization("Optimization options"); optimization.add_options() ("Opt,O", po::value<int>()->implicit_value(0)->default_value(2), "Define the optimization level") ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations. This can be slow for big programs.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ; po::options_description backend("Backend options"); backend.add_options() ("log", po::value<int>()->default_value(0), "Define the logging") ("quiet,q", "Do not print anything") ("verbose,v", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("timing", "Activate timing system") ("input", po::value<std::string>(), "Input file") ; all.add(general).add(display).add(optimization).add(backend); visible.add(general).add(display).add(optimization); add_trigger("warning-all", {"warning-unused", "warning-cast"}); //Special triggers for optimization levels add_trigger("__1", {"fpeephole-optimization"}); add_trigger("__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"}); } inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){ for(auto& child : childs){ configuration->values[child].defined = true; configuration->values[child].value = std::string("true"); } } } //end of anonymous namespace std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) { //Create a new configuration auto configuration = std::make_shared<Configuration>(); try { //Only if the description has not been already defined if(!description_flag.load()){ bool old_value = description_flag.load(); if(description_flag.compare_exchange_strong(old_value, true)){ init_descriptions(); } } //Add the option of the input file po::positional_options_description p; p.add("input", -1); //Create a new set of options po::variables_map options; //Parse the command line options po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options); po::notify(options); //Transfer the options in the eddic configuration for(auto& option : all.options()){ ConfigValue value; if(options.count(option->long_name())){ value.defined = true; value.value = options[option->long_name()].value(); } else { value.defined = false; value.value = std::string("false"); } configuration->values[option->long_name()] = value; } if(options.count("O0") + options.count("O1") + options.count("O2") > 1){ std::cout << "Invalid command line options : only one optimization level should be set" << std::endl; return nullptr; } if(options.count("64") && options.count("32")){ std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl; return nullptr; } //Update optimization level based on special switches if(options.count("O0")){ configuration->values["Opt"].value = 0; } else if(options.count("O1")){ configuration->values["Opt"].value = 1; } else if(options.count("O2")){ configuration->values["Opt"].value = 2; } //Triggers dependent options for(auto& trigger : triggers){ if(configuration->option_defined(trigger.first)){ trigger_childs(configuration, trigger.second); } } if(configuration->option_int_value("Opt") >= 1){ trigger_childs(configuration, triggers["__1"]); } if(configuration->option_int_value("Opt") >= 2){ trigger_childs(configuration, triggers["__2"]); } } catch (const po::ambiguous_option& e) { std::cout << "Invalid command line options : " << e.what() << std::endl; return nullptr; } catch (const po::unknown_option& e) { std::cout << "Invalid command line options : " << e.what() << std::endl; return nullptr; } catch (const po::multiple_occurrences& e) { std::cout << "Only one file can be compiled" << std::endl; return nullptr; } return configuration; } bool Configuration::option_defined(const std::string& option_name){ return values[option_name].defined; } std::string Configuration::option_value(const std::string& option_name){ return boost::any_cast<std::string>(values[option_name].value); } int Configuration::option_int_value(const std::string& option_name){ return boost::any_cast<int>(values[option_name].value); } void eddic::print_help(){ std::cout << visible << std::endl; } void eddic::print_version(){ std::cout << "eddic version 1.1.4" << std::endl; } <commit_msg>The new warning is automatically executed<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <string> #include <iostream> #include <vector> #include <atomic> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "assert.hpp" #include "Options.hpp" using namespace eddic; namespace po = boost::program_options; namespace { std::pair<std::string, std::string> numeric_parser(const std::string& s){ if (s.find("-32") == 0) { return make_pair("32", std::string("true")); } else if (s.find("-64") == 0) { return make_pair("64", std::string("true")); } else { return make_pair(std::string(), std::string()); } } std::atomic<bool> description_flag; po::options_description visible("Usage : eddic [options] source.eddi"); po::options_description all("Usage : eddic [options] source.eddi"); std::unordered_map<std::string, std::vector<std::string>> triggers; void add_trigger(const std::string& option, const std::vector<std::string>& childs){ triggers[option] = childs; } void init_descriptions(){ po::options_description general("General options"); general.add_options() ("help,h", "Generate this help message") ("assembly,S", "Generate only the assembly") ("keep,k", "Keep the assembly file") ("version", "Print the version of eddic") ("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable") ("debug,g", "Add debugging symbols") ("template-depth", po::value<int>()->default_value(100), "Define the maximum template depth") ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ; po::options_description display("Display options"); display.add_options() ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; po::options_description optimization("Optimization options"); optimization.add_options() ("Opt,O", po::value<int>()->implicit_value(0)->default_value(2), "Define the optimization level") ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations. This can be slow for big programs.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ; po::options_description backend("Backend options"); backend.add_options() ("log", po::value<int>()->default_value(0), "Define the logging") ("quiet,q", "Do not print anything") ("verbose,v", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("timing", "Activate timing system") ("input", po::value<std::string>(), "Input file") ; all.add(general).add(display).add(optimization).add(backend); visible.add(general).add(display).add(optimization); add_trigger("warning-all", {"warning-unused", "warning-cast", "warning-effects"}); //Special triggers for optimization levels add_trigger("__1", {"fpeephole-optimization"}); add_trigger("__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"}); } inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){ for(auto& child : childs){ configuration->values[child].defined = true; configuration->values[child].value = std::string("true"); } } } //end of anonymous namespace std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) { //Create a new configuration auto configuration = std::make_shared<Configuration>(); try { //Only if the description has not been already defined if(!description_flag.load()){ bool old_value = description_flag.load(); if(description_flag.compare_exchange_strong(old_value, true)){ init_descriptions(); } } //Add the option of the input file po::positional_options_description p; p.add("input", -1); //Create a new set of options po::variables_map options; //Parse the command line options po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options); po::notify(options); //Transfer the options in the eddic configuration for(auto& option : all.options()){ ConfigValue value; if(options.count(option->long_name())){ value.defined = true; value.value = options[option->long_name()].value(); } else { value.defined = false; value.value = std::string("false"); } configuration->values[option->long_name()] = value; } if(options.count("O0") + options.count("O1") + options.count("O2") > 1){ std::cout << "Invalid command line options : only one optimization level should be set" << std::endl; return nullptr; } if(options.count("64") && options.count("32")){ std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl; return nullptr; } //Update optimization level based on special switches if(options.count("O0")){ configuration->values["Opt"].value = 0; } else if(options.count("O1")){ configuration->values["Opt"].value = 1; } else if(options.count("O2")){ configuration->values["Opt"].value = 2; } //Triggers dependent options for(auto& trigger : triggers){ if(configuration->option_defined(trigger.first)){ trigger_childs(configuration, trigger.second); } } if(configuration->option_int_value("Opt") >= 1){ trigger_childs(configuration, triggers["__1"]); } if(configuration->option_int_value("Opt") >= 2){ trigger_childs(configuration, triggers["__2"]); } } catch (const po::ambiguous_option& e) { std::cout << "Invalid command line options : " << e.what() << std::endl; return nullptr; } catch (const po::unknown_option& e) { std::cout << "Invalid command line options : " << e.what() << std::endl; return nullptr; } catch (const po::multiple_occurrences& e) { std::cout << "Only one file can be compiled" << std::endl; return nullptr; } return configuration; } bool Configuration::option_defined(const std::string& option_name){ return values[option_name].defined; } std::string Configuration::option_value(const std::string& option_name){ return boost::any_cast<std::string>(values[option_name].value); } int Configuration::option_int_value(const std::string& option_name){ return boost::any_cast<int>(values[option_name].value); } void eddic::print_help(){ std::cout << visible << std::endl; } void eddic::print_version(){ std::cout << "eddic version 1.1.4" << std::endl; } <|endoftext|>
<commit_before>/* * Copyright 2010-2013 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "HTMLStyleElementImp.h" #include "css/CSSParser.h" #include "css/CSSStyleSheetImp.h" #include <boost/bind.hpp> #include "TextImp.h" #include "DocumentImp.h" #include "WindowImp.h" #include "Test.util.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { HTMLStyleElementImp::HTMLStyleElementImp(DocumentImp* ownerDocument) : ObjectMixin(ownerDocument, u"style"), mutationListener(boost::bind(&HTMLStyleElementImp::handleMutation, this, _1, _2)), type(u"text/css"), media(u"all"), scoped(false), styleSheet(0) { addEventListener(u"DOMNodeInserted", &mutationListener, false, EventTargetImp::UseDefault); addEventListener(u"DOMNodeRemoved", &mutationListener, false, EventTargetImp::UseDefault); // TODO: The following code makes the html paser very slow... addEventListener(u"DOMCharacterDataModified", &mutationListener, false, EventTargetImp::UseDefault); } HTMLStyleElementImp::HTMLStyleElementImp(HTMLStyleElementImp* org, bool deep) : ObjectMixin(org, deep), mutationListener(boost::bind(&HTMLStyleElementImp::handleMutation, this, _1, _2)), type(org->type), media(org->media), scoped(org->scoped), styleSheet(org->styleSheet) // TODO: make a clone sheet, too? { addEventListener(u"DOMNodeInserted", &mutationListener, false, EventTargetImp::UseDefault); addEventListener(u"DOMNodeRemoved", &mutationListener, false, EventTargetImp::UseDefault); // TODO: The following code makes the the html paser very slow... addEventListener(u"DOMCharacterDataModified", &mutationListener, false, EventTargetImp::UseDefault); } void HTMLStyleElementImp::handleMutation(EventListenerImp* listener, events::Event event) { // TODO: update type, media, and scoped. Then check type. events::MutationEvent mutation(interface_cast<events::MutationEvent>(event)); DocumentImp* document = getOwnerDocumentImp(); if (!document) return; if (mutation.getType() == u"DOMNodeRemoved" && event.getTarget().self() == this) { styleSheet = 0; if (WindowImp* view = document->getDefaultWindow()) view->setFlags(Box::NEED_SELECTOR_REMATCHING); } else { std::u16string content; for (Node node = getFirstChild(); node; node = node.getNextSibling()) { if (TextImp* text = dynamic_cast<TextImp*>(node.self())) // TODO better to avoid imp call? content += text->getData(); } CSSParser parser; styleSheet = parser.parse(document, content); if (auto imp = dynamic_cast<CSSStyleSheetImp*>(styleSheet.self())) imp->setOwnerNode(this); if (4 <= getLogLevel()) dumpStyleSheet(std::cerr, styleSheet.self()); if (WindowImp* view = document->getDefaultWindow()) view->setFlags(Box::NEED_SELECTOR_REMATCHING); } document->resetStyleSheets(); } // Node Node HTMLStyleElementImp::cloneNode(bool deep) { return new(std::nothrow) HTMLStyleElementImp(this, deep); } // HTMLStyleElement bool HTMLStyleElementImp::getDisabled() { if (!styleSheet) return false; return styleSheet.getDisabled(); } void HTMLStyleElementImp::setDisabled(bool disabled) { if (styleSheet) styleSheet.setDisabled(disabled); } std::u16string HTMLStyleElementImp::getMedia() { return media; } void HTMLStyleElementImp::setMedia(const std::u16string& media) { this->media = media; } std::u16string HTMLStyleElementImp::getType() { return type; } void HTMLStyleElementImp::setType(const std::u16string& type) { this->type = type; } bool HTMLStyleElementImp::getScoped() { return scoped; } void HTMLStyleElementImp::setScoped(bool scoped) { this->scoped = scoped; } // LinkStyle stylesheets::StyleSheet HTMLStyleElementImp::getSheet() { return styleSheet; } }}}} // org::w3c::dom::bootstrap <commit_msg>(HTMLStyleElementImp::handleMutation): Clean up<commit_after>/* * Copyright 2010-2013 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "HTMLStyleElementImp.h" #include "css/CSSParser.h" #include "css/CSSStyleSheetImp.h" #include <boost/bind.hpp> #include "TextImp.h" #include "DocumentImp.h" #include "WindowImp.h" #include "Test.util.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { HTMLStyleElementImp::HTMLStyleElementImp(DocumentImp* ownerDocument) : ObjectMixin(ownerDocument, u"style"), mutationListener(boost::bind(&HTMLStyleElementImp::handleMutation, this, _1, _2)), type(u"text/css"), media(u"all"), scoped(false), styleSheet(0) { addEventListener(u"DOMNodeInserted", &mutationListener, false, EventTargetImp::UseDefault); addEventListener(u"DOMNodeRemoved", &mutationListener, false, EventTargetImp::UseDefault); // TODO: The following code makes the html paser very slow... addEventListener(u"DOMCharacterDataModified", &mutationListener, false, EventTargetImp::UseDefault); } HTMLStyleElementImp::HTMLStyleElementImp(HTMLStyleElementImp* org, bool deep) : ObjectMixin(org, deep), mutationListener(boost::bind(&HTMLStyleElementImp::handleMutation, this, _1, _2)), type(org->type), media(org->media), scoped(org->scoped), styleSheet(org->styleSheet) // TODO: make a clone sheet, too? { addEventListener(u"DOMNodeInserted", &mutationListener, false, EventTargetImp::UseDefault); addEventListener(u"DOMNodeRemoved", &mutationListener, false, EventTargetImp::UseDefault); // TODO: The following code makes the the html paser very slow... addEventListener(u"DOMCharacterDataModified", &mutationListener, false, EventTargetImp::UseDefault); } void HTMLStyleElementImp::handleMutation(EventListenerImp* listener, events::Event event) { // TODO: update type, media, and scoped. Then check type. events::MutationEvent mutation(interface_cast<events::MutationEvent>(event)); DocumentImp* document = getOwnerDocumentImp(); if (!document) return; if (mutation.getType() == u"DOMNodeRemoved" && event.getTarget().self() == this) styleSheet = 0; else { std::u16string content; for (Node node = getFirstChild(); node; node = node.getNextSibling()) { if (TextImp* text = dynamic_cast<TextImp*>(node.self())) // TODO better to avoid imp call? content += text->getData(); } CSSParser parser; styleSheet = parser.parse(document, content); if (auto imp = dynamic_cast<CSSStyleSheetImp*>(styleSheet.self())) { imp->setOwnerNode(this); if (4 <= getLogLevel()) dumpStyleSheet(std::cerr, imp); } } if (WindowImp* view = document->getDefaultWindow()) view->setFlags(Box::NEED_SELECTOR_REMATCHING); document->resetStyleSheets(); } // Node Node HTMLStyleElementImp::cloneNode(bool deep) { return new(std::nothrow) HTMLStyleElementImp(this, deep); } // HTMLStyleElement bool HTMLStyleElementImp::getDisabled() { if (!styleSheet) return false; return styleSheet.getDisabled(); } void HTMLStyleElementImp::setDisabled(bool disabled) { if (styleSheet) styleSheet.setDisabled(disabled); } std::u16string HTMLStyleElementImp::getMedia() { return media; } void HTMLStyleElementImp::setMedia(const std::u16string& media) { this->media = media; } std::u16string HTMLStyleElementImp::getType() { return type; } void HTMLStyleElementImp::setType(const std::u16string& type) { this->type = type; } bool HTMLStyleElementImp::getScoped() { return scoped; } void HTMLStyleElementImp::setScoped(bool scoped) { this->scoped = scoped; } // LinkStyle stylesheets::StyleSheet HTMLStyleElementImp::getSheet() { return styleSheet; } }}}} // org::w3c::dom::bootstrap <|endoftext|>
<commit_before>// Plugins.cpp #include "stdafx.h" #include "Plugins.h" #include "wx/sizer.h" #include "wx/menuitem.h" #include "wx/checklst.h" #include <wx/config.h> #include <wx/confbase.h> #include <wx/fileconf.h> enum { ID_BUTTON_ADD, ID_BUTTON_EDIT, ID_BUTTON_REMOVE, ID_BUTTON_PLUGIN_BROWSE, ID_LISTBOX_CONTROL }; BEGIN_EVENT_TABLE( CPluginItemDialog, wxDialog ) EVT_BUTTON( ID_BUTTON_PLUGIN_BROWSE, CPluginItemDialog::OnButtonBrowse ) EVT_BUTTON( wxID_OK, CPluginItemDialog::OnButtonOK ) EVT_BUTTON( wxID_CANCEL, CPluginItemDialog::OnButtonCancel ) END_EVENT_TABLE() CPluginItemDialog::CPluginItemDialog(wxWindow *parent, const wxString& title, PluginData& pd):wxDialog(parent, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) { m_pd = &pd; m_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); // create buttons wxButton *button1 = new wxButton(m_panel, wxID_OK); wxButton *button2 = new wxButton(m_panel, wxID_CANCEL); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxFlexGridSizer *gridsizer = new wxFlexGridSizer(3, 5, 5); gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _("Name")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); m_name_text_ctrl = new wxTextCtrl(m_panel, wxID_ANY, pd.name); gridsizer->Add(m_name_text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Expand()); gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _T("")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _("File Path")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); m_path_text_ctrl = new wxTextCtrl(m_panel, wxID_ANY, pd.path, wxDefaultPosition, wxSize(400, 0)); gridsizer->Add(m_path_text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Expand()); gridsizer->Add(new wxButton(m_panel, ID_BUTTON_PLUGIN_BROWSE, _T("...")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); gridsizer->AddGrowableCol(1, 1); wxBoxSizer *bottomsizer = new wxBoxSizer( wxHORIZONTAL ); bottomsizer->Add( button1, 0, wxALL, 10 ); bottomsizer->Add( button2, 0, wxALL, 10 ); mainsizer->Add( gridsizer, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); mainsizer->Add( bottomsizer, wxSizerFlags().Align(wxALIGN_CENTER) ); // tell frame to make use of sizer (or constraints, if any) m_panel->SetAutoLayout( true ); m_panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CPluginItemDialog::OnButtonOK(wxCommandEvent& event) { // it must have a name if(m_name_text_ctrl->GetValue().Len() == 0) { wxMessageBox(_("Plugin must have a name!")); m_name_text_ctrl->SetFocus(); return; } // it must have a file path if(m_path_text_ctrl->GetValue().Len() == 0) { wxMessageBox(_("No file specified!")); m_path_text_ctrl->SetFocus(); return; } m_pd->name = m_name_text_ctrl->GetValue(); m_pd->path = m_path_text_ctrl->GetValue(); EndModal(wxID_OK); } void CPluginItemDialog::OnButtonCancel(wxCommandEvent& event) { EndModal(wxID_CANCEL); } void CPluginItemDialog::OnButtonBrowse(wxCommandEvent& event) { #ifdef WIN32 wxString ext_str(_T("*.dll")); #else wxString ext_str(_T("*.so")); #endif wxString wildcard_string = wxString(_("shared library files")) + _T(" |") + ext_str; wxFileDialog dialog(this, _("Choose shared library file"), wxEmptyString, wxEmptyString, wildcard_string); dialog.CentreOnParent(); if (dialog.ShowModal() == wxID_OK) { m_path_text_ctrl->SetValue(dialog.GetPath()); } } BEGIN_EVENT_TABLE( CPluginsDialog, wxDialog ) EVT_BUTTON( ID_BUTTON_ADD, CPluginsDialog::OnButtonAdd ) EVT_BUTTON( ID_BUTTON_EDIT, CPluginsDialog::OnButtonEdit ) EVT_UPDATE_UI(ID_BUTTON_EDIT, CPluginsDialog::OnUpdateEdit) EVT_BUTTON( ID_BUTTON_REMOVE, CPluginsDialog::OnButtonRemove ) EVT_UPDATE_UI(ID_BUTTON_REMOVE, CPluginsDialog::OnUpdateRemove) EVT_BUTTON( wxID_OK, CPluginsDialog::OnButtonOK ) EVT_BUTTON( wxID_CANCEL, CPluginsDialog::OnButtonCancel ) EVT_LISTBOX_DCLICK(ID_LISTBOX_CONTROL, CPluginsDialog::OnListboxDblClick) END_EVENT_TABLE() CPluginsDialog::CPluginsDialog(wxWindow *parent):wxDialog(parent, wxID_ANY, _("HeeksCAD plugin libraries"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) { // make a panel with some controls m_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); ReadPluginsList(m_plugins); CreateCheckListbox(); // create buttons wxButton *button1 = new wxButton(m_panel, ID_BUTTON_ADD, _("New")); wxButton *button2 = new wxButton(m_panel, ID_BUTTON_EDIT, _("Edit")); wxButton *button3 = new wxButton(m_panel, ID_BUTTON_REMOVE, _("Delete")); wxButton *button4 = new wxButton(m_panel, wxID_OK); wxButton *button5 = new wxButton(m_panel, wxID_CANCEL); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); mainsizer->Add( m_pListBox, 1, wxGROW|wxALL, 10 ); wxBoxSizer *bottomsizer = new wxBoxSizer( wxHORIZONTAL ); bottomsizer->Add( button1, 0, wxALL, 10 ); bottomsizer->Add( button2, 0, wxALL, 10 ); bottomsizer->Add( button3, 0, wxALL, 10 ); bottomsizer->Add( button4, 0, wxALL, 10 ); bottomsizer->Add( button5, 0, wxALL, 10 ); mainsizer->Add( bottomsizer, 0, wxCENTER ); // tell frame to make use of sizer (or constraints, if any) m_panel->SetAutoLayout( true ); m_panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void ReadPluginsList(std::list<PluginData> &plugins) { plugins.clear(); ::wxSetWorkingDirectory(wxGetApp().GetExeFolder()); wxConfig plugins_config(_T("HeeksCAD")); plugins_config.SetPath(_T("/plugins")); wxString key; long Index; wxString str; bool entry_found = false; entry_found = plugins_config.GetFirstEntry(key, Index); while(entry_found) { plugins_config.Read(key, &str); PluginData pd; if(str[0] == '#') { str = str.Mid(1); pd.enabled = false; } else { pd.enabled = true; } pd.name = key; pd.path = str; plugins.push_back(pd); entry_found = plugins_config.GetNextEntry(key, Index); } } void CPluginsDialog::CreateCheckListbox(long flags) { wxString *astrChoices = new wxString[m_plugins.size()]; unsigned int ui = 0; for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ ) { PluginData &pd = *It; astrChoices[ui] = pd.name; } m_pListBox = new wxCheckListBox ( m_panel, // parent ID_LISTBOX_CONTROL, // control id wxPoint(10, 10), // listbox poistion wxSize(400, 100), // listbox size m_plugins.size(), // number of strings astrChoices, // array of strings flags ); delete [] astrChoices; ui = 0; for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ ) { PluginData &pd = *It; if(pd.enabled)m_pListBox->Check(ui); } } void CPluginsDialog::EditSelected(int selection) { unsigned int ui = 0; for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ ) { if(ui == selection) { PluginData &pd = *It; CPluginItemDialog dlg(this, _("Add New Plugin"), pd); if(dlg.ShowModal() == wxID_OK) { // updata the check list delete m_pListBox; CreateCheckListbox(); } } } } void CPluginsDialog::OnButtonAdd(wxCommandEvent& event) { PluginData pd; CPluginItemDialog dlg(this, _("Add New Plugin"), pd); if(dlg.ShowModal() == wxID_OK) { // add the new item m_plugins.push_back(pd); // updata the check list delete m_pListBox; CreateCheckListbox(); } } void CPluginsDialog::OnButtonEdit(wxCommandEvent& event) { int selection = m_pListBox->GetSelection(); EditSelected(selection); } void CPluginsDialog::OnUpdateEdit( wxUpdateUIEvent& event ) { event.Enable(m_pListBox->GetSelection() >= 0); } void CPluginsDialog::OnUpdateRemove( wxUpdateUIEvent& event ) { event.Enable(m_pListBox->GetSelection() >= 0); } void CPluginsDialog::OnButtonRemove(wxCommandEvent& event) { delete m_pListBox; CreateCheckListbox(); } void CPluginsDialog::OnButtonOK(wxCommandEvent& event) { ::wxSetWorkingDirectory(wxGetApp().GetExeFolder()); wxConfig plugins_config(_T("HeeksCAD")); plugins_config.SetPath(_T("/plugins")); plugins_config.DeleteGroup(_T("plugins")); unsigned int ui = 0; for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ ) { PluginData &pd = *It; pd.enabled = m_pListBox->IsChecked(ui); wxString value = pd.path; if(!(pd.enabled))value.Prepend(_T("#")); plugins_config.Write(pd.name, value); } EndModal(wxID_OK); } void CPluginsDialog::OnButtonCancel(wxCommandEvent& event) { EndModal(wxID_CANCEL); } void CPluginsDialog::OnListboxDblClick(wxCommandEvent& WXUNUSED(event)) { int selection = m_pListBox->GetSelection(); EditSelected(selection); } <commit_msg>unsigned comparison warning<commit_after>// Plugins.cpp #include "stdafx.h" #include "Plugins.h" #include "wx/sizer.h" #include "wx/menuitem.h" #include "wx/checklst.h" #include <wx/config.h> #include <wx/confbase.h> #include <wx/fileconf.h> enum { ID_BUTTON_ADD, ID_BUTTON_EDIT, ID_BUTTON_REMOVE, ID_BUTTON_PLUGIN_BROWSE, ID_LISTBOX_CONTROL }; BEGIN_EVENT_TABLE( CPluginItemDialog, wxDialog ) EVT_BUTTON( ID_BUTTON_PLUGIN_BROWSE, CPluginItemDialog::OnButtonBrowse ) EVT_BUTTON( wxID_OK, CPluginItemDialog::OnButtonOK ) EVT_BUTTON( wxID_CANCEL, CPluginItemDialog::OnButtonCancel ) END_EVENT_TABLE() CPluginItemDialog::CPluginItemDialog(wxWindow *parent, const wxString& title, PluginData& pd):wxDialog(parent, wxID_ANY, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) { m_pd = &pd; m_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); // create buttons wxButton *button1 = new wxButton(m_panel, wxID_OK); wxButton *button2 = new wxButton(m_panel, wxID_CANCEL); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxFlexGridSizer *gridsizer = new wxFlexGridSizer(3, 5, 5); gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _("Name")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); m_name_text_ctrl = new wxTextCtrl(m_panel, wxID_ANY, pd.name); gridsizer->Add(m_name_text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Expand()); gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _T("")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); gridsizer->Add(new wxStaticText(m_panel, wxID_ANY, _("File Path")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); m_path_text_ctrl = new wxTextCtrl(m_panel, wxID_ANY, pd.path, wxDefaultPosition, wxSize(400, 0)); gridsizer->Add(m_path_text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL).Expand()); gridsizer->Add(new wxButton(m_panel, ID_BUTTON_PLUGIN_BROWSE, _T("...")), wxSizerFlags().Align(wxALIGN_CENTER_VERTICAL)); gridsizer->AddGrowableCol(1, 1); wxBoxSizer *bottomsizer = new wxBoxSizer( wxHORIZONTAL ); bottomsizer->Add( button1, 0, wxALL, 10 ); bottomsizer->Add( button2, 0, wxALL, 10 ); mainsizer->Add( gridsizer, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); mainsizer->Add( bottomsizer, wxSizerFlags().Align(wxALIGN_CENTER) ); // tell frame to make use of sizer (or constraints, if any) m_panel->SetAutoLayout( true ); m_panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CPluginItemDialog::OnButtonOK(wxCommandEvent& event) { // it must have a name if(m_name_text_ctrl->GetValue().Len() == 0) { wxMessageBox(_("Plugin must have a name!")); m_name_text_ctrl->SetFocus(); return; } // it must have a file path if(m_path_text_ctrl->GetValue().Len() == 0) { wxMessageBox(_("No file specified!")); m_path_text_ctrl->SetFocus(); return; } m_pd->name = m_name_text_ctrl->GetValue(); m_pd->path = m_path_text_ctrl->GetValue(); EndModal(wxID_OK); } void CPluginItemDialog::OnButtonCancel(wxCommandEvent& event) { EndModal(wxID_CANCEL); } void CPluginItemDialog::OnButtonBrowse(wxCommandEvent& event) { #ifdef WIN32 wxString ext_str(_T("*.dll")); #else wxString ext_str(_T("*.so")); #endif wxString wildcard_string = wxString(_("shared library files")) + _T(" |") + ext_str; wxFileDialog dialog(this, _("Choose shared library file"), wxEmptyString, wxEmptyString, wildcard_string); dialog.CentreOnParent(); if (dialog.ShowModal() == wxID_OK) { m_path_text_ctrl->SetValue(dialog.GetPath()); } } BEGIN_EVENT_TABLE( CPluginsDialog, wxDialog ) EVT_BUTTON( ID_BUTTON_ADD, CPluginsDialog::OnButtonAdd ) EVT_BUTTON( ID_BUTTON_EDIT, CPluginsDialog::OnButtonEdit ) EVT_UPDATE_UI(ID_BUTTON_EDIT, CPluginsDialog::OnUpdateEdit) EVT_BUTTON( ID_BUTTON_REMOVE, CPluginsDialog::OnButtonRemove ) EVT_UPDATE_UI(ID_BUTTON_REMOVE, CPluginsDialog::OnUpdateRemove) EVT_BUTTON( wxID_OK, CPluginsDialog::OnButtonOK ) EVT_BUTTON( wxID_CANCEL, CPluginsDialog::OnButtonCancel ) EVT_LISTBOX_DCLICK(ID_LISTBOX_CONTROL, CPluginsDialog::OnListboxDblClick) END_EVENT_TABLE() CPluginsDialog::CPluginsDialog(wxWindow *parent):wxDialog(parent, wxID_ANY, _("HeeksCAD plugin libraries"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) { // make a panel with some controls m_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); ReadPluginsList(m_plugins); CreateCheckListbox(); // create buttons wxButton *button1 = new wxButton(m_panel, ID_BUTTON_ADD, _("New")); wxButton *button2 = new wxButton(m_panel, ID_BUTTON_EDIT, _("Edit")); wxButton *button3 = new wxButton(m_panel, ID_BUTTON_REMOVE, _("Delete")); wxButton *button4 = new wxButton(m_panel, wxID_OK); wxButton *button5 = new wxButton(m_panel, wxID_CANCEL); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); mainsizer->Add( m_pListBox, 1, wxGROW|wxALL, 10 ); wxBoxSizer *bottomsizer = new wxBoxSizer( wxHORIZONTAL ); bottomsizer->Add( button1, 0, wxALL, 10 ); bottomsizer->Add( button2, 0, wxALL, 10 ); bottomsizer->Add( button3, 0, wxALL, 10 ); bottomsizer->Add( button4, 0, wxALL, 10 ); bottomsizer->Add( button5, 0, wxALL, 10 ); mainsizer->Add( bottomsizer, 0, wxCENTER ); // tell frame to make use of sizer (or constraints, if any) m_panel->SetAutoLayout( true ); m_panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void ReadPluginsList(std::list<PluginData> &plugins) { plugins.clear(); ::wxSetWorkingDirectory(wxGetApp().GetExeFolder()); wxConfig plugins_config(_T("HeeksCAD")); plugins_config.SetPath(_T("/plugins")); wxString key; long Index; wxString str; bool entry_found = false; entry_found = plugins_config.GetFirstEntry(key, Index); while(entry_found) { plugins_config.Read(key, &str); PluginData pd; if(str[0] == '#') { str = str.Mid(1); pd.enabled = false; } else { pd.enabled = true; } pd.name = key; pd.path = str; plugins.push_back(pd); entry_found = plugins_config.GetNextEntry(key, Index); } } void CPluginsDialog::CreateCheckListbox(long flags) { wxString *astrChoices = new wxString[m_plugins.size()]; unsigned int ui = 0; for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ ) { PluginData &pd = *It; astrChoices[ui] = pd.name; } m_pListBox = new wxCheckListBox ( m_panel, // parent ID_LISTBOX_CONTROL, // control id wxPoint(10, 10), // listbox poistion wxSize(400, 100), // listbox size m_plugins.size(), // number of strings astrChoices, // array of strings flags ); delete [] astrChoices; ui = 0; for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ ) { PluginData &pd = *It; if(pd.enabled)m_pListBox->Check(ui); } } void CPluginsDialog::EditSelected(unsigned int selection) { unsigned int ui = 0; for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ ) { if(ui == selection) { PluginData &pd = *It; CPluginItemDialog dlg(this, _("Add New Plugin"), pd); if(dlg.ShowModal() == wxID_OK) { // updata the check list delete m_pListBox; CreateCheckListbox(); } } } } void CPluginsDialog::OnButtonAdd(wxCommandEvent& event) { PluginData pd; CPluginItemDialog dlg(this, _("Add New Plugin"), pd); if(dlg.ShowModal() == wxID_OK) { // add the new item m_plugins.push_back(pd); // updata the check list delete m_pListBox; CreateCheckListbox(); } } void CPluginsDialog::OnButtonEdit(wxCommandEvent& event) { int selection = m_pListBox->GetSelection(); EditSelected(selection); } void CPluginsDialog::OnUpdateEdit( wxUpdateUIEvent& event ) { event.Enable(m_pListBox->GetSelection() >= 0); } void CPluginsDialog::OnUpdateRemove( wxUpdateUIEvent& event ) { event.Enable(m_pListBox->GetSelection() >= 0); } void CPluginsDialog::OnButtonRemove(wxCommandEvent& event) { delete m_pListBox; CreateCheckListbox(); } void CPluginsDialog::OnButtonOK(wxCommandEvent& event) { ::wxSetWorkingDirectory(wxGetApp().GetExeFolder()); wxConfig plugins_config(_T("HeeksCAD")); plugins_config.SetPath(_T("/plugins")); plugins_config.DeleteGroup(_T("plugins")); unsigned int ui = 0; for ( std::list<PluginData>::iterator It = m_plugins.begin(); It != m_plugins.end(); It++, ui++ ) { PluginData &pd = *It; pd.enabled = m_pListBox->IsChecked(ui); wxString value = pd.path; if(!(pd.enabled))value.Prepend(_T("#")); plugins_config.Write(pd.name, value); } EndModal(wxID_OK); } void CPluginsDialog::OnButtonCancel(wxCommandEvent& event) { EndModal(wxID_CANCEL); } void CPluginsDialog::OnListboxDblClick(wxCommandEvent& WXUNUSED(event)) { int selection = m_pListBox->GetSelection(); EditSelected(selection); } <|endoftext|>
<commit_before>#include "includemodifier.h" #include "includetree.h" #include <coreplugin/editormanager/editormanager.h> #include <texteditor/texteditor.h> #include <texteditor/textdocument.h> #include <texteditor/textdocumentlayout.h> #include <texteditor/codeassist/textdocumentmanipulator.h> #include <utils/qtcassert.h> #include <QDebug> IncludeModifier::IncludeModifier (CPlusPlus::Document::Ptr document) : document_ (document) { auto editor = qobject_cast<TextEditor::BaseTextEditor *>( Core::EditorManager::openEditor (document_->fileName ())); if (editor) { textDocument_ = editor->textDocument ()->document (); } unfoldDocument (); } void IncludeModifier::queueDuplicatesRemoval () { QTC_ASSERT (document_, return ); QSet<QString> used; for (const auto &include: document_->resolvedIncludes ()) { if (!used.contains (include.resolvedFileName ())) { used.insert (include.resolvedFileName ()); continue; } qDebug () << "remove duplicate" << include.line () << include.unresolvedFileName (); removeIncludeAt (include.line () - 1); } } void IncludeModifier::queueUpdates (const IncludeTree &tree) { const auto become = tree.includes (); for (const auto &include: document_->resolvedIncludes ()) { if (!become.contains (include.resolvedFileName ())) { qDebug () << "remove include" << include.line () << include.unresolvedFileName (); removeIncludeAt (include.line () - 1); } } } void IncludeModifier::executeQueue () { std::sort (linesToRemove_.begin (), linesToRemove_.end (), std::greater<int>()); auto prev = 0; for (auto line: linesToRemove_) { if (line == prev) { continue; } prev = line; auto c = QTextCursor (textDocument_->findBlockByLineNumber (line)); c.select (QTextCursor::LineUnderCursor); c.removeSelectedText (); c.deleteChar (); // for eol } linesToRemove_.clear (); } void IncludeModifier::removeIncludeAt (int line) { auto c = QTextCursor (textDocument_->findBlockByLineNumber (line)); linesToRemove_.append (line); while (true) { --line; c.movePosition (QTextCursor::Up); if (!c.block ().text ().isEmpty ()) { break; } linesToRemove_.append (line); } } void IncludeModifier::removeNewLinesBefore (int line) { auto c = QTextCursor (textDocument_->findBlockByLineNumber (line)); while (true) { c.movePosition (QTextCursor::Up); if (c.block ().text ().isEmpty ()) { c.deleteChar (); continue; } break; } } void IncludeModifier::unfoldDocument () { for (auto i = 0, end = textDocument_->blockCount (); i < end; ++i) { auto block = textDocument_->findBlockByNumber (i); if (TextEditor::TextDocumentLayout::isFolded (block)) { TextEditor::TextDocumentLayout::doFoldOrUnfold (block, true); } } } <commit_msg>Changed empty lines removal: from preceding to succeeding<commit_after>#include "includemodifier.h" #include "includetree.h" #include <coreplugin/editormanager/editormanager.h> #include <texteditor/texteditor.h> #include <texteditor/textdocument.h> #include <texteditor/textdocumentlayout.h> #include <texteditor/codeassist/textdocumentmanipulator.h> #include <utils/qtcassert.h> #include <QDebug> IncludeModifier::IncludeModifier (CPlusPlus::Document::Ptr document) : document_ (document) { auto editor = qobject_cast<TextEditor::BaseTextEditor *>( Core::EditorManager::openEditor (document_->fileName ())); if (editor) { textDocument_ = editor->textDocument ()->document (); } unfoldDocument (); } void IncludeModifier::queueDuplicatesRemoval () { QTC_ASSERT (document_, return ); QSet<QString> used; for (const auto &include: document_->resolvedIncludes ()) { if (!used.contains (include.resolvedFileName ())) { used.insert (include.resolvedFileName ()); continue; } qDebug () << "remove duplicate" << include.line () << include.unresolvedFileName (); removeIncludeAt (include.line () - 1); } } void IncludeModifier::queueUpdates (const IncludeTree &tree) { const auto become = tree.includes (); for (const auto &include: document_->resolvedIncludes ()) { if (!become.contains (include.resolvedFileName ())) { qDebug () << "remove include" << include.line () << include.unresolvedFileName (); removeIncludeAt (include.line () - 1); } } } void IncludeModifier::executeQueue () { std::sort (linesToRemove_.begin (), linesToRemove_.end (), std::greater<int>()); auto prev = 0; for (auto line: linesToRemove_) { if (line == prev) { continue; } prev = line; auto c = QTextCursor (textDocument_->findBlockByLineNumber (line)); c.select (QTextCursor::LineUnderCursor); c.removeSelectedText (); c.deleteChar (); // for eol } linesToRemove_.clear (); } void IncludeModifier::removeIncludeAt (int line) { auto c = QTextCursor (textDocument_->findBlockByLineNumber (line)); linesToRemove_.append (line); while (true) { ++line; c.movePosition (QTextCursor::Down); if (!c.block ().text ().isEmpty ()) { break; } linesToRemove_.append (line); } } void IncludeModifier::removeNewLinesBefore (int line) { auto c = QTextCursor (textDocument_->findBlockByLineNumber (line)); while (true) { c.movePosition (QTextCursor::Up); if (c.block ().text ().isEmpty ()) { c.deleteChar (); continue; } break; } } void IncludeModifier::unfoldDocument () { for (auto i = 0, end = textDocument_->blockCount (); i < end; ++i) { auto block = textDocument_->findBlockByNumber (i); if (TextEditor::TextDocumentLayout::isFolded (block)) { TextEditor::TextDocumentLayout::doFoldOrUnfold (block, true); } } } <|endoftext|>
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGfdmSocket.cpp Author: Jon S. Berndt Date started: 11/08/99 Purpose: Encapsulates a socket Called by: FGOutput, et. al. ------------- Copyright (C) 1999 Jon S. Berndt ([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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- This class excapsulates a socket for simple data writing HISTORY -------------------------------------------------------------------------------- 11/08/99 JSB Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGfdmSocket.h" namespace JSBSim { static const char *IdSrc = "$Id: FGfdmSocket.cpp,v 1.8 2005/07/28 03:54:20 jberndt Exp $"; static const char *IdHdr = ID_FDMSOCKET; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGfdmSocket::FGfdmSocket(string address, int port) { sckt = sckt_in = size = 0; connected = false; #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__) WSADATA wsaData; int wsaReturnCode; wsaReturnCode = WSAStartup(MAKEWORD(1,1), &wsaData); if (wsaReturnCode == 0) cout << "Winsock DLL loaded ..." << endl; else cout << "Winsock DLL not initialized ..." << endl; #endif if (address.find_first_not_of("0123456789.",0) != address.npos) { if ((host = gethostbyname(address.c_str())) == NULL) { cout << "Could not get host net address by name..." << endl; } } else { if ((host = gethostbyaddr(address.c_str(), address.size(), PF_INET)) == NULL) { cout << "Could not get host net address by number..." << endl; } } if (host != NULL) { cout << "Got host net address..." << endl; sckt = socket(AF_INET, SOCK_STREAM, 0); if (sckt >= 0) { // successful memset(&scktName, 0, sizeof(struct sockaddr_in)); scktName.sin_family = AF_INET; scktName.sin_port = htons(port); memcpy(&scktName.sin_addr, host->h_addr_list[0], host->h_length); int len = sizeof(struct sockaddr_in); if (connect(sckt, (struct sockaddr*)&scktName, len) == 0) { // successful cout << "Successfully connected to socket ..." << endl; connected = true; } else { // unsuccessful cout << "Could not connect to socket ..." << endl; } } else { // unsuccessful cout << "Could not create socket for FDM, error = " << errno << endl; } } Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGfdmSocket::FGfdmSocket(int port) { size = 0; connected = false; unsigned long NoBlock = true; #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__) WSADATA wsaData; int wsaReturnCode; wsaReturnCode = WSAStartup(MAKEWORD(1,1), &wsaData); if (wsaReturnCode == 0) cout << "Winsock DLL loaded ..." << endl; else cerr << "Winsock DLL not initialized ..." << endl; #endif sckt = socket(AF_INET, SOCK_STREAM, 0); if (sckt >= 0) { // successful memset(&scktName, 0, sizeof(struct sockaddr_in)); scktName.sin_family = AF_INET; scktName.sin_port = htons(port); // memcpy(&scktName.sin_addr, host->h_addr_list[0], host->h_length); int len = sizeof(struct sockaddr_in); if (bind(sckt, (struct sockaddr*)&scktName, len) == 0) { // successful cout << "Successfully bound to socket ..." << endl; if (listen(sckt, 5) >= 0) { // successful listen() #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__) ioctlsocket(sckt, FIONBIO, &NoBlock); #else ioctl(sckt, FIONBIO, &NoBlock); #endif sckt_in = accept(sckt, (struct sockaddr*)&scktName, &len); } else { cerr << "Could not listen ..." << endl; } connected = true; } else { // unsuccessful cerr << "Could not bind to socket ..." << endl; } } else { // unsuccessful cerr << "Could not create socket for FDM, error = " << errno << endl; } Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGfdmSocket::~FGfdmSocket() { #ifndef macintosh if (sckt) shutdown(sckt,2); if (sckt_in) shutdown(sckt_in,2); #endif #ifdef __BORLANDC__ WSACleanup(); #endif Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGfdmSocket::Receive(void) { char buf[1024]; int len = sizeof(struct sockaddr_in); int num_chars=0; int total_chars = 0; unsigned long NoBlock = true; string data = ""; // todo: should allocate this with a standard size as a // class attribute and pass as a reference? if (sckt_in <= 0) { sckt_in = accept(sckt, (struct sockaddr*)&scktName, &len); if (sckt_in > 0) { #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__) ioctlsocket(sckt_in, FIONBIO,&NoBlock); #else ioctl(sckt_in, FIONBIO, &NoBlock); #endif send(sckt_in, "Connected to JSBSim server\nJSBSim> ", 35, 0); } } if (sckt_in > 0) { while ((num_chars = recv(sckt_in, buf, 1024, 0)) > 0) { data += string(buf).substr(0,num_chars); total_chars += num_chars; } // new line prompt if (total_chars > 0) send(sckt_in, "JSBSim> ", 8, 0); } return data.substr(0, total_chars); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% int FGfdmSocket::Reply(string text) { int num_chars_sent=0; if (sckt_in >= 0) { num_chars_sent = send(sckt_in, text.c_str(), text.size(), 0); send(sckt_in, "JSBSim> ", 8, 0); } else { cerr << "Socket reply must be to a valid socket" << endl; return -1; } return num_chars_sent; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Close(void) { close(sckt_in); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Clear(void) { buffer = ""; size = 0; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Clear(string s) { buffer = s + " "; size = buffer.size(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Append(const char* item) { if (size == 0) buffer += string(item); else buffer += string(",") + string(item); size++; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Append(double item) { char s[25]; sprintf(s,"%12.7f",item); if (size == 0) buffer += string(s); else buffer += string(",") + string(s); size++; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Append(long item) { char s[25]; sprintf(s,"%12ld",item); if (size == 0) buffer += string(s); else buffer += string(",") + string(s); size++; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Send(void) { buffer += string("\n"); if ((send(sckt,buffer.c_str(),buffer.size(),0)) <= 0) { perror("send"); } else { } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGfdmSocket::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGfdmSocket" << endl; if (from == 1) cout << "Destroyed: FGfdmSocket" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } } <commit_msg>Tweaks to socket class for better prompting<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Module: FGfdmSocket.cpp Author: Jon S. Berndt Date started: 11/08/99 Purpose: Encapsulates a socket Called by: FGOutput, et. al. ------------- Copyright (C) 1999 Jon S. Berndt ([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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- This class excapsulates a socket for simple data writing HISTORY -------------------------------------------------------------------------------- 11/08/99 JSB Created %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGfdmSocket.h" namespace JSBSim { static const char *IdSrc = "$Id: FGfdmSocket.cpp,v 1.9 2005/08/03 14:16:15 jberndt Exp $"; static const char *IdHdr = ID_FDMSOCKET; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGfdmSocket::FGfdmSocket(string address, int port) { sckt = sckt_in = size = 0; connected = false; #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__) WSADATA wsaData; int wsaReturnCode; wsaReturnCode = WSAStartup(MAKEWORD(1,1), &wsaData); if (wsaReturnCode == 0) cout << "Winsock DLL loaded ..." << endl; else cout << "Winsock DLL not initialized ..." << endl; #endif if (address.find_first_not_of("0123456789.",0) != address.npos) { if ((host = gethostbyname(address.c_str())) == NULL) { cout << "Could not get host net address by name..." << endl; } } else { if ((host = gethostbyaddr(address.c_str(), address.size(), PF_INET)) == NULL) { cout << "Could not get host net address by number..." << endl; } } if (host != NULL) { cout << "Got host net address..." << endl; sckt = socket(AF_INET, SOCK_STREAM, 0); if (sckt >= 0) { // successful memset(&scktName, 0, sizeof(struct sockaddr_in)); scktName.sin_family = AF_INET; scktName.sin_port = htons(port); memcpy(&scktName.sin_addr, host->h_addr_list[0], host->h_length); int len = sizeof(struct sockaddr_in); if (connect(sckt, (struct sockaddr*)&scktName, len) == 0) { // successful cout << "Successfully connected to socket ..." << endl; connected = true; } else { // unsuccessful cout << "Could not connect to socket ..." << endl; } } else { // unsuccessful cout << "Could not create socket for FDM, error = " << errno << endl; } } Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGfdmSocket::FGfdmSocket(int port) { size = 0; connected = false; unsigned long NoBlock = true; #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__) WSADATA wsaData; int wsaReturnCode; wsaReturnCode = WSAStartup(MAKEWORD(1,1), &wsaData); if (wsaReturnCode == 0) cout << "Winsock DLL loaded ..." << endl; else cerr << "Winsock DLL not initialized ..." << endl; #endif sckt = socket(AF_INET, SOCK_STREAM, 0); if (sckt >= 0) { // successful memset(&scktName, 0, sizeof(struct sockaddr_in)); scktName.sin_family = AF_INET; scktName.sin_port = htons(port); // memcpy(&scktName.sin_addr, host->h_addr_list[0], host->h_length); int len = sizeof(struct sockaddr_in); if (bind(sckt, (struct sockaddr*)&scktName, len) == 0) { // successful cout << "Successfully bound to socket ..." << endl; if (listen(sckt, 5) >= 0) { // successful listen() #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__) ioctlsocket(sckt, FIONBIO, &NoBlock); #else ioctl(sckt, FIONBIO, &NoBlock); #endif sckt_in = accept(sckt, (struct sockaddr*)&scktName, &len); } else { cerr << "Could not listen ..." << endl; } connected = true; } else { // unsuccessful cerr << "Could not bind to socket ..." << endl; } } else { // unsuccessful cerr << "Could not create socket for FDM, error = " << errno << endl; } Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGfdmSocket::~FGfdmSocket() { #ifndef macintosh if (sckt) shutdown(sckt,2); if (sckt_in) shutdown(sckt_in,2); #endif #ifdef __BORLANDC__ WSACleanup(); #endif Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGfdmSocket::Receive(void) { char buf[1024]; int len = sizeof(struct sockaddr_in); int num_chars=0; int total_chars = 0; unsigned long NoBlock = true; string data = ""; // todo: should allocate this with a standard size as a // class attribute and pass as a reference? if (sckt_in <= 0) { sckt_in = accept(sckt, (struct sockaddr*)&scktName, &len); if (sckt_in > 0) { #if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__) ioctlsocket(sckt_in, FIONBIO,&NoBlock); #else ioctl(sckt_in, FIONBIO, &NoBlock); #endif send(sckt_in, "Connected to JSBSim server\nJSBSim> ", 35, 0); } } if (sckt_in > 0) { while ((num_chars = recv(sckt_in, buf, 1024, 0)) > 0) { data += string(buf).substr(0,num_chars); total_chars += num_chars; } // new line prompt // if (total_chars <= 1) send(sckt_in, "JSBSim> ", 8, 0); } return data.substr(0, total_chars); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% int FGfdmSocket::Reply(string text) { int num_chars_sent=0; if (sckt_in >= 0) { num_chars_sent = send(sckt_in, text.c_str(), text.size(), 0); send(sckt_in, "JSBSim> ", 8, 0); } else { cerr << "Socket reply must be to a valid socket" << endl; return -1; } return num_chars_sent; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Close(void) { close(sckt_in); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Clear(void) { buffer = ""; size = 0; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Clear(string s) { buffer = s + " "; size = buffer.size(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Append(const char* item) { if (size == 0) buffer += string(item); else buffer += string(",") + string(item); size++; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Append(double item) { char s[25]; sprintf(s,"%12.7f",item); if (size == 0) buffer += string(s); else buffer += string(",") + string(s); size++; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Append(long item) { char s[25]; sprintf(s,"%12ld",item); if (size == 0) buffer += string(s); else buffer += string(",") + string(s); size++; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGfdmSocket::Send(void) { buffer += string("\n"); if ((send(sckt,buffer.c_str(),buffer.size(),0)) <= 0) { perror("send"); } else { } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGfdmSocket::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGfdmSocket" << endl; if (from == 1) cout << "Destroyed: FGfdmSocket" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } } <|endoftext|>
<commit_before>#include "collector.hh" #include "registry.hh" #include "standard_exports.hh" #include "prometheus/proto/metrics.pb.h" #include <unistd.h> #include <fstream> #include <iostream> namespace prometheus { namespace impl { class ProcessCollector : public ICollector { private: // Convenience function to add a gauge to the list of // MetricFamilies and set its name/help/type and one value. static void set_gauge(std::list<MetricFamily*>& l, std::string const& name, std::string const& help, double value) { MetricFamily* mf = new MetricFamily(); mf->set_name(name); mf->set_help(help); mf->set_type(::prometheus::client::MetricType::GAUGE); mf->add_metric()->mutable_gauge()->set_value(value); l.push_back(mf); } const double pagesize_; const double ticks_per_ms_; public: ProcessCollector() : pagesize_(sysconf(_SC_PAGESIZE)), ticks_per_ms_(sysconf(_SC_CLK_TCK)) { global_registry.register_collector(this); } ~ProcessCollector() { global_registry.unregister_collector(this); } std::list<MetricFamily*> collect() const { std::list<MetricFamily*> l; std::ifstream in("/proc/self/stat"); int pid; std::string filename; // Extracts all fields from /proc/self/stat. This assumes a // Linux 2.6 distro (importantly, times are expressed in ticks // and not in jffies). Not all fields are actually used for // exports. char state; int ppid, pgrp, session, ttynr, tpgid; unsigned int flags; unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime; long int cutime, cstime, priority, nice, numthreads, itrealvalue; unsigned long long int starttime; unsigned long int vsize; long int rss; in >> pid >> filename >> state >> ppid >> pgrp >> session >> ttynr >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt >> utime >> stime >> cutime >> cstime >> priority >> nice >> numthreads >> itrealvalue >> starttime >> vsize >> rss; set_gauge(l, "process_virtual_memory_bytes", "Virtual memory size in bytes (vsize)", vsize); set_gauge(l, "process_resident_memory_bytes", "Resident memory size in bytes (rss)", rss * pagesize_); int btime = 0; // TODO(korfuri): Get this from /proc/stat set_gauge(l, "process_start_time_seconds", "Start time of the process since unix epoch in seconds.", starttime / ticks_per_ms_ + btime); set_gauge(l, "process_cpu_seconds_total", "Total user and system CPU time spent in seconds.", (double)(utime + stime) / ticks_per_ms_); // TODO(korfuri): process_open_fds // TODO(korfuri): process_max_fds return l; } }; } /* namespace impl */ impl::ProcessCollector* global_process_collector = nullptr; void install_process_exports() { global_process_collector = new impl::ProcessCollector(); } } /* namespace prometheus */ <commit_msg>Add parsing of /proc/stat to standard_exports.cc.<commit_after>#include "collector.hh" #include "registry.hh" #include "standard_exports.hh" #include "prometheus/proto/metrics.pb.h" #include <unistd.h> #include <fstream> #include <iostream> namespace prometheus { namespace impl { struct ProcSelfStatReader { ProcSelfStatReader() { std::ifstream in("/proc/self/stat"); // Extracts all fields from /proc/self/stat. This assumes a // Linux 2.6 distro (importantly, times are expressed in ticks // and not in jffies). Not all fields are actually used for // exports. in >> pid >> filename >> state >> ppid >> pgrp >> session >> ttynr >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt >> utime >> stime >> cutime >> cstime >> priority >> nice >> numthreads >> itrealvalue >> starttime >> vsize >> rss; } char state; int pid, ppid, pgrp, session, ttynr, tpgid; unsigned int flags; unsigned long int minflt, cminflt, majflt, cmajflt, utime, stime; long int cutime, cstime, priority, nice, numthreads, itrealvalue; unsigned long long int starttime; unsigned long int vsize; long int rss; std::string filename; }; struct ProcStatReader { ProcStatReader() { std::ifstream in("/proc/stat"); std::string line; while (in.good()) { std::getline(in, line); if (line.compare(0, 6, "btime ") == 0) { btime = std::stoi(line.substr(6)); } } } int btime; }; class ProcessCollector : public ICollector { private: // Convenience function to add a gauge to the list of // MetricFamilies and set its name/help/type and one value. static void set_gauge(std::list<MetricFamily*>& l, std::string const& name, std::string const& help, double value) { MetricFamily* mf = new MetricFamily(); mf->set_name(name); mf->set_help(help); mf->set_type(::prometheus::client::MetricType::GAUGE); mf->add_metric()->mutable_gauge()->set_value(value); l.push_back(mf); } const double pagesize_; const double ticks_per_ms_; public: ProcessCollector() : pagesize_(sysconf(_SC_PAGESIZE)), ticks_per_ms_(sysconf(_SC_CLK_TCK)) { global_registry.register_collector(this); } ~ProcessCollector() { global_registry.unregister_collector(this); } std::list<MetricFamily*> collect() const { std::list<MetricFamily*> l; ProcSelfStatReader pss; ProcStatReader ps; set_gauge(l, "process_virtual_memory_bytes", "Virtual memory size in bytes (vsize)", pss.vsize); set_gauge(l, "process_resident_memory_bytes", "Resident memory size in bytes (rss)", pss.rss * pagesize_); set_gauge(l, "process_start_time_seconds", "Start time of the process since unix epoch in seconds.", pss.starttime / ticks_per_ms_ + ps.btime); set_gauge(l, "process_cpu_seconds_total", "Total user and system CPU time spent in seconds.", (double)(pss.utime + pss.stime) / ticks_per_ms_); // TODO(korfuri): process_open_fds, get this from ls(/prod/fd/*) // TODO(korfuri): process_max_fds, get this from /proc/self/limits return l; } }; } /* namespace impl */ impl::ProcessCollector* global_process_collector = nullptr; void install_process_exports() { global_process_collector = new impl::ProcessCollector(); } } /* namespace prometheus */ <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 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 "Xerces" 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 apache\@apache.org. * * 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/>. */ /* * $Log$ * Revision 1.4 2000/03/02 19:54:29 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.3 2000/02/06 07:47:53 rahulj * Year 2K copyright swat. * * Revision 1.2 1999/12/15 19:49:37 roddey * Added second getValue() method which takes a short name for the attribute * to get the value for. Just a convenience method. * * Revision 1.1.1.1 1999/11/09 01:08:19 twl * Initial checkin * * Revision 1.2 1999/11/08 20:44:44 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/Janitor.hpp> #include <internal/VecAttrListImpl.hpp> // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- VecAttrListImpl::VecAttrListImpl() : fAdopt(false) , fCount(0) , fVector(0) { } VecAttrListImpl::~VecAttrListImpl() { // // Note that some compilers can't deal with the fact that the pointer // is to a const object, so we have to cast off the const'ness here! // if (fAdopt) delete (RefVectorOf<XMLAttr>*)fVector; } // --------------------------------------------------------------------------- // Implementation of the attribute list interface // --------------------------------------------------------------------------- unsigned int VecAttrListImpl::getLength() const { return fCount; } const XMLCh* VecAttrListImpl::getName(const unsigned int index) const { if (index >= fCount) ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex); return fVector->elementAt(index)->getName(); } const XMLCh* VecAttrListImpl::getType(const unsigned int index) const { if (index >= fCount) ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex); return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType()); } const XMLCh* VecAttrListImpl::getValue(const unsigned int index) const { if (index >= fCount) ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex); return fVector->elementAt(index)->getValue(); } const XMLCh* VecAttrListImpl::getType(const XMLCh* const name) const { // // Search the vector for the attribute with the given name and return // its type. // for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); if (!XMLString::compareString(curElem->getName(), name)) return XMLAttDef::getAttTypeString(curElem->getType()); } return 0; } const XMLCh* VecAttrListImpl::getValue(const XMLCh* const name) const { // // Search the vector for the attribute with the given name and return // its type. // for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); if (!XMLString::compareString(curElem->getName(), name)) return curElem->getValue(); } return 0; } const XMLCh* VecAttrListImpl::getValue(const char* const name) const { // Temporarily transcode the name for lookup XMLCh* wideName = XMLString::transcode(name); ArrayJanitor<XMLCh> janName(wideName); // // Search the vector for the attribute with the given name and return // its type. // for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); if (!XMLString::compareString(curElem->getName(), wideName)) return curElem->getValue(); } return 0; } // --------------------------------------------------------------------------- // Setter methods // --------------------------------------------------------------------------- void VecAttrListImpl::setVector(const RefVectorOf<XMLAttr>* const srcVec , const unsigned int count , const bool adopt) { // // Delete the previous vector (if any) if we are adopting. Note that some // compilers can't deal with the fact that the pointer is to a const // object, so we have to cast off the const'ness here! // if (fAdopt) delete (RefVectorOf<XMLAttr>*)fVector; fAdopt = fAdopt; fCount = count; fVector = srcVec; } <commit_msg>Fixed #54. Changed self-assignment to now use the parameter value. Reported by Helmut Eiken <[email protected]><commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 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 "Xerces" 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 apache\@apache.org. * * 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/>. */ /* * $Log$ * Revision 1.5 2000/03/13 20:19:11 rahulj * Fixed #54. Changed self-assignment to now use the parameter value. * Reported by Helmut Eiken <[email protected]> * * Revision 1.4 2000/03/02 19:54:29 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.3 2000/02/06 07:47:53 rahulj * Year 2K copyright swat. * * Revision 1.2 1999/12/15 19:49:37 roddey * Added second getValue() method which takes a short name for the attribute * to get the value for. Just a convenience method. * * Revision 1.1.1.1 1999/11/09 01:08:19 twl * Initial checkin * * Revision 1.2 1999/11/08 20:44:44 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/Janitor.hpp> #include <internal/VecAttrListImpl.hpp> // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- VecAttrListImpl::VecAttrListImpl() : fAdopt(false) , fCount(0) , fVector(0) { } VecAttrListImpl::~VecAttrListImpl() { // // Note that some compilers can't deal with the fact that the pointer // is to a const object, so we have to cast off the const'ness here! // if (fAdopt) delete (RefVectorOf<XMLAttr>*)fVector; } // --------------------------------------------------------------------------- // Implementation of the attribute list interface // --------------------------------------------------------------------------- unsigned int VecAttrListImpl::getLength() const { return fCount; } const XMLCh* VecAttrListImpl::getName(const unsigned int index) const { if (index >= fCount) ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex); return fVector->elementAt(index)->getName(); } const XMLCh* VecAttrListImpl::getType(const unsigned int index) const { if (index >= fCount) ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex); return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType()); } const XMLCh* VecAttrListImpl::getValue(const unsigned int index) const { if (index >= fCount) ThrowXML(ArrayIndexOutOfBoundsException, XMLExcepts::AttrList_BadIndex); return fVector->elementAt(index)->getValue(); } const XMLCh* VecAttrListImpl::getType(const XMLCh* const name) const { // // Search the vector for the attribute with the given name and return // its type. // for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); if (!XMLString::compareString(curElem->getName(), name)) return XMLAttDef::getAttTypeString(curElem->getType()); } return 0; } const XMLCh* VecAttrListImpl::getValue(const XMLCh* const name) const { // // Search the vector for the attribute with the given name and return // its type. // for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); if (!XMLString::compareString(curElem->getName(), name)) return curElem->getValue(); } return 0; } const XMLCh* VecAttrListImpl::getValue(const char* const name) const { // Temporarily transcode the name for lookup XMLCh* wideName = XMLString::transcode(name); ArrayJanitor<XMLCh> janName(wideName); // // Search the vector for the attribute with the given name and return // its type. // for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); if (!XMLString::compareString(curElem->getName(), wideName)) return curElem->getValue(); } return 0; } // --------------------------------------------------------------------------- // Setter methods // --------------------------------------------------------------------------- void VecAttrListImpl::setVector(const RefVectorOf<XMLAttr>* const srcVec , const unsigned int count , const bool adopt) { // // Delete the previous vector (if any) if we are adopting. Note that some // compilers can't deal with the fact that the pointer is to a const // object, so we have to cast off the const'ness here! // if (fAdopt) delete (RefVectorOf<XMLAttr>*)fVector; fAdopt = adopt; fCount = count; fVector = srcVec; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/visualization/software-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. * *=========================================================================*/ #include <algorithm> // std::count #include <cassert> #include "Sampler.h" #include "Parameter.h" namespace madai { Sampler ::Sampler() : m_Model( NULL ) { } Sampler ::~Sampler() { } void Sampler ::SetModel( const Model * model ) { if (model != m_Model) this->Initialize( model ); // no need to reinitialize if model already there.. } const Model * Sampler ::GetModel() const { return m_Model; } unsigned int Sampler ::GetNumberOfParameters() const { if (this->GetModel() != NULL) return this->GetModel()->GetNumberOfParameters(); else return 0; } const std::vector< Parameter > & Sampler ::GetParameters() const { assert (this->GetModel() != NULL); return this->GetModel()->GetParameters(); } std::set< std::string > Sampler ::GetActiveParameters() const { return m_ActiveParameters; } const std::vector< bool > & Sampler ::GetActiveParametersByIndex() const { return m_ActiveParameterIndices; } unsigned int Sampler ::GetNumberOfActiveParameters() const { return static_cast< unsigned int >( m_ActiveParameters.size() ); } bool Sampler ::IsParameterActive( const std::string & parameterName ) const { return ( m_ActiveParameters.find( parameterName ) != m_ActiveParameters.end() ); } bool Sampler ::IsParameterActive( unsigned int parameterIndex ) const { assert(parameterIndex < m_ActiveParameterIndices.size()); assert(this->GetNumberOfParameters() == this->GetParameters().size()); return m_ActiveParameterIndices[parameterIndex]; } void Sampler ::ActivateParameter( const std::string & parameterName ) { unsigned int parameterIndex = this->GetParameterIndex( parameterName ); assert( parameterIndex != static_cast< unsigned int >(-1) ); // should return an error, but this is a void function :( if ( parameterIndex != static_cast< unsigned int >(-1) ) { m_ActiveParameterIndices[parameterIndex] = true; m_ActiveParameters.insert( parameterName ); } assert (std::count(m_ActiveParameterIndices.begin(), m_ActiveParameterIndices.end(), true) == static_cast< int >(m_ActiveParameters.size())); } void Sampler ::ActivateParameter( unsigned int parameterIndex ) { assert(parameterIndex < this->GetNumberOfParameters()); assert(this->GetNumberOfParameters() == this->GetParameters().size()); assert(this->GetNumberOfParameters() == m_ActiveParameterIndices.size()); m_ActiveParameterIndices[parameterIndex] = true; m_ActiveParameters.insert(this->GetParameters()[parameterIndex].m_Name); assert (std::count(m_ActiveParameterIndices.begin(), m_ActiveParameterIndices.end(), true) == static_cast< int >(m_ActiveParameters.size())); } void Sampler ::DeactivateParameter( const std::string & parameterName ) { unsigned int parameterIndex = this->GetParameterIndex( parameterName ); assert ( parameterIndex != static_cast< unsigned int >(-1) ); // should return an error, but this is a void function :( if ( parameterIndex != static_cast< unsigned int >(-1) ) { m_ActiveParameterIndices[ parameterIndex ] = false; m_ActiveParameters.erase( parameterName ); } assert (std::count(m_ActiveParameterIndices.begin(), m_ActiveParameterIndices.end(), true) == static_cast< int >(m_ActiveParameters.size())); } void Sampler ::DeactivateParameter( unsigned int parameterIndex ) { assert(parameterIndex < this->GetNumberOfParameters()); assert(this->GetNumberOfParameters() == this->GetParameters().size()); assert(this->GetNumberOfParameters() == m_ActiveParameterIndices.size()); m_ActiveParameterIndices[parameterIndex] = false; m_ActiveParameters.erase(this->GetParameters()[parameterIndex].m_Name); assert (std::count(m_ActiveParameterIndices.begin(), m_ActiveParameterIndices.end(), true) == static_cast< int >(m_ActiveParameters.size())); } Sampler::ErrorType Sampler ::SetParameterValue( const std::string & parameterName, double value ) { unsigned int parameterIndex = this->GetParameterIndex( parameterName ); if ( parameterIndex == static_cast< unsigned int >( -1 ) ) { // Error. Parameter not found. return INVALID_PARAMETER_INDEX_ERROR; } if (m_CurrentParameters[parameterIndex] != value) { m_CurrentParameters[parameterIndex] = value; this->ParameterSetExternally(); // set dirty flag } return NO_ERROR; } Sampler::ErrorType Sampler ::SetParameterValue( unsigned int parameterIndex, double value ) { if ( parameterIndex >= this->GetNumberOfParameters() ) { return INVALID_PARAMETER_INDEX_ERROR; } if (m_CurrentParameters[parameterIndex] != value) { m_CurrentParameters[parameterIndex] = value; this->ParameterSetExternally(); // set dirty flag } return NO_ERROR; } Sampler::ErrorType Sampler ::SetParameterValues(const std::vector< double > & parameterValues) { if ( parameterValues.size() != this->GetNumberOfParameters() ) { // wrong vector size return INVALID_PARAMETER_INDEX_ERROR; } m_CurrentParameters = parameterValues; this->ParameterSetExternally(); // set dirty flag return NO_ERROR; } double Sampler ::GetParameterValue( const std::string & parameterName ) const { unsigned int parameterIndex = this->GetParameterIndex( parameterName ); if ( parameterIndex == static_cast< unsigned int >( -1 ) ) { return 0.0; } return m_CurrentParameters[parameterIndex]; } const std::vector< double > & Sampler ::GetCurrentParameters() const { return m_CurrentParameters; } const std::vector< double > & Sampler ::GetCurrentOutputs() const { return m_CurrentOutputs; } double Sampler ::GetCurrentLogLikelihood() const { return m_CurrentLogLikelihood; } std::string Sampler ::GetErrorTypeAsString( ErrorType error ) { switch(error) { case NO_ERROR: return "NO_ERROR"; case INVALID_PARAMETER_INDEX_ERROR: return "INVALID_PARAMETER_INDEX_ERROR"; case INVALID_OUTPUT_SCALAR_INDEX_ERROR: return "INVALID_OUTPUT_SCALAR_INDEX_ERROR"; default: return "UNKNOWN"; } } void Sampler ::Initialize( const Model * model ) { assert(model != NULL); if (! model) return; m_Model = model; unsigned int np = m_Model->GetNumberOfParameters(); // Activate all parameters by default. const std::vector< Parameter > & params = m_Model->GetParameters(); assert(np == params.size()); m_ActiveParameters.clear(); for (unsigned int i = 0; (i < np); ++i) { m_ActiveParameters.insert( params[i].m_Name ); } m_ActiveParameterIndices = std::vector< bool >( model->GetNumberOfParameters(), true ); m_CurrentParameters = std::vector< double >( model->GetNumberOfParameters(), 0.0 ); m_CurrentOutputs = std::vector< double >( model->GetNumberOfScalarOutputs(), 0.0 ); for (unsigned int i = 0; (i < np); ++i) { m_CurrentParameters[i] = params[i].GetPriorDistribution()->GetPercentile(0.5); // set a reasonable default value for the parameters. // most subclasses will do something smarter. } this->ParameterSetExternally(); // valid values for m_CurrentOutputs } unsigned int Sampler ::GetParameterIndex( const std::string & parameterName ) const { const std::vector< Parameter > & parameters = this->m_Model->GetParameters(); for ( unsigned int i = 0; i < m_Model->GetNumberOfParameters(); i++ ) { if ( parameters[i].m_Name == parameterName ) return i; } return static_cast< unsigned int >(-1); // Intentional underflow } void Sampler ::ParameterSetExternally() { if (! m_Model) return; if (m_CurrentParameters.size() != m_Model->GetNumberOfParameters()) return; if (m_CurrentOutputs.size() == m_Model->GetNumberOfScalarOutputs()) return; Model::ErrorType error = m_Model->GetScalarOutputsAndLogLikelihood( m_CurrentParameters, m_CurrentOutputs, m_CurrentLogLikelihood); assert(error == Model::NO_ERROR); } } // end namespace madai <commit_msg>Fixed unused variable warning in release mode<commit_after>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/visualization/software-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. * *=========================================================================*/ #include <algorithm> // std::count #include <cassert> #include "Sampler.h" #include "Parameter.h" namespace madai { Sampler ::Sampler() : m_Model( NULL ) { } Sampler ::~Sampler() { } void Sampler ::SetModel( const Model * model ) { if (model != m_Model) this->Initialize( model ); // no need to reinitialize if model already there.. } const Model * Sampler ::GetModel() const { return m_Model; } unsigned int Sampler ::GetNumberOfParameters() const { if (this->GetModel() != NULL) return this->GetModel()->GetNumberOfParameters(); else return 0; } const std::vector< Parameter > & Sampler ::GetParameters() const { assert (this->GetModel() != NULL); return this->GetModel()->GetParameters(); } std::set< std::string > Sampler ::GetActiveParameters() const { return m_ActiveParameters; } const std::vector< bool > & Sampler ::GetActiveParametersByIndex() const { return m_ActiveParameterIndices; } unsigned int Sampler ::GetNumberOfActiveParameters() const { return static_cast< unsigned int >( m_ActiveParameters.size() ); } bool Sampler ::IsParameterActive( const std::string & parameterName ) const { return ( m_ActiveParameters.find( parameterName ) != m_ActiveParameters.end() ); } bool Sampler ::IsParameterActive( unsigned int parameterIndex ) const { assert(parameterIndex < m_ActiveParameterIndices.size()); assert(this->GetNumberOfParameters() == this->GetParameters().size()); return m_ActiveParameterIndices[parameterIndex]; } void Sampler ::ActivateParameter( const std::string & parameterName ) { unsigned int parameterIndex = this->GetParameterIndex( parameterName ); assert( parameterIndex != static_cast< unsigned int >(-1) ); // should return an error, but this is a void function :( if ( parameterIndex != static_cast< unsigned int >(-1) ) { m_ActiveParameterIndices[parameterIndex] = true; m_ActiveParameters.insert( parameterName ); } assert (std::count(m_ActiveParameterIndices.begin(), m_ActiveParameterIndices.end(), true) == static_cast< int >(m_ActiveParameters.size())); } void Sampler ::ActivateParameter( unsigned int parameterIndex ) { assert(parameterIndex < this->GetNumberOfParameters()); assert(this->GetNumberOfParameters() == this->GetParameters().size()); assert(this->GetNumberOfParameters() == m_ActiveParameterIndices.size()); m_ActiveParameterIndices[parameterIndex] = true; m_ActiveParameters.insert(this->GetParameters()[parameterIndex].m_Name); assert (std::count(m_ActiveParameterIndices.begin(), m_ActiveParameterIndices.end(), true) == static_cast< int >(m_ActiveParameters.size())); } void Sampler ::DeactivateParameter( const std::string & parameterName ) { unsigned int parameterIndex = this->GetParameterIndex( parameterName ); assert ( parameterIndex != static_cast< unsigned int >(-1) ); // should return an error, but this is a void function :( if ( parameterIndex != static_cast< unsigned int >(-1) ) { m_ActiveParameterIndices[ parameterIndex ] = false; m_ActiveParameters.erase( parameterName ); } assert (std::count(m_ActiveParameterIndices.begin(), m_ActiveParameterIndices.end(), true) == static_cast< int >(m_ActiveParameters.size())); } void Sampler ::DeactivateParameter( unsigned int parameterIndex ) { assert(parameterIndex < this->GetNumberOfParameters()); assert(this->GetNumberOfParameters() == this->GetParameters().size()); assert(this->GetNumberOfParameters() == m_ActiveParameterIndices.size()); m_ActiveParameterIndices[parameterIndex] = false; m_ActiveParameters.erase(this->GetParameters()[parameterIndex].m_Name); assert (std::count(m_ActiveParameterIndices.begin(), m_ActiveParameterIndices.end(), true) == static_cast< int >(m_ActiveParameters.size())); } Sampler::ErrorType Sampler ::SetParameterValue( const std::string & parameterName, double value ) { unsigned int parameterIndex = this->GetParameterIndex( parameterName ); if ( parameterIndex == static_cast< unsigned int >( -1 ) ) { // Error. Parameter not found. return INVALID_PARAMETER_INDEX_ERROR; } if (m_CurrentParameters[parameterIndex] != value) { m_CurrentParameters[parameterIndex] = value; this->ParameterSetExternally(); // set dirty flag } return NO_ERROR; } Sampler::ErrorType Sampler ::SetParameterValue( unsigned int parameterIndex, double value ) { if ( parameterIndex >= this->GetNumberOfParameters() ) { return INVALID_PARAMETER_INDEX_ERROR; } if (m_CurrentParameters[parameterIndex] != value) { m_CurrentParameters[parameterIndex] = value; this->ParameterSetExternally(); // set dirty flag } return NO_ERROR; } Sampler::ErrorType Sampler ::SetParameterValues(const std::vector< double > & parameterValues) { if ( parameterValues.size() != this->GetNumberOfParameters() ) { // wrong vector size return INVALID_PARAMETER_INDEX_ERROR; } m_CurrentParameters = parameterValues; this->ParameterSetExternally(); // set dirty flag return NO_ERROR; } double Sampler ::GetParameterValue( const std::string & parameterName ) const { unsigned int parameterIndex = this->GetParameterIndex( parameterName ); if ( parameterIndex == static_cast< unsigned int >( -1 ) ) { return 0.0; } return m_CurrentParameters[parameterIndex]; } const std::vector< double > & Sampler ::GetCurrentParameters() const { return m_CurrentParameters; } const std::vector< double > & Sampler ::GetCurrentOutputs() const { return m_CurrentOutputs; } double Sampler ::GetCurrentLogLikelihood() const { return m_CurrentLogLikelihood; } std::string Sampler ::GetErrorTypeAsString( ErrorType error ) { switch(error) { case NO_ERROR: return "NO_ERROR"; case INVALID_PARAMETER_INDEX_ERROR: return "INVALID_PARAMETER_INDEX_ERROR"; case INVALID_OUTPUT_SCALAR_INDEX_ERROR: return "INVALID_OUTPUT_SCALAR_INDEX_ERROR"; default: return "UNKNOWN"; } } void Sampler ::Initialize( const Model * model ) { assert(model != NULL); if (! model) return; m_Model = model; unsigned int np = m_Model->GetNumberOfParameters(); // Activate all parameters by default. const std::vector< Parameter > & params = m_Model->GetParameters(); assert(np == params.size()); m_ActiveParameters.clear(); for (unsigned int i = 0; (i < np); ++i) { m_ActiveParameters.insert( params[i].m_Name ); } m_ActiveParameterIndices = std::vector< bool >( model->GetNumberOfParameters(), true ); m_CurrentParameters = std::vector< double >( model->GetNumberOfParameters(), 0.0 ); m_CurrentOutputs = std::vector< double >( model->GetNumberOfScalarOutputs(), 0.0 ); for (unsigned int i = 0; (i < np); ++i) { m_CurrentParameters[i] = params[i].GetPriorDistribution()->GetPercentile(0.5); // set a reasonable default value for the parameters. // most subclasses will do something smarter. } this->ParameterSetExternally(); // valid values for m_CurrentOutputs } unsigned int Sampler ::GetParameterIndex( const std::string & parameterName ) const { const std::vector< Parameter > & parameters = this->m_Model->GetParameters(); for ( unsigned int i = 0; i < m_Model->GetNumberOfParameters(); i++ ) { if ( parameters[i].m_Name == parameterName ) return i; } return static_cast< unsigned int >(-1); // Intentional underflow } void Sampler ::ParameterSetExternally() { if (! m_Model) return; if (m_CurrentParameters.size() != m_Model->GetNumberOfParameters()) return; if (m_CurrentOutputs.size() == m_Model->GetNumberOfScalarOutputs()) return; Model::ErrorType error = m_Model->GetScalarOutputsAndLogLikelihood( m_CurrentParameters, m_CurrentOutputs, m_CurrentLogLikelihood); assert(error == Model::NO_ERROR); (void) error; } } // end namespace madai <|endoftext|>
<commit_before>/* Greesound Copyright (C) 2015 Grame 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/. Grame Centre national de création musicale 11, cours de Verdun Gensoul 69002 Lyon - France */ #include <vector> #include <exception> #include <iostream> #include <sstream> #include <QPushButton> #include <QCoreApplication> #include <QVBoxLayout> #include <QTimer> #include <QMessageBox> #include <QSettings> #include <QQuickView> #include <QDebug> #include "osc/OscReceivedElements.h" #include "Sensors.h" #include "Tools.h" using namespace std; using namespace osc; #define DEFAULT_ADDRESS "192.168.1.21" //#define DEFAULT_ADDRESS "192.168.43.88" #define DEFAULT_PORT 7001 const char* kGreensoundsAddr= "/greensounds"; const char* kButtonsAddr = "/greensounds/buttons"; const char* kModeAddr = "/mode"; const char* kParamBaseAddr = "/param/"; const char* kSliderBaseAddr = "/slider/"; //------------------------------------------------------------------------ void Sensors::timerEvent(QTimerEvent * ) { if (!fPlay) return; if (fSensor->active()) { int count = fSensor->count(); if (count) { OSCStream osc; osc.start( fSensor->address()); for (int i=0; i<count; i++) #ifdef ANDROID osc << -fSensor->value(i); #else osc << fSensor->value(i); #endif osc.end(); fSocket->SendTo(fDestPoint, osc.Data(), osc.Size()); } } // for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) { // Sensor* sensor = fSensors[i]; // if (sensor && sensor->active()) { // int count = sensor->count(); // if (count) { // OSCStream osc; // osc.start( sensor->address()); // for (int i=0; i<count; i++) // osc << sensor->value(i); // osc.end(); // fSocket->SendTo(fDestPoint, osc.Data(), osc.Size()); // } // } // } } //------------------------------------------------------------------------ //void Sensors::initSensors() //{ // for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) { // fSensors[i] = new Sensor(i); // } //} //------------------------------------------------------------------------ bool Sensors::initSensor () // initialises the rotation sensor { // fSensor = new Sensor(Sensor::kRotation); fSensor = new Sensor(Sensor::kAccelerometer); if (fSensor && fSensor->available()) { fSensor->activate(true); return true; } return false; } //------------------------------------------------------------------------ Sensors::Sensors() : fUIRoot(0), fDestPoint("localhost", DEFAULT_PORT), fIPNum(0), //fListener(this, LISTENING_PORT), fConnected(false), fSkipError(false), fPlay(false), fSensor(0), fTimerID(0) { // initSensors(); fDestination = DEFAULT_ADDRESS; fPort = DEFAULT_PORT; fDestPoint = IpEndpointName (fDestination.toStdString().c_str(), fPort); try { fSocket = new UdpSocket(); if (fSocket) fSocket->SetEnableBroadcast(true); fIPNum = Tools::getIP(); fIPStr = Tools::ip2string(fIPNum); fTimerID = startTimer(10); } catch(std::exception e) { fSocket = 0; } } //------------------------------------------------------------------------ Sensors::~Sensors() { killTimer(fTimerID); delete fSensor; // for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) { // delete fSensors[i]; // } } //------------------------------------------------------------------------ void Sensors::start() { fPlay = true; } void Sensors::stop() { fPlay = false;} //------------------------------------------------------------------------ void Sensors::connect(const char* dst) { destination(dst); fConnected = true; send (kGreensoundsAddr, Tools::ip2string(ip()).c_str(), "connected"); } //------------------------------------------------------------------------ unsigned long Sensors::ip() const { return fIPNum; } //------------------------------------------------------------------------ unsigned long Sensors::broadcastAddress() const { return (ip() & 0xffffff00) | 0xff;; } //------------------------------------------------------------------------ void Sensors::hello() const { if (fSocket) { OSCStream p; p.start( kGreensoundsAddr ); p << "hello" << Tools::ip2string(Tools::getIP()).c_str() << LISTENING_PORT; p.end(); unsigned long dest = broadcastAddress (); fSocket->SendTo(IpEndpointName(dest, fPort), p.Data(), p.Size()); IpEndpointName ip (dest, fPort); char buff[256]; ip.AddressAsString(buff); } } //------------------------------------------------------------------------ void Sensors::start(QObject* o) { fUIRoot = o; } //------------------------------------------------------------------------ // Q_INVOKABLE methods //------------------------------------------------------------------------ //void Sensors::activate(int index, bool state) //{ // Sensor* s = fSensors[index]; // if (s) s->activate(state); // else if (index == Sensor::kSensorMax) // skipChge(state); //} // //bool Sensors::available(int index) //{ // Sensor* s = fSensors[index]; // if (s) return s->available(); // return (index == Sensor::kSensorMax); //} void Sensors::destination(QString dest) { if (dest.length()) { fDestination = dest; destchge(); } } void Sensors::port(QString port) { bool converted = false; unsigned int p = port.toUInt (&converted); if (converted) { fPort = p; destchge(); } } void Sensors::param(int num, bool state) { stringstream addr; addr << kParamBaseAddr << num; send (addr.str().c_str(), int(state)); } void Sensors::slider(int num, float value) { stringstream addr; addr << kSliderBaseAddr << num; send (addr.str().c_str(), value); } void Sensors::pmode(bool state) { send (kModeAddr, state ? 2 : 1); } //------------------------------------------------------------------------ //void Sensors::skipChge(int state) //{ // for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) { // Sensor* s = fSensors[i]; // if (s) s->skipDuplicates (state); // } //} //------------------------------------------------------------------------ void Sensors::destchge() { fDestPoint = IpEndpointName( destination().toStdString().c_str() , port() ); } <commit_msg>remove android sensors values inversion<commit_after>/* Greesound Copyright (C) 2015 Grame 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/. Grame Centre national de création musicale 11, cours de Verdun Gensoul 69002 Lyon - France */ #include <vector> #include <exception> #include <iostream> #include <sstream> #include <QPushButton> #include <QCoreApplication> #include <QVBoxLayout> #include <QTimer> #include <QMessageBox> #include <QSettings> #include <QQuickView> #include <QDebug> #include "osc/OscReceivedElements.h" #include "Sensors.h" #include "Tools.h" using namespace std; using namespace osc; #define DEFAULT_ADDRESS "192.168.1.21" //#define DEFAULT_ADDRESS "192.168.43.88" #define DEFAULT_PORT 7001 const char* kGreensoundsAddr= "/greensounds"; const char* kButtonsAddr = "/greensounds/buttons"; const char* kModeAddr = "/mode"; const char* kParamBaseAddr = "/param/"; const char* kSliderBaseAddr = "/slider/"; //------------------------------------------------------------------------ void Sensors::timerEvent(QTimerEvent * ) { if (!fPlay) return; if (fSensor->active()) { int count = fSensor->count(); if (count) { OSCStream osc; osc.start( fSensor->address()); for (int i=0; i<count; i++) //#ifdef ANDROID // osc << -fSensor->value(i); //#else osc << fSensor->value(i); //#endif osc.end(); fSocket->SendTo(fDestPoint, osc.Data(), osc.Size()); } } // for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) { // Sensor* sensor = fSensors[i]; // if (sensor && sensor->active()) { // int count = sensor->count(); // if (count) { // OSCStream osc; // osc.start( sensor->address()); // for (int i=0; i<count; i++) // osc << sensor->value(i); // osc.end(); // fSocket->SendTo(fDestPoint, osc.Data(), osc.Size()); // } // } // } } //------------------------------------------------------------------------ //void Sensors::initSensors() //{ // for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) { // fSensors[i] = new Sensor(i); // } //} //------------------------------------------------------------------------ bool Sensors::initSensor () // initialises the rotation sensor { // fSensor = new Sensor(Sensor::kRotation); fSensor = new Sensor(Sensor::kAccelerometer); if (fSensor && fSensor->available()) { fSensor->activate(true); return true; } return false; } //------------------------------------------------------------------------ Sensors::Sensors() : fUIRoot(0), fDestPoint("localhost", DEFAULT_PORT), fIPNum(0), //fListener(this, LISTENING_PORT), fConnected(false), fSkipError(false), fPlay(false), fSensor(0), fTimerID(0) { // initSensors(); fDestination = DEFAULT_ADDRESS; fPort = DEFAULT_PORT; fDestPoint = IpEndpointName (fDestination.toStdString().c_str(), fPort); try { fSocket = new UdpSocket(); if (fSocket) fSocket->SetEnableBroadcast(true); fIPNum = Tools::getIP(); fIPStr = Tools::ip2string(fIPNum); fTimerID = startTimer(10); } catch(std::exception e) { fSocket = 0; } } //------------------------------------------------------------------------ Sensors::~Sensors() { killTimer(fTimerID); delete fSensor; // for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) { // delete fSensors[i]; // } } //------------------------------------------------------------------------ void Sensors::start() { fPlay = true; } void Sensors::stop() { fPlay = false;} //------------------------------------------------------------------------ void Sensors::connect(const char* dst) { destination(dst); fConnected = true; send (kGreensoundsAddr, Tools::ip2string(ip()).c_str(), "connected"); } //------------------------------------------------------------------------ unsigned long Sensors::ip() const { return fIPNum; } //------------------------------------------------------------------------ unsigned long Sensors::broadcastAddress() const { return (ip() & 0xffffff00) | 0xff;; } //------------------------------------------------------------------------ void Sensors::hello() const { if (fSocket) { OSCStream p; p.start( kGreensoundsAddr ); p << "hello" << Tools::ip2string(Tools::getIP()).c_str() << LISTENING_PORT; p.end(); unsigned long dest = broadcastAddress (); fSocket->SendTo(IpEndpointName(dest, fPort), p.Data(), p.Size()); IpEndpointName ip (dest, fPort); char buff[256]; ip.AddressAsString(buff); } } //------------------------------------------------------------------------ void Sensors::start(QObject* o) { fUIRoot = o; } //------------------------------------------------------------------------ // Q_INVOKABLE methods //------------------------------------------------------------------------ //void Sensors::activate(int index, bool state) //{ // Sensor* s = fSensors[index]; // if (s) s->activate(state); // else if (index == Sensor::kSensorMax) // skipChge(state); //} // //bool Sensors::available(int index) //{ // Sensor* s = fSensors[index]; // if (s) return s->available(); // return (index == Sensor::kSensorMax); //} void Sensors::destination(QString dest) { if (dest.length()) { fDestination = dest; destchge(); } } void Sensors::port(QString port) { bool converted = false; unsigned int p = port.toUInt (&converted); if (converted) { fPort = p; destchge(); } } void Sensors::param(int num, bool state) { stringstream addr; addr << kParamBaseAddr << num; send (addr.str().c_str(), int(state)); } void Sensors::slider(int num, float value) { stringstream addr; addr << kSliderBaseAddr << num; send (addr.str().c_str(), value); } void Sensors::pmode(bool state) { send (kModeAddr, state ? 2 : 1); } //------------------------------------------------------------------------ //void Sensors::skipChge(int state) //{ // for (int i = Sensor::kSensorStart; i < Sensor::kSensorMax; i++) { // Sensor* s = fSensors[i]; // if (s) s->skipDuplicates (state); // } //} //------------------------------------------------------------------------ void Sensors::destchge() { fDestPoint = IpEndpointName( destination().toStdString().c_str() , port() ); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: Threshld.cc Language: C++ Date: $Date$ Version: $Revision$ Description: --------------------------------------------------------------------------- This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Threshld.hh" vlThreshold::vlThreshold() { this->LowerThreshold = 0.0; this->UpperThreshold = 1.0; // this->ThresholdFunction = this->Upper; } void vlThreshold::Execute() { int cellId; vlIdList *cellPts, *pointMap; vlIdList newCellPts(MAX_CELL_SIZE); vlScalars *inScalars; vlFloatScalars cellScalars(MAX_CELL_SIZE); vlCell *cell; vlFloatPoints *newPoints; vlPointData *pd; int i, ptId, newId, numPts, numCellPts; float *x; vlDebugMacro(<< "Executing threshold filter"); // check input this->Initialize(); if ( ! (inScalars = this->Input->GetPointData()->GetScalars()) ) { vlErrorMacro(<<"No scalar data to threshold"); return; } numPts = this->Input->GetNumberOfPoints(); this->Allocate(this->Input->GetNumberOfCells()); newPoints = new vlFloatPoints(numPts); pd = this->Input->GetPointData(); this->PointData.CopyAllocate(pd); pointMap = new vlIdList(numPts); // maps old point ids into new for (i=0; i < numPts; i++) pointMap->SetId(i,-1); // Check that the scalars of each cell satisfy the threshold criterion for (cellId=0; cellId < this->Input->GetNumberOfCells(); cellId++) { cell = this->Input->GetCell(cellId); cellPts = cell->GetPointIds(); inScalars->GetScalars(*cellPts,cellScalars); numCellPts = cell->GetNumberOfPoints(); for ( i=0; i < numCellPts; i++) { ptId = cellPts->GetId(i); if ( !(*(this->ThresholdFunction))(cellScalars.GetScalar(ptId)) ) break; } if ( i >= numCellPts ) // satisfied thresholding { for (i=0; i < numCellPts; i++) { ptId = cellPts->GetId(i); if ( (newId = pointMap->GetId(ptId)) < 0 ) { x = this->Input->GetPoint(ptId); newId = newPoints->InsertNextPoint(x); pointMap->SetId(ptId,newId); this->PointData.CopyData(pd,ptId,newId); } newCellPts.SetId(i,newId); } this->InsertNextCell(cell->GetCellType(),newCellPts); } // satisfied thresholding } // for all cells vlDebugMacro(<< "Extracted " << this->GetNumberOfCells() << " number of cells."); // now clean up / update ourselves delete pointMap; this->Squeeze(); newPoints->Squeeze(); this->SetPoints(newPoints); } <commit_msg>*** empty log message ***<commit_after>/*========================================================================= Program: Visualization Library Module: Threshld.cc Language: C++ Date: $Date$ Version: $Revision$ Description: --------------------------------------------------------------------------- This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Threshld.hh" vlThreshold::vlThreshold() { this->LowerThreshold = 0.0; this->UpperThreshold = 1.0; // this->ThresholdFunction = this->Upper; } void vlThreshold::Execute() { int cellId; vlIdList *cellPts, *pointMap; vlIdList newCellPts(MAX_CELL_SIZE); vlScalars *inScalars; vlFloatScalars cellScalars(MAX_CELL_SIZE); vlCell *cell; vlFloatPoints *newPoints; vlPointData *pd; int i, ptId, newId, numPts, numCellPts; float *x; vlDebugMacro(<< "Executing threshold filter"); // check input this->Initialize(); if ( ! (inScalars = this->Input->GetPointData()->GetScalars()) ) { vlErrorMacro(<<"No scalar data to threshold"); return; } numPts = this->Input->GetNumberOfPoints(); this->Allocate(this->Input->GetNumberOfCells()); newPoints = new vlFloatPoints(numPts); pd = this->Input->GetPointData(); this->PointData.CopyAllocate(pd); pointMap = new vlIdList(numPts); // maps old point ids into new for (i=0; i < numPts; i++) pointMap->SetId(i,-1); // Check that the scalars of each cell satisfy the threshold criterion for (cellId=0; cellId < this->Input->GetNumberOfCells(); cellId++) { cell = this->Input->GetCell(cellId); cellPts = cell->GetPointIds(); inScalars->GetScalars(*cellPts,cellScalars); numCellPts = cell->GetNumberOfPoints(); for ( i=0; i < numCellPts; i++) { ptId = cellPts->GetId(i); if ( !(*(this->ThresholdFunction))(cellScalars.GetScalar(ptId)) ) break; } if ( i >= numCellPts ) // satisfied thresholding { for (i=0; i < numCellPts; i++) { ptId = cellPts->GetId(i); if ( (newId = pointMap->GetId(ptId)) < 0 ) { x = this->Input->GetPoint(ptId); newId = newPoints->InsertNextPoint(x); pointMap->SetId(ptId,newId); this->PointData.CopyData(pd,ptId,newId); } newCellPts.SetId(i,newId); } this->InsertNextCell(cell->GetCellType(),newCellPts); } // satisfied thresholding } // for all cells vlDebugMacro(<< "Extracted " << this->GetNumberOfCells() << " number of cells."); // now clean up / update ourselves delete pointMap; this->Squeeze(); newPoints->Squeeze(); this->SetPoints(newPoints); } void vlThreshold::PrintSelf() { if (this->ShouldIPrint(vlThreshold::GetClassName())) { vlDataSetToUnstructuredGridFilter::PrintSelf(os,indent); os << indent << "Lower Threshold: " << this->LowerThreshold << "\n";; os << indent << "Upper Threshold: " << this->UpperThreshold << "\n";; } } <|endoftext|>
<commit_before>#include "Tracker.hpp" #include <stdexcept> #include <iostream> #include <stdlib.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <cvblob.h> #include <ros/console.h> #include <cmath> #include "profiling.hpp" // Use this to use the register keyword in some places. Might make things faster, but I didn't test it. //#define QC_REGISTER // Use this for debugging the object recognition. WARNING: Might lead to errors or strange behaviour when used with visualTracker == true. //#define QC_DEBUG_TRACKER Tracker::Tracker(ITrackerDataReceiver* dataReceiver, QuadcopterColor* color) { this->dataReceiver = dataReceiver; this->thread = 0; this->image = 0; this->qc = color; this->visualTracker = false; this->useMaskedImage = false; } Tracker::Tracker(ITrackerDataReceiver* dataReceiver, QuadcopterColor* color, bool visualTracker, bool useMaskedImage) { this->dataReceiver = dataReceiver; this->thread = 0; this->image = 0; this->qc = color; this->visualTracker = visualTracker; this->useMaskedImage = useMaskedImage; if (visualTracker) { std::stringstream ss; ss << "Tracker of id " << ((QuadcopterColor*) this->qc)->getId(); this->windowName = ss.str(); cv::startWindowThread(); } } Tracker::~Tracker() { } void Tracker::start() { if (thread != 0) { throw new std::runtime_error("Already started. (Maybe you forgot to call join?)"); } if (visualTracker) { cv::namedWindow(windowName); } imageDirty = false; stopFlag = false; thread = new boost::thread(boost::bind(&Tracker::executeTracker, this)); } void Tracker::stop() { if (thread == 0) { throw new std::runtime_error("Not started."); } stopFlag = true; } void Tracker::join() { if (thread != 0) { thread->join(); delete thread; thread = 0; } if (this->image != 0) { delete this->image; this->image = 0; } } bool Tracker::isStarted() { return thread != 0; } void Tracker::setNextImage(cv::Mat* image, long int time) { imageMutex.lock(); if (this->image != 0) { delete this->image; } this->image = new cv::Mat(*image); imageTime = time; imageDirty = true; imageMutex.unlock(); } QuadcopterColor* Tracker::getQuadcopterColor() { return (QuadcopterColor*) qc; } void Tracker::drawCross(cv::Mat* mat, const int x, const int y) { ROS_DEBUG("Drawing cross."); for (int i = x - 10; i <= x + 10; i++) { int j = y; // ROS_DEBUG("i/j: %d/%d", i, j); if (i >= 0 && i < mat->rows && j >= 0 && j < mat->cols) { unsigned char* element = mat->data + mat->step[0] * j + mat->step[1] * i; unsigned char color; if (i + j % 3 > 0) { color = 0xFF; } else { color = 0; } element[0] = color; element[1] = color; element[2] = color; } } for (int j = y - 10; j <= y + 10; j++) { int i = x; // ROS_DEBUG("i/j: %d/%d", i, j); if (i >= 0 && i < mat->rows && j >= 0 && j < mat->cols) { unsigned char* element = mat->data + mat->step[0] * j + mat->step[1] * i; unsigned char color; if (i + j % 3 > 0) { color = 0xFF; } else { color = 0; } element[0] = color; element[1] = color; element[2] = color; } } ROS_DEBUG("Cross drawed"); } void Tracker::executeTracker() { #ifdef QC_DEBUG_TRACKER cv::startWindowThread(); cv::namedWindow("Tracker"); #endif #define PI (3.1415926535897932384626433832795028841) // Kinect fow: 43° vertical, 57° horizontal double verticalScalingFactor = tan(43 * PI / 180) / 240; double horizontalScalingFactor = tan(57 * PI / 180) / 320; ROS_DEBUG("Scaling factors: %lf/%lf", horizontalScalingFactor, verticalScalingFactor); while (!stopFlag) { if (!imageDirty) { usleep(100); continue; } START_CLOCK(trackerClock) imageMutex.lock(); cv::Mat* image = (cv::Mat*) this->image; image = new cv::Mat(*image); long int time = this->imageTime; imageDirty = false; imageMutex.unlock(); cv::Mat* visualImage = 0; if (visualTracker && !useMaskedImage) { visualImage = new cv::Mat(image->size(), image->type()); image->copyTo(*visualImage); } #ifdef QC_DEBUG_TRACKER cv::imshow("Tracker", *image); cv::waitKey(100000); #endif cv::Mat* mapImage = createColorMapImage(image); if (visualTracker && useMaskedImage) { // Convert to 3 channel image. visualImage = new cv::Mat(cv::Size(640, 480), CV_8UC3); int target = 0; for (int i = 0; i < mapImage->total(); ++i) { visualImage->data[target++] = mapImage->data[i]; visualImage->data[target++] = mapImage->data[i]; visualImage->data[target++] = mapImage->data[i]; } } #ifdef QC_DEBUG_TRACKER cv::imshow("Tracker", *mapImage); cv::waitKey(100000); #endif cv::Mat morphKernel = cv::getStructuringElement(CV_SHAPE_RECT, cv::Size(5, 5)); cv::morphologyEx(*mapImage, *mapImage, cv::MORPH_OPEN, morphKernel); // Finding blobs cvb::CvBlobs blobs; IplImage *labelImg = cvCreateImage(image->size(), IPL_DEPTH_LABEL, 1); IplImage iplMapImage = *mapImage; unsigned int result = cvLabel(&iplMapImage, labelImg, blobs); ROS_DEBUG("Blob result: %d", result); // Filter blobs cvFilterByArea(blobs, 25, 1000000); #ifdef QC_DEBUG_TRACKER IplImage iplImage = *image; cvRenderBlobs(labelImg, blobs, &iplImage, &iplImage, CV_BLOB_RENDER_BOUNDING_BOX); cvb::CvTracks tracks; cvUpdateTracks(blobs, tracks, 200., 5); cvRenderTracks(tracks, &iplImage, &iplImage, CV_TRACK_RENDER_ID | CV_TRACK_RENDER_BOUNDING_BOX); cv::imshow("Tracker", cv::Mat(&iplImage)); cv::waitKey(100000); cvReleaseTracks(tracks); ROS_DEBUG("Exiting debug block"); // TODO Tracking down issue #7 #endif if (visualTracker) { IplImage iplImage = *visualImage; cvRenderBlobs(labelImg, blobs, &iplImage, &iplImage, CV_BLOB_RENDER_BOUNDING_BOX); cvb::CvTracks tracks; cvUpdateTracks(blobs, tracks, 200., 5); cvRenderTracks(tracks, &iplImage, &iplImage, CV_TRACK_RENDER_ID | CV_TRACK_RENDER_BOUNDING_BOX); cvReleaseTracks(tracks); ROS_DEBUG("Exiting visual block"); // TODO Tracking down issue #7 } if (blobs.size() != 0) { // Find biggest blob cvb::CvLabel largestBlob = cvLargestBlob(blobs); CvPoint2D64f center = blobs.find(largestBlob)->second->centroid; double x = center.x; double y = center.y; // Set (0, 0) to center. x -= 320; y = 240 - y; ROS_DEBUG("Center: %lf/%lf", x, y); // Apply scaling x *= horizontalScalingFactor; y *= verticalScalingFactor; dataReceiver->receiveTrackingData(cv::Scalar(x, y, 1.0), ((QuadcopterColor*) qc)->getId(), time); if (visualTracker) { drawCross(visualImage, center.x, center.y); } } // Free cvb stuff. cvReleaseBlobs(blobs); cvReleaseImage(&labelImg); ROS_DEBUG("cvb stuff freed"); // TODO Tracking down issue #7 if (visualTracker) { cv::imshow(windowName, *visualImage); delete visualImage; ROS_DEBUG("showed visual image"); // TODO Tracking down issue #7 } delete mapImage; delete image; STOP_CLOCK(trackerClock, "Calculation of quadcopter position took: ") } #ifdef QC_DEBUG_TRACKER cv::destroyWindow("Tracker"); #endif if (visualTracker) { cv::destroyWindow(windowName); } ROS_INFO("Tracker with id %d terminated", ((QuadcopterColor*) this->qc)->getId()); } cv::Mat* Tracker::createColorMapImage(cv::Mat* image) { START_CLOCK(convertColorClock) cv::Mat* mapImage = new cv::Mat(image->size(), CV_8UC1); // Debug HSV color range unsigned char* element = image->data + image->step[0] * 240 + image->step[1] * 320; ROS_DEBUG("R: %d G: %d B: %d", element[2], element[1], element[0]); cv::cvtColor(*image, *image, CV_BGR2HSV); // Debug HSV color range ROS_DEBUG("H: %d S: %d V: %d", element[0], element[1], element[2]); STOP_CLOCK(convertColorClock, "Converting colors took: ") START_CLOCK(maskImageClock) // Trying to make this fast. #ifdef QC_REGISTER register uint8_t *current, *end, *source; register int minHue, maxHue, minSaturation, /*maxSaturation,*/ minValue/*, maxValue*/; #else uint8_t *current, *end, *source; int minHue, maxHue, minSaturation, /*maxSaturation,*/ minValue/*, maxValue*/; #endif QuadcopterColor* color = (QuadcopterColor*) qc; minHue = color->getMinColor().val[0]; maxHue = color->getMaxColor().val[0]; minSaturation = color->getMinColor().val[1]; //maxSaturation = color->getMaxColor().val[1]; // unused minValue = color->getMinColor().val[2]; //maxValue = color->getMaxColor().val[2]; // unused end = mapImage->data + mapImage->size().width * mapImage->size().height; source = image->data; if (minHue < maxHue) { for (current = mapImage->data; current < end; ++current, source += 3) { //if (*source > maxHue || *source < minHue || *(++source) > maxSaturation || *source < minSaturation || *(++source) > maxValue || *(source++) < minValue) { if (*source > maxHue || *source < minHue || *(source + 1) < minSaturation || *(source + 2) < minValue) { *current = 0; } else { *current = 255; } } } else { // Hue interval inverted here. for (current = mapImage->data; current < end; ++current, source += 3) { //if (*source < maxHue || *source > minHue || *(++source) > maxSaturation || *source < minSaturation || *(++source) > maxValue || *(source++) < minValue) { if ((*source > maxHue && *source < minHue) || *(source + 1) < minSaturation || *(source + 2) < minValue) { *current = 0; } else { *current = 255; } } } STOP_CLOCK(maskImageClock, "Image masking took: ") return mapImage; } <commit_msg>Made y axis point down<commit_after>#include "Tracker.hpp" #include <stdexcept> #include <iostream> #include <stdlib.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <cvblob.h> #include <ros/console.h> #include <cmath> #include "profiling.hpp" // Use this to use the register keyword in some places. Might make things faster, but I didn't test it. //#define QC_REGISTER // Use this for debugging the object recognition. WARNING: Might lead to errors or strange behaviour when used with visualTracker == true. //#define QC_DEBUG_TRACKER Tracker::Tracker(ITrackerDataReceiver* dataReceiver, QuadcopterColor* color) { this->dataReceiver = dataReceiver; this->thread = 0; this->image = 0; this->qc = color; this->visualTracker = false; this->useMaskedImage = false; } Tracker::Tracker(ITrackerDataReceiver* dataReceiver, QuadcopterColor* color, bool visualTracker, bool useMaskedImage) { this->dataReceiver = dataReceiver; this->thread = 0; this->image = 0; this->qc = color; this->visualTracker = visualTracker; this->useMaskedImage = useMaskedImage; if (visualTracker) { std::stringstream ss; ss << "Tracker of id " << ((QuadcopterColor*) this->qc)->getId(); this->windowName = ss.str(); cv::startWindowThread(); } } Tracker::~Tracker() { } void Tracker::start() { if (thread != 0) { throw new std::runtime_error("Already started. (Maybe you forgot to call join?)"); } if (visualTracker) { cv::namedWindow(windowName); } imageDirty = false; stopFlag = false; thread = new boost::thread(boost::bind(&Tracker::executeTracker, this)); } void Tracker::stop() { if (thread == 0) { throw new std::runtime_error("Not started."); } stopFlag = true; } void Tracker::join() { if (thread != 0) { thread->join(); delete thread; thread = 0; } if (this->image != 0) { delete this->image; this->image = 0; } } bool Tracker::isStarted() { return thread != 0; } void Tracker::setNextImage(cv::Mat* image, long int time) { imageMutex.lock(); if (this->image != 0) { delete this->image; } this->image = new cv::Mat(*image); imageTime = time; imageDirty = true; imageMutex.unlock(); } QuadcopterColor* Tracker::getQuadcopterColor() { return (QuadcopterColor*) qc; } void Tracker::drawCross(cv::Mat* mat, const int x, const int y) { ROS_DEBUG("Drawing cross."); for (int i = x - 10; i <= x + 10; i++) { int j = y; // ROS_DEBUG("i/j: %d/%d", i, j); if (i >= 0 && i < mat->rows && j >= 0 && j < mat->cols) { unsigned char* element = mat->data + mat->step[0] * j + mat->step[1] * i; unsigned char color; if (i + j % 3 > 0) { color = 0xFF; } else { color = 0; } element[0] = color; element[1] = color; element[2] = color; } } for (int j = y - 10; j <= y + 10; j++) { int i = x; // ROS_DEBUG("i/j: %d/%d", i, j); if (i >= 0 && i < mat->rows && j >= 0 && j < mat->cols) { unsigned char* element = mat->data + mat->step[0] * j + mat->step[1] * i; unsigned char color; if (i + j % 3 > 0) { color = 0xFF; } else { color = 0; } element[0] = color; element[1] = color; element[2] = color; } } ROS_DEBUG("Cross drawed"); } void Tracker::executeTracker() { #ifdef QC_DEBUG_TRACKER cv::startWindowThread(); cv::namedWindow("Tracker"); #endif #define PI (3.1415926535897932384626433832795028841) // Kinect fow: 43° vertical, 57° horizontal double verticalScalingFactor = tan(43 * PI / 180) / 240; double horizontalScalingFactor = tan(57 * PI / 180) / 320; ROS_DEBUG("Scaling factors: %lf/%lf", horizontalScalingFactor, verticalScalingFactor); while (!stopFlag) { if (!imageDirty) { usleep(100); continue; } START_CLOCK(trackerClock) imageMutex.lock(); cv::Mat* image = (cv::Mat*) this->image; image = new cv::Mat(*image); long int time = this->imageTime; imageDirty = false; imageMutex.unlock(); cv::Mat* visualImage = 0; if (visualTracker && !useMaskedImage) { visualImage = new cv::Mat(image->size(), image->type()); image->copyTo(*visualImage); } #ifdef QC_DEBUG_TRACKER cv::imshow("Tracker", *image); cv::waitKey(100000); #endif cv::Mat* mapImage = createColorMapImage(image); if (visualTracker && useMaskedImage) { // Convert to 3 channel image. visualImage = new cv::Mat(cv::Size(640, 480), CV_8UC3); int target = 0; for (int i = 0; i < mapImage->total(); ++i) { visualImage->data[target++] = mapImage->data[i]; visualImage->data[target++] = mapImage->data[i]; visualImage->data[target++] = mapImage->data[i]; } } #ifdef QC_DEBUG_TRACKER cv::imshow("Tracker", *mapImage); cv::waitKey(100000); #endif cv::Mat morphKernel = cv::getStructuringElement(CV_SHAPE_RECT, cv::Size(5, 5)); cv::morphologyEx(*mapImage, *mapImage, cv::MORPH_OPEN, morphKernel); // Finding blobs cvb::CvBlobs blobs; IplImage *labelImg = cvCreateImage(image->size(), IPL_DEPTH_LABEL, 1); IplImage iplMapImage = *mapImage; unsigned int result = cvLabel(&iplMapImage, labelImg, blobs); ROS_DEBUG("Blob result: %d", result); // Filter blobs cvFilterByArea(blobs, 25, 1000000); #ifdef QC_DEBUG_TRACKER IplImage iplImage = *image; cvRenderBlobs(labelImg, blobs, &iplImage, &iplImage, CV_BLOB_RENDER_BOUNDING_BOX); cvb::CvTracks tracks; cvUpdateTracks(blobs, tracks, 200., 5); cvRenderTracks(tracks, &iplImage, &iplImage, CV_TRACK_RENDER_ID | CV_TRACK_RENDER_BOUNDING_BOX); cv::imshow("Tracker", cv::Mat(&iplImage)); cv::waitKey(100000); cvReleaseTracks(tracks); ROS_DEBUG("Exiting debug block"); // TODO Tracking down issue #7 #endif if (visualTracker) { IplImage iplImage = *visualImage; cvRenderBlobs(labelImg, blobs, &iplImage, &iplImage, CV_BLOB_RENDER_BOUNDING_BOX); cvb::CvTracks tracks; cvUpdateTracks(blobs, tracks, 200., 5); cvRenderTracks(tracks, &iplImage, &iplImage, CV_TRACK_RENDER_ID | CV_TRACK_RENDER_BOUNDING_BOX); cvReleaseTracks(tracks); ROS_DEBUG("Exiting visual block"); // TODO Tracking down issue #7 } if (blobs.size() != 0) { // Find biggest blob cvb::CvLabel largestBlob = cvLargestBlob(blobs); CvPoint2D64f center = blobs.find(largestBlob)->second->centroid; double x = center.x; double y = center.y; // Set (0, 0) to center. x -= 320; y -= 240; ROS_DEBUG("Center: %lf/%lf", x, y); // Apply scaling x *= horizontalScalingFactor; y *= verticalScalingFactor; dataReceiver->receiveTrackingData(cv::Scalar(x, y, 1.0), ((QuadcopterColor*) qc)->getId(), time); if (visualTracker) { drawCross(visualImage, center.x, center.y); } } // Free cvb stuff. cvReleaseBlobs(blobs); cvReleaseImage(&labelImg); ROS_DEBUG("cvb stuff freed"); // TODO Tracking down issue #7 if (visualTracker) { cv::imshow(windowName, *visualImage); delete visualImage; ROS_DEBUG("showed visual image"); // TODO Tracking down issue #7 } delete mapImage; delete image; STOP_CLOCK(trackerClock, "Calculation of quadcopter position took: ") } #ifdef QC_DEBUG_TRACKER cv::destroyWindow("Tracker"); #endif if (visualTracker) { cv::destroyWindow(windowName); } ROS_INFO("Tracker with id %d terminated", ((QuadcopterColor*) this->qc)->getId()); } cv::Mat* Tracker::createColorMapImage(cv::Mat* image) { START_CLOCK(convertColorClock) cv::Mat* mapImage = new cv::Mat(image->size(), CV_8UC1); // Debug HSV color range unsigned char* element = image->data + image->step[0] * 240 + image->step[1] * 320; ROS_DEBUG("R: %d G: %d B: %d", element[2], element[1], element[0]); cv::cvtColor(*image, *image, CV_BGR2HSV); // Debug HSV color range ROS_DEBUG("H: %d S: %d V: %d", element[0], element[1], element[2]); STOP_CLOCK(convertColorClock, "Converting colors took: ") START_CLOCK(maskImageClock) // Trying to make this fast. #ifdef QC_REGISTER register uint8_t *current, *end, *source; register int minHue, maxHue, minSaturation, /*maxSaturation,*/ minValue/*, maxValue*/; #else uint8_t *current, *end, *source; int minHue, maxHue, minSaturation, /*maxSaturation,*/ minValue/*, maxValue*/; #endif QuadcopterColor* color = (QuadcopterColor*) qc; minHue = color->getMinColor().val[0]; maxHue = color->getMaxColor().val[0]; minSaturation = color->getMinColor().val[1]; //maxSaturation = color->getMaxColor().val[1]; // unused minValue = color->getMinColor().val[2]; //maxValue = color->getMaxColor().val[2]; // unused end = mapImage->data + mapImage->size().width * mapImage->size().height; source = image->data; if (minHue < maxHue) { for (current = mapImage->data; current < end; ++current, source += 3) { //if (*source > maxHue || *source < minHue || *(++source) > maxSaturation || *source < minSaturation || *(++source) > maxValue || *(source++) < minValue) { if (*source > maxHue || *source < minHue || *(source + 1) < minSaturation || *(source + 2) < minValue) { *current = 0; } else { *current = 255; } } } else { // Hue interval inverted here. for (current = mapImage->data; current < end; ++current, source += 3) { //if (*source < maxHue || *source > minHue || *(++source) > maxSaturation || *source < minSaturation || *(++source) > maxValue || *(source++) < minValue) { if ((*source > maxHue && *source < minHue) || *(source + 1) < minSaturation || *(source + 2) < minValue) { *current = 0; } else { *current = 255; } } } STOP_CLOCK(maskImageClock, "Image masking took: ") return mapImage; } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmljsdocument.h" #include "qmljsbind.h" #include <qmljs/parser/qmljsast_p.h> #include <qmljs/parser/qmljslexer_p.h> #include <qmljs/parser/qmljsparser_p.h> #include <qmljs/parser/qmljsnodepool_p.h> #include <qmljs/parser/qmljsastfwd_p.h> #include <QtCore/QDir> using namespace QmlJS; using namespace QmlJS::AST; Document::Document(const QString &fileName) : _engine(0) , _pool(0) , _ast(0) , _bind(0) , _isQmlDocument(false) , _documentRevision(0) , _parsedCorrectly(false) , _fileName(fileName) { QFileInfo fileInfo(fileName); _path = fileInfo.absolutePath(); if (fileInfo.suffix() == QLatin1String("qml")) { _isQmlDocument = true; _componentName = fileInfo.baseName(); if (! _componentName.isEmpty()) { // ### TODO: check the component name. if (! _componentName.at(0).isUpper()) _componentName.clear(); } } } Document::~Document() { if (_bind) delete _bind; if (_engine) delete _engine; if (_pool) delete _pool; } Document::Ptr Document::create(const QString &fileName) { Document::Ptr doc(new Document(fileName)); return doc; } bool Document::isQmlDocument() const { return _isQmlDocument; } bool Document::isJSDocument() const { return ! _isQmlDocument; } AST::UiProgram *Document::qmlProgram() const { return cast<UiProgram *>(_ast); } AST::Program *Document::jsProgram() const { return cast<Program *>(_ast); } AST::ExpressionNode *Document::expression() const { if (_ast) return _ast->expressionCast(); return 0; } AST::Node *Document::ast() const { return _ast; } QList<DiagnosticMessage> Document::diagnosticMessages() const { return _diagnosticMessages; } QString Document::source() const { return _source; } void Document::setSource(const QString &source) { _source = source; } int Document::documentRevision() const { return _documentRevision; } void Document::setDocumentRevision(int revision) { _documentRevision = revision; } QString Document::fileName() const { return _fileName; } QString Document::path() const { return _path; } QString Document::componentName() const { return _componentName; } bool Document::parse_helper(int startToken) { Q_ASSERT(! _engine); Q_ASSERT(! _pool); Q_ASSERT(! _ast); Q_ASSERT(! _bind); _engine = new Engine(); _pool = new NodePool(_fileName, _engine); Lexer lexer(_engine); Parser parser(_engine); lexer.setCode(_source, /*line = */ 1); switch (startToken) { case QmlJSGrammar::T_FEED_UI_PROGRAM: _parsedCorrectly = parser.parse(); break; case QmlJSGrammar::T_FEED_JS_PROGRAM: _parsedCorrectly = parser.parseProgram(); break; case QmlJSGrammar::T_FEED_JS_EXPRESSION: _parsedCorrectly = parser.parseExpression(); break; default: Q_ASSERT(0); } _ast = parser.rootNode(); _diagnosticMessages = parser.diagnosticMessages(); _bind = new Bind(this); return _parsedCorrectly; } bool Document::parse() { if (isQmlDocument()) return parseQml(); return parseJavaScript(); } bool Document::parseQml() { return parse_helper(QmlJSGrammar::T_FEED_UI_PROGRAM); } bool Document::parseJavaScript() { return parse_helper(QmlJSGrammar::T_FEED_JS_PROGRAM); } bool Document::parseExpression() { return parse_helper(QmlJSGrammar::T_FEED_JS_EXPRESSION); } Bind *Document::bind() const { return _bind; } LibraryInfo::LibraryInfo() : _valid(false) { } LibraryInfo::LibraryInfo(const QmlDirParser &parser) : _valid(true) , _components(parser.components()) , _plugins(parser.plugins()) { } LibraryInfo::~LibraryInfo() { } Snapshot::Snapshot() { } Snapshot::~Snapshot() { } void Snapshot::insert(const Document::Ptr &document) { if (document && (document->qmlProgram() || document->jsProgram())) _documents.insert(document->fileName(), document); } void Snapshot::insertLibraryInfo(const QString &path, const LibraryInfo &info) { _libraries.insert(path, info); } Document::Ptr Snapshot::documentFromSource(const QString &code, const QString &fileName) const { Document::Ptr newDoc = Document::create(fileName); if (Document::Ptr thisDocument = document(fileName)) { newDoc->_documentRevision = thisDocument->_documentRevision; } newDoc->setSource(code); return newDoc; } QList<Document::Ptr> Snapshot::importedDocuments(const Document::Ptr &doc, const QString &importPath) const { // ### TODO: maybe we should add all imported documents in the parse Document::parse() method, regardless of whether they're in the path or not. QList<Document::Ptr> result; QString docPath = doc->path(); docPath += QLatin1Char('/'); docPath += importPath; docPath = QDir::cleanPath(docPath); foreach (Document::Ptr candidate, _documents) { if (candidate == doc) continue; // ignore this document else if (candidate->isJSDocument()) continue; // skip JS documents if (candidate->path() == doc->path() || candidate->path() == docPath) result.append(candidate); } return result; } QMap<QString, Document::Ptr> Snapshot::componentsDefinedByImportedDocuments(const Document::Ptr &doc, const QString &importPath) const { QMap<QString, Document::Ptr> result; const QString docPath = doc->path() + '/' + importPath; foreach (Document::Ptr candidate, *this) { if (candidate == doc) continue; if (candidate->path() == doc->path() || candidate->path() == docPath) result.insert(candidate->componentName(), candidate); } return result; } <commit_msg>QmlJS: Fix invalid errors inside qmlproject files.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmljsdocument.h" #include "qmljsbind.h" #include <qmljs/parser/qmljsast_p.h> #include <qmljs/parser/qmljslexer_p.h> #include <qmljs/parser/qmljsparser_p.h> #include <qmljs/parser/qmljsnodepool_p.h> #include <qmljs/parser/qmljsastfwd_p.h> #include <QtCore/QDir> using namespace QmlJS; using namespace QmlJS::AST; Document::Document(const QString &fileName) : _engine(0) , _pool(0) , _ast(0) , _bind(0) , _isQmlDocument(false) , _documentRevision(0) , _parsedCorrectly(false) , _fileName(fileName) { QFileInfo fileInfo(fileName); _path = fileInfo.absolutePath(); // ### Should use mime type if (fileInfo.suffix() == QLatin1String("qml") || fileInfo.suffix() == QLatin1String("qmlproject")) { _isQmlDocument = true; _componentName = fileInfo.baseName(); if (! _componentName.isEmpty()) { // ### TODO: check the component name. if (! _componentName.at(0).isUpper()) _componentName.clear(); } } } Document::~Document() { if (_bind) delete _bind; if (_engine) delete _engine; if (_pool) delete _pool; } Document::Ptr Document::create(const QString &fileName) { Document::Ptr doc(new Document(fileName)); return doc; } bool Document::isQmlDocument() const { return _isQmlDocument; } bool Document::isJSDocument() const { return ! _isQmlDocument; } AST::UiProgram *Document::qmlProgram() const { return cast<UiProgram *>(_ast); } AST::Program *Document::jsProgram() const { return cast<Program *>(_ast); } AST::ExpressionNode *Document::expression() const { if (_ast) return _ast->expressionCast(); return 0; } AST::Node *Document::ast() const { return _ast; } QList<DiagnosticMessage> Document::diagnosticMessages() const { return _diagnosticMessages; } QString Document::source() const { return _source; } void Document::setSource(const QString &source) { _source = source; } int Document::documentRevision() const { return _documentRevision; } void Document::setDocumentRevision(int revision) { _documentRevision = revision; } QString Document::fileName() const { return _fileName; } QString Document::path() const { return _path; } QString Document::componentName() const { return _componentName; } bool Document::parse_helper(int startToken) { Q_ASSERT(! _engine); Q_ASSERT(! _pool); Q_ASSERT(! _ast); Q_ASSERT(! _bind); _engine = new Engine(); _pool = new NodePool(_fileName, _engine); Lexer lexer(_engine); Parser parser(_engine); lexer.setCode(_source, /*line = */ 1); switch (startToken) { case QmlJSGrammar::T_FEED_UI_PROGRAM: _parsedCorrectly = parser.parse(); break; case QmlJSGrammar::T_FEED_JS_PROGRAM: _parsedCorrectly = parser.parseProgram(); break; case QmlJSGrammar::T_FEED_JS_EXPRESSION: _parsedCorrectly = parser.parseExpression(); break; default: Q_ASSERT(0); } _ast = parser.rootNode(); _diagnosticMessages = parser.diagnosticMessages(); _bind = new Bind(this); return _parsedCorrectly; } bool Document::parse() { if (isQmlDocument()) return parseQml(); return parseJavaScript(); } bool Document::parseQml() { return parse_helper(QmlJSGrammar::T_FEED_UI_PROGRAM); } bool Document::parseJavaScript() { return parse_helper(QmlJSGrammar::T_FEED_JS_PROGRAM); } bool Document::parseExpression() { return parse_helper(QmlJSGrammar::T_FEED_JS_EXPRESSION); } Bind *Document::bind() const { return _bind; } LibraryInfo::LibraryInfo() : _valid(false) { } LibraryInfo::LibraryInfo(const QmlDirParser &parser) : _valid(true) , _components(parser.components()) , _plugins(parser.plugins()) { } LibraryInfo::~LibraryInfo() { } Snapshot::Snapshot() { } Snapshot::~Snapshot() { } void Snapshot::insert(const Document::Ptr &document) { if (document && (document->qmlProgram() || document->jsProgram())) _documents.insert(document->fileName(), document); } void Snapshot::insertLibraryInfo(const QString &path, const LibraryInfo &info) { _libraries.insert(path, info); } Document::Ptr Snapshot::documentFromSource(const QString &code, const QString &fileName) const { Document::Ptr newDoc = Document::create(fileName); if (Document::Ptr thisDocument = document(fileName)) { newDoc->_documentRevision = thisDocument->_documentRevision; } newDoc->setSource(code); return newDoc; } QList<Document::Ptr> Snapshot::importedDocuments(const Document::Ptr &doc, const QString &importPath) const { // ### TODO: maybe we should add all imported documents in the parse Document::parse() method, regardless of whether they're in the path or not. QList<Document::Ptr> result; QString docPath = doc->path(); docPath += QLatin1Char('/'); docPath += importPath; docPath = QDir::cleanPath(docPath); foreach (Document::Ptr candidate, _documents) { if (candidate == doc) continue; // ignore this document else if (candidate->isJSDocument()) continue; // skip JS documents if (candidate->path() == doc->path() || candidate->path() == docPath) result.append(candidate); } return result; } QMap<QString, Document::Ptr> Snapshot::componentsDefinedByImportedDocuments(const Document::Ptr &doc, const QString &importPath) const { QMap<QString, Document::Ptr> result; const QString docPath = doc->path() + '/' + importPath; foreach (Document::Ptr candidate, *this) { if (candidate == doc) continue; if (candidate->path() == doc->path() || candidate->path() == docPath) result.insert(candidate->componentName(), candidate); } return result; } <|endoftext|>
<commit_before>#include <echolib/opencv.h> #include <chrono> #include <memory> #include <experimental/filesystem> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/video/video.hpp> #ifdef MANUS_DEBUG #include <opencv2/highgui/highgui.hpp> #endif #include <ary/complex.h> #include <ary/utilities.h> using namespace std; using namespace cv; using namespace echolib; using namespace ary; bool debug = false; Ptr<CameraModel> model; Ptr<Scene> scene; Header header_current; Mat image_current; Mat image_gray; Ptr<BackgroundSubtractorMOG2> scene_model; int force_update_counter; int force_update_threshold; SharedLocalization localization; SharedCameraModel parameters(new CameraModel(Size(640, 480))); bool scene_change(Mat& image) { setDrawScale(1000); if (image.empty()) return false; Mat candidate, mask; resize(image, candidate, Size(64, 64)); if (scene_model.empty()) { scene_model = Ptr<BackgroundSubtractorMOG2>(new BackgroundSubtractorMOG2(100, 4, false)); } if (force_update_counter > force_update_threshold) { force_update_counter = 0; return true; } force_update_counter++; scene_model->operator()(candidate, mask); #ifdef MANUS_DEBUG if (debug) { imshow("Changes", mask); } #endif float changes = (float)(sum(mask)[0]) / (float)(mask.cols * mask.rows * 255); if (changes > 0.2) { force_update_counter = 0; return true; } else { return false; } } void handle_frame(shared_ptr<Frame> frame) { if (frame->image.empty()) return; header_current = frame->header; image_current = frame->image; } SharedTypedPublisher<CameraExtrinsics> location_publisher; SharedTypedSubscriber<CameraIntrinsics> parameters_listener; vector<Point3f> blobs; void read_blobs(const char* file) { blobs.clear(); FileStorage fs(file, FileStorage::READ); if (!fs.isOpened()) { return; } FileNode centers = fs["centers"]; for (FileNodeIterator it = centers.begin(); it != centers.end(); ++it) { float x, y; read((*it)["x"], x, 0); read((*it)["y"], y, 0); blobs.push_back(Point3f(x, y, 0)); } } #ifdef MANUS_DEBUG SharedLocalization improveLocalizationWithKeypointBlobs(SharedLocalization localization, SharedCameraModel camera, Mat debug = Mat()) #else SharedLocalization improveLocalizationWithKeypointBlobs(SharedLocalization localization, SharedCameraModel camera) #endif { vector<Point2f> estimates; projectPoints(blobs, localization->getCameraPosition().rotation, localization->getCameraPosition().translation, camera->getIntrinsics(), camera->getDistortion(), estimates); Ptr<FeatureDetector> blobDetector = FeatureDetector::create("SimpleBlob"); std::vector<KeyPoint> keypoints; blobDetector->detect(image_gray, keypoints); std::vector<Point2f> points; for (size_t i = 0; i < keypoints.size(); i++) { points.push_back (keypoints[i].pt); } vector<Point2f> imagePoints; vector<Point3f> objectPoints; for (int i = 0; i < estimates.size(); i++) { float min_distance = 100000; int best_match = -1; // Let's skip all points that are projected out of frame if (estimates[i].x < 0 || estimates[i].y < 0 || estimates[i].x >= image_gray.cols || estimates[i].y >= image_gray.rows) continue; for (int j = 0; j < points.size(); j++) { float dx = estimates[i].x - points[j].x; float dy = estimates[i].y - points[j].y; float dist = sqrt (dx * dx + dy * dy); if (dist < 20) { imagePoints.push_back(points[j]); objectPoints.push_back(blobs[i]); #ifdef MANUS_DEBUG if (!debug.empty()) { circle(debug, estimates[i], 3, Scalar(255, 255, 0)); circle(debug, points[j], 3, Scalar(255, 0, 0)); line(debug, estimates[i], points[j], Scalar(0, 255, 255), 1); } #endif } } } if (imagePoints.size() > 5) { CameraPosition position; Mat rotation, translation; vector<int> inliers; solvePnPRansac(objectPoints, imagePoints, camera->getIntrinsics(), camera->getDistortion(), rotation, translation, false, 200, 4, imagePoints.size(), inliers); rotation.convertTo(position.rotation, CV_32F); translation.convertTo(position.translation, CV_32F); float err = cv::norm(localization->getCameraPosition().translation, position.translation); // Some heuristic criteria if (err < 100 && inliers.size() > imagePoints.size() / 2) localization = Ptr<Localization>(new Localization(0, position)); } return localization; } int main(int argc, char** argv) { if (argc < 2) { cerr << "No AR board description specified." << endl; exit(-1); } string blobs_file; string scene_file(argv[1]); cout << "AR scene file: " << scene_file << endl; if (argc > 2) { blobs_file = string(argv[2]); } if (!blobs_file.empty()) { read_blobs(blobs_file.c_str()); cout << "Blobs file: " << blobs_file << endl; } #ifdef MANUS_DEBUG Mat debug_image; debug = getenv("SHOW_DEBUG") != NULL; #endif bool localized = false; CameraExtrinsics last_location; force_update_threshold = 100; force_update_counter = force_update_threshold; SharedClient client = echolib::connect(string(), "artracker"); SharedTypedSubscriber<Frame> sub; location_publisher = make_shared<TypedPublisher<CameraExtrinsics> >(client, "location"); parameters_listener = make_shared<TypedSubscriber<CameraIntrinsics> >(client, "intrinsics", [&scene_file](shared_ptr<CameraIntrinsics> p) { parameters = Ptr<CameraModel>(new CameraModel(p->intrinsics, p->distortion)); parameters_listener.reset(); if (!scene) scene = Ptr<Scene>(new Scene(parameters, scene_file)); }); bool processing = false; SubscriptionWatcher watcher(client, "location", [&processing, &sub, &client](int subscribers) { processing = subscribers > 0; if (processing && !sub) { sub = make_shared<TypedSubscriber<Frame> >(client, "camera", handle_frame); } if (!processing && sub && !debug) { sub.reset(); } }); if (debug) { sub = make_shared<TypedSubscriber<Frame> >(client, "camera", handle_frame); } while (true) { if (!echolib::wait(100)) break; if (!image_current.empty()) { if (scene_change(image_current)) { cvtColor(image_current, image_gray, CV_BGR2GRAY); vector<SharedLocalization> anchors; if (scene) anchors = scene->localize(image_gray); if (anchors.size() > 0) { localization = anchors[0]; localized = true; } else { localized = false; } #ifdef MANUS_DEBUG if (debug) { image_current.copyTo(debug_image); } #endif if (blobs.size() > 0 && localized) { #ifdef MANUS_DEBUG localization = improveLocalizationWithKeypointBlobs(localization, parameters, debug_image); #else localization = improveLocalizationWithKeypointBlobs(localization, parameters); #endif } #ifdef MANUS_DEBUG if (debug && localized) { localization->draw(debug_image, parameters); } #endif #ifdef MANUS_DEBUG if (debug) { imshow("AR Track", debug_image); } #endif } if (localized) { last_location.header = header_current; Rodrigues(localization->getCameraPosition().rotation, last_location.rotation); last_location.translation = localization->getCameraPosition().translation; location_publisher->send(last_location); } image_current.release(); } #ifdef MANUS_DEBUG if (debug) { int k = waitKey(1); if ((char)k == 'r' && scene) { cout << "Reloading markers" << endl; scene = Ptr<Scene>(new Scene(parameters, scene_file)); } } #endif } exit(0); } <commit_msg>AR track compatibility with OpenCV 3+<commit_after>#include <echolib/opencv.h> #include <chrono> #include <memory> #include <experimental/filesystem> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/video/video.hpp> #ifdef MANUS_DEBUG #include <opencv2/highgui/highgui.hpp> #endif #include <ary/complex.h> #include <ary/utilities.h> using namespace std; using namespace cv; using namespace echolib; using namespace ary; bool debug = false; Ptr<CameraModel> model; Ptr<Scene> scene; Header header_current; Mat image_current; Mat image_gray; Ptr<BackgroundSubtractorMOG2> scene_model; int force_update_counter; int force_update_threshold; SharedLocalization localization; SharedCameraModel parameters(new CameraModel(Size(640, 480))); bool scene_change(Mat& image) { setDrawScale(1000); if (image.empty()) return false; Mat candidate, mask; resize(image, candidate, Size(64, 64)); if (scene_model.empty()) { #if CV_MAJOR_VERSION == 3 scene_model = cv::createBackgroundSubtractorMOG2(); scene_model->setHistory(100); scene_model->setNMixtures(4); scene_model->setDetectShadows(false); #else scene_model = Ptr<BackgroundSubtractorMOG2>(new BackgroundSubtractorMOG2(100, 4, false)); #endif } if (force_update_counter > force_update_threshold) { force_update_counter = 0; return true; } force_update_counter++; #if CV_MAJOR_VERSION == 3 scene_model->apply(candidate, mask); #else scene_model->operator()(candidate, mask); #endif #ifdef MANUS_DEBUG if (debug) { imshow("Changes", mask); } #endif float changes = (float)(sum(mask)[0]) / (float)(mask.cols * mask.rows * 255); if (changes > 0.2) { force_update_counter = 0; return true; } else { return false; } } void handle_frame(shared_ptr<Frame> frame) { if (frame->image.empty()) return; header_current = frame->header; image_current = frame->image; } SharedTypedPublisher<CameraExtrinsics> location_publisher; SharedTypedSubscriber<CameraIntrinsics> parameters_listener; vector<Point3f> blobs; void read_blobs(const char* file) { blobs.clear(); FileStorage fs(file, FileStorage::READ); if (!fs.isOpened()) { return; } FileNode centers = fs["centers"]; for (FileNodeIterator it = centers.begin(); it != centers.end(); ++it) { float x, y; read((*it)["x"], x, 0); read((*it)["y"], y, 0); blobs.push_back(Point3f(x, y, 0)); } } #ifdef MANUS_DEBUG SharedLocalization improveLocalizationWithKeypointBlobs(SharedLocalization localization, SharedCameraModel camera, Mat debug = Mat()) #else SharedLocalization improveLocalizationWithKeypointBlobs(SharedLocalization localization, SharedCameraModel camera) #endif { vector<Point2f> estimates; projectPoints(blobs, localization->getCameraPosition().rotation, localization->getCameraPosition().translation, camera->getIntrinsics(), camera->getDistortion(), estimates); #if CV_MAJOR_VERSION == 3 Ptr<FeatureDetector> blobDetector = SimpleBlobDetector::create(); #else Ptr<FeatureDetector> blobDetector = FeatureDetector::create("SimpleBlob"); #endif std::vector<KeyPoint> keypoints; blobDetector->detect(image_gray, keypoints); std::vector<Point2f> points; for (size_t i = 0; i < keypoints.size(); i++) { points.push_back (keypoints[i].pt); } vector<Point2f> imagePoints; vector<Point3f> objectPoints; for (int i = 0; i < estimates.size(); i++) { float min_distance = 100000; int best_match = -1; // Let's skip all points that are projected out of frame if (estimates[i].x < 0 || estimates[i].y < 0 || estimates[i].x >= image_gray.cols || estimates[i].y >= image_gray.rows) continue; for (int j = 0; j < points.size(); j++) { float dx = estimates[i].x - points[j].x; float dy = estimates[i].y - points[j].y; float dist = sqrt (dx * dx + dy * dy); if (dist < 20) { imagePoints.push_back(points[j]); objectPoints.push_back(blobs[i]); #ifdef MANUS_DEBUG if (!debug.empty()) { circle(debug, estimates[i], 3, Scalar(255, 255, 0)); circle(debug, points[j], 3, Scalar(255, 0, 0)); line(debug, estimates[i], points[j], Scalar(0, 255, 255), 1); } #endif } } } if (imagePoints.size() > 5) { CameraPosition position; Mat rotation, translation; vector<int> inliers; #if CV_MAJOR_VERSION == 3 solvePnPRansac(objectPoints, imagePoints, camera->getIntrinsics(), camera->getDistortion(), rotation, translation, false, 200, 4, 0.999, inliers); #else solvePnPRansac(objectPoints, imagePoints, camera->getIntrinsics(), camera->getDistortion(), rotation, translation, false, 200, 4, imagePoints.size(), inliers); #endif rotation.convertTo(position.rotation, CV_32F); translation.convertTo(position.translation, CV_32F); float err = cv::norm(localization->getCameraPosition().translation, position.translation); // Some heuristic criteria if (err < 100 && inliers.size() > imagePoints.size() / 2) localization = Ptr<Localization>(new Localization(0, position)); } return localization; } int main(int argc, char** argv) { if (argc < 2) { cerr << "No AR board description specified." << endl; exit(-1); } string blobs_file; string scene_file(argv[1]); cout << "AR scene file: " << scene_file << endl; if (argc > 2) { blobs_file = string(argv[2]); } if (!blobs_file.empty()) { read_blobs(blobs_file.c_str()); cout << "Blobs file: " << blobs_file << endl; } #ifdef MANUS_DEBUG Mat debug_image; debug = getenv("SHOW_DEBUG") != NULL; #endif bool localized = false; CameraExtrinsics last_location; force_update_threshold = 100; force_update_counter = force_update_threshold; SharedClient client = echolib::connect(string(), "artracker"); SharedTypedSubscriber<Frame> sub; location_publisher = make_shared<TypedPublisher<CameraExtrinsics> >(client, "location"); parameters_listener = make_shared<TypedSubscriber<CameraIntrinsics> >(client, "intrinsics", [&scene_file](shared_ptr<CameraIntrinsics> p) { parameters = Ptr<CameraModel>(new CameraModel(p->intrinsics, p->distortion)); parameters_listener.reset(); if (!scene) scene = Ptr<Scene>(new Scene(parameters, scene_file)); }); bool processing = false; SubscriptionWatcher watcher(client, "location", [&processing, &sub, &client](int subscribers) { processing = subscribers > 0; if (processing && !sub) { sub = make_shared<TypedSubscriber<Frame> >(client, "camera", handle_frame); } if (!processing && sub && !debug) { sub.reset(); } }); if (debug) { sub = make_shared<TypedSubscriber<Frame> >(client, "camera", handle_frame); } while (true) { if (!echolib::wait(100)) break; if (!image_current.empty()) { if (scene_change(image_current)) { cvtColor(image_current, image_gray, CV_BGR2GRAY); vector<SharedLocalization> anchors; if (scene) anchors = scene->localize(image_gray); if (anchors.size() > 0) { localization = anchors[0]; localized = true; } else { localized = false; } #ifdef MANUS_DEBUG if (debug) { image_current.copyTo(debug_image); } #endif if (blobs.size() > 0 && localized) { #ifdef MANUS_DEBUG localization = improveLocalizationWithKeypointBlobs(localization, parameters, debug_image); #else localization = improveLocalizationWithKeypointBlobs(localization, parameters); #endif } #ifdef MANUS_DEBUG if (debug && localized) { localization->draw(debug_image, parameters); } #endif #ifdef MANUS_DEBUG if (debug) { imshow("AR Track", debug_image); } #endif } if (localized) { last_location.header = header_current; Rodrigues(localization->getCameraPosition().rotation, last_location.rotation); last_location.translation = localization->getCameraPosition().translation; location_publisher->send(last_location); } image_current.release(); } #ifdef MANUS_DEBUG if (debug) { int k = waitKey(1); if ((char)k == 'r' && scene) { cout << "Reloading markers" << endl; scene = Ptr<Scene>(new Scene(parameters, scene_file)); } } #endif } exit(0); } <|endoftext|>
<commit_before>// vim:cindent:cino=\:0:et:fenc=utf-8:ff=unix:sw=4:ts=4: #include <QDebug> #include <string> #include <json/value.h> #include <jsonrpc.h> #include <conveyor/connection.h> #include <conveyor/connectionstatus.h> #include "connectionstream.h" #include "connectionthread.h" #include "conveyorprivate.h" #include "jobprivate.h" #include "synchronouscallback.h" namespace conveyor { Conveyor * ConveyorPrivate::connect (Address const * const address) { Connection * const connection (address->createConnection ()); ConnectionStream * const connectionStream ( new ConnectionStream (connection) ); JsonRpc * const jsonRpc (new JsonRpc (connectionStream)); ConnectionThread * const connectionThread ( new ConnectionThread (connection, jsonRpc) ); connectionThread->start (); try { Json::Value const hello ( SynchronousCallback::invoke ( jsonRpc , "hello" , Json::Value (Json::arrayValue) ) ); Conveyor * const conveyor ( new Conveyor ( connection , connectionStream , jsonRpc , connectionThread ) ); return conveyor; } catch (...) { connectionThread->stop (); connectionThread->wait (); delete connectionThread; delete jsonRpc; delete connectionStream; delete connection; throw; } } ConveyorPrivate::ConveyorPrivate ( Conveyor * const conveyor , Connection * const connection , ConnectionStream * const connectionStream , JsonRpc * const jsonRpc , ConnectionThread * const connectionThread ) : m_conveyor (conveyor) , m_connection (connection) , m_connectionStream (connectionStream) , m_jsonRpc (jsonRpc) , m_connectionThread (connectionThread) , m_printerAddedMethod(this) , m_printerChangedMethod(this) , m_printerRemovedMethod(this) , m_jobAddedMethod(this) , m_jobChangedMethod(this) , m_jobRemovedMethod(this) { this->m_jsonRpc->addMethod("printeradded", & m_printerAddedMethod); this->m_jsonRpc->addMethod("printerchanged", & m_printerChangedMethod); this->m_jsonRpc->addMethod("printerremoved", & m_printerRemovedMethod); this->m_jsonRpc->addMethod("jobadded", & m_jobAddedMethod); this->m_jsonRpc->addMethod("jobchanged", & m_jobChangedMethod); this->m_jsonRpc->addMethod("jobremoved", & m_jobRemovedMethod); } ConveyorPrivate::~ConveyorPrivate (void) { this->m_connectionThread->stop (); this->m_connectionThread->wait (); delete this->m_connectionThread; delete this->m_jsonRpc; delete this->m_connectionStream; delete this->m_connection; } QList<Printer *> ConveyorPrivate::printers() { Json::Value params (Json::arrayValue); Json::Value const results ( SynchronousCallback::invoke ( this->m_jsonRpc , "getprinters" , params ) ); QList<Printer*> activePrinters; for (unsigned i = 0; i < results.size(); i++) { const Json::Value &r(results[i]); Printer * const printer ( printerByUniqueName ( QString(r["uniqueName"].asCString()))); printer->m_private->updateFromJson(r); activePrinters.append(printer); } return activePrinters; } Printer * ConveyorPrivate::printerByUniqueName(QString uniqueName) { Printer * p = m_printers.value(uniqueName); if(p == 0) { p = new Printer(this->m_conveyor, uniqueName); m_printers.insert(uniqueName, p); } return p; } /** Get a list jobs from the server. TODO: is there any filtering that needs to happen here? The Job objects are cached, so any subsequent access of the same job (which is referenced by its unique numeric ID) will return the same Job object. At present, Job objects live as long as Conveyor, so its safe to keep references to a Job even after the Job has finished. */ QList<Job *> ConveyorPrivate::jobs() { Json::Value params (Json::arrayValue); Json::Value const results ( SynchronousCallback::invoke ( this->m_jsonRpc , "getjobs" , params ) ); const Json::Value::Members &ids(results.getMemberNames()); QList<Job *> jobs; for (unsigned i = 0; i < ids.size(); i++) { // Job ID is sent as a string const std::string &key(ids[i]); int id = QString(key.c_str()).toInt(); if (results[key]["conclusion"].isNull()) { // Look up Job by its ID. This will also create the Job // object if it doesn't exist already. Job * const job(jobById(id)); job->m_private->updateFromJson(results[key]); jobs.append(job); } } return jobs; } Job * ConveyorPrivate::jobById(int id) { Job * job = m_jobs.value(id); if (!job) { job = new Job(this->m_conveyor, id); m_jobs.insert(id, job); } return job; } Job * ConveyorPrivate::print ( Printer * const printer , QString const & inputFile , const SlicerConfiguration & slicer_conf , QString const & material ) { Json::Value params (Json::objectValue); Json::Value null; params["printername"] = printer->uniqueName().toStdString(); params["inputpath"] = Json::Value (inputFile.toStdString ()); params["preprocessor"] = null; params["skip_start_end"] = Json::Value (false); params["archive_lvl"] = Json::Value ("all"); params["archive_dir"] = null; params["slicer_settings"] = slicer_conf.toJSON(); params["material"] = Json::Value (material.toStdString()); Json::Value const result ( SynchronousCallback::invoke (this->m_jsonRpc, "print", params) ); return jobById(result["id"].asInt()); } Job * ConveyorPrivate::printToFile ( Printer * const printer , QString const & inputFile , QString const & outputFile , const SlicerConfiguration & slicer_conf , QString const & material ) { Json::Value params (Json::objectValue); Json::Value null; params["profilename"] = printer->uniqueName().toStdString(); params["inputpath"] = Json::Value (inputFile.toStdString ()); params["outputpath"] = Json::Value (outputFile.toStdString ()); params["preprocessor"] = null; params["skip_start_end"] = Json::Value (false); params["archive_lvl"] = Json::Value ("all"); params["archive_dir"] = null; params["slicer_settings"] = slicer_conf.toJSON(); params["material"] = Json::Value (material.toStdString()); Json::Value const result ( SynchronousCallback::invoke (this->m_jsonRpc, "printtofile", params) ); return jobById(result["id"].asInt()); } Job * ConveyorPrivate::slice ( Printer * const printer , QString const & inputFile , QString const & outputFile , const SlicerConfiguration & slicer_conf , QString const & material ) { Json::Value params (Json::objectValue); Json::Value null; params["profilename"] = printer->uniqueName().toStdString(); params["inputpath"] = Json::Value (inputFile.toStdString ()); params["outputpath"] = Json::Value (outputFile.toStdString ()); params["preprocessor"] = null; params["with_start_end"] = Json::Value (false); params["slicer_settings"] = slicer_conf.toJSON(); params["material"] = Json::Value (material.toStdString()); Json::Value const result ( SynchronousCallback::invoke (this->m_jsonRpc, "slice", params) ); return jobById(result["id"].asInt()); } void ConveyorPrivate::cancelJob (int jobId) { Json::Value params (Json::objectValue); Json::Value null; params["id"] = Json::Value(jobId); Json::Value const result ( SynchronousCallback::invoke (this->m_jsonRpc, "canceljob", params) ); // TODO: check result? } void ConveyorPrivate::emitPrinterAdded (Printer * const p) { m_conveyor->emitPrinterAdded(p); } void ConveyorPrivate::emitPrinterChanged (Printer * const p) { p->emitChanged(); } void ConveyorPrivate::emitPrinterRemoved (Printer * const p) { m_conveyor->emitPrinterRemoved(p); // Disconnect all event listeners from the printer object. p->disconnect(); } void ConveyorPrivate::emitJobAdded (Job * const j) { m_conveyor->emitJobAdded(j); } void ConveyorPrivate::emitJobChanged (Job * const j) { j->emitChanged(); } void ConveyorPrivate::emitJobRemoved (Job * const j) { m_conveyor->emitJobRemoved(j); } } <commit_msg>Check job state instead of job conclusion for filtering jobs<commit_after>// vim:cindent:cino=\:0:et:fenc=utf-8:ff=unix:sw=4:ts=4: #include <QDebug> #include <string> #include <json/value.h> #include <jsonrpc.h> #include <conveyor/connection.h> #include <conveyor/connectionstatus.h> #include "connectionstream.h" #include "connectionthread.h" #include "conveyorprivate.h" #include "jobprivate.h" #include "synchronouscallback.h" namespace conveyor { Conveyor * ConveyorPrivate::connect (Address const * const address) { Connection * const connection (address->createConnection ()); ConnectionStream * const connectionStream ( new ConnectionStream (connection) ); JsonRpc * const jsonRpc (new JsonRpc (connectionStream)); ConnectionThread * const connectionThread ( new ConnectionThread (connection, jsonRpc) ); connectionThread->start (); try { Json::Value const hello ( SynchronousCallback::invoke ( jsonRpc , "hello" , Json::Value (Json::arrayValue) ) ); Conveyor * const conveyor ( new Conveyor ( connection , connectionStream , jsonRpc , connectionThread ) ); return conveyor; } catch (...) { connectionThread->stop (); connectionThread->wait (); delete connectionThread; delete jsonRpc; delete connectionStream; delete connection; throw; } } ConveyorPrivate::ConveyorPrivate ( Conveyor * const conveyor , Connection * const connection , ConnectionStream * const connectionStream , JsonRpc * const jsonRpc , ConnectionThread * const connectionThread ) : m_conveyor (conveyor) , m_connection (connection) , m_connectionStream (connectionStream) , m_jsonRpc (jsonRpc) , m_connectionThread (connectionThread) , m_printerAddedMethod(this) , m_printerChangedMethod(this) , m_printerRemovedMethod(this) , m_jobAddedMethod(this) , m_jobChangedMethod(this) , m_jobRemovedMethod(this) { this->m_jsonRpc->addMethod("printeradded", & m_printerAddedMethod); this->m_jsonRpc->addMethod("printerchanged", & m_printerChangedMethod); this->m_jsonRpc->addMethod("printerremoved", & m_printerRemovedMethod); this->m_jsonRpc->addMethod("jobadded", & m_jobAddedMethod); this->m_jsonRpc->addMethod("jobchanged", & m_jobChangedMethod); this->m_jsonRpc->addMethod("jobremoved", & m_jobRemovedMethod); } ConveyorPrivate::~ConveyorPrivate (void) { this->m_connectionThread->stop (); this->m_connectionThread->wait (); delete this->m_connectionThread; delete this->m_jsonRpc; delete this->m_connectionStream; delete this->m_connection; } QList<Printer *> ConveyorPrivate::printers() { Json::Value params (Json::arrayValue); Json::Value const results ( SynchronousCallback::invoke ( this->m_jsonRpc , "getprinters" , params ) ); QList<Printer*> activePrinters; for (unsigned i = 0; i < results.size(); i++) { const Json::Value &r(results[i]); Printer * const printer ( printerByUniqueName ( QString(r["uniqueName"].asCString()))); printer->m_private->updateFromJson(r); activePrinters.append(printer); } return activePrinters; } Printer * ConveyorPrivate::printerByUniqueName(QString uniqueName) { Printer * p = m_printers.value(uniqueName); if(p == 0) { p = new Printer(this->m_conveyor, uniqueName); m_printers.insert(uniqueName, p); } return p; } /** Get a list jobs from the server. TODO: is there any filtering that needs to happen here? The Job objects are cached, so any subsequent access of the same job (which is referenced by its unique numeric ID) will return the same Job object. At present, Job objects live as long as Conveyor, so its safe to keep references to a Job even after the Job has finished. */ QList<Job *> ConveyorPrivate::jobs() { Json::Value params (Json::arrayValue); Json::Value const results ( SynchronousCallback::invoke ( this->m_jsonRpc , "getjobs" , params ) ); const Json::Value::Members &ids(results.getMemberNames()); QList<Job *> jobs; for (unsigned i = 0; i < ids.size(); i++) { // Job ID is sent as a string const std::string &key(ids[i]); int id = QString(key.c_str()).toInt(); if (results[key]["state"].asString() != "STOPPED") { // Look up Job by its ID. This will also create the Job // object if it doesn't exist already. Job * const job(jobById(id)); job->m_private->updateFromJson(results[key]); jobs.append(job); } } return jobs; } Job * ConveyorPrivate::jobById(int id) { Job * job = m_jobs.value(id); if (!job) { job = new Job(this->m_conveyor, id); m_jobs.insert(id, job); } return job; } Job * ConveyorPrivate::print ( Printer * const printer , QString const & inputFile , const SlicerConfiguration & slicer_conf , QString const & material ) { Json::Value params (Json::objectValue); Json::Value null; params["printername"] = printer->uniqueName().toStdString(); params["inputpath"] = Json::Value (inputFile.toStdString ()); params["preprocessor"] = null; params["skip_start_end"] = Json::Value (false); params["archive_lvl"] = Json::Value ("all"); params["archive_dir"] = null; params["slicer_settings"] = slicer_conf.toJSON(); params["material"] = Json::Value (material.toStdString()); Json::Value const result ( SynchronousCallback::invoke (this->m_jsonRpc, "print", params) ); return jobById(result["id"].asInt()); } Job * ConveyorPrivate::printToFile ( Printer * const printer , QString const & inputFile , QString const & outputFile , const SlicerConfiguration & slicer_conf , QString const & material ) { Json::Value params (Json::objectValue); Json::Value null; params["profilename"] = printer->uniqueName().toStdString(); params["inputpath"] = Json::Value (inputFile.toStdString ()); params["outputpath"] = Json::Value (outputFile.toStdString ()); params["preprocessor"] = null; params["skip_start_end"] = Json::Value (false); params["archive_lvl"] = Json::Value ("all"); params["archive_dir"] = null; params["slicer_settings"] = slicer_conf.toJSON(); params["material"] = Json::Value (material.toStdString()); Json::Value const result ( SynchronousCallback::invoke (this->m_jsonRpc, "printtofile", params) ); return jobById(result["id"].asInt()); } Job * ConveyorPrivate::slice ( Printer * const printer , QString const & inputFile , QString const & outputFile , const SlicerConfiguration & slicer_conf , QString const & material ) { Json::Value params (Json::objectValue); Json::Value null; params["profilename"] = printer->uniqueName().toStdString(); params["inputpath"] = Json::Value (inputFile.toStdString ()); params["outputpath"] = Json::Value (outputFile.toStdString ()); params["preprocessor"] = null; params["with_start_end"] = Json::Value (false); params["slicer_settings"] = slicer_conf.toJSON(); params["material"] = Json::Value (material.toStdString()); Json::Value const result ( SynchronousCallback::invoke (this->m_jsonRpc, "slice", params) ); return jobById(result["id"].asInt()); } void ConveyorPrivate::cancelJob (int jobId) { Json::Value params (Json::objectValue); Json::Value null; params["id"] = Json::Value(jobId); Json::Value const result ( SynchronousCallback::invoke (this->m_jsonRpc, "canceljob", params) ); // TODO: check result? } void ConveyorPrivate::emitPrinterAdded (Printer * const p) { m_conveyor->emitPrinterAdded(p); } void ConveyorPrivate::emitPrinterChanged (Printer * const p) { p->emitChanged(); } void ConveyorPrivate::emitPrinterRemoved (Printer * const p) { m_conveyor->emitPrinterRemoved(p); // Disconnect all event listeners from the printer object. p->disconnect(); } void ConveyorPrivate::emitJobAdded (Job * const j) { m_conveyor->emitJobAdded(j); } void ConveyorPrivate::emitJobChanged (Job * const j) { j->emitChanged(); } void ConveyorPrivate::emitJobRemoved (Job * const j) { m_conveyor->emitJobRemoved(j); } } <|endoftext|>
<commit_before>//includes #include <iostream> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "glad/glad.h" #include "shader.hpp" #include "camera.hpp" #include "tinyFileDialogs/tinyfiledialogs.h" #include "particle.hpp" #include "settingsIO.hpp" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb/stb_image_write.h" #ifdef _WIN32 //Windows Includes #include <windows.h> #include <SDL.h> #else //Includes for Linux and OSX #include <SDL2/SDL.h> #endif //end includes //function prototypes static void sdl_die(const char * message); //finds SDL errors / kills the app if something doesn't init properly void init_screen(const char * caption); //initializes the screen / window / context void manageFPS(uint32_t &ticks, uint32_t &lastticks); //limits FPS to 60 and update deltaTime void beforeDraw(); //the generic clear screen and other stuff before anything else has to be done void drawFunct(); //Draws stuff to the screen void readInput(SDL_Event &event); //takes in all input void setupGLStuff(); //sets up the VAOs and the VBOs void cleanup(); //destroy it all with fire void setupRender(); //Updates the VBOs for position changes void seekFrame(int frame, bool isForward); //skips frames //end function prototypes //variables const int SCREEN_FULLSCREEN = 0, SCREEN_WIDTH = 1280, SCREEN_HEIGHT = 720; int curFrame = 0; bool quit = false, highRes = false; float sphereScale = 1.0; float sphereRadius = 250.0f; bool isRecording = false; GLuint circleVAO, circleVBO; std::string recordFolder = ""; uint32_t ticks,lastticks = 0; GLfloat deltaTime = 0.0f, lastFrame = 0.0f; int imageError = 0; SDL_Window *window = NULL; glm::vec3 com; SDL_GLContext maincontext; unsigned char * pixels = new unsigned char[SCREEN_WIDTH*SCREEN_HEIGHT*3]; unsigned char * pixels2 = new unsigned char[SCREEN_WIDTH*SCREEN_HEIGHT*3]; Shader sphereShader; Camera cam = Camera(SCREEN_WIDTH,SCREEN_HEIGHT); Particle* part; glm::mat4 view; std::string sphereVertexShader = #include "shaders/sphereVertex.vs" , sphereFragmentShader = #include "shaders/sphereFragment.frag" ; //end variables const std::string posLoc = "/Users/JPEG/Desktop/500kSlam/PosAndVel"; const std::string setLoc = "/Users/JPEG/Desktop/500kSlam/RunSetup"; SettingsIO *set = new SettingsIO(); //functions that should not be changed void manageFPS(uint32_t &ticks, uint32_t &lastticks) { ticks = SDL_GetTicks(); deltaTime = ticks - lastticks; if ( ((ticks*10-lastticks*10)) < 167 ) { SDL_Delay( (167-((ticks*10-lastticks*10)))/10 ); } lastticks = SDL_GetTicks(); } static void sdl_die(const char * message) { fprintf(stderr, "%s: %s\n", message, SDL_GetError()); exit(2); } void init_screen(const char * title) { // Init SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) sdl_die("SDL Initialize Failed!"); atexit (SDL_Quit); //loads base GL Libs SDL_GL_LoadLibrary(NULL); //set base GL stuff SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); //creates the window window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL); if (window == NULL) sdl_die("Failed to create window!"); //creates the main GL context maincontext = SDL_GL_CreateContext(window); if (maincontext == NULL) sdl_die("Failed to create an OpenGL context!"); gladLoadGLLoader(SDL_GL_GetProcAddress); // Use v-sync SDL_GL_SetSwapInterval(1); int w,h; SDL_GetWindowSize(window, &w, &h); glViewport(0, 0, w, h); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); } //functions <commit_msg>simple doc cleanup<commit_after>//includes #include <iostream> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "glad/glad.h" #include "shader.hpp" #include "camera.hpp" #include "tinyFileDialogs/tinyfiledialogs.h" #include "particle.hpp" #include "settingsIO.hpp" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb/stb_image_write.h" #ifdef _WIN32 //Windows Includes #include <windows.h> #include <SDL.h> #else //Includes for Linux and OSX #include <SDL2/SDL.h> #endif //function prototypes static void sdl_die(const char * message); //finds SDL errors / kills the app if something doesn't init properly void init_screen(const char * caption); //initializes the screen / window / context void manageFPS(uint32_t &ticks, uint32_t &lastticks); //limits FPS to 60 and update deltaTime void beforeDraw(); //the generic clear screen and other stuff before anything else has to be done void drawFunct(); //Draws stuff to the screen void readInput(SDL_Event &event); //takes in all input void setupGLStuff(); //sets up the VAOs and the VBOs void cleanup(); //destroy it all with fire void setupRender(); //Updates the VBOs for position changes void seekFrame(int frame, bool isForward); //skips frames //variables const int SCREEN_FULLSCREEN = 0, SCREEN_WIDTH = 1280, SCREEN_HEIGHT = 720; int curFrame = 0; bool quit = false, highRes = false; float sphereScale = 1.0; float sphereRadius = 250.0f; bool isRecording = false; GLuint circleVAO, circleVBO; std::string recordFolder = ""; uint32_t ticks,lastticks = 0; GLfloat deltaTime = 0.0f, lastFrame = 0.0f; int imageError = 0; SDL_Window *window = NULL; glm::vec3 com; SDL_GLContext maincontext; unsigned char * pixels = new unsigned char[SCREEN_WIDTH*SCREEN_HEIGHT*3]; unsigned char * pixels2 = new unsigned char[SCREEN_WIDTH*SCREEN_HEIGHT*3]; Shader sphereShader; Camera cam = Camera(SCREEN_WIDTH,SCREEN_HEIGHT); Particle* part; glm::mat4 view; std::string sphereVertexShader = #include "shaders/sphereVertex.vs" , sphereFragmentShader = #include "shaders/sphereFragment.frag" ; const std::string posLoc = "/Users/JPEG/Desktop/500kSlam/PosAndVel"; const std::string setLoc = "/Users/JPEG/Desktop/500kSlam/RunSetup"; SettingsIO *set = new SettingsIO(); //functions that should not be changed void manageFPS(uint32_t &ticks, uint32_t &lastticks) { ticks = SDL_GetTicks(); deltaTime = ticks - lastticks; if ( ((ticks*10-lastticks*10)) < 167 ) { SDL_Delay( (167-((ticks*10-lastticks*10)))/10 ); } lastticks = SDL_GetTicks(); } static void sdl_die(const char * message) { fprintf(stderr, "%s: %s\n", message, SDL_GetError()); exit(2); } void init_screen(const char * title) { // Init SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) sdl_die("SDL Initialize Failed!"); atexit (SDL_Quit); //loads base GL Libs SDL_GL_LoadLibrary(NULL); //set base GL stuff SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); //creates the window window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL); if (window == NULL) sdl_die("Failed to create window!"); //creates the main GL context maincontext = SDL_GL_CreateContext(window); if (maincontext == NULL) sdl_die("Failed to create an OpenGL context!"); gladLoadGLLoader(SDL_GL_GetProcAddress); // Use v-sync SDL_GL_SetSwapInterval(1); int w,h; SDL_GetWindowSize(window, &w, &h); glViewport(0, 0, w, h); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); } <|endoftext|>
<commit_before>#include <cpr/cpr.h> #include <json/json.h> #include <iomanip> #include <locale> #include <sstream> #include <utils.h> #include "command.h" #include "../CommandHandler.h" #include "../OptionParser.h" /* full name of the command */ CMDNAME("age"); /* description of the command */ CMDDESCR("check length of channel releationships"); /* command usage synopsis */ CMDUSAGE("age <-f|-s>"); static const std::string TWITCH_API = "https://api.twitch.tv/kraken"; static std::string parse_time(const std::string &ftime); /* followage: check how long you have been following a channel */ std::string CommandHandler::age(struct cmdinfo *c) { static cpr::Header head{{ "Accept","application/vnd.twitchtv.v3+json" }, { "Authorization", "OAuth " + m_token }}; cpr::Response resp; Json::Reader reader; Json::Value response; std::string msg, url, out; int opt; OptionParser op(c->fullCmd, "fs"); static struct OptionParser::option long_opts[] = { { "follow", NO_ARG, 'f' }, { "help", NO_ARG, 'h' }, { "sub", NO_ARG, 's' }, { 0, 0, 0 } }; while ((opt = op.getopt_long(long_opts)) != EOF) { switch (opt) { case 'f': url = TWITCH_API + "/users/" + c->nick + "/follows/channels/" + m_channel; msg = "following"; break; case 'h': return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR); case 's': url = TWITCH_API + "/channels/" + m_channel + "/subscriptions/" + c->nick; msg = "subscribed to"; break; case '?': return std::string(op.opterr()); default: return ""; } } if (op.optind() != c->fullCmd.length() || url.empty()) return USAGEMSG(CMDNAME, CMDUSAGE); resp = cpr::Get(cpr::Url(url), head); out = "@" + c->nick + ", "; if (!reader.parse(resp.text, response)) return CMDNAME + ": could not parse response"; if (!response.isMember("created_at")) return out + "you are not " + msg + " " + m_channel + "."; return out + "you have been " + msg + " " + m_channel + " for " + parse_time(response["created_at"].asString()) + "."; } /* parse_time: extract time and date from ftime */ static std::string parse_time(const std::string &ftime) { std::tm tm, curr; time_t t, now; std::ostringstream out; std::istringstream ss(ftime); #ifdef __linux__ ss.imbue(std::locale("en_US.utf-8")); #endif #ifdef _WIN32 ss.imbue(std::locale("en-US")); #endif ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%S"); t = std::mktime(&tm); now = time(NULL); curr = *std::gmtime(&now); now = std::mktime(&curr); out << utils::conv_time(now - t); out << " (since " << std::put_time(&tm, "%H:%M:%S UTC, %d %b %Y") << ")"; return out.str(); } <commit_msg>Set tm_isdst for age command<commit_after>#include <cpr/cpr.h> #include <json/json.h> #include <iomanip> #include <locale> #include <sstream> #include <utils.h> #include "command.h" #include "../CommandHandler.h" #include "../OptionParser.h" /* full name of the command */ CMDNAME("age"); /* description of the command */ CMDDESCR("check length of channel releationships"); /* command usage synopsis */ CMDUSAGE("age <-f|-s>"); static const std::string TWITCH_API = "https://api.twitch.tv/kraken"; static std::string parse_time(const std::string &ftime); /* followage: check how long you have been following a channel */ std::string CommandHandler::age(struct cmdinfo *c) { static cpr::Header head{{ "Accept","application/vnd.twitchtv.v3+json" }, { "Authorization", "OAuth " + m_token }}; cpr::Response resp; Json::Reader reader; Json::Value response; std::string msg, url, out; int opt; OptionParser op(c->fullCmd, "fs"); static struct OptionParser::option long_opts[] = { { "follow", NO_ARG, 'f' }, { "help", NO_ARG, 'h' }, { "sub", NO_ARG, 's' }, { 0, 0, 0 } }; while ((opt = op.getopt_long(long_opts)) != EOF) { switch (opt) { case 'f': url = TWITCH_API + "/users/" + c->nick + "/follows/channels/" + m_channel; msg = "following"; break; case 'h': return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR); case 's': url = TWITCH_API + "/channels/" + m_channel + "/subscriptions/" + c->nick; msg = "subscribed to"; break; case '?': return std::string(op.opterr()); default: return ""; } } if (op.optind() != c->fullCmd.length() || url.empty()) return USAGEMSG(CMDNAME, CMDUSAGE); resp = cpr::Get(cpr::Url(url), head); out = "@" + c->nick + ", "; if (!reader.parse(resp.text, response)) return CMDNAME + ": could not parse response"; if (!response.isMember("created_at")) return out + "you are not " + msg + " " + m_channel + "."; return out + "you have been " + msg + " " + m_channel + " for " + parse_time(response["created_at"].asString()) + "."; } /* parse_time: extract time and date from ftime */ static std::string parse_time(const std::string &ftime) { std::tm tm, curr; time_t t, now; std::ostringstream out; std::istringstream ss(ftime); #ifdef __linux__ ss.imbue(std::locale("en_US.utf-8")); #endif #ifdef _WIN32 ss.imbue(std::locale("en-US")); #endif ss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%S"); tm.tm_isdst = 0; t = std::mktime(&tm); now = time(NULL); curr = *std::gmtime(&now); curr.tm_isdst = 0; now = std::mktime(&curr); out << utils::conv_time(now - t); out << " (since " << std::put_time(&tm, "%H:%M:%S UTC, %d %b %Y") << ")"; return out.str(); } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2011-03-07 // Updated : 2011-04-26 // Licence : This source is under MIT License // File : glm/gtx/ulp.inl /////////////////////////////////////////////////////////////////////////////////////////////////// #include <cmath> #include <cfloat> /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ typedef union { float value; /* FIXME: Assumes 32 bit int. */ unsigned int word; } ieee_float_shape_type; typedef union { double value; struct { glm::detail::int32 lsw; glm::detail::int32 msw; } parts; } ieee_double_shape_type; #define GLM_EXTRACT_WORDS(ix0,ix1,d) \ do { \ ieee_double_shape_type ew_u; \ ew_u.value = (d); \ (ix0) = ew_u.parts.msw; \ (ix1) = ew_u.parts.lsw; \ } while (0) #define GLM_GET_FLOAT_WORD(i,d) \ do { \ ieee_float_shape_type gf_u; \ gf_u.value = (d); \ (i) = gf_u.word; \ } while (0) #define GLM_SET_FLOAT_WORD(d,i) \ do { \ ieee_float_shape_type sf_u; \ sf_u.word = (i); \ (d) = sf_u.value; \ } while (0) #define GLM_INSERT_WORDS(d,ix0,ix1) \ do { \ ieee_double_shape_type iw_u; \ iw_u.parts.msw = (ix0); \ iw_u.parts.lsw = (ix1); \ (d) = iw_u.value; \ } while (0) namespace glm{ namespace detail { GLM_FUNC_QUALIFIER float nextafterf(float x, float y) { volatile float t; glm::detail::int32 hx, hy, ix, iy; GLM_GET_FLOAT_WORD(hx,x); GLM_GET_FLOAT_WORD(hy,y); ix = hx&0x7fffffff; // |x| iy = hy&0x7fffffff; // |y| if((ix>0x7f800000) || // x is nan (iy>0x7f800000)) // y is nan return x+y; if(x==y) return y; // x=y, return y if(ix==0) { // x == 0 GLM_SET_FLOAT_WORD(x,(hy&0x80000000)|1);// return +-minsubnormal t = x*x; if(t==x) return t; else return x; // raise underflow flag } if(hx>=0) { // x > 0 if(hx>hy) { // x > y, x -= ulp hx -= 1; } else { // x < y, x += ulp hx += 1; } } else { // x < 0 if(hy>=0||hx>hy){ // x < y, x -= ulp hx -= 1; } else { // x > y, x += ulp hx += 1; } } hy = hx&0x7f800000; if(hy>=0x7f800000) return x+x; // overflow if(hy<0x00800000) { // underflow t = x*x; if(t!=x) { // raise underflow flag GLM_SET_FLOAT_WORD(y,hx); return y; } } GLM_SET_FLOAT_WORD(x,hx); return x; } GLM_FUNC_QUALIFIER double nextafter(double x, double y) { volatile double t; glm::detail::int32 hx, hy, ix, iy; glm::detail::uint32 lx, ly; GLM_EXTRACT_WORDS(hx, lx, x); GLM_EXTRACT_WORDS(hy, ly, y); ix = hx & 0x7fffffff; // |x| iy = hy & 0x7fffffff; // |y| if(((ix>=0x7ff00000)&&((ix-0x7ff00000)|lx)!=0) || // x is nan ((iy>=0x7ff00000)&&((iy-0x7ff00000)|ly)!=0)) // y is nan return x+y; if(x==y) return y; // x=y, return y if((ix|lx)==0) { // x == 0 GLM_INSERT_WORDS(x, hy & 0x80000000, 1); // return +-minsubnormal t = x*x; if(t==x) return t; else return x; // raise underflow flag } if(hx>=0) { // x > 0 if(hx>hy||((hx==hy)&&(lx>ly))) { // x > y, x -= ulp if(lx==0) hx -= 1; lx -= 1; } else { // x < y, x += ulp lx += 1; if(lx==0) hx += 1; } } else { // x < 0 if(hy>=0||hx>hy||((hx==hy)&&(lx>ly))){// x < y, x -= ulp if(lx==0) hx -= 1; lx -= 1; } else { // x > y, x += ulp lx += 1; if(lx==0) hx += 1; } } hy = hx&0x7ff00000; if(hy>=0x7ff00000) return x+x; // overflow if(hy<0x00100000) { // underflow t = x*x; if(t!=x) { // raise underflow flag GLM_INSERT_WORDS(y,hx,lx); return y; } } GLM_INSERT_WORDS(x,hx,lx); return x; } }//namespace detail }//namespace glm #if(GLM_COMPILER & GLM_COMPILER_VC) # if(GLM_MODEL == GLM_MODEL_32) # define GLM_NEXT_AFTER_FLT(x, toward) glm::detail::nextafterf((x), (toward)) # else # define GLM_NEXT_AFTER_FLT(x, toward) _nextafterf((x), (toward)) # endif # define GLM_NEXT_AFTER_DBL(x, toward) _nextafter((x), (toward)) #else # define GLM_NEXT_AFTER_FLT(x, toward) nextafterf((x), (toward)) # define GLM_NEXT_AFTER_DBL(x, toward) nextafter((x), (toward)) #endif namespace glm{ namespace gtx{ namespace ulp { GLM_FUNC_QUALIFIER float next_float(float const & x) { return GLM_NEXT_AFTER_FLT(x, std::numeric_limits<float>::max()); } GLM_FUNC_QUALIFIER double next_float(double const & x) { return GLM_NEXT_AFTER_DBL(x, std::numeric_limits<double>::max()); } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<T> next_float(vecType<T> const & x) { vecType<T> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = next_float(x[i]); return Result; } GLM_FUNC_QUALIFIER float prev_float(float const & x) { return GLM_NEXT_AFTER_FLT(x, std::numeric_limits<float>::min()); } GLM_FUNC_QUALIFIER double prev_float(double const & x) { return GLM_NEXT_AFTER_DBL(x, std::numeric_limits<double>::min()); } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<T> prev_float(vecType<T> const & x) { vecType<T> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = prev_float(x[i]); return Result; } template <typename T> GLM_FUNC_QUALIFIER T next_float(T const & x, uint const & ulps) { T temp = x; for(std::size_t i = 0; i < ulps; ++i) temp = next_float(temp); return temp; } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<T> next_float(vecType<T> const & x, vecType<uint> const & ulps) { vecType<T> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = next_float(x[i], ulps[i]); return Result; } template <typename T> GLM_FUNC_QUALIFIER T prev_float(T const & x, uint const & ulps) { T temp = x; for(std::size_t i = 0; i < ulps; ++i) temp = prev_float(temp); return temp; } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<T> prev_float(vecType<T> const & x, vecType<uint> const & ulps) { vecType<T> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = prev_float(x[i], ulps[i]); return Result; } template <typename T> GLM_FUNC_QUALIFIER uint float_distance(T const & x, T const & y) { uint ulp = 0; if(x < y) { T temp = x; while(temp != y && ulp < std::numeric_limits<std::size_t>::max()) { ++ulp; temp = next_float(temp); } } else if(y < x) { T temp = y; while(temp != x && ulp < std::numeric_limits<std::size_t>::max()) { ++ulp; temp = next_float(temp); } } else // == { } return ulp; } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<uint> float_distance(vecType<T> const & x, vecType<T> const & y) { vecType<uint> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = float_distance(x[i], y[i]); return Result; } /* inline std::size_t ulp ( detail::thalf const & a, detail::thalf const & b ) { std::size_t Count = 0; float TempA(a); float TempB(b); //while((TempA = _nextafterf(TempA, TempB)) != TempB) ++Count; return Count; } inline std::size_t ulp ( float const & a, float const & b ) { std::size_t Count = 0; float Temp = a; //while((Temp = _nextafterf(Temp, b)) != b) { std::cout << Temp << " " << b << std::endl; ++Count; } return Count; } inline std::size_t ulp ( double const & a, double const & b ) { std::size_t Count = 0; double Temp = a; //while((Temp = _nextafter(Temp, b)) != b) { std::cout << Temp << " " << b << std::endl; ++Count; } return Count; } template <typename T> inline std::size_t ulp ( detail::tvec2<T> const & a, detail::tvec2<T> const & b ) { std::size_t ulps[] = { ulp(a[0], b[0]), ulp(a[1], b[1]) }; return glm::max(ulps[0], ulps[1]); } template <typename T> inline std::size_t ulp ( detail::tvec3<T> const & a, detail::tvec3<T> const & b ) { std::size_t ulps[] = { ulp(a[0], b[0]), ulp(a[1], b[1]), ulp(a[2], b[2]) }; return glm::max(glm::max(ulps[0], ulps[1]), ulps[2]); } template <typename T> inline std::size_t ulp ( detail::tvec4<T> const & a, detail::tvec4<T> const & b ) { std::size_t ulps[] = { ulp(a[0], b[0]), ulp(a[1], b[1]), ulp(a[2], b[2]), ulp(a[3], b[3]) }; return glm::max(glm::max(ulps[0], ulps[1]), glm::max(ulps[2], ulps[3])); } */ }//namespace ulp }//namespace gtx }//namespace glm <commit_msg>Fixed nextafterf on Visual C++<commit_after>/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2011-03-07 // Updated : 2011-04-26 // Licence : This source is under MIT License // File : glm/gtx/ulp.inl /////////////////////////////////////////////////////////////////////////////////////////////////// #include <cmath> #include <cfloat> /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ typedef union { float value; /* FIXME: Assumes 32 bit int. */ unsigned int word; } ieee_float_shape_type; typedef union { double value; struct { glm::detail::int32 lsw; glm::detail::int32 msw; } parts; } ieee_double_shape_type; #define GLM_EXTRACT_WORDS(ix0,ix1,d) \ do { \ ieee_double_shape_type ew_u; \ ew_u.value = (d); \ (ix0) = ew_u.parts.msw; \ (ix1) = ew_u.parts.lsw; \ } while (0) #define GLM_GET_FLOAT_WORD(i,d) \ do { \ ieee_float_shape_type gf_u; \ gf_u.value = (d); \ (i) = gf_u.word; \ } while (0) #define GLM_SET_FLOAT_WORD(d,i) \ do { \ ieee_float_shape_type sf_u; \ sf_u.word = (i); \ (d) = sf_u.value; \ } while (0) #define GLM_INSERT_WORDS(d,ix0,ix1) \ do { \ ieee_double_shape_type iw_u; \ iw_u.parts.msw = (ix0); \ iw_u.parts.lsw = (ix1); \ (d) = iw_u.value; \ } while (0) namespace glm{ namespace detail { GLM_FUNC_QUALIFIER float nextafterf(float x, float y) { volatile float t; glm::detail::int32 hx, hy, ix, iy; GLM_GET_FLOAT_WORD(hx,x); GLM_GET_FLOAT_WORD(hy,y); ix = hx&0x7fffffff; // |x| iy = hy&0x7fffffff; // |y| if((ix>0x7f800000) || // x is nan (iy>0x7f800000)) // y is nan return x+y; if(x==y) return y; // x=y, return y if(ix==0) { // x == 0 GLM_SET_FLOAT_WORD(x,(hy&0x80000000)|1);// return +-minsubnormal t = x*x; if(t==x) return t; else return x; // raise underflow flag } if(hx>=0) { // x > 0 if(hx>hy) { // x > y, x -= ulp hx -= 1; } else { // x < y, x += ulp hx += 1; } } else { // x < 0 if(hy>=0||hx>hy){ // x < y, x -= ulp hx -= 1; } else { // x > y, x += ulp hx += 1; } } hy = hx&0x7f800000; if(hy>=0x7f800000) return x+x; // overflow if(hy<0x00800000) { // underflow t = x*x; if(t!=x) { // raise underflow flag GLM_SET_FLOAT_WORD(y,hx); return y; } } GLM_SET_FLOAT_WORD(x,hx); return x; } GLM_FUNC_QUALIFIER double nextafter(double x, double y) { volatile double t; glm::detail::int32 hx, hy, ix, iy; glm::detail::uint32 lx, ly; GLM_EXTRACT_WORDS(hx, lx, x); GLM_EXTRACT_WORDS(hy, ly, y); ix = hx & 0x7fffffff; // |x| iy = hy & 0x7fffffff; // |y| if(((ix>=0x7ff00000)&&((ix-0x7ff00000)|lx)!=0) || // x is nan ((iy>=0x7ff00000)&&((iy-0x7ff00000)|ly)!=0)) // y is nan return x+y; if(x==y) return y; // x=y, return y if((ix|lx)==0) { // x == 0 GLM_INSERT_WORDS(x, hy & 0x80000000, 1); // return +-minsubnormal t = x*x; if(t==x) return t; else return x; // raise underflow flag } if(hx>=0) { // x > 0 if(hx>hy||((hx==hy)&&(lx>ly))) { // x > y, x -= ulp if(lx==0) hx -= 1; lx -= 1; } else { // x < y, x += ulp lx += 1; if(lx==0) hx += 1; } } else { // x < 0 if(hy>=0||hx>hy||((hx==hy)&&(lx>ly))){// x < y, x -= ulp if(lx==0) hx -= 1; lx -= 1; } else { // x > y, x += ulp lx += 1; if(lx==0) hx += 1; } } hy = hx&0x7ff00000; if(hy>=0x7ff00000) return x+x; // overflow if(hy<0x00100000) { // underflow t = x*x; if(t!=x) { // raise underflow flag GLM_INSERT_WORDS(y,hx,lx); return y; } } GLM_INSERT_WORDS(x,hx,lx); return x; } }//namespace detail }//namespace glm #if(GLM_COMPILER & GLM_COMPILER_VC) # define GLM_NEXT_AFTER_FLT(x, toward) glm::detail::nextafterf((x), (toward)) # define GLM_NEXT_AFTER_DBL(x, toward) _nextafter((x), (toward)) #else # define GLM_NEXT_AFTER_FLT(x, toward) nextafterf((x), (toward)) # define GLM_NEXT_AFTER_DBL(x, toward) nextafter((x), (toward)) #endif namespace glm{ namespace gtx{ namespace ulp { GLM_FUNC_QUALIFIER float next_float(float const & x) { return GLM_NEXT_AFTER_FLT(x, std::numeric_limits<float>::max()); } GLM_FUNC_QUALIFIER double next_float(double const & x) { return GLM_NEXT_AFTER_DBL(x, std::numeric_limits<double>::max()); } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<T> next_float(vecType<T> const & x) { vecType<T> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = next_float(x[i]); return Result; } GLM_FUNC_QUALIFIER float prev_float(float const & x) { return GLM_NEXT_AFTER_FLT(x, std::numeric_limits<float>::min()); } GLM_FUNC_QUALIFIER double prev_float(double const & x) { return GLM_NEXT_AFTER_DBL(x, std::numeric_limits<double>::min()); } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<T> prev_float(vecType<T> const & x) { vecType<T> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = prev_float(x[i]); return Result; } template <typename T> GLM_FUNC_QUALIFIER T next_float(T const & x, uint const & ulps) { T temp = x; for(std::size_t i = 0; i < ulps; ++i) temp = next_float(temp); return temp; } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<T> next_float(vecType<T> const & x, vecType<uint> const & ulps) { vecType<T> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = next_float(x[i], ulps[i]); return Result; } template <typename T> GLM_FUNC_QUALIFIER T prev_float(T const & x, uint const & ulps) { T temp = x; for(std::size_t i = 0; i < ulps; ++i) temp = prev_float(temp); return temp; } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<T> prev_float(vecType<T> const & x, vecType<uint> const & ulps) { vecType<T> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = prev_float(x[i], ulps[i]); return Result; } template <typename T> GLM_FUNC_QUALIFIER uint float_distance(T const & x, T const & y) { uint ulp = 0; if(x < y) { T temp = x; while(temp != y && ulp < std::numeric_limits<std::size_t>::max()) { ++ulp; temp = next_float(temp); } } else if(y < x) { T temp = y; while(temp != x && ulp < std::numeric_limits<std::size_t>::max()) { ++ulp; temp = next_float(temp); } } else // == { } return ulp; } template<typename T, template<typename> class vecType> GLM_FUNC_QUALIFIER vecType<uint> float_distance(vecType<T> const & x, vecType<T> const & y) { vecType<uint> Result; for(std::size_t i = 0; i < Result.length(); ++i) Result[i] = float_distance(x[i], y[i]); return Result; } /* inline std::size_t ulp ( detail::thalf const & a, detail::thalf const & b ) { std::size_t Count = 0; float TempA(a); float TempB(b); //while((TempA = _nextafterf(TempA, TempB)) != TempB) ++Count; return Count; } inline std::size_t ulp ( float const & a, float const & b ) { std::size_t Count = 0; float Temp = a; //while((Temp = _nextafterf(Temp, b)) != b) { std::cout << Temp << " " << b << std::endl; ++Count; } return Count; } inline std::size_t ulp ( double const & a, double const & b ) { std::size_t Count = 0; double Temp = a; //while((Temp = _nextafter(Temp, b)) != b) { std::cout << Temp << " " << b << std::endl; ++Count; } return Count; } template <typename T> inline std::size_t ulp ( detail::tvec2<T> const & a, detail::tvec2<T> const & b ) { std::size_t ulps[] = { ulp(a[0], b[0]), ulp(a[1], b[1]) }; return glm::max(ulps[0], ulps[1]); } template <typename T> inline std::size_t ulp ( detail::tvec3<T> const & a, detail::tvec3<T> const & b ) { std::size_t ulps[] = { ulp(a[0], b[0]), ulp(a[1], b[1]), ulp(a[2], b[2]) }; return glm::max(glm::max(ulps[0], ulps[1]), ulps[2]); } template <typename T> inline std::size_t ulp ( detail::tvec4<T> const & a, detail::tvec4<T> const & b ) { std::size_t ulps[] = { ulp(a[0], b[0]), ulp(a[1], b[1]), ulp(a[2], b[2]), ulp(a[3], b[3]) }; return glm::max(glm::max(ulps[0], ulps[1]), glm::max(ulps[2], ulps[3])); } */ }//namespace ulp }//namespace gtx }//namespace glm <|endoftext|>
<commit_before>/* * graph.cpp * * Created on: 14.01.2016 г. * Author: trifon */ #ifndef __GRAPH_CPP #define __GRAPH_CPP #include <iostream> using namespace std; #include "hashtable.hpp" #include "linked_list.cpp" template <typename T> class Graph { protected: LinkedHashTable<T, LinkedList<T> > g; public: using VI = LinkedListIterator<T>; LinkedList<T> vertices() { return g.keys(); } VI successors(T const& u) { return g[u].begin(); } bool isEdge(T const& u, T const& v) { VI it = successors(u); while(it && *it != v) ++it; return it; } void addVertex(T const& u) { g.add(u, LinkedList<T>()); } void removeVertex(T const& u) { for(VI it = vertices().begin();it; ++it) removeEdge(*it, u); g.remove(u); } void addEdge(T const& u, T const& v) { g[u].insertEnd(v); } void removeEdge(T const& u, T const& v) { LinkedList<T>& su = g[u]; T tmp; for(VI it = su.begin(); it; ++it) if (*it == v) su.deleteAt(tmp, it); } void printDOT(ostream& os = cout) { os << "digraph g {\n"; // всички ребра: // за всеки връх в графа: LinkedList<T> v = vertices(); for(VI it = v.begin(); it; ++it) // обхождаме всеки негов наследник for(VI sit = successors(*it); sit; ++sit) os << "\"" << *it << "\" -> \"" << *sit << "\";\n"; os << "}\n"; } }; int inthash(unsigned const& x, int MAX) { return x % MAX; } class IntGraph : public Graph<unsigned> { public: IntGraph() { g.setHashFunction(inthash); } using Graph<unsigned>::addVertex; using Graph<unsigned>::removeVertex; using Graph<unsigned>::addEdge; using Graph<unsigned>::removeEdge; using Graph<unsigned>::isEdge; using Graph<unsigned>::vertices; using Graph<unsigned>::successors; using Graph<unsigned>::printDOT; }; #endif <commit_msg>Добавен клас за множество от двойки от цели числа.<commit_after>/* * graph.cpp * * Created on: 14.01.2016 г. * Author: trifon */ #ifndef __GRAPH_CPP #define __GRAPH_CPP #include <iostream> using namespace std; #include "hashtable.hpp" #include "linked_list.cpp" #include "set.cpp" template <typename T> class Graph { protected: LinkedHashTable<T, LinkedList<T> > g; public: using VI = LinkedListIterator<T>; LinkedList<T> vertices() { return g.keys(); } VI successors(T const& u) { return g[u].begin(); } bool isEdge(T const& u, T const& v) { VI it = successors(u); while(it && *it != v) ++it; return it; } void addVertex(T const& u) { g.add(u, LinkedList<T>()); } void removeVertex(T const& u) { for(VI it = vertices().begin();it; ++it) removeEdge(*it, u); g.remove(u); } void addEdge(T const& u, T const& v) { g[u].insertEnd(v); } void removeEdge(T const& u, T const& v) { LinkedList<T>& su = g[u]; T tmp; for(VI it = su.begin(); it; ++it) if (*it == v) su.deleteAt(tmp, it); } void printDOT(ostream& os = cout) { os << "digraph g {\n"; // всички ребра: // за всеки връх в графа: LinkedList<T> v = vertices(); for(VI it = v.begin(); it; ++it) // обхождаме всеки негов наследник for(VI sit = successors(*it); sit; ++sit) os << "\"" << *it << "\" -> \"" << *sit << "\";\n"; os << "}\n"; } }; int inthash(unsigned const& x, int MAX) { return x % MAX; } class IntGraph : public Graph<unsigned> { public: IntGraph() { g.setHashFunction(inthash); } using Graph<unsigned>::addVertex; using Graph<unsigned>::removeVertex; using Graph<unsigned>::addEdge; using Graph<unsigned>::removeEdge; using Graph<unsigned>::isEdge; using Graph<unsigned>::vertices; using Graph<unsigned>::successors; using Graph<unsigned>::printDOT; }; class IntSet : public Set<unsigned, LinkedHashTable> { public: using S = Set<unsigned, LinkedHashTable>; IntSet() { S::setHashFunction(inthash); } using S::empty; using S::insert; using S::remove; using S::contains; using S::elements; }; int intinthash(pair<unsigned, unsigned>const& p, int MAX) { return (inthash(p.first, MAX) ^ inthash(p.second, MAX)) % MAX; } class IntIntSet : public Set<pair<unsigned, unsigned>, LinkedHashTable> { public: using S = Set<pair<unsigned, unsigned>, LinkedHashTable>; IntIntSet() { S::setHashFunction(intinthash); } using S::empty; using S::insert; using S::remove; using S::contains; using S::elements; }; #endif <|endoftext|>
<commit_before>#include <cmath> #include <algorithm> #include "contest.hpp" #include "helper.hpp" #include "problem.hpp" #include "attempt.hpp" #include "user.hpp" using namespace std; static bool isjudge(int user, const JSON& contest) { JSON tmp = contest("judges"); if (!tmp.isarr()) return false; auto& a = tmp.arr(); auto i = lower_bound(a.begin(),a.end(),user,std::less<int>())-a.begin(); return i < a.size() && int(a[i]) == user; } static JSON list_problems(const JSON& contest, int user) { JSON probs = contest("problems"); JSON ans(vector<JSON>{}), tmp; for (int pid : probs.arr()) { tmp = Problem::get_short(pid,user); if (!tmp) continue; ans.push_back(move(tmp)); } return ans; } namespace Contest { void fix() { DB(contests); DB(problems); JSON aux; contests.update([&](Database::Document& doc) { if (doc.second("judges").isarr()) { auto& a = doc.second["judges"].arr(); sort(a.begin(),a.end(),std::less<int>()); } auto& ps = doc.second["problems"]; if (!ps.isarr()) { ps = JSON(vector<JSON>{}); return true; } for (int id : ps.arr()) if (problems.retrieve(id,aux)) { aux["contest"] = doc.first; problems.update(id,move(aux)); } return true; }); problems.update([&](Database::Document& doc) { int cid; if ( !doc.second["contest"].read(cid) || !contests.retrieve(cid,aux)) { doc.second.erase("contest"); return true; } for (int id : aux["problems"].arr()) if (id == doc.first) return true; doc.second.erase("contest"); return true; }); } Time time(const JSON& contest) { Time ans; ans.begin = begin(contest); ans.end = end(contest); ans.freeze = freeze(contest); ans.blind = blind(contest); return ans; } time_t begin(const JSON& contest) { int Y = contest("start","year"); int M = contest("start","month"); int D = contest("start","day"); int h = contest("start","hour"); int m = contest("start","minute"); time_t tmp = ::time(nullptr); tm ti; localtime_r(&tmp,&ti); ti.tm_year = Y - 1900; ti.tm_mon = M - 1; ti.tm_mday = D; ti.tm_hour = h; ti.tm_min = m; ti.tm_sec = 0; return mktime(&ti); } time_t end(const JSON& contest) { return begin(contest) + 60*int(contest("duration")); } time_t freeze(const JSON& contest) { return end(contest) - 60*int(contest("freeze")); } time_t blind(const JSON& contest) { return end(contest) - 60*int(contest("blind")); } bool allow_problem(const JSON& problem, int user) { int cid; if (!problem("contest").read(cid)) return true; DB(contests); JSON contest = contests.retrieve(cid); return contest("finished") || isjudge(user,contest) || begin(contest) <= ::time(nullptr) ; } bool allow_create_attempt(JSON& attempt, const JSON& problem) { int cid; if (!problem("contest").read(cid)) return true; DB(contests); JSON contest = contests.retrieve(cid); if (contest("finished")) return true; if (isjudge(attempt["user"],contest)) { attempt["contest"] = cid; attempt["privileged"].settrue(); return true; } auto t = time(contest); time_t when = attempt["when"]; if (t.begin <= when && when < t.end) { attempt["contest"] = cid; attempt["contest_time"] = int(roundl((when-t.begin)/60.0L)); return true; } return false; } JSON get(int id, int user) { DB(contests); JSON ans; if ( !contests.retrieve(id,ans) || (!isjudge(user,ans) && ::time(nullptr) < begin(ans)) ) { return JSON::null(); } ans["id"] = id; return ans; } JSON get_problems(int id, int user) { JSON contest = get(id,user); if (!contest) return contest; return list_problems(contest,user); } JSON get_attempts(int id, int user) { JSON contest = get(id,user); if (!contest) return contest; // get problem info JSON probs = list_problems(contest,user); map<int,JSON> pinfo; int i = 0; for (auto& prob : probs.arr()) pinfo[prob["id"]] = map<string,JSON>{ {"id" , prob["id"]}, {"name" , prob["name"]}, {"color", prob["color"]}, {"idx" , i++} }; // get attempts JSON ans = Attempt::page(user,0,0,id); // set problem info for (auto& att : ans.arr()) att["problem"] = pinfo[att["problem"]["id"]]; // no blind filtering needed? if ( contest("finished") || int(contest["blind"]) == 0 || isjudge(user,contest) ) return ans; // blind filtering int blind = int(contest["duration"])-int(contest["blind"]); for (auto& att : ans.arr()) { if (int(att["contest_time"]) < blind) continue; att["status"] = "blind"; att.erase("verdict"); } return ans; } JSON scoreboard(int id, int user) { JSON contest = get(id,user); if (!contest) return contest; JSON ans(map<string,JSON>{{"attempts",JSON()},{"colors",vector<JSON>{}}}); // get problem info JSON probs = list_problems(contest,user); map<int,int> idx; for (auto& prob : probs.arr()) { idx[prob["id"]] = ans["colors"].size(); ans["colors"].push_back(prob["color"]); } // get attempts ans["attempts"] = Attempt::page(user,0,0,id,true); // set info auto& arr = ans["attempts"].arr(); for (auto& att : arr) { att["problem"] = idx[att["problem"]["id"]]; att["user"] = User::name(att["user"]); } // no freeze/blind filtering needed? if ( contest("finished") || (int(contest["freeze"]) == 0 && int(contest["blind"]) == 0) || isjudge(user,contest) ) return ans; // freeze/blind filtering int freeze = int(contest["duration"])-int(contest["freeze"]); int blind = int(contest["duration"])-int(contest["blind"]); freeze = min(freeze,blind); JSON tmp(vector<JSON>{}); for (auto& att : arr) if (int(att["contest_time"]) < freeze) { tmp.push_back(move(att)); } ans["attempts"] = move(tmp); return ans; } JSON page(unsigned p, unsigned ps) { DB(contests); return contests.retrieve_page(p,ps); } } // namespace Contest <commit_msg>Freeze status on scoreboard<commit_after>#include <cmath> #include <algorithm> #include "contest.hpp" #include "helper.hpp" #include "problem.hpp" #include "attempt.hpp" #include "user.hpp" using namespace std; static bool isjudge(int user, const JSON& contest) { JSON tmp = contest("judges"); if (!tmp.isarr()) return false; auto& a = tmp.arr(); auto i = lower_bound(a.begin(),a.end(),user,std::less<int>())-a.begin(); return i < a.size() && int(a[i]) == user; } static JSON list_problems(const JSON& contest, int user) { JSON probs = contest("problems"); JSON ans(vector<JSON>{}), tmp; for (int pid : probs.arr()) { tmp = Problem::get_short(pid,user); if (!tmp) continue; ans.push_back(move(tmp)); } return ans; } namespace Contest { void fix() { DB(contests); DB(problems); JSON aux; contests.update([&](Database::Document& doc) { if (doc.second("judges").isarr()) { auto& a = doc.second["judges"].arr(); sort(a.begin(),a.end(),std::less<int>()); } auto& ps = doc.second["problems"]; if (!ps.isarr()) { ps = JSON(vector<JSON>{}); return true; } for (int id : ps.arr()) if (problems.retrieve(id,aux)) { aux["contest"] = doc.first; problems.update(id,move(aux)); } return true; }); problems.update([&](Database::Document& doc) { int cid; if ( !doc.second["contest"].read(cid) || !contests.retrieve(cid,aux)) { doc.second.erase("contest"); return true; } for (int id : aux["problems"].arr()) if (id == doc.first) return true; doc.second.erase("contest"); return true; }); } Time time(const JSON& contest) { Time ans; ans.begin = begin(contest); ans.end = end(contest); ans.freeze = freeze(contest); ans.blind = blind(contest); return ans; } time_t begin(const JSON& contest) { int Y = contest("start","year"); int M = contest("start","month"); int D = contest("start","day"); int h = contest("start","hour"); int m = contest("start","minute"); time_t tmp = ::time(nullptr); tm ti; localtime_r(&tmp,&ti); ti.tm_year = Y - 1900; ti.tm_mon = M - 1; ti.tm_mday = D; ti.tm_hour = h; ti.tm_min = m; ti.tm_sec = 0; return mktime(&ti); } time_t end(const JSON& contest) { return begin(contest) + 60*int(contest("duration")); } time_t freeze(const JSON& contest) { return end(contest) - 60*int(contest("freeze")); } time_t blind(const JSON& contest) { return end(contest) - 60*int(contest("blind")); } bool allow_problem(const JSON& problem, int user) { int cid; if (!problem("contest").read(cid)) return true; DB(contests); JSON contest = contests.retrieve(cid); return contest("finished") || isjudge(user,contest) || begin(contest) <= ::time(nullptr) ; } bool allow_create_attempt(JSON& attempt, const JSON& problem) { int cid; if (!problem("contest").read(cid)) return true; DB(contests); JSON contest = contests.retrieve(cid); if (contest("finished")) return true; if (isjudge(attempt["user"],contest)) { attempt["contest"] = cid; attempt["privileged"].settrue(); return true; } auto t = time(contest); time_t when = attempt["when"]; if (t.begin <= when && when < t.end) { attempt["contest"] = cid; attempt["contest_time"] = int(roundl((when-t.begin)/60.0L)); return true; } return false; } JSON get(int id, int user) { DB(contests); JSON ans; if ( !contests.retrieve(id,ans) || (!isjudge(user,ans) && ::time(nullptr) < begin(ans)) ) { return JSON::null(); } ans["id"] = id; return ans; } JSON get_problems(int id, int user) { JSON contest = get(id,user); if (!contest) return contest; return list_problems(contest,user); } JSON get_attempts(int id, int user) { JSON contest = get(id,user); if (!contest) return contest; // get problem info JSON probs = list_problems(contest,user); map<int,JSON> pinfo; int i = 0; for (auto& prob : probs.arr()) pinfo[prob["id"]] = map<string,JSON>{ {"id" , prob["id"]}, {"name" , prob["name"]}, {"color", prob["color"]}, {"idx" , i++} }; // get attempts JSON ans = Attempt::page(user,0,0,id); // set problem info for (auto& att : ans.arr()) att["problem"] = pinfo[att["problem"]["id"]]; // no blind filtering needed? if ( contest("finished") || int(contest["blind"]) == 0 || isjudge(user,contest) ) return ans; // blind filtering int blind = int(contest["duration"])-int(contest["blind"]); for (auto& att : ans.arr()) { if (int(att["contest_time"]) < blind) continue; att["status"] = "blind"; att.erase("verdict"); } return ans; } JSON scoreboard(int id, int user) { JSON contest = get(id,user); if (!contest) return contest; JSON ans(map<string,JSON>{ {"status" , contest("finished") ? "final" : ""}, {"attempts" , JSON()}, {"colors" , vector<JSON>{}} }); // get problem info JSON probs = list_problems(contest,user); map<int,int> idx; for (auto& prob : probs.arr()) { idx[prob["id"]] = ans["colors"].size(); ans["colors"].push_back(prob["color"]); } // get attempts ans["attempts"] = Attempt::page(user,0,0,id,true); // set info auto& arr = ans["attempts"].arr(); for (auto& att : arr) { att["problem"] = idx[att["problem"]["id"]]; att["user"] = User::name(att["user"]); } // no freeze/blind filtering needed? if ( contest("finished") || (int(contest["freeze"]) == 0 && int(contest["blind"]) == 0) || isjudge(user,contest) ) return ans; // freeze/blind filtering int freeze = int(contest["duration"])-int(contest["freeze"]); int blind = int(contest["duration"])-int(contest["blind"]); freeze = min(freeze,blind); ans["status"] = "frozen"; ans["freeze"] = freeze; JSON tmp(vector<JSON>{}); for (auto& att : arr) if (int(att["contest_time"]) < freeze) { tmp.push_back(move(att)); } ans["attempts"] = move(tmp); return ans; } JSON page(unsigned p, unsigned ps) { DB(contests); return contests.retrieve_page(p,ps); } } // namespace Contest <|endoftext|>
<commit_before>#include <node.h> #include <windows.h> #include <TlHelp32.h> #include <string> #include "process.h" namespace Memory { using v8::Exception; using v8::Function; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Number; using v8::Value; using v8::Handle; using v8::Array; process Memory; void throwError(char* error, Isolate* isolate){ isolate->ThrowException( Exception::TypeError(String::NewFromUtf8(isolate, error)) ); return; } const char* toCharString(const v8::String::Utf8Value &value) { return *value; } void openProcess(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); // Argument is the process name, // if this hasn't been provided throw an error if(args.Length() != 1 && args.Length() != 2){ throwError("requires 1 argument, or 2 arguments if a callback is being used", isolate); return; } // If the argument we've been given is // not a string, throw an error if(!args[0]->IsString()){ throwError("first argument must be a string", isolate); return; } // If there is a second argument and it's not // a function, throw an error if (args.Length() == 2 && !args[1]->IsFunction()) { throwError("second argument must be a function", isolate); return; } // Convert from v8 to char with toCharString v8::String::Utf8Value processName(args[0]); // Opens a process and returns PROCESSENTRY32 class PROCESSENTRY32 process = Memory.openProcess(toCharString(processName), isolate); // In case it failed to open, let's keep retrying while(!strcmp(process.szExeFile, "")) { process = Memory.openProcess(toCharString(processName), isolate); }; // Create a v8 Object (JSON) to store the process information Local<Object> processInfo = Object::New(isolate); // Set the key/values processInfo->Set(String::NewFromUtf8(isolate, "cntThreads"), Number::New(isolate, (int)process.cntThreads)); processInfo->Set(String::NewFromUtf8(isolate, "cntUsage"), Number::New(isolate, (int)process.cntUsage)); processInfo->Set(String::NewFromUtf8(isolate, "dwFlags"), Number::New(isolate, (int)process.dwFlags)); processInfo->Set(String::NewFromUtf8(isolate, "dwSize"), Number::New(isolate, (int)process.dwSize)); processInfo->Set(String::NewFromUtf8(isolate, "szExeFile"), String::NewFromUtf8(isolate, process.szExeFile)); processInfo->Set(String::NewFromUtf8(isolate, "th32ProcessID"), Number::New(isolate, (int)process.th32ProcessID)); processInfo->Set(String::NewFromUtf8(isolate, "th32ParentProcessID"), Number::New(isolate, (int)process.th32ParentProcessID)); // openProcess can either take one argument or can take // two arguments for asychronous use (second argument is the callback) if(args.Length() == 2){ // Callback to let the user handle with the information Local<Function> callback = Local<Function>::Cast(args[1]); const unsigned argc = 1; Local<Value> argv[argc] = { processInfo }; callback->Call(Null(isolate), argc, argv); } else { // return JSON args.GetReturnValue().Set(processInfo); } } void closeProcess(const FunctionCallbackInfo<Value>& args){ Isolate* isolate = args.GetIsolate(); Memory.closeProcess(); } void getProcesses(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); // Argument is the process name, // if this hasn't been provided throw an error if (args.Length() > 1) { throwError("requires either 0 arguments or 1 argument", isolate); return; } // If there is an argument and it's not // a function, throw an error if (args.Length() == 1 && !args[0]->IsFunction()) { throwError("first argument must be a function", isolate); return; } std::vector<PROCESSENTRY32> processEntries = Memory.getProcesses(isolate); Handle<Array> processes = Array::New(isolate, processEntries.size()); for (std::vector<PROCESSENTRY32>::size_type i = 0; i != processEntries.size(); i++) { Local<Object> process = Object::New(isolate); process->Set(String::NewFromUtf8(isolate, "cntThreads"), Number::New(isolate, (int)processEntries[i].cntThreads)); process->Set(String::NewFromUtf8(isolate, "cntUsage"), Number::New(isolate, (int)processEntries[i].cntUsage)); process->Set(String::NewFromUtf8(isolate, "dwFlags"), Number::New(isolate, (int)processEntries[i].dwFlags)); process->Set(String::NewFromUtf8(isolate, "dwSize"), Number::New(isolate, (int)processEntries[i].dwSize)); process->Set(String::NewFromUtf8(isolate, "szExeFile"), String::NewFromUtf8(isolate, processEntries[i].szExeFile)); process->Set(String::NewFromUtf8(isolate, "th32ProcessID"), Number::New(isolate, (int)processEntries[i].th32ProcessID)); process->Set(String::NewFromUtf8(isolate, "th32ParentProcessID"), Number::New(isolate, (int)processEntries[i].th32ParentProcessID)); processes->Set(i, process); } // getProcesses can either take no arguments or one argument // one argument is for asychronous use (the callback) if (args.Length() == 1) { // Callback to let the user handle with the information Local<Function> callback = Local<Function>::Cast(args[0]); const unsigned argc = 1; Local<Value> argv[argc] = { processes }; callback->Call(Null(isolate), argc, argv); } else { // return JSON args.GetReturnValue().Set(processes); } } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "openProcess", openProcess); NODE_SET_METHOD(exports, "closeProcess", closeProcess); NODE_SET_METHOD(exports, "getProcesses", getProcesses); } NODE_MODULE(memoryjs, init) } <commit_msg>commented code<commit_after>#include <node.h> #include <windows.h> #include <TlHelp32.h> #include <string> #include "process.h" namespace Memory { using v8::Exception; using v8::Function; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Number; using v8::Value; using v8::Handle; using v8::Array; process Memory; void throwError(char* error, Isolate* isolate){ isolate->ThrowException( Exception::TypeError(String::NewFromUtf8(isolate, error)) ); return; } const char* toCharString(const v8::String::Utf8Value &value) { return *value; } void openProcess(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); // Argument is the process name, // if this hasn't been provided throw an error if(args.Length() != 1 && args.Length() != 2){ throwError("requires 1 argument, or 2 arguments if a callback is being used", isolate); return; } // If the argument we've been given is // not a string, throw an error if(!args[0]->IsString()){ throwError("first argument must be a string", isolate); return; } // If there is a second argument and it's not // a function, throw an error if (args.Length() == 2 && !args[1]->IsFunction()) { throwError("second argument must be a function", isolate); return; } // Convert from v8 to char with toCharString v8::String::Utf8Value processName(args[0]); // Opens a process and returns PROCESSENTRY32 class PROCESSENTRY32 process = Memory.openProcess(toCharString(processName), isolate); // In case it failed to open, let's keep retrying while(!strcmp(process.szExeFile, "")) { process = Memory.openProcess(toCharString(processName), isolate); }; // Create a v8 Object (JSON) to store the process information Local<Object> processInfo = Object::New(isolate); // Set the key/values processInfo->Set(String::NewFromUtf8(isolate, "cntThreads"), Number::New(isolate, (int)process.cntThreads)); processInfo->Set(String::NewFromUtf8(isolate, "cntUsage"), Number::New(isolate, (int)process.cntUsage)); processInfo->Set(String::NewFromUtf8(isolate, "dwFlags"), Number::New(isolate, (int)process.dwFlags)); processInfo->Set(String::NewFromUtf8(isolate, "dwSize"), Number::New(isolate, (int)process.dwSize)); processInfo->Set(String::NewFromUtf8(isolate, "szExeFile"), String::NewFromUtf8(isolate, process.szExeFile)); processInfo->Set(String::NewFromUtf8(isolate, "th32ProcessID"), Number::New(isolate, (int)process.th32ProcessID)); processInfo->Set(String::NewFromUtf8(isolate, "th32ParentProcessID"), Number::New(isolate, (int)process.th32ParentProcessID)); // openProcess can either take one argument or can take // two arguments for asychronous use (second argument is the callback) if(args.Length() == 2){ // Callback to let the user handle with the information Local<Function> callback = Local<Function>::Cast(args[1]); const unsigned argc = 1; Local<Value> argv[argc] = { processInfo }; callback->Call(Null(isolate), argc, argv); } else { // return JSON args.GetReturnValue().Set(processInfo); } } void closeProcess(const FunctionCallbackInfo<Value>& args){ Isolate* isolate = args.GetIsolate(); Memory.closeProcess(); } void getProcesses(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); // Argument is the process name, // if this hasn't been provided throw an error if (args.Length() > 1) { throwError("requires either 0 arguments or 1 argument", isolate); return; } // If there is an argument and it's not // a function, throw an error if (args.Length() == 1 && !args[0]->IsFunction()) { throwError("first argument must be a function", isolate); return; } // processEntries stores PROCESSENTRY32s in a vector std::vector<PROCESSENTRY32> processEntries = Memory.getProcesses(isolate); // Creates v8 array with the size being that of the processEntries vector // processes is an array of JavaScript objects Handle<Array> processes = Array::New(isolate, processEntries.size()); // Loop over all processes found for (std::vector<PROCESSENTRY32>::size_type i = 0; i != processEntries.size(); i++) { // Create a v8 object to store the current process' information Local<Object> process = Object::New(isolate); // Assign key/values process->Set(String::NewFromUtf8(isolate, "cntThreads"), Number::New(isolate, (int)processEntries[i].cntThreads)); process->Set(String::NewFromUtf8(isolate, "cntUsage"), Number::New(isolate, (int)processEntries[i].cntUsage)); process->Set(String::NewFromUtf8(isolate, "dwFlags"), Number::New(isolate, (int)processEntries[i].dwFlags)); process->Set(String::NewFromUtf8(isolate, "dwSize"), Number::New(isolate, (int)processEntries[i].dwSize)); process->Set(String::NewFromUtf8(isolate, "szExeFile"), String::NewFromUtf8(isolate, processEntries[i].szExeFile)); process->Set(String::NewFromUtf8(isolate, "th32ProcessID"), Number::New(isolate, (int)processEntries[i].th32ProcessID)); process->Set(String::NewFromUtf8(isolate, "th32ParentProcessID"), Number::New(isolate, (int)processEntries[i].th32ParentProcessID)); // Push the object to the array processes->Set(i, process); } // getProcesses can either take no arguments or one argument // one argument is for asychronous use (the callback) if (args.Length() == 1) { // Callback to let the user handle with the information Local<Function> callback = Local<Function>::Cast(args[0]); const unsigned argc = 1; Local<Value> argv[argc] = { processes }; callback->Call(Null(isolate), argc, argv); } else { // return JSON args.GetReturnValue().Set(processes); } } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "openProcess", openProcess); NODE_SET_METHOD(exports, "closeProcess", closeProcess); NODE_SET_METHOD(exports, "getProcesses", getProcesses); } NODE_MODULE(memoryjs, init) } <|endoftext|>
<commit_before>// Copyright 2013 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../include/v8-defaults.h" #include "platform.h" #include "globals.h" #include "v8.h" namespace v8 { bool ConfigureResourceConstraintsForCurrentPlatform( ResourceConstraints* constraints) { if (constraints == NULL) { return false; } uint64_t physical_memory = i::OS::TotalPhysicalMemory(); int lump_of_memory = (i::kPointerSize / 4) * i::MB; // The young_space_size should be a power of 2 and old_generation_size should // be a multiple of Page::kPageSize. if (physical_memory > 2ul * i::GB) { constraints->set_max_young_space_size(16 * lump_of_memory); constraints->set_max_old_space_size(700 * lump_of_memory); constraints->set_max_executable_size(256 * lump_of_memory); } else if (physical_memory > 512ul * i::MB) { constraints->set_max_young_space_size(8 * lump_of_memory); constraints->set_max_old_space_size(192 * lump_of_memory); constraints->set_max_executable_size(192 * lump_of_memory); } else /* (physical_memory <= 512GB) */ { constraints->set_max_young_space_size(2 * lump_of_memory); constraints->set_max_old_space_size(96 * lump_of_memory); constraints->set_max_executable_size(96 * lump_of_memory); } return true; } bool SetDefaultResourceConstraintsForCurrentPlatform() { ResourceConstraints constraints; if (!ConfigureResourceConstraintsForCurrentPlatform(&constraints)) return false; return SetResourceConstraints(&constraints); } } // namespace v8::internal <commit_msg>Tweak default max heap size constants for platforms with swap.<commit_after>// Copyright 2013 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../include/v8-defaults.h" #include "platform.h" #include "globals.h" #include "v8.h" namespace v8 { #if V8_OS_ANDROID const bool kOsHasSwap = false; #else const bool kOsHasSwap = true; #endif bool ConfigureResourceConstraintsForCurrentPlatform( ResourceConstraints* constraints) { if (constraints == NULL) { return false; } uint64_t physical_memory = i::OS::TotalPhysicalMemory(); int lump_of_memory = (i::kPointerSize / 4) * i::MB; // The young_space_size should be a power of 2 and old_generation_size should // be a multiple of Page::kPageSize. if (physical_memory <= 512ul * i::MB) { constraints->set_max_young_space_size(2 * lump_of_memory); constraints->set_max_old_space_size(128 * lump_of_memory); constraints->set_max_executable_size(96 * lump_of_memory); } else if (physical_memory <= (kOsHasSwap ? 768ul * i::MB : 1ul * i::GB)) { constraints->set_max_young_space_size(8 * lump_of_memory); constraints->set_max_old_space_size(256 * lump_of_memory); constraints->set_max_executable_size(192 * lump_of_memory); } else if (physical_memory <= (kOsHasSwap ? 1ul * i::GB : 2ul * i::GB)) { constraints->set_max_young_space_size(16 * lump_of_memory); constraints->set_max_old_space_size(512 * lump_of_memory); constraints->set_max_executable_size(256 * lump_of_memory); } else { constraints->set_max_young_space_size(16 * lump_of_memory); constraints->set_max_old_space_size(700 * lump_of_memory); constraints->set_max_executable_size(256 * lump_of_memory); } return true; } bool SetDefaultResourceConstraintsForCurrentPlatform() { ResourceConstraints constraints; if (!ConfigureResourceConstraintsForCurrentPlatform(&constraints)) return false; return SetResourceConstraints(&constraints); } } // namespace v8 <|endoftext|>
<commit_before> #include "yacas/yacasprivate.h" #include "yacas/deffile.h" #include "yacas/lispuserfunc.h" #include "yacas/standard.h" #include "yacas/lispio.h" #include "yacas/platfileio.h" #include "yacas/lispenvironment.h" #include "yacas/tokenizer.h" #include "yacas/stringio.h" LispDefFile::LispDefFile(const std::string& aFileName): iFileName(aFileName), iIsLoaded(false) { } void LispDefFile::SetLoaded() { iIsLoaded = true; } LispDefFile* LispDefFiles::File(const std::string& aFileName) { auto i = _map.find(aFileName); if (i == _map.end()) i = _map.emplace(aFileName, aFileName).first; return &i->second; } static void DoLoadDefFile( LispEnvironment& aEnvironment, LispInput* aInput, LispDefFile* def) { LispLocalInput localInput(aEnvironment, aInput); const LispString* eof = aEnvironment.iEndOfFile->String(); const LispString* end = aEnvironment.iListClose->String(); bool endoffile = false; LispTokenizer tok; while (!endoffile) { // Read expression const LispString* token = tok.NextToken(*aEnvironment.CurrentInput(), aEnvironment.HashTable()); // Check for end of file if (token == eof || token == end) { endoffile = true; } // Else evaluate else { LispMultiUserFunction* multiUser = aEnvironment.MultiUserFunction(token); if (multiUser->iFileToOpen != nullptr) { aEnvironment.CurrentOutput() << '[' << *token << "]\n"; if (multiUser->iFileToOpen) throw LispErrDefFileAlreadyChosen(); } multiUser->iFileToOpen = def; } } } void LoadDefFile(LispEnvironment& aEnvironment, const std::string& aFileName) { assert(aFileName!=nullptr); const std::string flatfile = InternalUnstringify(aFileName) + ".def"; LispDefFile* def = aEnvironment.DefFiles().File(aFileName); InputStatus oldstatus = aEnvironment.iInputStatus; aEnvironment.iInputStatus.SetTo(flatfile); LispLocalFile localFP(aEnvironment, flatfile, true, aEnvironment.iInputDirectories); if (!localFP.stream.is_open()) throw LispErrFileNotFound(); CachedStdFileInput newInput(localFP,aEnvironment.iInputStatus); DoLoadDefFile(aEnvironment, &newInput,def); aEnvironment.iInputStatus.RestoreFrom(oldstatus); } <commit_msg>get rid of stray assert<commit_after> #include "yacas/yacasprivate.h" #include "yacas/deffile.h" #include "yacas/lispuserfunc.h" #include "yacas/standard.h" #include "yacas/lispio.h" #include "yacas/platfileio.h" #include "yacas/lispenvironment.h" #include "yacas/tokenizer.h" #include "yacas/stringio.h" LispDefFile::LispDefFile(const std::string& aFileName): iFileName(aFileName), iIsLoaded(false) { } void LispDefFile::SetLoaded() { iIsLoaded = true; } LispDefFile* LispDefFiles::File(const std::string& aFileName) { auto i = _map.find(aFileName); if (i == _map.end()) i = _map.emplace(aFileName, aFileName).first; return &i->second; } static void DoLoadDefFile( LispEnvironment& aEnvironment, LispInput* aInput, LispDefFile* def) { LispLocalInput localInput(aEnvironment, aInput); const LispString* eof = aEnvironment.iEndOfFile->String(); const LispString* end = aEnvironment.iListClose->String(); bool endoffile = false; LispTokenizer tok; while (!endoffile) { // Read expression const LispString* token = tok.NextToken(*aEnvironment.CurrentInput(), aEnvironment.HashTable()); // Check for end of file if (token == eof || token == end) { endoffile = true; } // Else evaluate else { LispMultiUserFunction* multiUser = aEnvironment.MultiUserFunction(token); if (multiUser->iFileToOpen != nullptr) { aEnvironment.CurrentOutput() << '[' << *token << "]\n"; if (multiUser->iFileToOpen) throw LispErrDefFileAlreadyChosen(); } multiUser->iFileToOpen = def; } } } void LoadDefFile(LispEnvironment& aEnvironment, const std::string& aFileName) { const std::string flatfile = InternalUnstringify(aFileName) + ".def"; LispDefFile* def = aEnvironment.DefFiles().File(aFileName); InputStatus oldstatus = aEnvironment.iInputStatus; aEnvironment.iInputStatus.SetTo(flatfile); LispLocalFile localFP(aEnvironment, flatfile, true, aEnvironment.iInputDirectories); if (!localFP.stream.is_open()) throw LispErrFileNotFound(); CachedStdFileInput newInput(localFP,aEnvironment.iInputStatus); DoLoadDefFile(aEnvironment, &newInput,def); aEnvironment.iInputStatus.RestoreFrom(oldstatus); } <|endoftext|>
<commit_before>// Copyright (c) 2012-2015 Dano Pernis // See LICENSE for details #include "CPU.h" #include <cassert> #include <fstream> #include <gtkmm.h> #include <iostream> #include <stdexcept> #include <vector> // sigc workaround namespace sigc { SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE } namespace { const unsigned int SCREEN_WIDTH = 512; const unsigned int SCREEN_HEIGHT = 256; struct ROM : public hcc::IROM { ROM() : data(0x8000, 0) { } uint16_t get(unsigned int address) const override { return data.at(address); } bool load(const char* filename); std::vector<uint16_t> data; }; struct RAM : public hcc::IRAM { RAM() : data(0x6001, 0) { } uint16_t get(unsigned int address) const override { return data.at(address); } void set(unsigned int address, uint16_t value) override { data.at(address) = value; } void keyboard(uint16_t value) { set(0x6000, value); }; std::vector<uint16_t> data; }; struct screen_widget : Gtk::DrawingArea { screen_widget(RAM& ram); bool draw(const Cairo::RefPtr<Cairo::Context>& cr); private: Glib::RefPtr<Gdk::Pixbuf> pixbuf; RAM& ram; }; struct emulator { emulator(); void load_clicked(); void run_clicked(); void pause_clicked(); bool keyboard_callback(GdkEventKey* event); void cpu_thread(); void screen_thread(); void setup_button(Gtk::ToolButton& button, const gchar* stock_id, const gchar* text); ROM rom; RAM ram; hcc::CPU cpu; bool running = false; Gtk::SeparatorToolItem separator; Gtk::Toolbar toolbar; Gtk::ToggleButton keyboard; Gtk::Grid grid; Gtk::Window window; Gtk::FileChooserDialog load_dialog; Gtk::MessageDialog error_dialog; Gtk::ToolButton button_load; Gtk::ToolButton button_run; Gtk::ToolButton button_pause; screen_widget screen; }; gpointer c_cpu_thread(gpointer user_data) { reinterpret_cast<emulator*>(user_data)->cpu_thread(); return NULL; } gpointer c_screen_thread(gpointer user_data) { reinterpret_cast<emulator*>(user_data)->screen_thread(); return NULL; } // Translate special keys. See Figure 5.6 in TECS book. uint16_t translate(guint keyval) { switch (keyval) { case GDK_KEY_Return: return 128; case GDK_KEY_BackSpace: return 129; case GDK_KEY_Left: return 130; case GDK_KEY_Up: return 131; case GDK_KEY_Right: return 132; case GDK_KEY_Down: return 133; case GDK_KEY_Home: return 134; case GDK_KEY_End: return 135; case GDK_KEY_Page_Up: return 136; case GDK_KEY_Page_Down: return 137; case GDK_KEY_Insert: return 138; case GDK_KEY_Delete: return 139; case GDK_KEY_Escape: return 140; case GDK_KEY_F1: return 141; case GDK_KEY_F2: return 142; case GDK_KEY_F3: return 143; case GDK_KEY_F4: return 144; case GDK_KEY_F5: return 145; case GDK_KEY_F6: return 146; case GDK_KEY_F7: return 147; case GDK_KEY_F8: return 148; case GDK_KEY_F9: return 149; case GDK_KEY_F10: return 150; case GDK_KEY_F11: return 151; case GDK_KEY_F12: return 152; } return keyval; } bool ROM::load(const char* filename) { std::ifstream input(filename); std::string line; auto it = begin(data); while (input.good() && it != end(data)) { getline(input, line); if (line.size() == 0) { continue; } if (line.size() != 16) { return false; } unsigned int instruction = 0; for (unsigned int i = 0; i<16; ++i) { instruction <<= 1; switch (line[i]) { case '0': break; case '1': instruction |= 1; break; default: return false; } } *it++ = instruction; } // clear the rest while (it != end(data)) { *it++ = 0; } return true; } screen_widget::screen_widget(RAM& ram) : pixbuf( Gdk::Pixbuf::create(Gdk::Colorspace::COLORSPACE_RGB, false, 8, SCREEN_WIDTH, SCREEN_HEIGHT)) , ram(ram) { set_size_request(SCREEN_WIDTH, SCREEN_HEIGHT); signal_draw().connect([&] (const Cairo::RefPtr<Cairo::Context>& cr) { return draw(cr); }); } bool screen_widget::draw(const Cairo::RefPtr<Cairo::Context>& cr) { const auto rowstride = pixbuf->get_rowstride(); auto first = begin(ram.data) + 0x4000; auto last = begin(ram.data) + 0x6000; guchar* row = pixbuf->get_pixels(); uint16_t value = 0; for (unsigned int y = 0; y < SCREEN_HEIGHT; ++y) { guchar* p = row; for (unsigned int x = 0; x < SCREEN_WIDTH; ++x) { if ((x % 16) == 0) { assert (first != last); value = *first++; } const auto color = (value & 1) ? 0x00 : 0xff; value = value >> 1; *p++ = color; *p++ = color; *p++ = color; } row += rowstride; } Gdk::Cairo::set_source_pixbuf(cr, pixbuf, 0, 0); cr->paint(); return false; } emulator::emulator() : keyboard("Grab keyboard focus") , load_dialog(window, "Load ROM") , error_dialog(window, "Error loading program", false, Gtk::MessageType::MESSAGE_ERROR, Gtk::ButtonsType::BUTTONS_CLOSE, true) , screen(ram) { /* toolbar buttons */ setup_button(button_load, "document-open", "Load..."); setup_button(button_run, "media-playback-start", "Run"); setup_button(button_pause, "media-playback-pause", "Pause"); button_load.signal_clicked().connect([&] () { load_clicked(); }); button_run.signal_clicked().connect([&] () { run_clicked(); }); button_pause.signal_clicked().connect([&] () { pause_clicked(); }); button_run.set_sensitive(false); button_pause.set_sensitive(false); /* toolbar itself */ toolbar.set_hexpand(true); toolbar.set_toolbar_style(Gtk::ToolbarStyle::TOOLBAR_ICONS); toolbar.insert(button_load, -1); toolbar.insert(separator, -1); toolbar.insert(button_run, -1); toolbar.insert(button_pause, -1); /* keyboard */ keyboard.add_events(Gdk::EventMask::KEY_PRESS_MASK | Gdk::EventMask::KEY_RELEASE_MASK); keyboard.signal_key_press_event().connect([&] (GdkEventKey* event) { return keyboard_callback(event); }); keyboard.signal_key_release_event().connect([&] (GdkEventKey* event) { return keyboard_callback(event); }); /* main layout */ grid.attach(toolbar, 0, 0, 1, 1); grid.attach(screen, 0, 1, 1, 1); grid.attach(keyboard, 0, 2, 1, 1); /* main window */ window.set_title("HACK emulator"); window.set_resizable(false); window.add(grid); window.show_all(); button_pause.set_visible(false); load_dialog.add_button("gtk-cancel", GTK_RESPONSE_CANCEL); load_dialog.add_button("gtk-open", GTK_RESPONSE_ACCEPT); } void emulator::setup_button(Gtk::ToolButton& button, const gchar* stock_id, const gchar* text) { button.set_label(text); button.set_tooltip_text(text); button.set_icon_name(stock_id); } void emulator::load_clicked() { const gint result = load_dialog.run(); load_dialog.hide(); if (result != GTK_RESPONSE_ACCEPT) { return; } auto filename = load_dialog.get_filename(); const bool loaded = rom.load(filename.c_str()); if (!loaded) { error_dialog.run(); error_dialog.hide(); return; } cpu.reset(); button_run.set_sensitive(true); } void emulator::run_clicked() { assert(!running); running = true; button_run.set_sensitive(false); button_run.set_visible(false); button_pause.set_sensitive(true); button_pause.set_visible(true); g_thread_new("c_cpu_thread", c_cpu_thread, this); g_thread_new("c_screen_thread", c_screen_thread, this); } void emulator::pause_clicked() { assert(running); running = false; button_pause.set_sensitive(false); button_pause.set_visible(false); button_run.set_sensitive(true); button_run.set_visible(true); } bool emulator::keyboard_callback(GdkEventKey* event) { if (event->type == GDK_KEY_RELEASE) { ram.keyboard(0); } else { ram.keyboard(translate(event->keyval)); } return true; } void emulator::cpu_thread() { int steps = 0; while (running) { cpu.step(&rom, &ram); if (steps>100) { g_usleep(10); steps = 0; } ++steps; } } void emulator::screen_thread() { while (running) { Glib::signal_idle().connect_once([&] () { screen.queue_draw(); }); g_usleep(10000); } } } // anonymous namespace int main(int argc, char *argv[]) { Glib::RefPtr<Gtk::Application> app = Gtk::Application::create( argc, argv, "hcc.emulator"); emulator e; return app->run(e.window); } <commit_msg>Use standard threads<commit_after>// Copyright (c) 2012-2015 Dano Pernis // See LICENSE for details #include "CPU.h" #include <cassert> #include <fstream> #include <gtkmm.h> #include <iostream> #include <mutex> #include <stdexcept> #include <thread> #include <vector> // sigc workaround namespace sigc { SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE } namespace { const unsigned int SCREEN_WIDTH = 512; const unsigned int SCREEN_HEIGHT = 256; struct ROM : public hcc::IROM { ROM() : data(0x8000, 0) { } uint16_t get(unsigned int address) const override { return data.at(address); } bool load(const char* filename); std::vector<uint16_t> data; }; struct RAM : public hcc::IRAM { RAM() : data(0x6001, 0) { } uint16_t get(unsigned int address) const override { return data.at(address); } void set(unsigned int address, uint16_t value) override { data.at(address) = value; } void keyboard(uint16_t value) { set(0x6000, value); }; std::vector<uint16_t> data; }; struct screen_widget : Gtk::DrawingArea { screen_widget(RAM& ram); bool draw(const Cairo::RefPtr<Cairo::Context>& cr); private: Glib::RefPtr<Gdk::Pixbuf> pixbuf; RAM& ram; }; struct emulator { emulator(); ~emulator() { pause(); } void load_clicked(); void run_clicked(); void pause_clicked(); bool keyboard_callback(GdkEventKey* event); void cpu_thread(); void screen_thread(); void setup_button(Gtk::ToolButton& button, const gchar* stock_id, const gchar* text); ROM rom; RAM ram; hcc::CPU cpu; private: std::thread thread_cpu; std::thread thread_screen; std::mutex running_mutex; bool running = false; public: void run() { std::lock_guard<std::mutex> lock(running_mutex); if (running) { return; } running = true; thread_cpu = std::thread([&] { cpu_thread(); }); thread_screen = std::thread([&] { screen_thread(); }); } void pause() { std::lock_guard<std::mutex> lock(running_mutex); if (!running) { return; } running = false; thread_cpu.join(); thread_screen.join(); } Gtk::SeparatorToolItem separator; Gtk::Toolbar toolbar; Gtk::ToggleButton keyboard; Gtk::Grid grid; Gtk::Window window; Gtk::FileChooserDialog load_dialog; Gtk::MessageDialog error_dialog; Gtk::ToolButton button_load; Gtk::ToolButton button_run; Gtk::ToolButton button_pause; screen_widget screen; }; // Translate special keys. See Figure 5.6 in TECS book. uint16_t translate(guint keyval) { switch (keyval) { case GDK_KEY_Return: return 128; case GDK_KEY_BackSpace: return 129; case GDK_KEY_Left: return 130; case GDK_KEY_Up: return 131; case GDK_KEY_Right: return 132; case GDK_KEY_Down: return 133; case GDK_KEY_Home: return 134; case GDK_KEY_End: return 135; case GDK_KEY_Page_Up: return 136; case GDK_KEY_Page_Down: return 137; case GDK_KEY_Insert: return 138; case GDK_KEY_Delete: return 139; case GDK_KEY_Escape: return 140; case GDK_KEY_F1: return 141; case GDK_KEY_F2: return 142; case GDK_KEY_F3: return 143; case GDK_KEY_F4: return 144; case GDK_KEY_F5: return 145; case GDK_KEY_F6: return 146; case GDK_KEY_F7: return 147; case GDK_KEY_F8: return 148; case GDK_KEY_F9: return 149; case GDK_KEY_F10: return 150; case GDK_KEY_F11: return 151; case GDK_KEY_F12: return 152; } return keyval; } bool ROM::load(const char* filename) { std::ifstream input(filename); std::string line; auto it = begin(data); while (input.good() && it != end(data)) { getline(input, line); if (line.size() == 0) { continue; } if (line.size() != 16) { return false; } unsigned int instruction = 0; for (unsigned int i = 0; i<16; ++i) { instruction <<= 1; switch (line[i]) { case '0': break; case '1': instruction |= 1; break; default: return false; } } *it++ = instruction; } // clear the rest while (it != end(data)) { *it++ = 0; } return true; } screen_widget::screen_widget(RAM& ram) : pixbuf( Gdk::Pixbuf::create(Gdk::Colorspace::COLORSPACE_RGB, false, 8, SCREEN_WIDTH, SCREEN_HEIGHT)) , ram(ram) { set_size_request(SCREEN_WIDTH, SCREEN_HEIGHT); signal_draw().connect([&] (const Cairo::RefPtr<Cairo::Context>& cr) { return draw(cr); }); } bool screen_widget::draw(const Cairo::RefPtr<Cairo::Context>& cr) { const auto rowstride = pixbuf->get_rowstride(); auto first = begin(ram.data) + 0x4000; auto last = begin(ram.data) + 0x6000; guchar* row = pixbuf->get_pixels(); uint16_t value = 0; for (unsigned int y = 0; y < SCREEN_HEIGHT; ++y) { guchar* p = row; for (unsigned int x = 0; x < SCREEN_WIDTH; ++x) { if ((x % 16) == 0) { assert (first != last); value = *first++; } const auto color = (value & 1) ? 0x00 : 0xff; value = value >> 1; *p++ = color; *p++ = color; *p++ = color; } row += rowstride; } Gdk::Cairo::set_source_pixbuf(cr, pixbuf, 0, 0); cr->paint(); return false; } emulator::emulator() : keyboard("Grab keyboard focus") , load_dialog(window, "Load ROM") , error_dialog(window, "Error loading program", false, Gtk::MessageType::MESSAGE_ERROR, Gtk::ButtonsType::BUTTONS_CLOSE, true) , screen(ram) { /* toolbar buttons */ setup_button(button_load, "document-open", "Load..."); setup_button(button_run, "media-playback-start", "Run"); setup_button(button_pause, "media-playback-pause", "Pause"); button_load.signal_clicked().connect([&] () { load_clicked(); }); button_run.signal_clicked().connect([&] () { run_clicked(); }); button_pause.signal_clicked().connect([&] () { pause_clicked(); }); button_run.set_sensitive(false); button_pause.set_sensitive(false); /* toolbar itself */ toolbar.set_hexpand(true); toolbar.set_toolbar_style(Gtk::ToolbarStyle::TOOLBAR_ICONS); toolbar.insert(button_load, -1); toolbar.insert(separator, -1); toolbar.insert(button_run, -1); toolbar.insert(button_pause, -1); /* keyboard */ keyboard.add_events(Gdk::EventMask::KEY_PRESS_MASK | Gdk::EventMask::KEY_RELEASE_MASK); keyboard.signal_key_press_event().connect([&] (GdkEventKey* event) { return keyboard_callback(event); }); keyboard.signal_key_release_event().connect([&] (GdkEventKey* event) { return keyboard_callback(event); }); /* main layout */ grid.attach(toolbar, 0, 0, 1, 1); grid.attach(screen, 0, 1, 1, 1); grid.attach(keyboard, 0, 2, 1, 1); /* main window */ window.set_title("HACK emulator"); window.set_resizable(false); window.add(grid); window.show_all(); button_pause.set_visible(false); load_dialog.add_button("gtk-cancel", GTK_RESPONSE_CANCEL); load_dialog.add_button("gtk-open", GTK_RESPONSE_ACCEPT); } void emulator::setup_button(Gtk::ToolButton& button, const gchar* stock_id, const gchar* text) { button.set_label(text); button.set_tooltip_text(text); button.set_icon_name(stock_id); } void emulator::load_clicked() { const gint result = load_dialog.run(); load_dialog.hide(); if (result != GTK_RESPONSE_ACCEPT) { return; } auto filename = load_dialog.get_filename(); const bool loaded = rom.load(filename.c_str()); if (!loaded) { error_dialog.run(); error_dialog.hide(); return; } cpu.reset(); button_run.set_sensitive(true); } void emulator::run_clicked() { run(); button_run.set_sensitive(false); button_run.set_visible(false); button_pause.set_sensitive(true); button_pause.set_visible(true); } void emulator::pause_clicked() { pause(); button_pause.set_sensitive(false); button_pause.set_visible(false); button_run.set_sensitive(true); button_run.set_visible(true); } bool emulator::keyboard_callback(GdkEventKey* event) { if (event->type == GDK_KEY_RELEASE) { ram.keyboard(0); } else { ram.keyboard(translate(event->keyval)); } return true; } void emulator::cpu_thread() { int steps = 0; while (running) { cpu.step(&rom, &ram); if (steps>100) { std::this_thread::sleep_for(std::chrono::microseconds(10)); steps = 0; } ++steps; } } void emulator::screen_thread() { while (running) { Glib::signal_idle().connect_once([&] () { screen.queue_draw(); }); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } } // anonymous namespace int main(int argc, char *argv[]) { Glib::RefPtr<Gtk::Application> app = Gtk::Application::create( argc, argv, "hcc.emulator"); emulator e; return app->run(e.window); } <|endoftext|>
<commit_before> /* This program sums all rows in an array using MPI parallelism. * The root process acts as a master and sends a portion of the * array to each child process. Master and child processes then * all calculate a partial sum of the portion of the array assigned * to them, and the child processes send their partial sums to * the master, who calculates a grand total. **/ #include <stdio.h> #include <mpi.h> #define max_rows 100000 #define send_data_tag 2001 #define return_data_tag 2002 int array[max_rows]; int array2[max_rows]; main(int argc, char **argv) { long int sum, partial_sum; MPI_Status status; int my_id, root_process, ierr, i, num_rows, num_procs, an_id, num_rows_to_receive, avg_rows_per_process, sender, num_rows_received, start_row, end_row, num_rows_to_send; /* Now replicte this process to create parallel processes. * From this point on, every process executes a seperate copy * of this program */ ierr = MPI_Init(&argc, &argv); root_process = 0; /* find out MY process ID, and how many processes were started. */ ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id); ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs); if(my_id == root_process) { /* I must be the root process, so I will query the user * to determine how many numbers to sum. */ printf("please enter the number of numbers to sum: "); scanf("%i", &num_rows); if(num_rows > max_rows) { printf("Too many numbers.\n"); exit(1); } avg_rows_per_process = num_rows / num_procs; /* initialize an array */ for(i = 0; i < num_rows; i++) { array[i] = i + 1; } /* distribute a portion of the bector to each child process */ for(an_id = 1; an_id < num_procs; an_id++) { start_row = an_id*avg_rows_per_process + 1; end_row = (an_id + 1)*avg_rows_per_process; if((num_rows - end_row) < avg_rows_per_process) end_row = num_rows - 1; num_rows_to_send = end_row - start_row + 1; ierr = MPI_Send( &num_rows_to_send, 1 , MPI_INT, an_id, send_data_tag, MPI_COMM_WORLD); ierr = MPI_Send( &array[start_row], num_rows_to_send, MPI_INT, an_id, send_data_tag, MPI_COMM_WORLD); } /* and calculate the sum of the values in the segment assigned * to the root process */ sum = 0; for(i = 0; i < avg_rows_per_process + 1; i++) { sum += array[i]; } printf("sum %i calculated by root process\n", sum); /* and, finally, I collet the partial sums from the slave processes, * print them, and add them to the grand sum, and print it */ for(an_id = 1; an_id < num_procs; an_id++) { ierr = MPI_Recv( &partial_sum, 1, MPI_LONG, MPI_ANY_SOURCE, return_data_tag, MPI_COMM_WORLD, &status); sender = status.MPI_SOURCE; printf("Partial sum %i returned from process %i\n", partial_sum, sender); sum += partial_sum; } printf("The grand total is: %i\n", sum); } else { /* I must be a slave process, so I must receive my array segment, * storing it in a "local" array, array1. */ ierr = MPI_Recv( &num_rows_to_receive, 1, MPI_INT, root_process, send_data_tag, MPI_COMM_WORLD, &status); ierr = MPI_Recv( &array2, num_rows_to_receive, MPI_INT, root_process, send_data_tag, MPI_COMM_WORLD, &status); num_rows_received = num_rows_to_receive; /* Calculate the sum of my portion of the array */ partial_sum = 0; for(i = 0; i < num_rows_received; i++) { partial_sum += array2[i]; } /* and finally, send my partial sum to hte root process */ ierr = MPI_Send( &partial_sum, 1, MPI_LONG, root_process, return_data_tag, MPI_COMM_WORLD); } ierr = MPI_Finalize(); }<commit_msg>Deleted example.cpp<commit_after><|endoftext|>
<commit_before>#include "feUtils.h" <commit_msg>Implementations of algorithms<commit_after>#include "feUtils.h" #include <vector> #include <cmath> /** * Parameters: * character_stats: vector of ints containing * values of the necessary character/weapon stats needed * for calculating the actual attack of a character * * Return: Nothing */ void feUtils::setAttack(const std::vector<int>& character_stats) { std::vector<int>::iterator itr = character_stats.begin(); for( ; itr != character_stats.end(); ++itr) attack += *itr; } /** * Parameters: * weapon_stats: vector of ints containing * values of the necessary character/weapon stats needed * for calculating the actual hit rate of a character * * Return: Nothing */ void feUtils::setHitRate(const std::vector<int>& weapon_stats) { hit_rate = weapon_stats[0] + ((weapon_stats[1] * 3) + ceil(weapon_stats[2])/2) + weapon_stats[4]; } /** * Parameters: * character_stats: vector of ints containing * values of the necessary character/weapon stats needed * for calculating the actual critical rate of a character * * Return: Nothing */ void feUtils::setCritical(const std::vector<int>& character_stats) { critical = character_stats[0] + ceil(character_stats[1]/2); } /** * Parameters: * character_stats: vector of ints containing * values of the necessary character/weapon stats needed * for calculating the actual avoid rate of a character * * Return: Nothing */ void feUtils::setAvoid(const std::vector<int>& character_stats) { avoid = ceil(((character_stats[0] * 3) + character_stats[1])/2); } /** * Parameters: * character_stats: vector of ints containing * values of the necessary character/weapon stats needed * for calculating the rating of a character * * Return: Nothing */ void feUtils::setRating(const std::vector<int>& character_stats) { std::vector<int>::iterator itr = character_stats.begin(); for( ; itr != character_stats.end(); ++itr) rating += *itr; } /** * Parameters: None * * Modifies: Sets all the combat stats back to zero. Use when a * character level ups or changes weapons, so that the proper values * can be recalculated * * Notes: Might not be needed if at the start of every "set" method, * resets the specified stat to 0 to calculate, since most likely * calling that method because it needs to be reset anyways. That * way can avoid having to reset everything at once. */ void feUtils::resetCombatStats() { attack = 0; hit_rate = 0; critical = 0; avoid = 0; rating = 0; } <|endoftext|>
<commit_before>#include <iterator> #include <vector> #include <sstream> #include <iomanip> #include <algorithm> #include <map> #include <ut/throwf.hxx> #include "handler.hxx" #include "grammar.hxx" #include "parser_action.hxx" #include "parser_state.hxx" namespace cl { void handler::check_required() { // Check if there ary any arguments that are required but not supplied for (auto& arg : m_Arguments) { auto& ptr = arg.second; if (ptr->required() && !ptr->supplied()) ut::throwf<std::runtime_error>("Required argument \"--%s\" was not supplied!", ptr->long_name().c_str()); } } void handler::check_exclusive() { // Maps group name to argument name std::map<std::string, std::string> t_map; for (auto& elem : m_Arguments) { auto& arg = elem.second; if (arg->supplied() && arg->exclusive()) { auto it = t_map.find(arg->exclusive_group()); if (it == t_map.end()) t_map[arg->exclusive_group()] = arg->long_name(); else ut::throwf<std::runtime_error>("\"--%s\": Already supplied argument \"--%s\" for exclusive group \"%s\"!", arg->long_name().c_str(), it->second.c_str(), it->first.c_str()); } } } auto handler::print_help() const -> void { std::cout << "help" << std::endl; } auto handler::read(int argc, const char* argv[]) -> bool { try { std::ostringstream ss{}; for (int ix = 1; ix < argc; ++ix) { ss << std::quoted(argv[ix]) << ' '; } internal::parser_state state{}; //pegtl::string_parser parser{ ss.str(), "" }; //parser.parse<internal::R_Commandline, internal::parser_action>(*this, state); pegtl::parse<internal::R_Commandline, internal::parser_action>(ss.str(), "", *this, state); // Call read_end on all arguments to refresh references etc for (auto& arg : m_Arguments) arg.second->read_end(); // Perform after-read tasks and checks check_required(); check_exclusive(); return true; } catch(const ::std::exception& p_ex) { // Handle error according to current error_mode. return handle_error(p_ex); } } auto handler::handle_error(const ::std::exception& p_ex) -> bool { // Select action based on current error_mode switch (m_Data.m_ErrorMode) { case internal::error_mode_::custom_handler: { // If no callback is registered rethrow exception if(m_Data.m_ErrorHandler) { m_Data.m_ErrorHandler(p_ex.what()); break; } else rethrow_error(); break; } case internal::error_mode_::return_value: { return false; break; } case internal::error_mode_::terminate: { if(m_Data.m_PrintHelp) print_help(); ::std::exit(EXIT_FAILURE); } case internal::error_mode_::throw_exception: default: { rethrow_error(); break; } } return false; } auto handler::rethrow_error() -> void { ::std::rethrow_exception(::std::current_exception()); } auto handler::argument_long(const std::string& p_name) const -> internal::argument_base* { // TODO make throw optional using flag argument auto it = m_Arguments.find(p_name); if (it != m_Arguments.end()) return it->second.get(); else ut::throwf<std::runtime_error>("Unknown commandline argument: \"--%s\"", p_name.c_str()); } auto handler::argument_short(char p_name) const -> internal::argument_base* { auto it = std::find_if(m_Arguments.begin(), m_Arguments.end(), [p_name](const auto& elem) -> bool { auto& t_tmp = elem.second; return t_tmp->has_short_name() && (t_tmp->short_name() == p_name); } ); if(it != m_Arguments.end()) return it->second.get(); else ut::throwf<std::runtime_error>("Unknown commandline argument: \"-%c\"", p_name); } auto handler::argument_str(const std::string& p_name, bool p_short) const -> internal::argument_base* { return p_short ? argument_short(p_name.at(0)) : argument_long(p_name); } auto handler::argument(size_t p_id) const -> internal::argument_base* { auto it = m_ArgMap.find(p_id); if (it != m_ArgMap.end()) return it->second.get(); else ut::throwf<std::runtime_error>("Unknown commandline argument ID: \"%u\"", p_id); } void handler::add_internal(std::unique_ptr<internal::argument_base> p_ptr) { if (p_ptr->has_id()) m_ArgMap[p_ptr->id()] = ut::make_observer<internal::argument_base>(p_ptr.get()); // Add argument and hand over ownership m_Arguments[p_ptr->long_name()] = std::move(p_ptr); } } <commit_msg>Fixed cl::terminate not displaying error message.<commit_after>#include <iterator> #include <vector> #include <sstream> #include <iomanip> #include <algorithm> #include <map> #include <ut/throwf.hxx> #include "handler.hxx" #include "grammar.hxx" #include "parser_action.hxx" #include "parser_state.hxx" namespace cl { void handler::check_required() { // Check if there ary any arguments that are required but not supplied for (auto& arg : m_Arguments) { auto& ptr = arg.second; if (ptr->required() && !ptr->supplied()) ut::throwf<std::runtime_error>("Required argument \"--%s\" was not supplied!", ptr->long_name().c_str()); } } void handler::check_exclusive() { // Maps group name to argument name std::map<std::string, std::string> t_map; for (auto& elem : m_Arguments) { auto& arg = elem.second; if (arg->supplied() && arg->exclusive()) { auto it = t_map.find(arg->exclusive_group()); if (it == t_map.end()) t_map[arg->exclusive_group()] = arg->long_name(); else ut::throwf<std::runtime_error>("\"--%s\": Already supplied argument \"--%s\" for exclusive group \"%s\"!", arg->long_name().c_str(), it->second.c_str(), it->first.c_str()); } } } auto handler::print_help() const -> void { std::cout << "help" << std::endl; } auto handler::read(int argc, const char* argv[]) -> bool { try { std::ostringstream ss{}; for (int ix = 1; ix < argc; ++ix) { ss << std::quoted(argv[ix]) << ' '; } internal::parser_state state{}; //pegtl::string_parser parser{ ss.str(), "" }; //parser.parse<internal::R_Commandline, internal::parser_action>(*this, state); pegtl::parse<internal::R_Commandline, internal::parser_action>(ss.str(), "", *this, state); // Call read_end on all arguments to refresh references etc for (auto& arg : m_Arguments) arg.second->read_end(); // Perform after-read tasks and checks check_required(); check_exclusive(); return true; } catch(const ::std::exception& p_ex) { // Handle error according to current error_mode. return handle_error(p_ex); } } auto handler::handle_error(const ::std::exception& p_ex) -> bool { // Select action based on current error_mode switch (m_Data.m_ErrorMode) { case internal::error_mode_::custom_handler: { // If no callback is registered rethrow exception if(m_Data.m_ErrorHandler) { m_Data.m_ErrorHandler(p_ex.what()); break; } else rethrow_error(); break; } case internal::error_mode_::return_value: { return false; break; } case internal::error_mode_::terminate: { // Print out error message ::std::cout << p_ex.what() << std::endl; if(m_Data.m_PrintHelp) print_help(); ::std::exit(EXIT_FAILURE); } case internal::error_mode_::throw_exception: default: { rethrow_error(); break; } } return false; } auto handler::rethrow_error() -> void { ::std::rethrow_exception(::std::current_exception()); } auto handler::argument_long(const std::string& p_name) const -> internal::argument_base* { // TODO make throw optional using flag argument auto it = m_Arguments.find(p_name); if (it != m_Arguments.end()) return it->second.get(); else ut::throwf<std::runtime_error>("Unknown commandline argument: \"--%s\"", p_name.c_str()); } auto handler::argument_short(char p_name) const -> internal::argument_base* { auto it = std::find_if(m_Arguments.begin(), m_Arguments.end(), [p_name](const auto& elem) -> bool { auto& t_tmp = elem.second; return t_tmp->has_short_name() && (t_tmp->short_name() == p_name); } ); if(it != m_Arguments.end()) return it->second.get(); else ut::throwf<std::runtime_error>("Unknown commandline argument: \"-%c\"", p_name); } auto handler::argument_str(const std::string& p_name, bool p_short) const -> internal::argument_base* { return p_short ? argument_short(p_name.at(0)) : argument_long(p_name); } auto handler::argument(size_t p_id) const -> internal::argument_base* { auto it = m_ArgMap.find(p_id); if (it != m_ArgMap.end()) return it->second.get(); else ut::throwf<std::runtime_error>("Unknown commandline argument ID: \"%u\"", p_id); } void handler::add_internal(std::unique_ptr<internal::argument_base> p_ptr) { if (p_ptr->has_id()) m_ArgMap[p_ptr->id()] = ut::make_observer<internal::argument_base>(p_ptr.get()); // Add argument and hand over ownership m_Arguments[p_ptr->long_name()] = std::move(p_ptr); } } <|endoftext|>
<commit_before>#include <Rcpp.h> #include <iostream> #include <fstream> #include <string> #include <regex> using namespace Rcpp; using namespace std; static CharacterVector clientIp; static CharacterVector clientPort; static CharacterVector acceptDate; static CharacterVector frontendName; static CharacterVector backendName; static CharacterVector serverName; static IntegerVector tq; static IntegerVector tw; static IntegerVector tc; static IntegerVector tr; static IntegerVector tt; static IntegerVector statusCode; static IntegerVector bytesRead; static CharacterVector capturedRequestCookie; static CharacterVector capturedResponseCookie; static CharacterVector terminationState; static IntegerVector actconn; static IntegerVector feconn; static IntegerVector beconn; static IntegerVector srvConn; static IntegerVector retries; static IntegerVector serverQueue; static IntegerVector backendQueue; int get_number_lines(String fileName) { std::ifstream inFile(fileName); return std::count(std::istreambuf_iterator<char>(inFile), std::istreambuf_iterator<char>(), '\n'); } int stoi_ignore_err(string s) { int i = 0; try { i = stoi(s); } catch(...) { // ignore } return i; } void parse(string current_line, int i) { // for fields definitions, see http://cbonte.github.io/haproxy-dconv/configuration-1.4.html#8.2.3 const std::regex re ( // process_name '[' pid ']:' # E.g. haproxy[14389]: "^(.*?):" // client_ip ':' client_port # E.g. 10.0.1.2:33317 " (\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b):(\\d*)" // '[' accept_date ']' # E.g. [06/Feb/2009:12:14:14.655] " \\[(\\d{2}/[a-zA-Z]{3}/\\d{4}:\\d{2}:\\d{2}:\\d{2}.\\d{3})\\]" // frontend_name # E.g. http-in " (\\S*)" // backend_name # E.g. backend_name '/' server_name " (.*?)/(.*?)" // Tq '/' Tw '/' Tc '/' Tr '/' Tt* # E.g. 10/0/30/69/109 " (\\d*)/(\\d*)/(\\d*)/(\\d*)/(\\d*)" // status_code # E.g. 200 " (\\d{3})" // bytes_read # E.g. 2750 " (\\d*)" #if CAPTURED_REQUEST_COOKIE_FIELD == 1 // captured_request_cookie # E.g. - " (\\S*)" #endif #if CAPTURED_RESPONSE_COOKIE_FIELD == 1 // captured_response_cookie # E.g. - " (\\S*)" #endif // termination_state # E.g. ---- "\\s+(\\S*)" // actconn '/' feconn '/' beconn '/' srv_conn '/' retries* # E.g 1/1/1/1/0 " (\\d*)/(\\d*)/(\\d*)/(\\d*)/(\\d*)" // srv_queue '/' backend_queue # E.g. 0/0 " (\\d*)/(\\d*)" /* 14 '{' captured_request_headers* '}' {haproxy.1wt.eu} 15 '{' captured_response_headers* '}' {} 16 '"' http_request '"' "GET /index.html HTTP/1.1" */ // discard everything else " .*$" ); std::smatch sm; std::regex_match (current_line, sm, re); int startMatchGroup = 2; clientIp[i] = Rcpp::String(sm[startMatchGroup++]); clientPort[i] = Rcpp::String(sm[startMatchGroup++]); acceptDate[i] = Rcpp::String(sm[startMatchGroup++]); frontendName[i] = Rcpp::String(sm[startMatchGroup++]); backendName[i] = Rcpp::String(sm[startMatchGroup++]); serverName[i] = Rcpp::String(sm[startMatchGroup++]); tq[i] = stoi_ignore_err(sm[startMatchGroup++]); tw[i] = stoi_ignore_err(sm[startMatchGroup++]); tc[i] = stoi_ignore_err(sm[startMatchGroup++]); tr[i] = stoi_ignore_err(sm[startMatchGroup++]); tt[i] = stoi_ignore_err(sm[startMatchGroup++]); statusCode[i] = stoi_ignore_err(sm[startMatchGroup++]); bytesRead[i] = stoi_ignore_err(sm[startMatchGroup++]); #if CAPTURED_REQUEST_COOKIE_FIELD == 1 capturedRequestCookie[i] = Rcpp::String(sm[startMatchGroup++]); #endif #if CAPTURED_RESPONSE_COOKIE_FIELD == 1 capturedResponseCookie[i] = Rcpp::String(sm[startMatchGroup++]); #endif terminationState[i] = Rcpp::String(sm[startMatchGroup++]); actconn[i] = stoi_ignore_err(sm[startMatchGroup++]); feconn[i] = stoi_ignore_err(sm[startMatchGroup++]); beconn[i] = stoi_ignore_err(sm[startMatchGroup++]); srvConn[i] = stoi_ignore_err(sm[startMatchGroup++]); retries[i] = stoi_ignore_err(sm[startMatchGroup++]); serverQueue[i] = stoi_ignore_err(sm[startMatchGroup++]); backendQueue[i] = stoi_ignore_err(sm[startMatchGroup++]); } // [[Rcpp::export]] DataFrame haproxy_read(String fileName) { int vsize = get_number_lines(fileName) + 1; clientIp = CharacterVector(vsize); clientPort = CharacterVector(vsize); acceptDate = CharacterVector(vsize); frontendName = CharacterVector(vsize); backendName = CharacterVector(vsize); serverName = CharacterVector(vsize); tq = IntegerVector(vsize); tw = IntegerVector(vsize); tc = IntegerVector(vsize); tr = IntegerVector(vsize); tt = IntegerVector(vsize); statusCode = IntegerVector(vsize); bytesRead = IntegerVector(vsize); #if CAPTURED_RESPONSE_COOKIE_FIELD == 1 capturedRequestCookie = CharacterVector(vsize); #endif #if CAPTURED_RESPONSE_COOKIE_FIELD == 1 capturedResponseCookie = CharacterVector(vsize); #endif terminationState = CharacterVector(vsize); actconn = IntegerVector(vsize); feconn = IntegerVector(vsize); beconn = IntegerVector(vsize); srvConn = IntegerVector(vsize); retries = IntegerVector(vsize); serverQueue = IntegerVector(vsize); backendQueue = IntegerVector(vsize); std::ifstream in(fileName); int i = 0; string current_line; while (!in.eof()) { getline(in, current_line, '\n'); parse(current_line, i); current_line.clear(); i++; } return DataFrame::create( _["clientIp"] = clientIp, _["clientPort"] = clientPort, _["acceptDate"] = acceptDate, _["frontendName"] = frontendName, _["backendName"] = backendName, _["serverName"] = serverName, _["tq"] = tq, _["tw"] = tw, _["tc"] = tc, _["tr"] = tr, _["tt"] = tt, _["status_code"] = statusCode, _["bytes_read"] = bytesRead, #if CAPTURED_REQUEST_COOKIE_FIELD == 1 _["capturedRequestCookie"] = capturedRequestCookie, #endif #if CAPTURED_REQUEST_COOKIE_FIELD == 1 _["capturedResponseCookie"] = capturedResponseCookie, #endif _["terminationState"] = terminationState, _["actconn"] = actconn, _["feconn"] = feconn, _["beconn"] = beconn, _["srv_conn"] = srvConn, _["retries"] = retries, _["serverQueue"] = serverQueue /*, _["backendQueue"] = backendQueue */ ); } <commit_msg>add remaining fields to regex<commit_after>#include <Rcpp.h> #include <iostream> #include <fstream> #include <string> #include <regex> using namespace Rcpp; using namespace std; // TODO move this to it's own file class ListBuilder { public: ListBuilder() {}; ~ListBuilder() {}; inline ListBuilder& add(std::string const& name, SEXP x) { names.push_back(name); // NOTE: we need to protect the SEXPs we pass in; there is // probably a nicer way to handle this but ... elements.push_back(PROTECT(x)); return *this; } inline operator List() const { List result(elements.size()); for (size_t i = 0; i < elements.size(); ++i) { result[i] = elements[i]; } result.attr("names") = wrap(names); UNPROTECT(elements.size()); return result; } inline operator DataFrame() const { List result = static_cast<List>(*this); result.attr("class") = "data.frame"; result.attr("row.names") = IntegerVector::create(NA_INTEGER, XLENGTH(elements[0])); return result; } private: std::vector<std::string> names; std::vector<SEXP> elements; ListBuilder(ListBuilder const&) {}; // not safe to copy }; // the R function code starts here static CharacterVector clientIp; static CharacterVector clientPort; static CharacterVector acceptDate; static CharacterVector frontendName; static CharacterVector backendName; static CharacterVector serverName; static IntegerVector tq; static IntegerVector tw; static IntegerVector tc; static IntegerVector tr; static IntegerVector tt; static IntegerVector statusCode; static IntegerVector bytesRead; static CharacterVector capturedRequestCookie; static CharacterVector capturedResponseCookie; static CharacterVector terminationState; static IntegerVector actconn; static IntegerVector feconn; static IntegerVector beconn; static IntegerVector srvConn; static IntegerVector retries; static IntegerVector serverQueue; static IntegerVector backendQueue; static CharacterVector capturedRequestHeaders; static CharacterVector capturedResponseHeaders; static CharacterVector httpRequest; int get_number_lines(String fileName) { std::ifstream inFile(fileName); return std::count(std::istreambuf_iterator<char>(inFile), std::istreambuf_iterator<char>(), '\n'); } int stoi_ignore_err(string s) { int i = 0; try { i = stoi(s); } catch(...) { // ignore } return i; } void parse(string current_line, int i) { // for fields definitions, see http://cbonte.github.io/haproxy-dconv/configuration-1.4.html#8.2.3 const std::regex re ( // process_name '[' pid ']:' # E.g. haproxy[14389]: "^(.*?):" // client_ip ':' client_port # E.g. 10.0.1.2:33317 " (\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b):(\\d*)" // '[' accept_date ']' # E.g. [06/Feb/2009:12:14:14.655] " \\[(\\d{2}/[a-zA-Z]{3}/\\d{4}:\\d{2}:\\d{2}:\\d{2}.\\d{3})\\]" // frontend_name # E.g. http-in " (\\S*)" // backend_name # E.g. backend_name '/' server_name " (.*?)/(.*?)" // Tq '/' Tw '/' Tc '/' Tr '/' Tt* # E.g. 10/0/30/69/109 " (\\d*)/(\\d*)/(\\d*)/(\\d*)/(\\d*)" // status_code # E.g. 200 " (\\d{3})" // bytes_read # E.g. 2750 " (\\d*)" #if CAPTURED_REQUEST_COOKIE_FIELD == 1 // captured_request_cookie # E.g. - " (\\S*)" #endif #if CAPTURED_RESPONSE_COOKIE_FIELD == 1 // captured_response_cookie # E.g. - " (\\S*)" #endif // termination_state # E.g. ---- "\\s+(\\S*)" // actconn '/' feconn '/' beconn '/' srv_conn '/' retries* # E.g 1/1/1/1/0 " (\\d*)/(\\d*)/(\\d*)/(\\d*)/(\\d*)" // srv_queue '/' backend_queue # E.g. 0/0 " (\\d*)/(\\d*)" // '{' captured_request_headers* '}' # E.g. {haproxy.1wt.eu} " \\{([^}]*)\\}" // '{' captured_response_headers* '}' # E.g {} " \\{([^}]*)\\}" // '"' http_request '"' # E.g. "GET /index.html HTTP/1.1" //" \"([^\"]*)\"" " \"(.*?)\"" // discard everything else //" .*$" ); std::smatch sm; std::regex_match (current_line, sm, re); int startMatchGroup = 2; clientIp[i] = Rcpp::String(sm[startMatchGroup++]); clientPort[i] = Rcpp::String(sm[startMatchGroup++]); acceptDate[i] = Rcpp::String(sm[startMatchGroup++]); frontendName[i] = Rcpp::String(sm[startMatchGroup++]); backendName[i] = Rcpp::String(sm[startMatchGroup++]); serverName[i] = Rcpp::String(sm[startMatchGroup++]); tq[i] = stoi_ignore_err(sm[startMatchGroup++]); tw[i] = stoi_ignore_err(sm[startMatchGroup++]); tc[i] = stoi_ignore_err(sm[startMatchGroup++]); tr[i] = stoi_ignore_err(sm[startMatchGroup++]); tt[i] = stoi_ignore_err(sm[startMatchGroup++]); statusCode[i] = stoi_ignore_err(sm[startMatchGroup++]); bytesRead[i] = stoi_ignore_err(sm[startMatchGroup++]); #if CAPTURED_REQUEST_COOKIE_FIELD == 1 capturedRequestCookie[i] = Rcpp::String(sm[startMatchGroup++]); #endif #if CAPTURED_RESPONSE_COOKIE_FIELD == 1 capturedResponseCookie[i] = Rcpp::String(sm[startMatchGroup++]); #endif terminationState[i] = Rcpp::String(sm[startMatchGroup++]); actconn[i] = stoi_ignore_err(sm[startMatchGroup++]); feconn[i] = stoi_ignore_err(sm[startMatchGroup++]); beconn[i] = stoi_ignore_err(sm[startMatchGroup++]); srvConn[i] = stoi_ignore_err(sm[startMatchGroup++]); retries[i] = stoi_ignore_err(sm[startMatchGroup++]); serverQueue[i] = stoi_ignore_err(sm[startMatchGroup++]); backendQueue[i] = stoi_ignore_err(sm[startMatchGroup++]); capturedRequestHeaders[i] = Rcpp::String(sm[startMatchGroup++]); capturedResponseHeaders[i] = Rcpp::String(sm[startMatchGroup++]); httpRequest[i] = Rcpp::String(sm[startMatchGroup++]); } // [[Rcpp::export]] DataFrame haproxy_read(String fileName) { int vsize = get_number_lines(fileName) + 1; clientIp = CharacterVector(vsize); clientPort = CharacterVector(vsize); acceptDate = CharacterVector(vsize); frontendName = CharacterVector(vsize); backendName = CharacterVector(vsize); serverName = CharacterVector(vsize); tq = IntegerVector(vsize); tw = IntegerVector(vsize); tc = IntegerVector(vsize); tr = IntegerVector(vsize); tt = IntegerVector(vsize); statusCode = IntegerVector(vsize); bytesRead = IntegerVector(vsize); #if CAPTURED_RESPONSE_COOKIE_FIELD == 1 capturedRequestCookie = CharacterVector(vsize); #endif #if CAPTURED_RESPONSE_COOKIE_FIELD == 1 capturedResponseCookie = CharacterVector(vsize); #endif terminationState = CharacterVector(vsize); actconn = IntegerVector(vsize); feconn = IntegerVector(vsize); beconn = IntegerVector(vsize); srvConn = IntegerVector(vsize); retries = IntegerVector(vsize); serverQueue = IntegerVector(vsize); backendQueue = IntegerVector(vsize); capturedRequestHeaders = CharacterVector(vsize); capturedResponseHeaders = CharacterVector(vsize); httpRequest = CharacterVector(vsize); std::ifstream in(fileName); int i = 0; string current_line; while (!in.eof()) { getline(in, current_line, '\n'); parse(current_line, i); current_line.clear(); i++; } return ListBuilder() .add("clientIp", clientIp) .add("clientPort", clientPort) .add("acceptDate", acceptDate) .add("frontendName", frontendName) .add("backendName", backendName) .add("serverName", serverName) .add("tq", tq) .add("tw", tw) .add("tc", tc) .add("tr", tr) .add("tt", tt) .add("status_code", statusCode) .add("bytes_read", bytesRead) #if CAPTURED_REQUEST_COOKIE_FIELD == 1 .add("capturedRequestCookie", capturedRequestCookie) #endif #if CAPTURED_REQUEST_COOKIE_FIELD == 1 .add("capturedResponseCookie", capturedResponseCookie) #endif .add("terminationState", terminationState) .add("actconn", actconn) .add("feconn", feconn) .add("beconn", beconn) .add("srv_conn", srvConn) .add("retries", retries) .add("serverQueue", serverQueue) .add("backendQueue", backendQueue) .add("capturedRequestHeaders", capturedRequestHeaders) .add("capturedResponseHeaders", capturedResponseHeaders) .add("httpRequest", httpRequest); }; <|endoftext|>
<commit_before>#include "../includes/declarations.h" void resetAll() { memset(arr,0,5000); z=0; next_level=false; if(play_game||lvlSelect) start_game=false; transx=0; transy=0; num_circles=0; red_black=0; mult=1; multflag=false; leftwall=true; rightwall=true; reflectionl=false; reflectionr=false; if(level==MAX_LEVELS) { level=0; start_game=true; play_game=lvlSelect=false; } genLevel(); } void init() { glClearColor( 245.0, 245.0, 245.0, 1.0); red_black=0; next_level=false; start_game=true; level=0; num_circles=0; mult=1; multflag=false; leftwall=true; rightwall=true; reflectionl=false; reflectionr=false; glLineWidth(5); glMatrixMode( GL_PROJECTION); gluOrtho2D(0.0,WIDTH,0.0,HEIGHT); memset(arr,0,5000); glPointSize(20.0); genLevel(); } float getOpenGLX(int x) { double ox = x/ (double)WIDTH*(WIDTH); return ox; } float getOpenGLY(int y) { double oy = (1 - y/ (double) HEIGHT)*HEIGHT; return oy; } void addValue(int x,int y) { arr[z][0]=getOpenGLX(x); arr[z++][1]=getOpenGLY(y); if(checkCollision(arr[z-1][0],arr[z-1][1])) { if(flag) { ptr=0; flag=0; } } } void keyPressed(unsigned char key, int x, int y) { if (key == 'm') { if(level==MAX_LEVELS) { resetAll(); } else { level++; if(level<MAX_LEVELS) resetAll(); else next_level=true; } } if (key == 'n') { if(level) level--; resetAll(); } if (key == 'r') { cout << key << "\n"; start_game = true; lvlSelect = false; play_game = false; level = 0; resetAll(); } if (key == 'q') { cout << "Thank you for playing!\n"; cout << "This game was designed by:\n"; cout << "Abraham Sebastian, 13IT103\n"; cout << "Kishor Bhat, 13IT114\n"; cout << "Chinmay Deshpande, 13IT210\n"; cout << "Sagar Ramprasad, 13IT233\n"; cout << "Pranav Konanur, 13IT228\n"; exit(0); } } void myMouseStat(int button,int state,int x, int y) { if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN) { if (highlight_lvls) { lvlSelect = true; highlight_lvls = false; resetAll(); } else if (highlight_play) { play_game = true; highlight_play = false; resetAll(); } else if (lvlSelect) { int fl = (int)((float) log10(circle_choose) / (float) log10(2)); cout << fl << "\n"; if (fl <= 8) { level = fl; play_game = true; lvlSelect = false; resetAll(); } } if(!flag) { if(temp_bit) { temp_bit=0; } resetAll(); flag=1; } } else if(button==GLUT_LEFT_BUTTON && state==GLUT_UP) { if(flag) { ptr=0; flag=0; } } } void myPressedMove(int x,int y) { if(flag) addValue(x,y); } void mouse_motion(int x, int y) { int cg_x = getOpenGLX(x), cg_y = getOpenGLY(y); if (start_game) { if (cg_x >= 0.367*WIDTH && cg_x <= 1.367*WIDTH && cg_y >= 0.492*HEIGHT && cg_y <= 0.542*HEIGHT) highlight_lvls = true; else highlight_lvls = false; if (cg_x >= 0.417*WIDTH && cg_x <= 0.8*WIDTH && cg_y >= 0.417*HEIGHT && cg_y <= 0.467*HEIGHT) highlight_play = true; else highlight_play = false; } if (lvlSelect) { for (int i = 0; i < 9; i++) { if (inCircle(cg_x, cg_y, circles[i].x, circles[i].y)) { circle_choose &= (int) pow(2, i); break; } else circle_choose = 511; } } } void myTimer(int t) { if(ptr!=z&&red_black==0) { ptr++; blackptr=0; ptrsave=ptr; } else if(ptr==z&&red_black==1) ptr=0; else { blackptr++; ptr=0; } glutTimerFunc(9,myTimer,0); }<commit_msg>Fixed Hover effect<commit_after>#include "../includes/declarations.h" void resetAll() { memset(arr,0,5000); z=0; next_level=false; if(play_game||lvlSelect) start_game=false; transx=0; transy=0; num_circles=0; red_black=0; mult=1; multflag=false; leftwall=true; rightwall=true; reflectionl=false; reflectionr=false; if(level==MAX_LEVELS) { level=0; start_game=true; play_game=lvlSelect=false; } genLevel(); } void init() { glClearColor( 245.0, 245.0, 245.0, 1.0); red_black=0; next_level=false; start_game=true; level=0; num_circles=0; mult=1; multflag=false; leftwall=true; rightwall=true; reflectionl=false; reflectionr=false; glLineWidth(5); glMatrixMode( GL_PROJECTION); gluOrtho2D(0.0,WIDTH,0.0,HEIGHT); memset(arr,0,5000); glPointSize(20.0); genLevel(); } float getOpenGLX(int x) { double ox = x/ (double)WIDTH*(WIDTH); return ox; } float getOpenGLY(int y) { double oy = (1 - y/ (double) HEIGHT)*HEIGHT; return oy; } void addValue(int x,int y) { arr[z][0]=getOpenGLX(x); arr[z++][1]=getOpenGLY(y); if(checkCollision(arr[z-1][0],arr[z-1][1])) { if(flag) { ptr=0; flag=0; } } } void keyPressed(unsigned char key, int x, int y) { if (key == 'm') { if(level==MAX_LEVELS) { resetAll(); } else { level++; if(level<MAX_LEVELS) resetAll(); else next_level=true; } } if (key == 'n') { if(level) level--; resetAll(); } if (key == 'r') { cout << key << "\n"; start_game = true; lvlSelect = false; play_game = false; level = 0; resetAll(); } if (key == 'q') { cout << "Thank you for playing!\n"; cout << "This game was designed by:\n"; cout << "Abraham Sebastian, 13IT103\n"; cout << "Kishor Bhat, 13IT114\n"; cout << "Chinmay Deshpande, 13IT210\n"; cout << "Sagar Ramprasad, 13IT233\n"; cout << "Pranav Konanur, 13IT228\n"; exit(0); } } void myMouseStat(int button,int state,int x, int y) { if(button==GLUT_LEFT_BUTTON && state==GLUT_DOWN) { if (highlight_lvls) { lvlSelect = true; highlight_lvls = false; resetAll(); } else if (highlight_play) { play_game = true; highlight_play = false; resetAll(); } else if (lvlSelect) { int fl = (int)((float) log10(circle_choose) / (float) log10(2)); cout << fl << "\n"; if (fl <= 8) { level = fl; play_game = true; lvlSelect = false; resetAll(); } } if(!flag) { if(temp_bit) { temp_bit=0; } resetAll(); flag=1; } } else if(button==GLUT_LEFT_BUTTON && state==GLUT_UP) { if(flag) { ptr=0; flag=0; } } } void myPressedMove(int x,int y) { if(flag) addValue(x,y); } void mouse_motion(int x, int y) { int cg_x = getOpenGLX(x), cg_y = getOpenGLY(y); if (start_game) { if (cg_x >= 0.367*WIDTH && cg_x <=0.495*WIDTH && cg_y >= 0.492*HEIGHT && cg_y <= 0.542*HEIGHT) highlight_lvls = true; else highlight_lvls = false; if (cg_x >= 0.417*WIDTH && cg_x <= 0.450*WIDTH && cg_y >= 0.417*HEIGHT && cg_y <= 0.467*HEIGHT) highlight_play = true; else highlight_play = false; } if (lvlSelect) { for (int i = 0; i < 9; i++) { if (inCircle(cg_x, cg_y, circles[i].x, circles[i].y)) { circle_choose &= (int) pow(2, i); break; } else circle_choose = 511; } } } void myTimer(int t) { if(ptr!=z&&red_black==0) { ptr++; blackptr=0; ptrsave=ptr; } else if(ptr==z&&red_black==1) ptr=0; else { blackptr++; ptr=0; } glutTimerFunc(9,myTimer,0); } <|endoftext|>
<commit_before>/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2015 Alexandre Kalendarev | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ part this code was derived from tarantool/msgpuck, author Roman Tsisyk for HHVM version 3.13 */ /* KindOfUninit = 0x00, // 00000000 KindOfNull = 0x01, // 00000001 KindOfBoolean = 0x09, // 00001001 9 KindOfInt64 = 0x11, // 00010001 17 KindOfDouble = 0x19, // 00011001 25 KindOfPersistentString = 0x1b, // 00011011 KindOfPersistentArray = 0x1d, // 00011101 KindOfString = 0x22, // 00100010 34 KindOfArray = 0x34, // 00110100 52 KindOfObject = 0x40, // 01000000 64 KindOfResource = 0x50, // 01010000 KindOfRef = 0x60, // 01100000 */ #include "hphp/runtime/ext/extension.h" #include "hphp/runtime/base/execution-context.h" // g_context #define MP_SOURCE 1 #include "msgpuck.h" #include "msgpack.h" namespace HPHP { #define BUFFSIZE 1024 static void printVariant(const Variant& data); static void packVariant(const Variant& el); static void test(const Array& el); static int sizeof_pack( const Array& data ) { int size = 0; for (int i=0; i < data.length(); i++) { Variant el(data[i]); switch(el.getType()) { case KindOfInt64 : { size += mp_sizeof_int( el.toInt64() ); break; } case KindOfNull : { size += mp_sizeof_nil(); break; } case KindOfString : { size += mp_sizeof_str( el.toString().length()); break; } case KindOfArray : { size += mp_sizeof_array( el.toArray().size() ); int arr_size = sizeof_pack( el.toArray() ); size += arr_size; break; } case KindOfDouble : size += mp_sizeof_float(el.toDouble()); break; case KindOfBoolean : size += mp_sizeof_bool(el.toBoolean()); break; default : g_context->write( "wrong\n"); } } return size; } static void arrayIteration(ArrayData* data, void (arrayIterationCb) (const Variant& , const Variant&)) { for (ssize_t pos = data->iter_begin(); pos != data->iter_end(); pos = data->iter_advance(pos)) { const Variant key = data->getKey(pos); const Variant val = data->getValue(pos); arrayIterationCb(key, val); } } static void encodeArrayElement(const Variant& key, const Variant& val) { packVariant(key); packVariant(val); } static void test(const Array& data) { printf( "call %s:%d\n", __FUNCTION__, __LINE__); for (ssize_t pos = data->iter_begin(); pos != data->iter_end(); pos = data->iter_advance(pos)) { const Variant key = data->getKey(pos); if (key.isString()) printf("key : [%s]\n", key.toString().c_str()); else if (key.isInteger()) printf("key : [%ld]\n", key.toInt64()); else printf("unknow type: %d", (int)key.getType()); } } static void packVariant(const Variant& el) { printf("packVariant type: %d\n", (int)el.getType()); switch(el.getType()) { case KindOfInt64 : { int64_t int_val = el.toInt64(); if (int_val >= 0) MsgpackExtension::BufferPtr = mp_encode_uint(MsgpackExtension::BufferPtr, int_val ); else MsgpackExtension::BufferPtr = mp_encode_int(MsgpackExtension::BufferPtr, int_val ); break; } case KindOfNull : { MsgpackExtension::BufferPtr = mp_encode_nil(MsgpackExtension::BufferPtr); break; } case KindOfBoolean : { MsgpackExtension::BufferPtr = mp_encode_bool(MsgpackExtension::BufferPtr, el.toBoolean()); break; } case KindOfString : { MsgpackExtension::BufferPtr = mp_encode_str(MsgpackExtension::BufferPtr, el.toString().c_str(), el.toString().length()); break; } case KindOfArray : { // тут надо проверить на тип массива, // если это массив без индексов, то сохранить как массив // иначе сохранить как карту (map) printf("packVariant Array\n"); test( el.toArray() ); MsgpackExtension::BufferPtr = mp_encode_map(MsgpackExtension::BufferPtr, el.toArray().length()); ArrayData* ad = el.toArray().get(); arrayIteration(ad, encodeArrayElement); break; } case KindOfDouble : { MsgpackExtension::BufferPtr = mp_encode_double(MsgpackExtension::BufferPtr, el.toDouble()); break; } default : raise_warning("error type of data element"); } }; void unpackElement( char **p, Variant* pout) { const char c = (**p); char * pos = *p; mp_type type = mp_typeof(c); switch(type) { case MP_NIL : { pout->setNull(); (*p)++; break; } case MP_UINT : { int64_t intval = mp_decode_uint(const_cast<const char**>(&pos)); *pout = intval; *p = pos; break; } case MP_INT : { int64_t intval = mp_decode_int(const_cast<const char**>(&pos)); *pout = intval; *p = pos; break; } case MP_STR : { uint32_t len = 0; const char * res = mp_decode_str(const_cast<const char**>(&pos), &len); *p = pos; *pout = String(StringData::Make( res, len, CopyString )); break; } case MP_BOOL : { const bool res = mp_decode_bool(const_cast<const char**>(&pos)); *p = pos; *pout = res ? true : false; break; } case MP_DOUBLE : { double dbl_val = mp_decode_double(const_cast<const char**>(&pos)); *pout = dbl_val; *p = pos; break; } case MP_ARRAY : { int count = mp_decode_array(const_cast<const char**>(&pos)); Array ret = Array::Create(); for(int i = 0; i < count; ++i) { Variant val; unpackElement( &pos, &val); ret.add(i,val); } *pout = ret; *p = pos; break; } case MP_MAP : { int count = mp_decode_map(const_cast<const char**>(&pos)); Array ret = Array::Create(); for(int i = 0; i < count; ++i) { Variant key, val; unpackElement( &pos, &key); unpackElement( &pos, &val); ret.add(key,val,true); } *pout = ret; *p = pos; break; } default : raise_warning("unpack error data element"); pout->setNull(); mp_next(const_cast<const char**>(p)); } } ////////////////////////////////////////////////////////////////////////////////////////////// void MsgpackExtension::moduleInit() { HHVM_FE(msgpack_pack); HHVM_FE(msgpack_unpack); loadSystemlib(); MsgpackExtension::BufferSize = BUFFSIZE; MsgpackExtension::Buffer = malloc(BUFFSIZE); } void MsgpackExtension::moduleShutdown() { free(MsgpackExtension::Buffer); // printf("moduleShutdown size=%d\n", MsgpackExtension::BufferSize); } ////////////////// static ///////////////////////// int MsgpackExtension::BufferSize = 0; int MsgpackExtension::Level = 0; void* MsgpackExtension::Buffer = NULL; char* MsgpackExtension::BufferPtr = NULL; static MsgpackExtension s_msgpack_extension; ////////////////// HHVM_FUNCTION ////////////////// static String HHVM_FUNCTION(msgpack_pack, const Array& data) { MsgpackExtension::Level = 0; MsgpackExtension::BufferPtr = static_cast<char*>(MsgpackExtension::Buffer); MsgpackExtension::BufferPtr = mp_encode_array( MsgpackExtension::BufferPtr, data.length()); for (int i = 0; i < data.length(); ++i) { packVariant(data[i]); } size_t len = reinterpret_cast<uint64_t>(MsgpackExtension::BufferPtr) - reinterpret_cast<uint64_t>(MsgpackExtension::Buffer); StringData* str = StringData::Make(reinterpret_cast<const char*>(MsgpackExtension::Buffer), len, CopyString); return String(str); } static Array HHVM_FUNCTION(msgpack_unpack, const String& data) { Array ret = Array::Create(); char * p = const_cast<char *>(data.c_str()); char c = *p; if ( mp_typeof(c) != MP_ARRAY ) { raise_warning("the root element must be array"); return ret; } int count = mp_decode_array( const_cast<const char**>(&p)); printf("elements %d\n", count); for (int i =0; i < count; i++) { Variant el; unpackElement(&p, &el); ret.set(i, el); } return ret; } HHVM_GET_MODULE(msgpack); } // namespace HPHP<commit_msg> modified: msgpack.cpp<commit_after>/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2015 Alexandre Kalendarev | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ part this code was derived from tarantool/msgpuck, author Roman Tsisyk for HHVM version 3.13 */ /* KindOfUninit = 0x00, // 00000000 0 KindOfNull = 0x01, // 00000001 1 KindOfBoolean = 0x09, // 00001001 9 KindOfInt64 = 0x11, // 00010001 17 KindOfDouble = 0x19, // 00011001 25 KindOfPersistentString = 0x1b, // 00011011 27 KindOfPersistentArray = 0x1d, // 00011101 29 KindOfString = 0x22, // 00100010 34 KindOfArray = 0x34, // 00110100 52 KindOfObject = 0x40, // 01000000 64 KindOfResource = 0x50, // 01010000 KindOfRef = 0x60, // 01100000 */ #include "hphp/runtime/ext/extension.h" #include "hphp/runtime/base/execution-context.h" // g_context #define MP_SOURCE 1 #include "msgpuck.h" #include "msgpack.h" namespace HPHP { #define BUFFSIZE 1024 static void printVariant(const Variant& data); static void packVariant(const Variant& el); static void test(const Array& el); static int sizeof_pack( const Array& data ) { int size = 0; for (int i=0; i < data.length(); i++) { Variant el(data[i]); switch(el.getType()) { case KindOfInt64 : { size += mp_sizeof_int( el.toInt64() ); break; } case KindOfNull : { size += mp_sizeof_nil(); break; } case KindOfString : { size += mp_sizeof_str( el.toString().length()); break; } case KindOfArray : { size += mp_sizeof_array( el.toArray().size() ); int arr_size = sizeof_pack( el.toArray() ); size += arr_size; break; } case KindOfDouble : size += mp_sizeof_float(el.toDouble()); break; case KindOfBoolean : size += mp_sizeof_bool(el.toBoolean()); break; default : g_context->write( "wrong\n"); } } return size; } static void arrayIteration(ArrayData* data, void (arrayIterationCb) (const Variant& , const Variant&)) { for (ssize_t pos = data->iter_begin(); pos != data->iter_end(); pos = data->iter_advance(pos)) { const Variant key = data->getKey(pos); const Variant val = data->getValue(pos); arrayIterationCb(key, val); } } static void encodeArrayElement(const Variant& key, const Variant& val) { packVariant(key); packVariant(val); } static void test(const Array& data) { printf( "call %s:%d\n", __FUNCTION__, __LINE__); for (ssize_t pos = data->iter_begin(); pos != data->iter_end(); pos = data->iter_advance(pos)) { const Variant key = data->getKey(pos); if (key.isString()) printf("key : [%s]\n", key.toString().c_str()); else if (key.isInteger()) printf("key : [%ld]\n", key.toInt64()); else printf("unknow type: %d", (int)key.getType()); } } static void packVariant(const Variant& el) { printf("packVariant type: %d\n", (int)el.getType()); switch(el.getType()) { case KindOfInt64 : { int64_t int_val = el.toInt64(); if (int_val >= 0) MsgpackExtension::BufferPtr = mp_encode_uint(MsgpackExtension::BufferPtr, int_val ); else MsgpackExtension::BufferPtr = mp_encode_int(MsgpackExtension::BufferPtr, int_val ); break; } case KindOfNull : { MsgpackExtension::BufferPtr = mp_encode_nil(MsgpackExtension::BufferPtr); break; } case KindOfBoolean : { MsgpackExtension::BufferPtr = mp_encode_bool(MsgpackExtension::BufferPtr, el.toBoolean()); break; } case KindOfString : { MsgpackExtension::BufferPtr = mp_encode_str(MsgpackExtension::BufferPtr, el.toString().c_str(), el.toString().length()); break; } case KindOfArray : { // тут надо проверить на тип массива, // если это массив без индексов, то сохранить как массив // иначе сохранить как карту (map) printf("packVariant Array\n"); test( el.toArray() ); MsgpackExtension::BufferPtr = mp_encode_map(MsgpackExtension::BufferPtr, el.toArray().length()); ArrayData* ad = el.toArray().get(); arrayIteration(ad, encodeArrayElement); break; } case KindOfDouble : { MsgpackExtension::BufferPtr = mp_encode_double(MsgpackExtension::BufferPtr, el.toDouble()); break; } default : raise_warning("error type of data element"); } }; void unpackElement( char **p, Variant* pout) { const char c = (**p); char * pos = *p; mp_type type = mp_typeof(c); switch(type) { case MP_NIL : { pout->setNull(); (*p)++; break; } case MP_UINT : { int64_t intval = mp_decode_uint(const_cast<const char**>(&pos)); *pout = intval; *p = pos; break; } case MP_INT : { int64_t intval = mp_decode_int(const_cast<const char**>(&pos)); *pout = intval; *p = pos; break; } case MP_STR : { uint32_t len = 0; const char * res = mp_decode_str(const_cast<const char**>(&pos), &len); *p = pos; *pout = String(StringData::Make( res, len, CopyString )); break; } case MP_BOOL : { const bool res = mp_decode_bool(const_cast<const char**>(&pos)); *p = pos; *pout = res ? true : false; break; } case MP_DOUBLE : { double dbl_val = mp_decode_double(const_cast<const char**>(&pos)); *pout = dbl_val; *p = pos; break; } case MP_ARRAY : { int count = mp_decode_array(const_cast<const char**>(&pos)); Array ret = Array::Create(); for(int i = 0; i < count; ++i) { Variant val; unpackElement( &pos, &val); ret.add(i,val); } *pout = ret; *p = pos; break; } case MP_MAP : { int count = mp_decode_map(const_cast<const char**>(&pos)); Array ret = Array::Create(); for(int i = 0; i < count; ++i) { Variant key, val; unpackElement( &pos, &key); unpackElement( &pos, &val); ret.add(key,val,true); } *pout = ret; *p = pos; break; } default : raise_warning("unpack error data element"); pout->setNull(); mp_next(const_cast<const char**>(p)); } } ////////////////////////////////////////////////////////////////////////////////////////////// void MsgpackExtension::moduleInit() { HHVM_FE(msgpack_pack); HHVM_FE(msgpack_unpack); loadSystemlib(); MsgpackExtension::BufferSize = BUFFSIZE; MsgpackExtension::Buffer = malloc(BUFFSIZE); } void MsgpackExtension::moduleShutdown() { free(MsgpackExtension::Buffer); // printf("moduleShutdown size=%d\n", MsgpackExtension::BufferSize); } ////////////////// static ///////////////////////// int MsgpackExtension::BufferSize = 0; int MsgpackExtension::Level = 0; void* MsgpackExtension::Buffer = NULL; char* MsgpackExtension::BufferPtr = NULL; static MsgpackExtension s_msgpack_extension; ////////////////// HHVM_FUNCTION ////////////////// static String HHVM_FUNCTION(msgpack_pack, const Array& data) { MsgpackExtension::Level = 0; MsgpackExtension::BufferPtr = static_cast<char*>(MsgpackExtension::Buffer); MsgpackExtension::BufferPtr = mp_encode_array( MsgpackExtension::BufferPtr, data.length()); for (int i = 0; i < data.length(); ++i) { packVariant(data[i]); } size_t len = reinterpret_cast<uint64_t>(MsgpackExtension::BufferPtr) - reinterpret_cast<uint64_t>(MsgpackExtension::Buffer); StringData* str = StringData::Make(reinterpret_cast<const char*>(MsgpackExtension::Buffer), len, CopyString); return String(str); } static Array HHVM_FUNCTION(msgpack_unpack, const String& data) { Array ret = Array::Create(); char * p = const_cast<char *>(data.c_str()); char c = *p; if ( mp_typeof(c) != MP_ARRAY ) { raise_warning("the root element must be array"); return ret; } int count = mp_decode_array( const_cast<const char**>(&p)); printf("elements %d\n", count); for (int i =0; i < count; i++) { Variant el; unpackElement(&p, &el); ret.set(i, el); } return ret; } HHVM_GET_MODULE(msgpack); } // namespace HPHP<|endoftext|>
<commit_before>/* * Copyright (c) 2012-2014 Stephen Williams ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form 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. */ # include "netclass.h" # include "netlist.h" # include <iostream> using namespace std; netclass_t::netclass_t(perm_string name, netclass_t*sup) : name_(name), super_(sup), class_scope_(0), definition_scope_(0) { } netclass_t::~netclass_t() { } bool netclass_t::set_property(perm_string pname, property_qualifier_t qual, ivl_type_s*ptype) { map<perm_string,size_t>::const_iterator cur; cur = properties_.find(pname); if (cur != properties_.end()) return false; prop_t tmp; tmp.name = pname; tmp.qual = qual; tmp.type = ptype; tmp.initialized_flag = false; property_table_.push_back(tmp); properties_[pname] = property_table_.size()-1; return true; } void netclass_t::set_class_scope(NetScope*class_scope__) { assert(class_scope_ == 0); class_scope_ = class_scope__; } void netclass_t::set_definition_scope(NetScope*use_definition_scope) { assert(definition_scope_ == 0); definition_scope_ = use_definition_scope; } ivl_variable_type_t netclass_t::base_type() const { return IVL_VT_CLASS; } size_t netclass_t::get_properties(void) const { size_t res = properties_.size(); if (super_) res += super_->get_properties(); return res; } int netclass_t::property_idx_from_name(perm_string pname) const { map<perm_string,size_t>::const_iterator cur; cur = properties_.find(pname); if (cur == properties_.end()) { if (super_) return super_->property_idx_from_name(pname); else return -1; } int pidx = cur->second; if (super_) pidx += super_->get_properties(); return pidx; } const char*netclass_t::get_prop_name(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx < (super_size + property_table_.size())); if (idx < super_size) return super_->get_prop_name(idx); else return property_table_[idx-super_size].name; } property_qualifier_t netclass_t::get_prop_qual(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx < (super_size+property_table_.size())); if (idx < super_size) return super_->get_prop_qual(idx); else return property_table_[idx-super_size].qual; } ivl_type_t netclass_t::get_prop_type(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx < (super_size+property_table_.size())); if (idx < super_size) return super_->get_prop_type(idx); else return property_table_[idx-super_size].type; } bool netclass_t::get_prop_initialized(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx < (super_size+property_table_.size())); if (idx < super_size) return super_->get_prop_initialized(idx); else return property_table_[idx].initialized_flag; } void netclass_t::set_prop_initialized(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx >= super_size && idx < (super_size+property_table_.size())); idx -= super_size; assert(! property_table_[idx].initialized_flag); property_table_[idx].initialized_flag = true; } bool netclass_t::test_for_missing_initializers() const { for (size_t idx = 0 ; idx < property_table_.size() ; idx += 1) { if (property_table_[idx].initialized_flag) continue; if (property_table_[idx].qual.test_const()) return true; } return false; } NetScope*netclass_t::method_from_name(perm_string name) const { NetScope*task = class_scope_->child( hname_t(name) ); if (task == 0) return 0; return task; } NetNet* netclass_t::find_static_property(perm_string name) const { NetNet*tmp = class_scope_->find_signal(name); return tmp; } bool netclass_t::test_scope_is_method(const NetScope*scope) const { while (scope && scope != class_scope_) { scope = scope->parent(); } if (scope == 0) return false; else return true; } <commit_msg>Enable base class tasks to be used in an extended class.<commit_after>/* * Copyright (c) 2012-2017 Stephen Williams ([email protected]) * * This source code is free software; you can redistribute it * and/or modify it in source code form 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. */ # include "netclass.h" # include "netlist.h" # include <iostream> using namespace std; netclass_t::netclass_t(perm_string name, netclass_t*sup) : name_(name), super_(sup), class_scope_(0), definition_scope_(0) { } netclass_t::~netclass_t() { } bool netclass_t::set_property(perm_string pname, property_qualifier_t qual, ivl_type_s*ptype) { map<perm_string,size_t>::const_iterator cur; cur = properties_.find(pname); if (cur != properties_.end()) return false; prop_t tmp; tmp.name = pname; tmp.qual = qual; tmp.type = ptype; tmp.initialized_flag = false; property_table_.push_back(tmp); properties_[pname] = property_table_.size()-1; return true; } void netclass_t::set_class_scope(NetScope*class_scope__) { assert(class_scope_ == 0); class_scope_ = class_scope__; } void netclass_t::set_definition_scope(NetScope*use_definition_scope) { assert(definition_scope_ == 0); definition_scope_ = use_definition_scope; } ivl_variable_type_t netclass_t::base_type() const { return IVL_VT_CLASS; } size_t netclass_t::get_properties(void) const { size_t res = properties_.size(); if (super_) res += super_->get_properties(); return res; } int netclass_t::property_idx_from_name(perm_string pname) const { map<perm_string,size_t>::const_iterator cur; cur = properties_.find(pname); if (cur == properties_.end()) { if (super_) return super_->property_idx_from_name(pname); else return -1; } int pidx = cur->second; if (super_) pidx += super_->get_properties(); return pidx; } const char*netclass_t::get_prop_name(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx < (super_size + property_table_.size())); if (idx < super_size) return super_->get_prop_name(idx); else return property_table_[idx-super_size].name; } property_qualifier_t netclass_t::get_prop_qual(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx < (super_size+property_table_.size())); if (idx < super_size) return super_->get_prop_qual(idx); else return property_table_[idx-super_size].qual; } ivl_type_t netclass_t::get_prop_type(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx < (super_size+property_table_.size())); if (idx < super_size) return super_->get_prop_type(idx); else return property_table_[idx-super_size].type; } bool netclass_t::get_prop_initialized(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx < (super_size+property_table_.size())); if (idx < super_size) return super_->get_prop_initialized(idx); else return property_table_[idx].initialized_flag; } void netclass_t::set_prop_initialized(size_t idx) const { size_t super_size = 0; if (super_) super_size = super_->get_properties(); assert(idx >= super_size && idx < (super_size+property_table_.size())); idx -= super_size; assert(! property_table_[idx].initialized_flag); property_table_[idx].initialized_flag = true; } bool netclass_t::test_for_missing_initializers() const { for (size_t idx = 0 ; idx < property_table_.size() ; idx += 1) { if (property_table_[idx].initialized_flag) continue; if (property_table_[idx].qual.test_const()) return true; } return false; } NetScope*netclass_t::method_from_name(perm_string name) const { NetScope*task = class_scope_->child( hname_t(name) ); if ((task == 0) && super_) task = super_->method_from_name(name); return task; } NetNet* netclass_t::find_static_property(perm_string name) const { NetNet*tmp = class_scope_->find_signal(name); return tmp; } bool netclass_t::test_scope_is_method(const NetScope*scope) const { while (scope && scope != class_scope_) { scope = scope->parent(); } if (scope == 0) return false; else return true; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <vector> #include <unordered_map> #include <tuple> #include <lemon/smart_graph.h> #include <lemon/lgf_writer.h> #include <lemon/capacity_scaling.h> using namespace lemon; int main(int argc, char* argv[]) { std::string path(argv[1]); uint64_t cacheSize(atoll(argv[2])); std::ifstream traceFile(path); uint64_t t, id, size, reqc=0, uniqc=0; std::vector<std::tuple<uint64_t,uint64_t,bool> > trace; std::unordered_map<uint64_t, uint64_t> lastSeen; while(traceFile >> t >> id >> size) { if(lastSeen.count(id)>0) { std::get<2>(trace[lastSeen[id]]) = true; } else { uniqc++; } trace.emplace_back(id,size,false); lastSeen[id]=reqc++; } traceFile.close(); std::cout << "scanned trace n=" << reqc << " m= " << uniqc << std::endl; SmartDigraph g; g.reserveNode(reqc-uniqc+1); // TODO: FORGOT THE END ARCS g.reserveArc(2*(reqc-uniqc)); lastSeen.clear(); reqc=0; SmartDigraph::Arc curArc; SmartDigraph::Node curNode = g.addNode(); // initial node SmartDigraph::Node prevNode; SmartDigraph::ArcMap<int> cap(g); // mcf capacities SmartDigraph::ArcMap<double> cost(g); // mcf costs SmartDigraph::NodeMap<int> supplies(g); // mcf demands/supplies std::unordered_map<uint64_t, uint64_t> lastSize; for(auto it: trace) { // only consider requests that reoccur // should we delete if does not reoccur? if(std::get<2>(it)) { const uint64_t id=std::get<0>(it); const uint64_t size=std::get<1>(it); if(lastSeen.count(id)>0) { if(size==lastSize[id]) { // create request arc ("outer") const SmartDigraph::Node lastReq = g.nodeFromId(lastSeen[id]); curArc = g.addArc(lastReq,curNode); cap[curArc] = size; cost[curArc] = 1/static_cast <double>(size); supplies[lastReq] += size; supplies[curNode] -= size; } else { std::cerr << "fuckup" << std::endl; return 1; } } // create capacity arc ("inner") prevNode = curNode; curNode = g.addNode(); // next node curArc = g.addArc(prevNode,curNode); cap[curArc] = cacheSize; cost[curArc] = 0; lastSeen[id]=reqc; lastSize[id]=size; reqc++; } } // there will m intervals without arcs // they all intersect and thus point to the same final node for(auto it: lastSeen) { const uint64_t id= it.second; const uint64_t size=lastSize[id]; const SmartDigraph::Node lastReq = g.nodeFromId(id); curArc = g.addArc(lastReq,curNode); cap[curArc] = size; cost[curArc] = 1/static_cast <double>(size); supplies[lastReq] += size; supplies[curNode] -= size; } std::cout << "created graph" << std::endl; // int nodes=0; // for (SmartDigraph::NodeIt n(g); n!=INVALID; ++n) ++nodes; // std::cout << nodes " nodes "; // for (SmartDigraph::ArcIt a(g); a != INVALID; ++a) { // std::cout << "cost " << cost[a] << std::endl; // } digraphWriter(g, std::cout). arcMap("capacity", cap). // write cap into 'capacity' arcMap("cost", cost). // write 'cost' for for arcs run(); // for(auto it: trace) { // std::cout << std::get<0>(it) << " " << std::get<1>(it) << " " << std::get<2>(it) << " " << std::endl; // } return 0; } <commit_msg>restructured graph construction<commit_after>#include <iostream> #include <cassert> #include <fstream> #include <string> #include <vector> #include <unordered_map> #include <tuple> #include <lemon/smart_graph.h> #include <lemon/lgf_writer.h> #include <lemon/capacity_scaling.h> using namespace lemon; void createMCF(SmartDigraph & g, std::vector<std::tuple<uint64_t,uint64_t,bool> > & trace, uint64_t cacheSize, SmartDigraph::ArcMap<int> & cap, SmartDigraph::ArcMap<double> & cost, SmartDigraph::NodeMap<int> & supplies) { // init std::unordered_map<uint64_t, uint64_t> lastSeen; uint64_t reqc=0; SmartDigraph::Arc curArc; SmartDigraph::Node curNode = g.addNode(); // initial node SmartDigraph::Node prevNode; std::unordered_map<uint64_t, uint64_t> lastSize; // iterate over trace for(auto it: trace) { // only consider requests that reoccur // should we delete if does not reoccur? if(std::get<2>(it)) { const uint64_t id=std::get<0>(it); const uint64_t size=std::get<1>(it); if(lastSeen.count(id)>0) { if(size==lastSize[id]) { // create request arc ("outer") const SmartDigraph::Node lastReq = g.nodeFromId(lastSeen[id]); curArc = g.addArc(lastReq,curNode); cap[curArc] = size; cost[curArc] = 1/static_cast <double>(size); supplies[lastReq] += size; supplies[curNode] -= size; } else { std::cerr << "fuckup" << std::endl; assert(false); } } // create capacity arc ("inner") prevNode = curNode; curNode = g.addNode(); // next node curArc = g.addArc(prevNode,curNode); cap[curArc] = cacheSize; cost[curArc] = 0; lastSeen[id]=reqc; lastSize[id]=size; reqc++; } } // there will m intervals without arcs // they all intersect and thus point to the same final node for(auto it: lastSeen) { const uint64_t id= it.second; const uint64_t size=lastSize[id]; const SmartDigraph::Node lastReq = g.nodeFromId(id); curArc = g.addArc(lastReq,curNode); cap[curArc] = size; cost[curArc] = 1/static_cast <double>(size); supplies[lastReq] += size; supplies[curNode] -= size; } } int main(int argc, char* argv[]) { std::string path(argv[1]); uint64_t cacheSize(atoll(argv[2])); std::ifstream traceFile(path); uint64_t t, id, size, reqc=0, uniqc=0; std::vector<std::tuple<uint64_t,uint64_t,bool> > trace; std::unordered_map<uint64_t, uint64_t> lastSeen; while(traceFile >> t >> id >> size) { if(lastSeen.count(id)>0) { std::get<2>(trace[lastSeen[id]]) = true; } else { uniqc++; } trace.emplace_back(id,size,false); lastSeen[id]=reqc++; } traceFile.close(); lastSeen.clear(); std::cout << "scanned trace n=" << reqc << " m= " << uniqc << std::endl; SmartDigraph g; // mcf graph g.reserveNode(reqc-uniqc+1); g.reserveArc(2*(reqc-uniqc)); SmartDigraph::ArcMap<int> cap(g); // mcf capacities SmartDigraph::ArcMap<double> cost(g); // mcf costs SmartDigraph::NodeMap<int> supplies(g); // mcf demands/supplies createMCF(g, trace, cacheSize, cap, cost, supplies); trace.clear(); std::cout << "created graph with "; int nodes=0, vertices=0; for (SmartDigraph::NodeIt n(g); n!=INVALID; ++n) ++nodes; std::cout << nodes << " nodes "; for (SmartDigraph::ArcIt a(g); a != INVALID; ++a) ++vertices; std::cout << vertices << " arcs "; digraphWriter(g, std::cout). arcMap("capacity", cap). // write cap into 'capacity' arcMap("cost", cost). // write 'cost' for for arcs run(); return 0; } <|endoftext|>