text
stringlengths
54
60.6k
<commit_before>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "mlir-hlo/Dialect/gml_st/transforms/tiling_interface_impl.h" #include "mlir-hlo/Dialect/gml_st/IR/gml_st_ops.h" #include "mlir-hlo/Dialect/gml_st/transforms/tiling_interface.h" #include "mlir/Dialect/Affine/IR/AffineOps.h" #include "mlir/Dialect/Linalg/IR/Linalg.h" #include "mlir/Dialect/Linalg/Utils/Utils.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" namespace mlir { namespace gml_st { namespace { using linalg::LinalgOp; using linalg::SliceParameters; /////////////////////////////////////////////////////////////////////////////// /// Linalg Tiling Interface. /////////////////////////////////////////////////////////////////////////////// SmallVector<OpFoldResult> getMixedValues(Location loc, OpBuilder &b, Value tensor) { SmallVector<OpFoldResult> tensorDims; auto tensorType = tensor.getType().cast<RankedTensorType>(); int64_t rank = tensorType.getRank(); for (auto i = 0; i < rank; ++i) { tensorDims.push_back( tensorType.isDynamicDim(i) ? OpFoldResult{b.createOrFold<tensor::DimOp>(loc, tensor, i)} : OpFoldResult{b.getI64IntegerAttr(tensorType.getDimSize(i))}); } return tensorDims; } template <typename LinalgOpTy> struct LinalgOpTilingInterface : public TilingInterface::ExternalModel<LinalgOpTilingInterface<LinalgOpTy>, LinalgOpTy> { /// Return the destination operands. SmallVector<Value> getDestinationOperands(Operation *op, OpBuilder & /*b*/) const { return cast<linalg::DestinationStyleOpInterface>(op).getOutputOperands(); } /// Return the loop iterator type. SmallVector<StringRef> getLoopIteratorTypes(Operation *op) const { LinalgOpTy concreteOp = cast<LinalgOpTy>(op); return llvm::to_vector( llvm::map_range(concreteOp.iterator_types(), [](Attribute strAttr) { return strAttr.cast<StringAttr>().getValue(); })); } /// Return the iteration domain range. SmallVector<Range> getIterationDomain(Operation *op, OpBuilder &b) const { OpBuilder::InsertionGuard g(b); b.setInsertionPoint(op); Location loc = op->getLoc(); LinalgOp linalgOp = cast<LinalgOp>(op); SmallVector<OpFoldResult> allShapesSizes = linalgOp.createFlatListOfOperandDims(b, loc); AffineMap map = linalgOp.getShapesToLoopsMap(); IRRewriter rewriter(b); return llvm::to_vector( llvm::map_range(map.getResults(), [&](AffineExpr loopExpr) { OpFoldResult ofr = makeComposedFoldedAffineApply( rewriter, loc, loopExpr, allShapesSizes); return Range{b.getIndexAttr(0), ofr, b.getIndexAttr(1)}; })); } // Instantiate the tiled implementation of the operation. TilingInterface getTiledImplementation(Operation *op, OpBuilder &b, ValueRange /*dest*/, ArrayRef<OpFoldResult> offsets, ArrayRef<OpFoldResult> sizes, bool /*tileDestOperands*/) const { Location loc = op->getLoc(); LinalgOp linalgOp = cast<LinalgOp>(op); SmallVector<Value> valuesToTile = linalgOp.getInputAndOutputOperands(); SmallVector<Optional<SliceParameters>> allSliceParams = linalg::computeAllSliceParameters(b, loc, linalgOp, valuesToTile, offsets, sizes, {}, true); SmallVector<Value> tiledOperands; for (auto item : llvm::zip(valuesToTile, allSliceParams)) { Value valueToTile = std::get<0>(item); const Optional<linalg::SliceParameters> &sliceParams = std::get<1>(item); SmallVector<OpFoldResult> tensorDims = getMixedValues(loc, b, valueToTile); Value set = b.create<SpaceOp>(loc, tensorDims); if (sliceParams.has_value()) { set = b.create<TileOp>(loc, set, sliceParams->offsets, sliceParams->sizes, sliceParams->strides); } Value materializedTile = b.create<MaterializeOp>(loc, valueToTile, set); tiledOperands.push_back(materializedTile); } SmallVector<Type> resultTensorTypes = llvm::to_vector(llvm::map_range( linalgOp.getOutputTensorOperands(), [&](OpOperand *opOperand) { return tiledOperands[opOperand->getOperandNumber()].getType(); })); Operation *tiledOp = linalgOp.clone(b, loc, resultTensorTypes, tiledOperands); offsetIndices(b, cast<LinalgOp>(tiledOp), offsets); return {tiledOp}; } FailureOr<Value> generateResultTileValue(Operation *op, OpBuilder &b, unsigned resultNumber, ValueRange dest, ArrayRef<OpFoldResult> offsets, ArrayRef<OpFoldResult> sizes, bool tileDestOperands) const { auto linalgOp = cast<LinalgOp>(op); // Check that the indexing map used for the output is a projected // permutation. This could be relaxed with a more general approach that can // map the offsets and sizes from the result to iteration space tiles // (filling in full extent for dimensions not used to access the result). AffineMap indexingMap = linalgOp.getTiedIndexingMapForResult(op->getResult(resultNumber)); if (!indexingMap.isProjectedPermutation()) { return op->emitOpError( "unhandled tiled implementation generation when result is not " "accessed using a permuted projection"); } auto numLoops = linalgOp.getNumLoops(); auto tilingInterfaceOp = cast<TilingInterface>(op); SmallVector<OpFoldResult> iterationTileOffsets(numLoops), iterationTileSizes(numLoops); if (!indexingMap.isPermutation()) { SmallVector<Range> iterationDomain = tilingInterfaceOp.getIterationDomain(b); for (const auto &range : llvm::enumerate(iterationDomain)) { iterationTileOffsets[range.index()] = range.value().offset; iterationTileSizes[range.index()] = range.value().size; } } for (const auto &resultExpr : llvm::enumerate(indexingMap.getResults())) { unsigned dimPosition = resultExpr.value().cast<AffineDimExpr>().getPosition(); iterationTileOffsets[dimPosition] = offsets[resultExpr.index()]; iterationTileSizes[dimPosition] = sizes[resultExpr.index()]; } TilingInterface tiledOp = tilingInterfaceOp.getTiledImplementation( b, dest, iterationTileOffsets, iterationTileSizes, tileDestOperands); return tiledOp->getResult(resultNumber); } }; } // namespace void registerGmlStTilingInterfaceExternalModels(DialectRegistry &registry) { registry.addExtension( +[](MLIRContext *ctx, linalg::LinalgDialect * /*dialect*/) { linalg::GenericOp::attachInterface< LinalgOpTilingInterface<linalg::GenericOp>>(*ctx); }); } } // namespace gml_st } // namespace mlir <commit_msg>[GML] Reuse `createDynamicDimValues` from upstream tensor utils<commit_after>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "mlir-hlo/Dialect/gml_st/transforms/tiling_interface_impl.h" #include "mlir-hlo/Dialect/gml_st/IR/gml_st_ops.h" #include "mlir-hlo/Dialect/gml_st/transforms/tiling_interface.h" #include "mlir/Dialect/Affine/IR/AffineOps.h" #include "mlir/Dialect/Linalg/IR/Linalg.h" #include "mlir/Dialect/Linalg/Utils/Utils.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" #include "mlir/Dialect/Tensor/Utils/Utils.h" namespace mlir { namespace gml_st { namespace { struct ExternalLinalgGenericTilingInterface : public TilingInterface::ExternalModel< ExternalLinalgGenericTilingInterface, linalg::GenericOp> { /// Return the destination operands. SmallVector<Value> getDestinationOperands(Operation *op, OpBuilder & /*b*/) const { return cast<linalg::DestinationStyleOpInterface>(op).getOutputOperands(); } /// Return the loop iterator type. SmallVector<StringRef> getLoopIteratorTypes(Operation *op) const { linalg::GenericOp concreteOp = cast<linalg::GenericOp>(op); return llvm::to_vector( llvm::map_range(concreteOp.iterator_types(), [](Attribute strAttr) { return strAttr.cast<StringAttr>().getValue(); })); } /// Return the iteration domain range. SmallVector<Range> getIterationDomain(Operation *op, OpBuilder &b) const { OpBuilder::InsertionGuard g(b); b.setInsertionPoint(op); Location loc = op->getLoc(); linalg::LinalgOp linalgOp = cast<linalg::LinalgOp>(op); SmallVector<OpFoldResult> allShapesSizes = linalgOp.createFlatListOfOperandDims(b, loc); AffineMap map = linalgOp.getShapesToLoopsMap(); IRRewriter rewriter(b); return llvm::to_vector( llvm::map_range(map.getResults(), [&](AffineExpr loopExpr) { OpFoldResult ofr = makeComposedFoldedAffineApply( rewriter, loc, loopExpr, allShapesSizes); return Range{b.getIndexAttr(0), ofr, b.getIndexAttr(1)}; })); } // Instantiate the tiled implementation of the operation. TilingInterface getTiledImplementation(Operation *op, OpBuilder &b, ValueRange /*dest*/, ArrayRef<OpFoldResult> offsets, ArrayRef<OpFoldResult> sizes, bool /*tileDestOperands*/) const { Location loc = op->getLoc(); linalg::LinalgOp linalgOp = cast<linalg::LinalgOp>(op); SmallVector<Value> valuesToTile = linalgOp.getInputAndOutputOperands(); SmallVector<Optional<linalg::SliceParameters>> allSliceParams = linalg::computeAllSliceParameters(b, loc, linalgOp, valuesToTile, offsets, sizes, {}, true); SmallVector<Value> tiledOperands; for (auto item : llvm::zip(valuesToTile, allSliceParams)) { Value valueToTile = std::get<0>(item); auto valueToTileTy = valueToTile.getType().cast<RankedTensorType>(); const Optional<linalg::SliceParameters> &sliceParams = std::get<1>(item); SmallVector<Value> dynamicSizes = tensor::createDynamicDimValues(b, loc, valueToTile); auto staticSizes = b.getI64ArrayAttr(valueToTileTy.getShape()); Value set = b.create<SpaceOp>(loc, dynamicSizes, staticSizes); if (sliceParams.has_value()) { set = b.create<TileOp>(loc, set, sliceParams->offsets, sliceParams->sizes, sliceParams->strides); } Value materializedTile = b.create<MaterializeOp>(loc, valueToTile, set); tiledOperands.push_back(materializedTile); } SmallVector<Type> resultTensorTypes = llvm::to_vector(llvm::map_range( linalgOp.getOutputTensorOperands(), [&](OpOperand *opOperand) { return tiledOperands[opOperand->getOperandNumber()].getType(); })); Operation *tiledOp = linalgOp.clone(b, loc, resultTensorTypes, tiledOperands); offsetIndices(b, cast<linalg::LinalgOp>(tiledOp), offsets); return {tiledOp}; } FailureOr<Value> generateResultTileValue(Operation *op, OpBuilder &b, unsigned resultNumber, ValueRange dest, ArrayRef<OpFoldResult> offsets, ArrayRef<OpFoldResult> sizes, bool tileDestOperands) const { auto linalgOp = cast<linalg::LinalgOp>(op); // Check that the indexing map used for the output is a projected // permutation. This could be relaxed with a more general approach that can // map the offsets and sizes from the result to iteration space tiles // (filling in full extent for dimensions not used to access the result). AffineMap indexingMap = linalgOp.getTiedIndexingMapForResult(op->getResult(resultNumber)); if (!indexingMap.isProjectedPermutation()) { return op->emitOpError( "unhandled tiled implementation generation when result is not " "accessed using a permuted projection"); } auto numLoops = linalgOp.getNumLoops(); auto tilingInterfaceOp = cast<TilingInterface>(op); SmallVector<OpFoldResult> iterationTileOffsets(numLoops), iterationTileSizes(numLoops); if (!indexingMap.isPermutation()) { SmallVector<Range> iterationDomain = tilingInterfaceOp.getIterationDomain(b); for (const auto &range : llvm::enumerate(iterationDomain)) { iterationTileOffsets[range.index()] = range.value().offset; iterationTileSizes[range.index()] = range.value().size; } } for (const auto &resultExpr : llvm::enumerate(indexingMap.getResults())) { unsigned dimPosition = resultExpr.value().cast<AffineDimExpr>().getPosition(); iterationTileOffsets[dimPosition] = offsets[resultExpr.index()]; iterationTileSizes[dimPosition] = sizes[resultExpr.index()]; } TilingInterface tiledOp = tilingInterfaceOp.getTiledImplementation( b, dest, iterationTileOffsets, iterationTileSizes, tileDestOperands); return tiledOp->getResult(resultNumber); } }; } // namespace void registerGmlStTilingInterfaceExternalModels(DialectRegistry &registry) { registry.addExtension(+[](MLIRContext *ctx, linalg::LinalgDialect *) { linalg::GenericOp::attachInterface<ExternalLinalgGenericTilingInterface>( *ctx); }); } } // namespace gml_st } // namespace mlir <|endoftext|>
<commit_before>#include <jni.h> #include <android/log.h> #include <stdio.h> #include <string> #include <vector> #include "AndroidCommon.h" #undef LOGV #undef LOGE #define LOGV(msg,args...) __android_log_print(ANDROID_LOG_ERROR, "NME::System", msg, ## args) #define LOGE(msg,args...) __android_log_print(ANDROID_LOG_ERROR, "NME::System", msg, ## args) namespace nme { double CapabilitiesGetPixelAspectRatio () { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetPixelAspectRatio", "()D"); if (mid == 0) return 1; return env->CallStaticDoubleMethod (cls, mid); } double CapabilitiesGetScreenDPI () { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetScreenDPI", "()D"); if (mid == 0) return 1; return env->CallStaticDoubleMethod (cls, mid); } double CapabilitiesGetScreenResolutionX () { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetScreenResolutionX", "()D"); if (mid == 0) return 1; return env->CallStaticDoubleMethod (cls, mid); } double CapabilitiesGetScreenResolutionY () { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetScreenResolutionY", "()D"); if (mid == 0) return 1; return env->CallStaticDoubleMethod (cls, mid); } std::string CapabilitiesGetLanguage() { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetLanguage", "()Ljava/lang/String;"); if(mid == 0) return std::string(""); jstring jLang = (jstring) env->CallStaticObjectMethod(cls, mid); return JStringToStdString(env,jLang,true); } void HapticVibrate (int period, int duration) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "vibrate", "(II)V"); if (mid) env->CallStaticVoidMethod(cls, mid, period, duration); } bool LaunchBrowser(const char *inUtf8URL) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "launchBrowser", "(Ljava/lang/String;)V"); if (mid == 0) return false; jstring str = env->NewStringUTF( inUtf8URL ); env->CallStaticVoidMethod(cls, mid, str ); env->DeleteLocalRef(str); return true; } std::string GetUserPreference(const char *inId) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "getUserPreference", "(Ljava/lang/String;)Ljava/lang/String;"); if (mid == 0) { return std::string(""); } jstring jInId = env->NewStringUTF(inId); jstring jPref = (jstring) env->CallStaticObjectMethod(cls, mid, jInId); env->DeleteLocalRef(jInId); return JStringToStdString(env,jPref,true); } bool SetUserPreference(const char *inId, const char *inPreference) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "setUserPreference", "(Ljava/lang/String;Ljava/lang/String;)V"); if (mid == 0) return false; jstring jInId = env->NewStringUTF( inId ); jstring jPref = env->NewStringUTF ( inPreference ); env->CallStaticVoidMethod(cls, mid, jInId, jPref ); env->DeleteLocalRef(jInId); env->DeleteLocalRef(jPref); return true; } bool ClearUserPreference(const char *inId) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "clearUserPreference", "(Ljava/lang/String;)V"); if (mid == 0) return false; jstring jInId = env->NewStringUTF( inId ); env->CallStaticVoidMethod(cls, mid, jInId ); env->DeleteLocalRef(jInId); return true; } bool SetClipboardText(const char* text) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "setClipboardText", "(Ljava/lang/String;)Z"); if (mid == 0) return false; jstring jtext = env->NewStringUTF( text ); bool result = env->CallStaticBooleanMethod (cls, mid, jtext); env->DeleteLocalRef(jtext); return result; } bool HasClipboardText(){ JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "hasClipboardText", "()Z"); if (mid == 0) return false; return env->CallStaticBooleanMethod (cls, mid); } const char* GetClipboardText(){ JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "getClipboardText", "()Ljava/lang/String;"); if (mid == 0) return std::string("").c_str(); jstring jPref = (jstring) env->CallStaticObjectMethod(cls, mid); return JStringToStdString(env,jPref,true).c_str(); } } <commit_msg>Clipboard fix on android<commit_after>#include <jni.h> #include <android/log.h> #include <stdio.h> #include <string> #include <vector> #include "AndroidCommon.h" #undef LOGV #undef LOGE #define LOGV(msg,args...) __android_log_print(ANDROID_LOG_ERROR, "NME::System", msg, ## args) #define LOGE(msg,args...) __android_log_print(ANDROID_LOG_ERROR, "NME::System", msg, ## args) namespace nme { double CapabilitiesGetPixelAspectRatio () { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetPixelAspectRatio", "()D"); if (mid == 0) return 1; return env->CallStaticDoubleMethod (cls, mid); } double CapabilitiesGetScreenDPI () { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetScreenDPI", "()D"); if (mid == 0) return 1; return env->CallStaticDoubleMethod (cls, mid); } double CapabilitiesGetScreenResolutionX () { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetScreenResolutionX", "()D"); if (mid == 0) return 1; return env->CallStaticDoubleMethod (cls, mid); } double CapabilitiesGetScreenResolutionY () { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetScreenResolutionY", "()D"); if (mid == 0) return 1; return env->CallStaticDoubleMethod (cls, mid); } std::string CapabilitiesGetLanguage() { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "CapabilitiesGetLanguage", "()Ljava/lang/String;"); if(mid == 0) return std::string(""); jstring jLang = (jstring) env->CallStaticObjectMethod(cls, mid); return JStringToStdString(env,jLang,true); } void HapticVibrate (int period, int duration) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "vibrate", "(II)V"); if (mid) env->CallStaticVoidMethod(cls, mid, period, duration); } bool LaunchBrowser(const char *inUtf8URL) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "launchBrowser", "(Ljava/lang/String;)V"); if (mid == 0) return false; jstring str = env->NewStringUTF( inUtf8URL ); env->CallStaticVoidMethod(cls, mid, str ); env->DeleteLocalRef(str); return true; } std::string GetUserPreference(const char *inId) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "getUserPreference", "(Ljava/lang/String;)Ljava/lang/String;"); if (mid == 0) { return std::string(""); } jstring jInId = env->NewStringUTF(inId); jstring jPref = (jstring) env->CallStaticObjectMethod(cls, mid, jInId); env->DeleteLocalRef(jInId); return JStringToStdString(env,jPref,true); } bool SetUserPreference(const char *inId, const char *inPreference) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "setUserPreference", "(Ljava/lang/String;Ljava/lang/String;)V"); if (mid == 0) return false; jstring jInId = env->NewStringUTF( inId ); jstring jPref = env->NewStringUTF ( inPreference ); env->CallStaticVoidMethod(cls, mid, jInId, jPref ); env->DeleteLocalRef(jInId); env->DeleteLocalRef(jPref); return true; } bool ClearUserPreference(const char *inId) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "clearUserPreference", "(Ljava/lang/String;)V"); if (mid == 0) return false; jstring jInId = env->NewStringUTF( inId ); env->CallStaticVoidMethod(cls, mid, jInId ); env->DeleteLocalRef(jInId); return true; } bool SetClipboardText(const char* text) { JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "setClipboardText", "(Ljava/lang/String;)Z"); if (mid == 0) return false; jstring jtext = env->NewStringUTF( text ); bool result = env->CallStaticBooleanMethod (cls, mid, jtext); env->DeleteLocalRef(jtext); return result; } bool HasClipboardText(){ JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "hasClipboardText", "()Z"); if (mid == 0) return false; return env->CallStaticBooleanMethod (cls, mid); } const char* GetClipboardText(){ JNIEnv *env = GetEnv(); jclass cls = FindClass("org/haxe/nme/GameActivity"); jmethodID mid = env->GetStaticMethodID(cls, "getClipboardText", "()Ljava/lang/String;"); if (mid == 0) return std::string("").c_str(); jstring jPref = (jstring) env->CallStaticObjectMethod(cls, mid); const char *c_ptr = env->GetStringUTFChars(jPref, 0); int len = strlen(c_ptr); const char *result = alloc_string_data(c_ptr, len); env->ReleaseStringUTFChars(jPref, c_ptr); return result; } } <|endoftext|>
<commit_before>/******************************************************************************\ * File: support.cpp * Purpose: Implementation of DecoratedFrame class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/stockitem.h> // for wxGetStockLabel #include <wx/extension/filedlg.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> #include <wx/extension/report/listviewfile.h> #include <wx/extension/report/stc.h> #ifndef __WXMSW__ #include "app.xpm" #endif #include "support.h" #include "defs.h" DecoratedFrame::DecoratedFrame() : wxExFrameWithHistory( NULL, wxID_ANY, wxTheApp->GetAppDisplayName(), // title 25, // maxFiles 4) // maxProjects , m_MenuVCS(new wxExMenu) { SetIcon(wxICON(app)); #if wxUSE_STATUSBAR std::vector<wxExStatusBarPane> panes; panes.push_back(wxExStatusBarPane()); panes.push_back(wxExStatusBarPane("PaneFileType", 50, _("File type"))); panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines or items"))); if (wxExLexers::Get()->Count() > 0) { #ifdef __WXMSW__ const int lexer_size = 60; #else const int lexer_size = 75; #endif panes.push_back(wxExStatusBarPane("PaneLexer", lexer_size, _("Lexer"))); panes.push_back(wxExStatusBarPane("PaneTheme", lexer_size, _("Theme"))); } SetupStatusBar(panes); #endif wxExMenu *menuFile = new wxExMenu(); menuFile->Append(wxID_NEW); menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENT_FILE_MENU, menuFile); wxMenu* menuOpen = new wxMenu(); menuOpen->Append(ID_OPEN_LEXERS, _("&Lexers File")); menuOpen->Append(ID_OPEN_LOGFILE, _("&Log File")); menuOpen->Append(ID_OPEN_VCS, _("&VCS File")); menuFile->AppendSeparator(); menuFile->AppendSubMenu(menuOpen, _("Open")); menuFile->AppendSeparator(); menuFile->Append(wxID_CLOSE); menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll")); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE); menuFile->AppendSeparator(); menuFile->AppendPrint(); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu *menuEdit = new wxExMenu(); menuEdit->Append(wxID_UNDO); menuEdit->Append(wxID_REDO); menuEdit->AppendSeparator(); menuEdit->Append(wxID_CUT); menuEdit->Append(wxID_COPY); menuEdit->Append(wxID_PASTE); menuEdit->AppendSeparator(); menuEdit->Append(wxID_JUMP_TO); menuEdit->AppendSeparator(); wxExMenu* menuFind = new wxExMenu(); menuFind->Append(wxID_FIND); menuFind->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3")); menuFind->Append(wxID_REPLACE); menuFind->Append(ID_FIND_IN_FILES, wxExEllipsed(_("Find &In Files"))); menuFind->Append(ID_REPLACE_IN_FILES, wxExEllipsed(_("Replace In File&s"))); menuEdit->AppendSubMenu(menuFind, _("&Find And Replace")); menuEdit->AppendSeparator(); wxExMenu* menuMore = new wxExMenu(); if (menuMore->AppendTools(ID_MENU_TOOLS)) { menuMore->AppendSeparator(); } menuMore->Append(ID_EDIT_ADD_HEADER, wxExEllipsed(_("&Add Header"))); menuMore->Append(ID_EDIT_INSERT_SEQUENCE, wxExEllipsed(_("Insert Sequence"))); menuMore->AppendSeparator(); menuMore->Append( ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl+H")); menuEdit->AppendSubMenu(menuMore, _("More")); menuEdit->AppendSeparator(); m_MenuVCS->BuildVCS(); menuEdit->AppendSubMenu(m_MenuVCS, "&VCS", wxEmptyString, ID_MENU_VCS); menuEdit->AppendSeparator(); wxExMenu* menuMacro = new wxExMenu(); menuMacro->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record")); menuMacro->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record")); menuMacro->AppendSeparator(); menuMacro->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M")); menuEdit->AppendSubMenu(menuMacro, _("&Macro")); wxExMenu *menuView = new wxExMenu; menuView->AppendBars(); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files")); menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects")); menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer")); menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History")); menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table")); wxMenu *menuProcess = new wxMenu(); menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select"))); menuProcess->AppendSeparator(); menuProcess->Append(wxID_EXECUTE); menuProcess->Append(wxID_STOP); wxExMenu *menuProject = new wxExMenu(); menuProject->Append( ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW); menuProject->Append( ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN); UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject); menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text")); menuProject->Append( ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE), wxEmptyString, wxART_CLOSE); menuProject->AppendSeparator(); menuProject->Append( ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE); menuProject->Append( ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS); menuProject->AppendSeparator(); menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort")); wxMenu *menuWindow = new wxMenu(); menuWindow->Append(ID_SPLIT, _("Split")); wxMenu* menuOptions = new wxMenu(); if (wxExLexers::Get()->Count() > 0) { menuOptions->Append(ID_OPTION_VCS, wxExEllipsed(_("Set &VCS"))); } else { menuOptions->Append( ID_OPTION_LIST_COMPARATOR, wxExEllipsed(_("Set List &Comparator"))); } menuOptions->AppendSeparator(); menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font"))); // text also used as caption menuOptions->Append( ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set List &Read Only Colour"))); wxMenu *menuListSort = new wxMenu; menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending")); menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending")); menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle")); menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method")); menuOptions->AppendSeparator(); menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options"))); wxMenu *menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar* menubar = new wxMenuBar(); menubar->Append(menuFile, wxGetStockLabel(wxID_FILE)); menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT)); menubar->Append(menuView, _("&View")); menubar->Append(menuProcess, _("&Process")); menubar->Append(menuProject, _("&Project")); menubar->Append(menuWindow, _("&Window")); menubar->Append(menuOptions, _("&Options")); #ifndef __WXOSX__ menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP)); #endif SetMenuBar(menubar); } bool DecoratedFrame::AllowClose(wxWindowID id, wxWindow* page) { if (ProcessIsRunning()) { return false; } else if (id == NOTEBOOK_EDITORS) { wxExFileDialog dlg(this, &((wxExSTC*)page)->GetFile()); return dlg.ShowModalIfChanged() == wxID_OK; } else if (id == NOTEBOOK_PROJECTS) { wxExFileDialog dlg(this, (wxExListViewFile*)page); return dlg.ShowModalIfChanged() == wxID_OK; } else { return wxExFrameWithHistory::AllowClose(id, page); } } void DecoratedFrame::OnNotebook(wxWindowID id, wxWindow* page) { if (id == NOTEBOOK_EDITORS) { ((wxExSTC*)page)->PropertiesMessage(); } else if (id == NOTEBOOK_PROJECTS) { #if wxUSE_STATUSBAR ((wxExListViewFile*)page)->GetFileName().StatusText(); ((wxExListViewFile*)page)->UpdateStatusBar(); #endif } else if (id == NOTEBOOK_LISTS) { // Do nothing special. } else { wxFAIL; } } <commit_msg>restore about menu, otherwise it is not shown correctly<commit_after>/******************************************************************************\ * File: support.cpp * Purpose: Implementation of DecoratedFrame class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/stockitem.h> // for wxGetStockLabel #include <wx/extension/filedlg.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> #include <wx/extension/report/listviewfile.h> #include <wx/extension/report/stc.h> #ifndef __WXMSW__ #include "app.xpm" #endif #include "support.h" #include "defs.h" DecoratedFrame::DecoratedFrame() : wxExFrameWithHistory( NULL, wxID_ANY, wxTheApp->GetAppDisplayName(), // title 25, // maxFiles 4) // maxProjects , m_MenuVCS(new wxExMenu) { SetIcon(wxICON(app)); #if wxUSE_STATUSBAR std::vector<wxExStatusBarPane> panes; panes.push_back(wxExStatusBarPane()); panes.push_back(wxExStatusBarPane("PaneFileType", 50, _("File type"))); panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines or items"))); if (wxExLexers::Get()->Count() > 0) { #ifdef __WXMSW__ const int lexer_size = 60; #else const int lexer_size = 75; #endif panes.push_back(wxExStatusBarPane("PaneLexer", lexer_size, _("Lexer"))); panes.push_back(wxExStatusBarPane("PaneTheme", lexer_size, _("Theme"))); } SetupStatusBar(panes); #endif wxExMenu *menuFile = new wxExMenu(); menuFile->Append(wxID_NEW); menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENT_FILE_MENU, menuFile); wxMenu* menuOpen = new wxMenu(); menuOpen->Append(ID_OPEN_LEXERS, _("&Lexers File")); menuOpen->Append(ID_OPEN_LOGFILE, _("&Log File")); menuOpen->Append(ID_OPEN_VCS, _("&VCS File")); menuFile->AppendSeparator(); menuFile->AppendSubMenu(menuOpen, _("Open")); menuFile->AppendSeparator(); menuFile->Append(wxID_CLOSE); menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll")); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE); menuFile->AppendSeparator(); menuFile->AppendPrint(); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu *menuEdit = new wxExMenu(); menuEdit->Append(wxID_UNDO); menuEdit->Append(wxID_REDO); menuEdit->AppendSeparator(); menuEdit->Append(wxID_CUT); menuEdit->Append(wxID_COPY); menuEdit->Append(wxID_PASTE); menuEdit->AppendSeparator(); menuEdit->Append(wxID_JUMP_TO); menuEdit->AppendSeparator(); wxExMenu* menuFind = new wxExMenu(); menuFind->Append(wxID_FIND); menuFind->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3")); menuFind->Append(wxID_REPLACE); menuFind->Append(ID_FIND_IN_FILES, wxExEllipsed(_("Find &In Files"))); menuFind->Append(ID_REPLACE_IN_FILES, wxExEllipsed(_("Replace In File&s"))); menuEdit->AppendSubMenu(menuFind, _("&Find And Replace")); menuEdit->AppendSeparator(); wxExMenu* menuMore = new wxExMenu(); if (menuMore->AppendTools(ID_MENU_TOOLS)) { menuMore->AppendSeparator(); } menuMore->Append(ID_EDIT_ADD_HEADER, wxExEllipsed(_("&Add Header"))); menuMore->Append(ID_EDIT_INSERT_SEQUENCE, wxExEllipsed(_("Insert Sequence"))); menuMore->AppendSeparator(); menuMore->Append( ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl+H")); menuEdit->AppendSubMenu(menuMore, _("More")); menuEdit->AppendSeparator(); m_MenuVCS->BuildVCS(); menuEdit->AppendSubMenu(m_MenuVCS, "&VCS", wxEmptyString, ID_MENU_VCS); menuEdit->AppendSeparator(); wxExMenu* menuMacro = new wxExMenu(); menuMacro->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record")); menuMacro->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record")); menuMacro->AppendSeparator(); menuMacro->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M")); menuEdit->AppendSubMenu(menuMacro, _("&Macro")); wxExMenu *menuView = new wxExMenu; menuView->AppendBars(); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files")); menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects")); menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer")); menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History")); menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table")); wxMenu *menuProcess = new wxMenu(); menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select"))); menuProcess->AppendSeparator(); menuProcess->Append(wxID_EXECUTE); menuProcess->Append(wxID_STOP); wxExMenu *menuProject = new wxExMenu(); menuProject->Append( ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW); menuProject->Append( ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN); UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject); menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text")); menuProject->Append( ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE), wxEmptyString, wxART_CLOSE); menuProject->AppendSeparator(); menuProject->Append( ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE); menuProject->Append( ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS); menuProject->AppendSeparator(); menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort")); wxMenu *menuWindow = new wxMenu(); menuWindow->Append(ID_SPLIT, _("Split")); wxMenu* menuOptions = new wxMenu(); if (wxExLexers::Get()->Count() > 0) { menuOptions->Append(ID_OPTION_VCS, wxExEllipsed(_("Set &VCS"))); } else { menuOptions->Append( ID_OPTION_LIST_COMPARATOR, wxExEllipsed(_("Set List &Comparator"))); } menuOptions->AppendSeparator(); menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font"))); // text also used as caption menuOptions->Append( ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set List &Read Only Colour"))); wxMenu *menuListSort = new wxMenu; menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending")); menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending")); menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle")); menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method")); menuOptions->AppendSeparator(); menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options"))); wxMenu *menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar* menubar = new wxMenuBar(); menubar->Append(menuFile, wxGetStockLabel(wxID_FILE)); menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT)); menubar->Append(menuView, _("&View")); menubar->Append(menuProcess, _("&Process")); menubar->Append(menuProject, _("&Project")); menubar->Append(menuWindow, _("&Window")); menubar->Append(menuOptions, _("&Options")); menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP)); SetMenuBar(menubar); } bool DecoratedFrame::AllowClose(wxWindowID id, wxWindow* page) { if (ProcessIsRunning()) { return false; } else if (id == NOTEBOOK_EDITORS) { wxExFileDialog dlg(this, &((wxExSTC*)page)->GetFile()); return dlg.ShowModalIfChanged() == wxID_OK; } else if (id == NOTEBOOK_PROJECTS) { wxExFileDialog dlg(this, (wxExListViewFile*)page); return dlg.ShowModalIfChanged() == wxID_OK; } else { return wxExFrameWithHistory::AllowClose(id, page); } } void DecoratedFrame::OnNotebook(wxWindowID id, wxWindow* page) { if (id == NOTEBOOK_EDITORS) { ((wxExSTC*)page)->PropertiesMessage(); } else if (id == NOTEBOOK_PROJECTS) { #if wxUSE_STATUSBAR ((wxExListViewFile*)page)->GetFileName().StatusText(); ((wxExListViewFile*)page)->UpdateStatusBar(); #endif } else if (id == NOTEBOOK_LISTS) { // Do nothing special. } else { wxFAIL; } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Tests.h" #include "Util/Util.h" #include "Core/Common.h" #include "Core/Assembler.h" #ifndef _WIN32 #include <dirent.h> #endif StringList TestRunner::listSubfolders(const std::wstring& dir) { StringList result; #ifdef _WIN32 WIN32_FIND_DATAW findFileData; HANDLE hFind; std::wstring m = dir + L"*"; hFind = FindFirstFileW(m.c_str(),&findFileData); if (hFind != INVALID_HANDLE_VALUE) { do { if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::wstring dirName = findFileData.cFileName; if (dirName != L"." && dirName != L"..") result.push_back(dirName); } } while (FindNextFileW(hFind,&findFileData)); } #else std::string utf8 = convertWStringToUtf8(dir); auto directory = opendir(utf8.c_str()); if (directory != NULL) { auto elem = readdir(directory); while (elem != NULL) { if(elem->d_type == DT_DIR) { std::wstring dirName = convertUtf8ToWString(elem->d_name); if (dirName != L"." && dirName != L"..") result.push_back(dirName); } elem = readdir(directory); } } #endif return result; } void TestRunner::initConsole() { #ifdef _WIN32 // initialize console hstdin = GetStdHandle(STD_INPUT_HANDLE); hstdout = GetStdHandle(STD_OUTPUT_HANDLE); // Remember how things were when we started GetConsoleScreenBufferInfo(hstdout,&csbi); #endif } void TestRunner::changeConsoleColor(ConsoleColors color) { #ifdef _WIN32 switch (color) { case ConsoleColors::White: SetConsoleTextAttribute(hstdout,0x7); break; case ConsoleColors::Red: SetConsoleTextAttribute(hstdout,(1 << 2) | (1 << 3)); break; case ConsoleColors::Green: SetConsoleTextAttribute(hstdout,(1 << 1) | (1 << 3)); break; } #else switch (color) { case ConsoleColors::White: Logger::print(L"\033[1;0m"); break; case ConsoleColors::Red: Logger::print(L"\033[1;31m"); break; case ConsoleColors::Green: Logger::print(L"\033[1;32m"); break; } #endif } void TestRunner::restoreConsole() { #ifdef _WIN32 FlushConsoleInputBuffer(hstdin); SetConsoleTextAttribute(hstdout,csbi.wAttributes); #endif } StringList TestRunner::getTestsList(const std::wstring& dir, const std::wstring& prefix) { StringList tests; StringList dirs = listSubfolders(dir+prefix); for (std::wstring& dirName: dirs) { std::wstring testName = prefix + dirName; std::wstring fileName = dir + testName + L"/" + dirName + L".asm"; if (fileExists(fileName)) { if (testName[0] == L'/') testName.erase(0,1); tests.push_back(testName); } else { StringList subTests = getTestsList(dir,testName+L"/"); tests.insert(tests.end(),subTests.begin(),subTests.end()); } } return tests; } bool TestRunner::executeTest(const std::wstring& dir, const std::wstring& testName, std::wstring& errorString) { std::wstring oldDir = getCurrentDirectory(); changeDirectory(dir); ArmipsArguments args; StringList errors; args.inputFileName = testName + L".asm"; args.errorsResult = &errors; args.silent = true; // may or may not be supposed to cause errors runArmips(args); // check errors bool result = true; if (fileExists(L"expected.txt")) { TextFile f; f.open(L"expected.txt",TextFile::Read); StringList expectedErrors = f.readAll(); if (errors.size() == expectedErrors.size()) { for (size_t i = 0; i < errors.size(); i++) { if (errors[i] != expectedErrors[i]) { errorString += formatString(L"Unexpected error: %S\n",errors[i]); result = false; } } } else { result = false; } } else { // if no errors are expected, there should be none for (size_t i = 0; i < errors.size(); i++) { errorString += formatString(L"Unexpected error: %S\n",errors[i]); result = false; } } // write errors to file TextFile output; output.open(L"output.txt",TextFile::Write); output.writeLines(errors); output.close(); if (fileExists(L"expected.bin")) { ByteArray expected = ByteArray::fromFile(L"expected.bin"); ByteArray actual = ByteArray::fromFile(L"output.bin"); if (expected.size() == actual.size()) { if (memcmp(expected.data(),actual.data(),actual.size()) != 0) { errorString += formatString(L"Output data does not match\n"); result = false; } } else { errorString += formatString(L"Output data size does not match\n"); result = false; } } changeDirectory(oldDir); return result; } bool TestRunner::runTests(const std::wstring& dir) { StringList tests = getTestsList(dir); if (tests.empty()) { Logger::printLine(L"No tests to run"); return true; } initConsole(); int successCount = 0; for (size_t i = 0; i < tests.size(); i++) { changeConsoleColor(ConsoleColors::White); std::wstring line = formatString(L"Test %d of %d, %s:",i+1,tests.size(),tests[i]); Logger::print(L"%-50s",line); std::wstring path = dir + L"/" + tests[i]; std::wstring errors; size_t n = tests[i].find_last_of('/'); std::wstring testName = n == tests[i].npos ? tests[i] : tests[i].substr(n+1); if (executeTest(path,testName,errors) == false) { changeConsoleColor(ConsoleColors::Red); Logger::printLine(L"FAILED"); Logger::print(L"%s",errors); } else { changeConsoleColor(ConsoleColors::Green); Logger::printLine(L"PASSED"); successCount++; } } changeConsoleColor(ConsoleColors::White); Logger::printLine(L"\n%d out of %d tests passed.",successCount,tests.size()); restoreConsole(); return successCount == tests.size(); } bool runTests(const std::wstring& dir) { TestRunner runner; return runner.runTests(dir); } <commit_msg>Output temp data for tests<commit_after>#include "stdafx.h" #include "Tests.h" #include "Util/Util.h" #include "Core/Common.h" #include "Core/Assembler.h" #ifndef _WIN32 #include <dirent.h> #endif StringList TestRunner::listSubfolders(const std::wstring& dir) { StringList result; #ifdef _WIN32 WIN32_FIND_DATAW findFileData; HANDLE hFind; std::wstring m = dir + L"*"; hFind = FindFirstFileW(m.c_str(),&findFileData); if (hFind != INVALID_HANDLE_VALUE) { do { if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { std::wstring dirName = findFileData.cFileName; if (dirName != L"." && dirName != L"..") result.push_back(dirName); } } while (FindNextFileW(hFind,&findFileData)); } #else std::string utf8 = convertWStringToUtf8(dir); auto directory = opendir(utf8.c_str()); if (directory != NULL) { auto elem = readdir(directory); while (elem != NULL) { if(elem->d_type == DT_DIR) { std::wstring dirName = convertUtf8ToWString(elem->d_name); if (dirName != L"." && dirName != L"..") result.push_back(dirName); } elem = readdir(directory); } } #endif return result; } void TestRunner::initConsole() { #ifdef _WIN32 // initialize console hstdin = GetStdHandle(STD_INPUT_HANDLE); hstdout = GetStdHandle(STD_OUTPUT_HANDLE); // Remember how things were when we started GetConsoleScreenBufferInfo(hstdout,&csbi); #endif } void TestRunner::changeConsoleColor(ConsoleColors color) { #ifdef _WIN32 switch (color) { case ConsoleColors::White: SetConsoleTextAttribute(hstdout,0x7); break; case ConsoleColors::Red: SetConsoleTextAttribute(hstdout,(1 << 2) | (1 << 3)); break; case ConsoleColors::Green: SetConsoleTextAttribute(hstdout,(1 << 1) | (1 << 3)); break; } #else switch (color) { case ConsoleColors::White: Logger::print(L"\033[1;0m"); break; case ConsoleColors::Red: Logger::print(L"\033[1;31m"); break; case ConsoleColors::Green: Logger::print(L"\033[1;32m"); break; } #endif } void TestRunner::restoreConsole() { #ifdef _WIN32 FlushConsoleInputBuffer(hstdin); SetConsoleTextAttribute(hstdout,csbi.wAttributes); #endif } StringList TestRunner::getTestsList(const std::wstring& dir, const std::wstring& prefix) { StringList tests; StringList dirs = listSubfolders(dir+prefix); for (std::wstring& dirName: dirs) { std::wstring testName = prefix + dirName; std::wstring fileName = dir + testName + L"/" + dirName + L".asm"; if (fileExists(fileName)) { if (testName[0] == L'/') testName.erase(0,1); tests.push_back(testName); } else { StringList subTests = getTestsList(dir,testName+L"/"); tests.insert(tests.end(),subTests.begin(),subTests.end()); } } return tests; } bool TestRunner::executeTest(const std::wstring& dir, const std::wstring& testName, std::wstring& errorString) { std::wstring oldDir = getCurrentDirectory(); changeDirectory(dir); ArmipsArguments args; StringList errors; args.inputFileName = testName + L".asm"; args.tempFileName = testName + L".temp.txt"; args.errorsResult = &errors; args.silent = true; // may or may not be supposed to cause errors runArmips(args); // check errors bool result = true; if (fileExists(L"expected.txt")) { TextFile f; f.open(L"expected.txt",TextFile::Read); StringList expectedErrors = f.readAll(); if (errors.size() == expectedErrors.size()) { for (size_t i = 0; i < errors.size(); i++) { if (errors[i] != expectedErrors[i]) { errorString += formatString(L"Unexpected error: %S\n",errors[i]); result = false; } } } else { result = false; } } else { // if no errors are expected, there should be none for (size_t i = 0; i < errors.size(); i++) { errorString += formatString(L"Unexpected error: %S\n",errors[i]); result = false; } } // write errors to file TextFile output; output.open(L"output.txt",TextFile::Write); output.writeLines(errors); output.close(); if (fileExists(L"expected.bin")) { ByteArray expected = ByteArray::fromFile(L"expected.bin"); ByteArray actual = ByteArray::fromFile(L"output.bin"); if (expected.size() == actual.size()) { if (memcmp(expected.data(),actual.data(),actual.size()) != 0) { errorString += formatString(L"Output data does not match\n"); result = false; } } else { errorString += formatString(L"Output data size does not match\n"); result = false; } } changeDirectory(oldDir); return result; } bool TestRunner::runTests(const std::wstring& dir) { StringList tests = getTestsList(dir); if (tests.empty()) { Logger::printLine(L"No tests to run"); return true; } initConsole(); int successCount = 0; for (size_t i = 0; i < tests.size(); i++) { changeConsoleColor(ConsoleColors::White); std::wstring line = formatString(L"Test %d of %d, %s:",i+1,tests.size(),tests[i]); Logger::print(L"%-50s",line); std::wstring path = dir + L"/" + tests[i]; std::wstring errors; size_t n = tests[i].find_last_of('/'); std::wstring testName = n == tests[i].npos ? tests[i] : tests[i].substr(n+1); if (executeTest(path,testName,errors) == false) { changeConsoleColor(ConsoleColors::Red); Logger::printLine(L"FAILED"); Logger::print(L"%s",errors); } else { changeConsoleColor(ConsoleColors::Green); Logger::printLine(L"PASSED"); successCount++; } } changeConsoleColor(ConsoleColors::White); Logger::printLine(L"\n%d out of %d tests passed.",successCount,tests.size()); restoreConsole(); return successCount == tests.size(); } bool runTests(const std::wstring& dir) { TestRunner runner; return runner.runTests(dir); } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef NASTY_CONTAINERS_H #define NASTY_CONTAINERS_H #include <cassert> #include <vector> #include <list> template <class T> class nasty_vector { public: typedef typename std::vector<T> nested_container; typedef typename nested_container::value_type value_type; typedef typename nested_container::reference reference; typedef typename nested_container::const_reference const_reference; typedef typename nested_container::iterator iterator; typedef typename nested_container::const_iterator const_iterator; typedef typename nested_container::size_type size_type; typedef typename nested_container::difference_type difference_type; typedef typename nested_container::pointer pointer; typedef typename nested_container::const_pointer const_pointer; typedef typename nested_container::reverse_iterator reverse_iterator; typedef typename nested_container::const_reverse_iterator const_reverse_iterator; nasty_vector() : v_() {} explicit nasty_vector(size_type n) : v_(n) {} nasty_vector(size_type n, const value_type& value) : v_(n, value) {} template <class InputIterator> nasty_vector(InputIterator first, InputIterator last) : v_(first, last) {} #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS nasty_vector(std::initializer_list<value_type> il) : v_(il) {} #endif ~nasty_vector() {} template <class InputIterator> void assign(InputIterator first, InputIterator last) { v_.assign(first, last); } void assign(size_type n, const value_type& u) { v_.assign(n, u); } #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS void assign(std::initializer_list<value_type> il) { v_.assign(il); } #endif iterator begin() _NOEXCEPT { return v_.begin(); } const_iterator begin() const _NOEXCEPT { return v_.begin(); } iterator end() _NOEXCEPT { return v_.end(); } const_iterator end() const _NOEXCEPT { return v_.end(); } reverse_iterator rbegin() _NOEXCEPT { return v_.rbegin(); } const_reverse_iterator rbegin() const _NOEXCEPT { return v_.rbegin(); } reverse_iterator rend() _NOEXCEPT { return v_.rend(); } const_reverse_iterator rend() const _NOEXCEPT { return v_.rend(); } const_iterator cbegin() const _NOEXCEPT { return v_.cbegin(); } const_iterator cend() const _NOEXCEPT { return v_.cend(); } const_reverse_iterator crbegin() const _NOEXCEPT { return v_.crbegin(); } const_reverse_iterator crend() const _NOEXCEPT { return v_.crend(); } size_type size() const _NOEXCEPT { return v_.size(); } size_type max_size() const _NOEXCEPT { return v_.max_size(); } size_type capacity() const _NOEXCEPT { return v_.capacity(); } bool empty() const _NOEXCEPT { return v_.empty(); } void reserve(size_type n) { v_.reserve(n); }; void shrink_to_fit() _NOEXCEPT { v_.shrink_to_fit(); } reference operator[](size_type n) { return v_[n]; } const_reference operator[](size_type n) const { return v_[n]; } reference at(size_type n) { return v_.at(n); } const_reference at(size_type n) const { return v_.at(n); } reference front() { return v_.front(); } const_reference front() const { return v_.front(); } reference back() { return v_.back(); } const_reference back() const { return v_.back(); } value_type* data() _NOEXCEPT { return v_.data(); } const value_type* data() const _NOEXCEPT { return v_.data(); } void push_back(const value_type& x) { v_.push_back(x); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES void push_back(value_type&& x) { v_.push_back(std::forward<value_type&&>(x)); } #ifndef _LIBCPP_HAS_NO_VARIADICS template <class... Args> void emplace_back(Args&&... args) { v_.emplace_back(std::forward<Args>(args)...); } #endif #endif void pop_back() { v_.pop_back(); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES #ifndef _LIBCPP_HAS_NO_VARIADICS template <class... Args> iterator emplace(const_iterator pos, Args&&... args) { return v_.emplace(pos, std::forward<Args>(args)...); } #endif #endif iterator insert(const_iterator pos, const value_type& x) { return v_.insert(pos, x); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES iterator insert(const_iterator pos, value_type&& x) { return v_.insert(pos, std::forward<value_type>(x)); } #endif iterator insert(const_iterator pos, size_type n, const value_type& x) { return v_.insert(pos, n, x); } template <class InputIterator> iterator insert(const_iterator pos, InputIterator first, InputIterator last) { return v_.insert(pos, first, last); } #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS iterator insert(const_iterator pos, std::initializer_list<value_type> il) { return v_.insert(pos, il); } #endif iterator erase(const_iterator pos) { return v_.erase(pos); } iterator erase(const_iterator first, const_iterator last) { return v_.erase(first, last); } void clear() _NOEXCEPT { v_.clear(); } void resize(size_type sz) { v_.resize(sz); } void resize(size_type sz, const value_type& c) { v_.resize(sz, c); } void swap(nasty_vector &nv) _NOEXCEPT_(std::__is_nothrow_swappable<nested_container>::value) { v_.swap(nv.v_); } nasty_vector *operator &() { assert(false); return nullptr; } // nasty const nasty_vector *operator &() const { assert(false); return nullptr; } // nasty nested_container v_; }; template <class T> bool operator==(const nasty_vector<T>& x, const nasty_vector<T>& y) { return x.v_ == y.v_; } template <class T> class nasty_list { public: typedef typename std::list<T> nested_container; typedef typename nested_container::value_type value_type; typedef typename nested_container::reference reference; typedef typename nested_container::const_reference const_reference; typedef typename nested_container::iterator iterator; typedef typename nested_container::const_iterator const_iterator; typedef typename nested_container::size_type size_type; typedef typename nested_container::difference_type difference_type; typedef typename nested_container::pointer pointer; typedef typename nested_container::const_pointer const_pointer; typedef typename nested_container::reverse_iterator reverse_iterator; typedef typename nested_container::const_reverse_iterator const_reverse_iterator; nasty_list() : l_() {} explicit nasty_list(size_type n) : l_(n) {} nasty_list(size_type n, const value_type& value) : l_(n,value) {} template <class Iter> nasty_list(Iter first, Iter last) : l_(first, last) {} #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS nasty_list(std::initializer_list<value_type> il) : l_(il) {} #endif ~nasty_list() {} #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS nasty_list& operator=(std::initializer_list<value_type> il) { l_ = il; return *this; } #endif template <class Iter> void assign(Iter first, Iter last) { l_.assign(first, last); } void assign(size_type n, const value_type& t) { l_.assign(n, t); } #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS void assign(std::initializer_list<value_type> il) { l_.assign(il); } #endif iterator begin() _NOEXCEPT { return l_.begin(); } const_iterator begin() const _NOEXCEPT { return l_.begin(); } iterator end() _NOEXCEPT { return l_.end(); } const_iterator end() const _NOEXCEPT { return l_.end(); } reverse_iterator rbegin() _NOEXCEPT { return l_.rbegin(); } const_reverse_iterator rbegin() const _NOEXCEPT { return l_.rbegin(); } reverse_iterator rend() _NOEXCEPT { return l_.rend(); } const_reverse_iterator rend() const _NOEXCEPT { return l_.rend(); } const_iterator cbegin() const _NOEXCEPT { return l_.cbegin(); } const_iterator cend() const _NOEXCEPT { return l_.cend(); } const_reverse_iterator crbegin() const _NOEXCEPT { return l_.crbegin(); } const_reverse_iterator crend() const _NOEXCEPT { return l_.crend(); } reference front() { return l_.front(); } const_reference front() const { return l_.front(); } reference back() { return l_.back(); } const_reference back() const { return l_.back(); } size_type size() const _NOEXCEPT { return l_.size(); } size_type max_size() const _NOEXCEPT { return l_.max_size(); } bool empty() const _NOEXCEPT { return l_.empty(); } void push_front(const value_type& x) { l_.push_front(x); } void push_back(const value_type& x) { l_.push_back(x); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES void push_back(value_type&& x) { l_.push_back(std::forward<value_type&&>(x)); } void push_front(value_type&& x) { l_.push_back(std::forward<value_type&&>(x)); } #ifndef _LIBCPP_HAS_NO_VARIADICS template <class... Args> void emplace_back(Args&&... args) { l_.emplace_back(std::forward<Args>(args)...); } template <class... Args> void emplace_front(Args&&... args) { l_.emplace_front(std::forward<Args>(args)...); } #endif #endif void pop_front() { l_.pop_front(); } void pop_back() { l_.pop_back(); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES #ifndef _LIBCPP_HAS_NO_VARIADICS template <class... Args> iterator emplace(const_iterator pos, Args&&... args) { return l_.emplace(pos, std::forward<Args>(args)...); } #endif #endif iterator insert(const_iterator pos, const value_type& x) { return l_.insert(pos, x); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES iterator insert(const_iterator pos, value_type&& x) { return l_.insert(pos, std::forward<value_type>(x)); } #endif iterator insert(const_iterator pos, size_type n, const value_type& x) { return l_.insert(pos, n, x); } template <class InputIterator> iterator insert(const_iterator pos, InputIterator first, InputIterator last) { return l_.insert(pos, first, last); } #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS iterator insert(const_iterator pos, std::initializer_list<value_type> il) { return l_.insert(pos, il); } #endif iterator erase(const_iterator pos) { return l_.erase(pos); } iterator erase(const_iterator pos, const_iterator last) { return l_.erase(pos, last); } void resize(size_type sz) { l_.resize(); } void resize(size_type sz, const value_type& c) { l_.resize(c); } void swap(nasty_list &nl) _NOEXCEPT_(std::__is_nothrow_swappable<nested_container>::value) { l_.swap(nl.l_); } void clear() _NOEXCEPT { l_.clear(); } // void splice(const_iterator position, list& x); // void splice(const_iterator position, list&& x); // void splice(const_iterator position, list& x, const_iterator i); // void splice(const_iterator position, list&& x, const_iterator i); // void splice(const_iterator position, list& x, const_iterator first, // const_iterator last); // void splice(const_iterator position, list&& x, const_iterator first, // const_iterator last); // // void remove(const value_type& value); // template <class Pred> void remove_if(Pred pred); // void unique(); // template <class BinaryPredicate> // void unique(BinaryPredicate binary_pred); // void merge(list& x); // void merge(list&& x); // template <class Compare> // void merge(list& x, Compare comp); // template <class Compare> // void merge(list&& x, Compare comp); // void sort(); // template <class Compare> // void sort(Compare comp); // void reverse() noexcept; nasty_list *operator &() { assert(false); return nullptr; } // nasty const nasty_list *operator &() const { assert(false); return nullptr; } // nasty nested_container l_; }; template <class T> bool operator==(const nasty_list<T>& x, const nasty_list<T>& y) { return x.l_ == y.l_; } // Not really a mutex, but can play one in tests class nasty_mutex { public: nasty_mutex() _NOEXCEPT {} ~nasty_mutex() {} nasty_mutex *operator& () { assert(false); } template <typename T> void operator, (const T &) { assert(false); } private: nasty_mutex(const nasty_mutex&) { assert(false); } nasty_mutex& operator=(const nasty_mutex&) { assert(false); return *this; } public: void lock() {} bool try_lock() _NOEXCEPT { return true; } void unlock() _NOEXCEPT {} // Shared ownership void lock_shared() {} bool try_lock_shared() { return true; } void unlock_shared() {} }; #endif <commit_msg>Add a return value for nasty_mutex::operator&. Patch from STL@microsoft.com<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef NASTY_CONTAINERS_H #define NASTY_CONTAINERS_H #include <cassert> #include <vector> #include <list> template <class T> class nasty_vector { public: typedef typename std::vector<T> nested_container; typedef typename nested_container::value_type value_type; typedef typename nested_container::reference reference; typedef typename nested_container::const_reference const_reference; typedef typename nested_container::iterator iterator; typedef typename nested_container::const_iterator const_iterator; typedef typename nested_container::size_type size_type; typedef typename nested_container::difference_type difference_type; typedef typename nested_container::pointer pointer; typedef typename nested_container::const_pointer const_pointer; typedef typename nested_container::reverse_iterator reverse_iterator; typedef typename nested_container::const_reverse_iterator const_reverse_iterator; nasty_vector() : v_() {} explicit nasty_vector(size_type n) : v_(n) {} nasty_vector(size_type n, const value_type& value) : v_(n, value) {} template <class InputIterator> nasty_vector(InputIterator first, InputIterator last) : v_(first, last) {} #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS nasty_vector(std::initializer_list<value_type> il) : v_(il) {} #endif ~nasty_vector() {} template <class InputIterator> void assign(InputIterator first, InputIterator last) { v_.assign(first, last); } void assign(size_type n, const value_type& u) { v_.assign(n, u); } #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS void assign(std::initializer_list<value_type> il) { v_.assign(il); } #endif iterator begin() _NOEXCEPT { return v_.begin(); } const_iterator begin() const _NOEXCEPT { return v_.begin(); } iterator end() _NOEXCEPT { return v_.end(); } const_iterator end() const _NOEXCEPT { return v_.end(); } reverse_iterator rbegin() _NOEXCEPT { return v_.rbegin(); } const_reverse_iterator rbegin() const _NOEXCEPT { return v_.rbegin(); } reverse_iterator rend() _NOEXCEPT { return v_.rend(); } const_reverse_iterator rend() const _NOEXCEPT { return v_.rend(); } const_iterator cbegin() const _NOEXCEPT { return v_.cbegin(); } const_iterator cend() const _NOEXCEPT { return v_.cend(); } const_reverse_iterator crbegin() const _NOEXCEPT { return v_.crbegin(); } const_reverse_iterator crend() const _NOEXCEPT { return v_.crend(); } size_type size() const _NOEXCEPT { return v_.size(); } size_type max_size() const _NOEXCEPT { return v_.max_size(); } size_type capacity() const _NOEXCEPT { return v_.capacity(); } bool empty() const _NOEXCEPT { return v_.empty(); } void reserve(size_type n) { v_.reserve(n); }; void shrink_to_fit() _NOEXCEPT { v_.shrink_to_fit(); } reference operator[](size_type n) { return v_[n]; } const_reference operator[](size_type n) const { return v_[n]; } reference at(size_type n) { return v_.at(n); } const_reference at(size_type n) const { return v_.at(n); } reference front() { return v_.front(); } const_reference front() const { return v_.front(); } reference back() { return v_.back(); } const_reference back() const { return v_.back(); } value_type* data() _NOEXCEPT { return v_.data(); } const value_type* data() const _NOEXCEPT { return v_.data(); } void push_back(const value_type& x) { v_.push_back(x); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES void push_back(value_type&& x) { v_.push_back(std::forward<value_type&&>(x)); } #ifndef _LIBCPP_HAS_NO_VARIADICS template <class... Args> void emplace_back(Args&&... args) { v_.emplace_back(std::forward<Args>(args)...); } #endif #endif void pop_back() { v_.pop_back(); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES #ifndef _LIBCPP_HAS_NO_VARIADICS template <class... Args> iterator emplace(const_iterator pos, Args&&... args) { return v_.emplace(pos, std::forward<Args>(args)...); } #endif #endif iterator insert(const_iterator pos, const value_type& x) { return v_.insert(pos, x); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES iterator insert(const_iterator pos, value_type&& x) { return v_.insert(pos, std::forward<value_type>(x)); } #endif iterator insert(const_iterator pos, size_type n, const value_type& x) { return v_.insert(pos, n, x); } template <class InputIterator> iterator insert(const_iterator pos, InputIterator first, InputIterator last) { return v_.insert(pos, first, last); } #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS iterator insert(const_iterator pos, std::initializer_list<value_type> il) { return v_.insert(pos, il); } #endif iterator erase(const_iterator pos) { return v_.erase(pos); } iterator erase(const_iterator first, const_iterator last) { return v_.erase(first, last); } void clear() _NOEXCEPT { v_.clear(); } void resize(size_type sz) { v_.resize(sz); } void resize(size_type sz, const value_type& c) { v_.resize(sz, c); } void swap(nasty_vector &nv) _NOEXCEPT_(std::__is_nothrow_swappable<nested_container>::value) { v_.swap(nv.v_); } nasty_vector *operator &() { assert(false); return nullptr; } // nasty const nasty_vector *operator &() const { assert(false); return nullptr; } // nasty nested_container v_; }; template <class T> bool operator==(const nasty_vector<T>& x, const nasty_vector<T>& y) { return x.v_ == y.v_; } template <class T> class nasty_list { public: typedef typename std::list<T> nested_container; typedef typename nested_container::value_type value_type; typedef typename nested_container::reference reference; typedef typename nested_container::const_reference const_reference; typedef typename nested_container::iterator iterator; typedef typename nested_container::const_iterator const_iterator; typedef typename nested_container::size_type size_type; typedef typename nested_container::difference_type difference_type; typedef typename nested_container::pointer pointer; typedef typename nested_container::const_pointer const_pointer; typedef typename nested_container::reverse_iterator reverse_iterator; typedef typename nested_container::const_reverse_iterator const_reverse_iterator; nasty_list() : l_() {} explicit nasty_list(size_type n) : l_(n) {} nasty_list(size_type n, const value_type& value) : l_(n,value) {} template <class Iter> nasty_list(Iter first, Iter last) : l_(first, last) {} #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS nasty_list(std::initializer_list<value_type> il) : l_(il) {} #endif ~nasty_list() {} #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS nasty_list& operator=(std::initializer_list<value_type> il) { l_ = il; return *this; } #endif template <class Iter> void assign(Iter first, Iter last) { l_.assign(first, last); } void assign(size_type n, const value_type& t) { l_.assign(n, t); } #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS void assign(std::initializer_list<value_type> il) { l_.assign(il); } #endif iterator begin() _NOEXCEPT { return l_.begin(); } const_iterator begin() const _NOEXCEPT { return l_.begin(); } iterator end() _NOEXCEPT { return l_.end(); } const_iterator end() const _NOEXCEPT { return l_.end(); } reverse_iterator rbegin() _NOEXCEPT { return l_.rbegin(); } const_reverse_iterator rbegin() const _NOEXCEPT { return l_.rbegin(); } reverse_iterator rend() _NOEXCEPT { return l_.rend(); } const_reverse_iterator rend() const _NOEXCEPT { return l_.rend(); } const_iterator cbegin() const _NOEXCEPT { return l_.cbegin(); } const_iterator cend() const _NOEXCEPT { return l_.cend(); } const_reverse_iterator crbegin() const _NOEXCEPT { return l_.crbegin(); } const_reverse_iterator crend() const _NOEXCEPT { return l_.crend(); } reference front() { return l_.front(); } const_reference front() const { return l_.front(); } reference back() { return l_.back(); } const_reference back() const { return l_.back(); } size_type size() const _NOEXCEPT { return l_.size(); } size_type max_size() const _NOEXCEPT { return l_.max_size(); } bool empty() const _NOEXCEPT { return l_.empty(); } void push_front(const value_type& x) { l_.push_front(x); } void push_back(const value_type& x) { l_.push_back(x); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES void push_back(value_type&& x) { l_.push_back(std::forward<value_type&&>(x)); } void push_front(value_type&& x) { l_.push_back(std::forward<value_type&&>(x)); } #ifndef _LIBCPP_HAS_NO_VARIADICS template <class... Args> void emplace_back(Args&&... args) { l_.emplace_back(std::forward<Args>(args)...); } template <class... Args> void emplace_front(Args&&... args) { l_.emplace_front(std::forward<Args>(args)...); } #endif #endif void pop_front() { l_.pop_front(); } void pop_back() { l_.pop_back(); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES #ifndef _LIBCPP_HAS_NO_VARIADICS template <class... Args> iterator emplace(const_iterator pos, Args&&... args) { return l_.emplace(pos, std::forward<Args>(args)...); } #endif #endif iterator insert(const_iterator pos, const value_type& x) { return l_.insert(pos, x); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES iterator insert(const_iterator pos, value_type&& x) { return l_.insert(pos, std::forward<value_type>(x)); } #endif iterator insert(const_iterator pos, size_type n, const value_type& x) { return l_.insert(pos, n, x); } template <class InputIterator> iterator insert(const_iterator pos, InputIterator first, InputIterator last) { return l_.insert(pos, first, last); } #ifndef _LIBCPP_HAS_NO_GENERALIZED_INITIALIZERS iterator insert(const_iterator pos, std::initializer_list<value_type> il) { return l_.insert(pos, il); } #endif iterator erase(const_iterator pos) { return l_.erase(pos); } iterator erase(const_iterator pos, const_iterator last) { return l_.erase(pos, last); } void resize(size_type sz) { l_.resize(); } void resize(size_type sz, const value_type& c) { l_.resize(c); } void swap(nasty_list &nl) _NOEXCEPT_(std::__is_nothrow_swappable<nested_container>::value) { l_.swap(nl.l_); } void clear() _NOEXCEPT { l_.clear(); } // void splice(const_iterator position, list& x); // void splice(const_iterator position, list&& x); // void splice(const_iterator position, list& x, const_iterator i); // void splice(const_iterator position, list&& x, const_iterator i); // void splice(const_iterator position, list& x, const_iterator first, // const_iterator last); // void splice(const_iterator position, list&& x, const_iterator first, // const_iterator last); // // void remove(const value_type& value); // template <class Pred> void remove_if(Pred pred); // void unique(); // template <class BinaryPredicate> // void unique(BinaryPredicate binary_pred); // void merge(list& x); // void merge(list&& x); // template <class Compare> // void merge(list& x, Compare comp); // template <class Compare> // void merge(list&& x, Compare comp); // void sort(); // template <class Compare> // void sort(Compare comp); // void reverse() noexcept; nasty_list *operator &() { assert(false); return nullptr; } // nasty const nasty_list *operator &() const { assert(false); return nullptr; } // nasty nested_container l_; }; template <class T> bool operator==(const nasty_list<T>& x, const nasty_list<T>& y) { return x.l_ == y.l_; } // Not really a mutex, but can play one in tests class nasty_mutex { public: nasty_mutex() _NOEXCEPT {} ~nasty_mutex() {} nasty_mutex *operator& () { assert(false); return nullptr; } template <typename T> void operator, (const T &) { assert(false); } private: nasty_mutex(const nasty_mutex&) { assert(false); } nasty_mutex& operator=(const nasty_mutex&) { assert(false); return *this; } public: void lock() {} bool try_lock() _NOEXCEPT { return true; } void unlock() _NOEXCEPT {} // Shared ownership void lock_shared() {} bool try_lock_shared() { return true; } void unlock_shared() {} }; #endif <|endoftext|>
<commit_before> #include "Pickle.h" #include <algorithm> #include <cassert> #include <cstdlib> #include <cstring> namespace KBase{ // static const int Pickle::kPayloadUnit = 64; static const size_t kCapacityReadOnly = static_cast<size_t>(-1); PickleIterator::PickleIterator(const Pickle& pickle) : read_ptr_(pickle.payload()), read_end_ptr_(pickle.end_of_payload()) {} bool PickleIterator::ReadBool(bool* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadInt(int* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadUInt32(uint32_t* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadInt64(int64_t* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadUInt64(uint64_t* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadFloat(float* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadDouble(double* result) { return ReadBuiltIninType(result); } // sizeof comparison in if statement causes constant expression warning // disable the warning temporarily #pragma warning(push) #pragma warning(disable:4127) template<typename T> inline bool PickleIterator::ReadBuiltIninType(T* result) { const char* read_from = GetReadPointerAndAdvance<T>(); if (!read_from) { return false; } if (sizeof(T) > sizeof(uint32_t)) { memcpy_s(result, sizeof(*result), read_from, sizeof(*result)); } else { *result = *reinterpret_cast<const T*>(read_from); } return true; } template<typename T> inline const char* PickleIterator::GetReadPointerAndAdvance() { const char* curr_read_ptr = read_ptr_; if (read_ptr_ + sizeof(T) > read_end_ptr_) { return nullptr; } // skip the memory hole if size of the type is less than uint32 if (sizeof(T) < sizeof(uint32_t)) { read_ptr_ += Pickle::AlignInt(sizeof(T), sizeof(uint32_t)); } else { read_ptr_ += sizeof(T); } return curr_read_ptr; } #pragma warning(pop) // payload is uint32 aligned Pickle::Pickle() : header_(nullptr), capacity_(0), buffer_offset_(0) { Resize(kPayloadUnit); header_->payload_size = 0; } Pickle::Pickle(const char* data, int) : header_(reinterpret_cast<Header*>(const_cast<char*>(data))), capacity_(kCapacityReadOnly), buffer_offset_(0) {} /* @ brief a deep copy of an Pickle object */ Pickle::Pickle(const Pickle& other) : header_(nullptr), capacity_(0), buffer_offset_(other.buffer_offset_) { // if [other] is constructed from a const buffer, its capacity value is // kCapacityReadOnly. therefore, calculate its capacity on hand. size_t capacity = sizeof(Header) + other.header_->payload_size; bool resized = Resize(capacity); assert(resized); memcpy_s(header_, capacity_, other.header_, capacity); } Pickle::~Pickle() { if (capacity_ != kCapacityReadOnly) { free(header_); } } Pickle& Pickle::operator=(const Pickle& rhs) { if (this == &rhs) { assert(false); return *this; } if (capacity_ == kCapacityReadOnly) { header_ = nullptr; capacity_ = 0; } size_t capacity = sizeof(Header) + rhs.header_->payload_size; bool resized = Resize(capacity); assert(resized); memcpy_s(header_, capacity_, rhs.header_, capacity); buffer_offset_ = rhs.buffer_offset_; return *this; } /* @ brief resize the capacity of internal buffer. this function internally rounds the [new_capacity] up to the next multiple of predefined alignment @ params new_capacity[in] new capacity of internal buffer and will be aligned internally. be wary of that, the new_capacity actually includes internal header size. e.g. new_capacity = header_size + your_desired_payload_size */ bool Pickle::Resize(size_t new_capacity) { assert(capacity_ != kCapacityReadOnly); new_capacity = AlignInt(new_capacity, kPayloadUnit); void* p = realloc(header_, new_capacity); if (!p) { return false; } header_ = static_cast<Header*>(p); capacity_ = new_capacity; return true; } // static size_t Pickle::AlignInt(size_t i, int alignment) { return i + (alignment - i % alignment) % alignment; } bool Pickle::WriteString(const std::string& value) { if (!WriteInt(static_cast<int>(value.size()))) { return false; } return WriteByte(value.data(), static_cast<int>(value.size())); } bool Pickle::WriteWString(const std::wstring& value) { if (!WriteInt(static_cast<int>(value.size()))) { return false; } return WriteByte(value.data(), static_cast<int>(value.size() * sizeof(wchar_t))); } /* @ brief serialize data in byte with specified length. PoD types only the function guarantees the internal data remains unchanged if this funtion fails. */ bool Pickle::WriteByte(const void* data, int data_len) { if (capacity_ == kCapacityReadOnly) { assert(false); return false; } char* dest = BeginWrite(data_len); if (!dest) { return false; } size_t extra_size = capacity_ - (dest - reinterpret_cast<char*>(header_)); memcpy_s(dest, extra_size, data, data_len); EndWrite(dest, data_len); return true; } /* @ brief locate to the next uint32-aligned offset. and resize internal buffer if necessary. @ return the location that the data should be written at, or nullptr if an error occured. */ char* Pickle::BeginWrite(size_t length) { // write at a uint32-aligned offset from the begining of head size_t offset = AlignInt(header_->payload_size, sizeof(uint32_t)); size_t required_size = offset + length; size_t total_required_size = required_size + sizeof(Header); if (total_required_size > capacity_ && !Resize(std::max(capacity_ << 1, total_required_size))) { return nullptr; } header_->payload_size = static_cast<uint32_t>(required_size); return mutable_payload() + offset; } /* @ brief zero pading memory; otherwise some memory detectors may complain about uninitialized memory. */ void Pickle::EndWrite(char* dest, size_t length) { if (length % sizeof(uint32_t)) { memset(dest + length, 0, sizeof(uint32_t) - (length % sizeof(uint32_t))); } } } <commit_msg>Pickle: add string/wstring read functions<commit_after> #include "Pickle.h" #include <algorithm> #include <cassert> #include <cstdlib> #include <cstring> namespace KBase{ // static const int Pickle::kPayloadUnit = 64; static const size_t kCapacityReadOnly = static_cast<size_t>(-1); PickleIterator::PickleIterator(const Pickle& pickle) : read_ptr_(pickle.payload()), read_end_ptr_(pickle.end_of_payload()) {} bool PickleIterator::ReadBool(bool* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadInt(int* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadUInt32(uint32_t* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadInt64(int64_t* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadUInt64(uint64_t* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadFloat(float* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadDouble(double* result) { return ReadBuiltIninType(result); } bool PickleIterator::ReadString(std::string* result) { int str_length; if (!ReadInt(&str_length)) { return false; } const char* read_from = GetReadPointerAndAdvance(str_length); if (!read_from) { return false; } result->assign(read_from, str_length); return true; } bool PickleIterator::ReadWString(std::wstring* result) { int str_length; if (!ReadInt(&str_length)) { return false; } const char* read_from = GetReadPointerAndAdvance(str_length, sizeof(wchar_t)); if (!read_from) { return false; } result->assign(reinterpret_cast<const wchar_t*>(read_from), str_length); return true; } // sizeof comparison in if statement causes constant expression warning // disable the warning temporarily #pragma warning(push) #pragma warning(disable:4127) template<typename T> inline bool PickleIterator::ReadBuiltIninType(T* result) { const char* read_from = GetReadPointerAndAdvance<T>(); if (!read_from) { return false; } if (sizeof(T) > sizeof(uint32_t)) { memcpy_s(result, sizeof(*result), read_from, sizeof(*result)); } else { *result = *reinterpret_cast<const T*>(read_from); } return true; } template<typename T> inline const char* PickleIterator::GetReadPointerAndAdvance() { const char* curr_read_ptr = read_ptr_; if (read_ptr_ + sizeof(T) > read_end_ptr_) { return nullptr; } // skip the memory hole if size of the type is less than uint32 if (sizeof(T) < sizeof(uint32_t)) { read_ptr_ += Pickle::AlignInt(sizeof(T), sizeof(uint32_t)); } else { read_ptr_ += sizeof(T); } return curr_read_ptr; } #pragma warning(pop) const char* PickleIterator::GetReadPointerAndAdvance(int num_bytes) { const char* curr_read_ptr = read_ptr_; if (num_bytes < 0 || read_ptr_ + num_bytes > read_end_ptr_) { return nullptr; } read_ptr_ += Pickle::AlignInt(num_bytes, sizeof(uint32_t)); return curr_read_ptr; } /* @ brief when the size of element doesn't equal to sizeof(char), use this function for safety consieration. this function runs overflow check on int32 num_bytes. */ const char* PickleIterator::GetReadPointerAndAdvance(int num_elements, size_t element_size) { int64_t num_bytes = static_cast<int64_t>(num_elements) * element_size; int num_bytes32 = static_cast<int>(num_bytes); if (num_bytes != static_cast<int64_t>(num_bytes32)) { return nullptr; } return GetReadPointerAndAdvance(num_bytes32); } // payload is uint32 aligned Pickle::Pickle() : header_(nullptr), capacity_(0), buffer_offset_(0) { Resize(kPayloadUnit); header_->payload_size = 0; } Pickle::Pickle(const char* data, int) : header_(reinterpret_cast<Header*>(const_cast<char*>(data))), capacity_(kCapacityReadOnly), buffer_offset_(0) {} /* @ brief a deep copy of an Pickle object */ Pickle::Pickle(const Pickle& other) : header_(nullptr), capacity_(0), buffer_offset_(other.buffer_offset_) { // if [other] is constructed from a const buffer, its capacity value is // kCapacityReadOnly. therefore, calculate its capacity on hand. size_t capacity = sizeof(Header) + other.header_->payload_size; bool resized = Resize(capacity); assert(resized); memcpy_s(header_, capacity_, other.header_, capacity); } Pickle::~Pickle() { if (capacity_ != kCapacityReadOnly) { free(header_); } } Pickle& Pickle::operator=(const Pickle& rhs) { if (this == &rhs) { assert(false); return *this; } if (capacity_ == kCapacityReadOnly) { header_ = nullptr; capacity_ = 0; } size_t capacity = sizeof(Header) + rhs.header_->payload_size; bool resized = Resize(capacity); assert(resized); memcpy_s(header_, capacity_, rhs.header_, capacity); buffer_offset_ = rhs.buffer_offset_; return *this; } /* @ brief resize the capacity of internal buffer. this function internally rounds the [new_capacity] up to the next multiple of predefined alignment @ params new_capacity[in] new capacity of internal buffer and will be aligned internally. be wary of that, the new_capacity actually includes internal header size. e.g. new_capacity = header_size + your_desired_payload_size */ bool Pickle::Resize(size_t new_capacity) { assert(capacity_ != kCapacityReadOnly); new_capacity = AlignInt(new_capacity, kPayloadUnit); void* p = realloc(header_, new_capacity); if (!p) { return false; } header_ = static_cast<Header*>(p); capacity_ = new_capacity; return true; } // static size_t Pickle::AlignInt(size_t i, int alignment) { return i + (alignment - i % alignment) % alignment; } bool Pickle::WriteString(const std::string& value) { if (!WriteInt(static_cast<int>(value.size()))) { return false; } return WriteByte(value.data(), static_cast<int>(value.size())); } bool Pickle::WriteWString(const std::wstring& value) { if (!WriteInt(static_cast<int>(value.size()))) { return false; } return WriteByte(value.data(), static_cast<int>(value.size() * sizeof(wchar_t))); } /* @ brief serialize data in byte with specified length. PoD types only the function guarantees the internal data remains unchanged if this funtion fails. */ bool Pickle::WriteByte(const void* data, int data_len) { if (capacity_ == kCapacityReadOnly) { assert(false); return false; } char* dest = BeginWrite(data_len); if (!dest) { return false; } size_t extra_size = capacity_ - (dest - reinterpret_cast<char*>(header_)); memcpy_s(dest, extra_size, data, data_len); EndWrite(dest, data_len); return true; } /* @ brief locate to the next uint32-aligned offset. and resize internal buffer if necessary. @ return the location that the data should be written at, or nullptr if an error occured. */ char* Pickle::BeginWrite(size_t length) { // write at a uint32-aligned offset from the begining of head size_t offset = AlignInt(header_->payload_size, sizeof(uint32_t)); size_t required_size = offset + length; size_t total_required_size = required_size + sizeof(Header); if (total_required_size > capacity_ && !Resize(std::max(capacity_ << 1, total_required_size))) { return nullptr; } header_->payload_size = static_cast<uint32_t>(required_size); return mutable_payload() + offset; } /* @ brief zero pading memory; otherwise some memory detectors may complain about uninitialized memory. */ void Pickle::EndWrite(char* dest, size_t length) { if (length % sizeof(uint32_t)) { memset(dest + length, 0, sizeof(uint32_t) - (length % sizeof(uint32_t))); } } } <|endoftext|>
<commit_before>/* * NicoW * 31.05.12 */ #include <iostream> // REMOVE #include <algorithm> #include <sstream> #include <vector> #include "Match.hpp" #include "GameResult.hpp" #include "GameManager.hpp" GameResult::GameResult(GameManager & game, Match & match) : AMenu("menu/background/backgroundResult.jpg", "menu/background/backgroundResult.jpg", 4800.0f, -1.0f, 0.0f, game), _isBuilt(false), _match(match) { this->_tags.push_back(new Tag("menu/tags/BackSmallNormal.png", "menu/tags/BackSmallHighlit.png", true, false, TokenMenu::GAMERESULT, 5950.0f, 0.0f, 700.0f)); } GameResult::~GameResult(void) { } double GameResult::getCenterX() const { return 5600.0f; } double GameResult::getCenterY() const { return 400.0f; } static bool orderKill(APlayer *one, APlayer *two) { return (one && two && one->getNbKills() > two->getNbKills()); } void GameResult::buildPlayerScore() { this->_playerScore = this->_match._players; for (std::list<APlayer*>::iterator deadIt = this->_match._dead.begin() ; deadIt != this->_match._dead.end() ; ++deadIt) this->_playerScore.push_back(*deadIt); for (std::list<APlayer*>::iterator cadaverIt = this->_match._cadaver.begin() ; cadaverIt != this->_match._cadaver.end() ; ++cadaverIt) this->_playerScore.push_back(*cadaverIt); } void GameResult::buildGameResult() { this->buildPlayerScore(); std::sort(_playerScore.begin(), _playerScore.end(), orderKill); this->_isBuilt = true; } /*void GameResult::saveStats(APlayer* p, Profile* pr) { } void GameResult::clearGame() { for (std::vector<APlayer*>::iterator it = this->_playerScore.begin(); it != this->_playerScore.end(); ++it) if ((*it)->getId() == this->_gameManager._mainProfile->getId()) this->saveStats((*it), this->_gameManager._mainProfile); else if ((*it)->getId() == this->_gameManager._secondProfile->getId()) this->saveStats((*it), this->_gameManager._secondProfile); while (this->_gameManager._match._players.size()) { delete _gameManager._match._players.back(); this->_gameManager._match._players.pop_back(); } while (this->_gameManager._match._dead.size()) { delete _gameManager._match._dead.back(); this->_gameManager._match._dead.pop_back(); } while (this->_gameManager._match._cadaver.size()) { delete _gameManager._match._cadaver.back(); this->_gameManager._match._cadaver.pop_back(); } while (this->_gameManager._match._bombs.size()) { delete this->_gameManager._match._bombs.back(); this->_gameManager._match._bombs.pop_back(); } while (this->_gameManager._match._bonus.size()) { delete this->_gameManager._match._bonus.back(); this->_gameManager._match._bonus.pop_back(); } while (this->_gameManager._match._explodedBombs.size()) { delete this->_gameManager._match._explodedBombs.back(); this->_gameManager._match._explodedBombs.pop_back(); } }*/ void GameResult::update(gdl::GameClock const& clock, gdl::Input& input) { if (this->_isBuilt) { for (size_t i = 0; i < this->_keyEvent.size(); ++i) if (input.isKeyDown(this->_keyEvent[i].first)) (this->*_keyEvent[i].second)(clock); if (this->_curToken == TokenMenu::GAMERESULT) this->_isBuilt = false; } else this->buildGameResult(); } void GameResult::draw() { int y = 358; AMenu::draw(); for (unsigned int i = 0 ; this->_textDraw == true && i < this->_playerScore.size() && i < 5; ++i) { int x = 400; gdl::Text text; std::string str; std::stringstream sstrm; APlayer* playerScore = this->_playerScore[i]; if (playerScore->getType() == AIType::HUMAN) str.assign("PLAYER"); else str.assign("Computer"); text.setText(str); text.setSize(20); text.setPosition(x, y); text.draw(); x += 310; sstrm.clear(); sstrm << playerScore->getTeamId(); sstrm >> str; text.setText(str); text.setSize(20); text.setPosition(x, y); text.draw(); x += 170; sstrm.clear(); sstrm << playerScore->getNbKills(); sstrm >> str; text.setText(str); text.setSize(20); text.setPosition(x, y); text.draw(); x += 250; sstrm.clear(); sstrm << playerScore->getNbKills() * 26; sstrm >> str; text.setText(str); text.setSize(20); text.setPosition(x, y); text.draw(); y += 53; } } <commit_msg>game result winning team<commit_after>/* * NicoW * 31.05.12 */ #include <iostream> // REMOVE #include <algorithm> #include <sstream> #include <vector> #include "Match.hpp" #include "GameResult.hpp" #include "GameManager.hpp" static const std::string g_refTeam[] = { "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red", "Red" }; GameResult::GameResult(GameManager & game, Match & match) : AMenu("menu/background/backgroundResult.jpg", "menu/background/backgroundResult.jpg", 4800.0f, -1.0f, 0.0f, game), _isBuilt(false), _match(match) { this->_tags.push_back(new Tag("menu/tags/BackSmallNormal.png", "menu/tags/BackSmallHighlit.png", true, false, TokenMenu::GAMERESULT, 5950.0f, 0.0f, 700.0f)); } GameResult::~GameResult(void) { } double GameResult::getCenterX() const { return 5600.0f; } double GameResult::getCenterY() const { return 400.0f; } static bool orderKill(APlayer *one, APlayer *two) { return (one && two && one->getNbKills() > two->getNbKills()); } void GameResult::buildPlayerScore() { this->_playerScore = this->_match._players; for (std::list<APlayer*>::iterator deadIt = this->_match._dead.begin() ; deadIt != this->_match._dead.end() ; ++deadIt) this->_playerScore.push_back(*deadIt); for (std::list<APlayer*>::iterator cadaverIt = this->_match._cadaver.begin() ; cadaverIt != this->_match._cadaver.end() ; ++cadaverIt) this->_playerScore.push_back(*cadaverIt); } void GameResult::buildGameResult() { this->buildPlayerScore(); std::sort(_playerScore.begin(), _playerScore.end(), orderKill); this->_isBuilt = true; } /*void GameResult::saveStats(APlayer* p, Profile* pr) { } void GameResult::clearGame() { for (std::vector<APlayer*>::iterator it = this->_playerScore.begin(); it != this->_playerScore.end(); ++it) if ((*it)->getId() == this->_gameManager._mainProfile->getId()) this->saveStats((*it), this->_gameManager._mainProfile); else if ((*it)->getId() == this->_gameManager._secondProfile->getId()) this->saveStats((*it), this->_gameManager._secondProfile); while (this->_gameManager._match._players.size()) { delete _gameManager._match._players.back(); this->_gameManager._match._players.pop_back(); } while (this->_gameManager._match._dead.size()) { delete _gameManager._match._dead.back(); this->_gameManager._match._dead.pop_back(); } while (this->_gameManager._match._cadaver.size()) { delete _gameManager._match._cadaver.back(); this->_gameManager._match._cadaver.pop_back(); } while (this->_gameManager._match._bombs.size()) { delete this->_gameManager._match._bombs.back(); this->_gameManager._match._bombs.pop_back(); } while (this->_gameManager._match._bonus.size()) { delete this->_gameManager._match._bonus.back(); this->_gameManager._match._bonus.pop_back(); } while (this->_gameManager._match._explodedBombs.size()) { delete this->_gameManager._match._explodedBombs.back(); this->_gameManager._match._explodedBombs.pop_back(); } }*/ void GameResult::update(gdl::GameClock const& clock, gdl::Input& input) { if (this->_isBuilt) { for (size_t i = 0; i < this->_keyEvent.size(); ++i) if (input.isKeyDown(this->_keyEvent[i].first)) (this->*_keyEvent[i].second)(clock); if (this->_curToken == TokenMenu::GAMERESULT) this->_isBuilt = false; } else this->buildGameResult(); } void GameResult::draw() { int y = 358; AMenu::draw(); if (this->_match._players.size()) { gdl::Text text; std::stringstream sstrm; sstrm << this->_match._players.front()->getTeamId() + 1; text.setText("Team " + sstrm.str() + " -- " + g_refTeam[this->_match._players.front()->getTeamId()]); text.setSize(20); text.setPosition(850, 196); text.draw(); } for (unsigned int i = 0 ; this->_textDraw == true && i < this->_playerScore.size() && i < 5; ++i) { int x = 400; gdl::Text text; std::string str; std::stringstream sstrm; APlayer* playerScore = this->_playerScore[i]; if (playerScore->getType() == AIType::HUMAN) str.assign("PLAYER"); else str.assign("Computer"); text.setText(str); text.setSize(20); text.setPosition(x, y); text.draw(); x += 310; sstrm.clear(); sstrm << playerScore->getTeamId() + 1; // MAJ +1 a tout les ID sstrm >> str; text.setText(str); text.setSize(20); text.setPosition(x, y); text.draw(); x += 170; sstrm.clear(); sstrm << playerScore->getNbKills(); sstrm >> str; text.setText(str); text.setSize(20); text.setPosition(x, y); text.draw(); x += 250; sstrm.clear(); sstrm << playerScore->getNbKills() * 26; sstrm >> str; text.setText(str); text.setSize(20); text.setPosition(x, y); text.draw(); y += 53; } } <|endoftext|>
<commit_before>#include "positiontracker.h" #include <cmath> #include <common/config/configmanager.h> PositionTracker::PositionTracker() : LOnGPSData(this), LOnMotionCommand(this), LOnIMUData(this) { } Position PositionTracker::GetPosition() { return _current_estimate; } Position PositionTracker::UpdateWithMeasurement(Position S, Position Measurement) { Position result; result.Latitude = ( S.Latitude*Measurement.Latitude.Variance + Measurement.Latitude*S.Latitude.Variance ) / (S.Latitude.Variance+Measurement.Latitude.Variance); result.Longitude = ( S.Longitude*Measurement.Longitude.Variance + Measurement.Longitude*S.Longitude.Variance ) / (S.Longitude.Variance+Measurement.Longitude.Variance); result.Heading = ( S.Heading*Measurement.Heading.Variance + Measurement.Heading*S.Heading.Variance ) / (S.Heading.Variance+Measurement.Heading.Variance); result.Latitude.Variance = ( 1.0 / (1.0/S.Latitude.Variance + 1.0 / Measurement.Latitude.Variance) ); result.Longitude.Variance = ( 1.0 / (1.0/S.Longitude.Variance + 1.0 / Measurement.Longitude.Variance) ); result.Heading.Variance = ( 1.0 / (1.0/S.Heading.Variance + 1.0 / Measurement.Heading.Variance) ); return result; } Position PositionTracker::UpdateWithMotion(Position S, Position Delta) { Position result; result.Latitude = S.Latitude + Delta.Latitude; result.Longitude = S.Longitude + Delta.Longitude; result.Heading = S.Heading + Delta.Heading; result.Latitude.Variance = S.Latitude.Variance + Delta.Latitude.Variance; result.Longitude.Variance = S.Longitude.Variance + Delta.Longitude.Variance; result.Heading.Variance = S.Heading.Variance + Delta.Heading.Variance; return result; } Position PositionTracker::DeltaFromMotionCommand(MotorCommand cmd) { using namespace std; double V = ( cmd.rightVel + cmd.leftVel ) / 2.0; double W = ( cmd.rightVel - cmd.leftVel ) / ConfigManager::Instance().getValue("Robot", "Baseline", 1.0); double t = cmd.millis / 1000.0; double R = V/W; Position delta; double theta = _current_estimate.Heading * M_PI/180.0; double thetaPrime = (_current_estimate.Heading + W*t) * M_PI/180.0; delta.Heading = W*t; delta.Latitude = R*(cos(theta) - cos(thetaPrime)); delta.Longitude = R*(sin(thetaPrime) - sin(theta)); // TODO - handle variances return delta; } Position PositionTracker::MeasurementFromIMUData(IMUData data) { // Uses the "Destination point given distance and bearing from start point" described here: // http://www.movable-type.co.uk/scripts/latlong.html#destPoint Position measurement; double lat1 = _current_estimate.Latitude; double lon1 = _current_estimate.Latitude; double hed1 = _current_estimate.Heading; double dx = data.X /* * time*time */; double dy = data.Y /* * time*time */; double d = sqrt(dx*dx + dy*dy); // Distance travelled double R = 6378137; // radius of Earth measurement.Latitude = asin(sin(lat1)*cos(d/R)+cos(lat1)*sin(d/R)*cos(hed1)); measurement.Longitude = (lon1 + atan2(sin(hed1)*sin(d/R)*cos(lat1),cos(d/R)-sin(lat1)*sin(measurement.Latitude))); measurement.Heading = (atan2((measurement.Longitude-lon1)*sin(lat1), cos(measurement.Latitude)*sin(lat1)-sin(measurement.Latitude)*cos(lat1)*cos(measurement.Longitude-lon1))); measurement.Heading = (measurement.Heading+180); while(measurement.Heading >= 360) measurement.Heading = (measurement.Heading - 360); while(measurement.Heading < 0) measurement.Heading = (measurement.Heading + 360); // TODO - handle variances return measurement; } void PositionTracker::OnGPSData(GPSData data) { Position measurement; measurement.Latitude = data.Lat(); measurement.Longitude = data.Long(); // TODO - make sure the GPS actually outputs heading data measurement.Heading = data.Heading(); // TODO - handle variances _current_estimate = UpdateWithMeasurement(_current_estimate, measurement); } void PositionTracker::OnIMUData(IMUData data) { _current_estimate = UpdateWithMeasurement(_current_estimate, MeasurementFromIMUData(data)); } void PositionTracker::OnMotionCommand(MotorCommand cmd) { _current_estimate = UpdateWithMotion(_current_estimate, DeltaFromMotionCommand(cmd)); } <commit_msg>Adds some TODO comments to PositionTracker.<commit_after>#include "positiontracker.h" #include <cmath> #include <common/config/configmanager.h> PositionTracker::PositionTracker() : LOnGPSData(this), LOnMotionCommand(this), LOnIMUData(this) { } Position PositionTracker::GetPosition() { return _current_estimate; } Position PositionTracker::UpdateWithMeasurement(Position S, Position Measurement) { Position result; result.Latitude = ( S.Latitude*Measurement.Latitude.Variance + Measurement.Latitude*S.Latitude.Variance ) / (S.Latitude.Variance+Measurement.Latitude.Variance); result.Longitude = ( S.Longitude*Measurement.Longitude.Variance + Measurement.Longitude*S.Longitude.Variance ) / (S.Longitude.Variance+Measurement.Longitude.Variance); result.Heading = ( S.Heading*Measurement.Heading.Variance + Measurement.Heading*S.Heading.Variance ) / (S.Heading.Variance+Measurement.Heading.Variance); result.Latitude.Variance = ( 1.0 / (1.0/S.Latitude.Variance + 1.0 / Measurement.Latitude.Variance) ); result.Longitude.Variance = ( 1.0 / (1.0/S.Longitude.Variance + 1.0 / Measurement.Longitude.Variance) ); result.Heading.Variance = ( 1.0 / (1.0/S.Heading.Variance + 1.0 / Measurement.Heading.Variance) ); return result; } Position PositionTracker::UpdateWithMotion(Position S, Position Delta) { Position result; result.Latitude = S.Latitude + Delta.Latitude; result.Longitude = S.Longitude + Delta.Longitude; result.Heading = S.Heading + Delta.Heading; result.Latitude.Variance = S.Latitude.Variance + Delta.Latitude.Variance; result.Longitude.Variance = S.Longitude.Variance + Delta.Longitude.Variance; result.Heading.Variance = S.Heading.Variance + Delta.Heading.Variance; return result; } Position PositionTracker::DeltaFromMotionCommand(MotorCommand cmd) { /* * TODO - Need to make sure this accounts for the time it takes to actually get to where we're going. * Perhaps fire this after the motion command is done. */ using namespace std; double V = ( cmd.rightVel + cmd.leftVel ) / 2.0; double W = ( cmd.rightVel - cmd.leftVel ) / ConfigManager::Instance().getValue("Robot", "Baseline", 1.0); double t = cmd.millis / 1000.0; double R = V/W; Position delta; double theta = _current_estimate.Heading * M_PI/180.0; double thetaPrime = (_current_estimate.Heading + W*t) * M_PI/180.0; delta.Heading = W*t; delta.Latitude = R*(cos(theta) - cos(thetaPrime)); delta.Longitude = R*(sin(thetaPrime) - sin(theta)); // TODO - handle variances return delta; } Position PositionTracker::MeasurementFromIMUData(IMUData data) { // Uses the "Destination point given distance and bearing from start point" described here: // http://www.movable-type.co.uk/scripts/latlong.html#destPoint Position measurement; double lat1 = _current_estimate.Latitude; double lon1 = _current_estimate.Latitude; double hed1 = _current_estimate.Heading; double dx = data.X /* * time*time */; double dy = data.Y /* * time*time */; double d = sqrt(dx*dx + dy*dy); // Distance travelled double R = 6378137; // radius of Earth measurement.Latitude = asin(sin(lat1)*cos(d/R)+cos(lat1)*sin(d/R)*cos(hed1)); measurement.Longitude = (lon1 + atan2(sin(hed1)*sin(d/R)*cos(lat1),cos(d/R)-sin(lat1)*sin(measurement.Latitude))); measurement.Heading = (atan2((measurement.Longitude-lon1)*sin(lat1), cos(measurement.Latitude)*sin(lat1)-sin(measurement.Latitude)*cos(lat1)*cos(measurement.Longitude-lon1))); measurement.Heading = (measurement.Heading+180); while(measurement.Heading >= 360) measurement.Heading = (measurement.Heading - 360); while(measurement.Heading < 0) measurement.Heading = (measurement.Heading + 360); // TODO - handle variances return measurement; } void PositionTracker::OnGPSData(GPSData data) { Position measurement; measurement.Latitude = data.Lat(); measurement.Longitude = data.Long(); // TODO - make sure the GPS actually outputs heading data measurement.Heading = data.Heading(); // TODO - handle variances _current_estimate = UpdateWithMeasurement(_current_estimate, measurement); } void PositionTracker::OnIMUData(IMUData data) { _current_estimate = UpdateWithMeasurement(_current_estimate, MeasurementFromIMUData(data)); } void PositionTracker::OnMotionCommand(MotorCommand cmd) { /* * TODO - Need to make sure this accounts for the time it takes to actually get to where we're going. * Perhaps fire this after the motion command is done. */ _current_estimate = UpdateWithMotion(_current_estimate, DeltaFromMotionCommand(cmd)); } <|endoftext|>
<commit_before>#include "Genes/Gene.h" #include <cmath> #include <iostream> #include <algorithm> #include <utility> #include <map> #include <fstream> #include <numeric> #include <iterator> #include <limits> #include "Game/Board.h" #include "Game/Color.h" #include "Utility/Random.h" #include "Utility/String.h" #include "Utility/Exceptions.h" #include "Utility/Math.h" std::map<std::string, double> Gene::list_properties() const noexcept { auto properties = std::map<std::string, double>{{"Priority - Opening", opening_priority}, {"Priority - Endgame", endgame_priority}}; adjust_properties(properties); return properties; } void Gene::adjust_properties(std::map<std::string, double>&) const noexcept { } void Gene::load_properties(const std::map<std::string, double>& properties) { if(properties.count("Priority - Opening") > 0) { opening_priority = properties.at("Priority - Opening"); } if(properties.count("Priority - Endgame") > 0) { endgame_priority = properties.at("Priority - Endgame"); } load_gene_properties(properties); } void Gene::load_gene_properties(const std::map<std::string, double>&) { } size_t Gene::mutatable_components() const noexcept { return list_properties().size(); } void Gene::read_from(std::istream& is) { auto properties = list_properties(); for(auto& [key, value] : properties) { value = std::numeric_limits<double>::quiet_NaN(); } for(std::string line; std::getline(is, line);) { if(String::trim_outer_whitespace(line).empty()) { break; } line = String::strip_comments(line, "#"); if(line.empty()) { continue; } auto split_line = String::split(line, ":"); if(split_line.size() != 2) { throw_on_invalid_line(line, "There should be exactly one colon per gene property line."); } auto property_name = String::remove_extra_whitespace(split_line[0]); auto property_data = String::remove_extra_whitespace(split_line[1]); if(property_name == "Name") { if(String::remove_extra_whitespace(property_data) == name()) { continue; } else { throw_on_invalid_line(line, "Reading data for wrong gene. Gene is " + name() + ", data is for " + property_data + "."); } } try { auto& current_value = properties.at(property_name); if(std::isnan(current_value)) { current_value = String::to_number<double>(property_data); } else { throw std::runtime_error("Duplicate parameter: " + property_name); } } catch(const std::out_of_range& e) { if(String::contains(e.what(), "at") || String::contains(e.what(), "invalid map<K, T> key")) { throw_on_invalid_line(line, "Unrecognized parameter name: " + property_name); } else if(String::contains(e.what(), "stod")) { throw_on_invalid_line(line, "Bad parameter value: " + property_data); } else { throw_on_invalid_line(line, e.what()); } } catch(const std::invalid_argument&) { throw_on_invalid_line(line, "Bad parameter value: " + property_data); } catch(const std::exception& e) { throw_on_invalid_line(line, e.what()); } } auto missing_data = std::accumulate(properties.begin(), properties.end(), std::string{}, [](const auto& so_far, const auto& key_value) { return so_far + (std::isnan(key_value.second) ? "\n" + key_value.first : ""); }); if( ! missing_data.empty()) { throw Genetic_AI_Creation_Error("Missing gene data for " + name() + ":" + missing_data); } load_properties(properties); } void Gene::read_from(const std::string& file_name) { auto ifs = std::ifstream(file_name); if( ! ifs) { throw Genetic_AI_Creation_Error("Could not open " + file_name + " to read."); } for(std::string line; std::getline(ifs, line);) { if(String::starts_with(line, "Name: ")) { auto gene_name = String::remove_extra_whitespace(String::split(line, ":", 1)[1]); if(gene_name == name()) { try { read_from(ifs); return; } catch(const std::exception& e) { throw Genetic_AI_Creation_Error("Error in reading data for " + name() + " from " + file_name + "\n" + e.what()); } } } } throw Genetic_AI_Creation_Error(name() + " not found in " + file_name); } void Gene::throw_on_invalid_line(const std::string& line, const std::string& reason) const { throw Genetic_AI_Creation_Error("Invalid line in while reading for " + name() + ": " + line + "\n" + reason); } void Gene::mutate() noexcept { auto properties = list_properties(); if(has_priority() && Random::success_probability(2, properties.size())) { (Random::coin_flip() ? opening_priority : endgame_priority) += Random::random_laplace(0.005); } else { gene_specific_mutation(); } } void Gene::gene_specific_mutation() noexcept { } double Gene::evaluate(const Board& board, Piece_Color perspective, size_t depth, double game_progress) const noexcept { auto scoring_priority = Math::interpolate(opening_priority, endgame_priority, game_progress); return scoring_priority*score_board(board, perspective, depth, game_progress); } void Gene::print(std::ostream& os) const noexcept { auto properties = list_properties(); os << "Name: " << name() << "\n"; for(const auto& [name, value] : properties) { os << name << ": " << value << "\n"; } os << "\n"; } void Gene::reset_piece_strength_gene(const Piece_Strength_Gene*) noexcept { } double Gene::priority(Game_Stage stage) const noexcept { return stage == Game_Stage::OPENING ? opening_priority : endgame_priority; } bool Gene::has_priority() const noexcept { return list_properties().count("Priority - Opening") != 0; } void Gene::scale_priority(Game_Stage stage, double k) noexcept { (stage == Game_Stage::OPENING ? opening_priority : endgame_priority) *= k; } void Gene::test(bool& test_variable, const Board& board, Piece_Color perspective, double expected_score) const noexcept { auto result = score_board(board, perspective, board.game_length(), 0.0); if(std::abs(result - expected_score) > 1e-6) { std::cerr << "Error in " << name() << ": Expected " << expected_score << ", Got: " << result << '\n'; test_variable = false; } } <commit_msg>Identify which gene test fails<commit_after>#include "Genes/Gene.h" #include <cmath> #include <iostream> #include <algorithm> #include <utility> #include <map> #include <fstream> #include <numeric> #include <iterator> #include <limits> #include "Game/Board.h" #include "Game/Color.h" #include "Utility/Random.h" #include "Utility/String.h" #include "Utility/Exceptions.h" #include "Utility/Math.h" std::map<std::string, double> Gene::list_properties() const noexcept { auto properties = std::map<std::string, double>{{"Priority - Opening", opening_priority}, {"Priority - Endgame", endgame_priority}}; adjust_properties(properties); return properties; } void Gene::adjust_properties(std::map<std::string, double>&) const noexcept { } void Gene::load_properties(const std::map<std::string, double>& properties) { if(properties.count("Priority - Opening") > 0) { opening_priority = properties.at("Priority - Opening"); } if(properties.count("Priority - Endgame") > 0) { endgame_priority = properties.at("Priority - Endgame"); } load_gene_properties(properties); } void Gene::load_gene_properties(const std::map<std::string, double>&) { } size_t Gene::mutatable_components() const noexcept { return list_properties().size(); } void Gene::read_from(std::istream& is) { auto properties = list_properties(); for(auto& [key, value] : properties) { value = std::numeric_limits<double>::quiet_NaN(); } for(std::string line; std::getline(is, line);) { if(String::trim_outer_whitespace(line).empty()) { break; } line = String::strip_comments(line, "#"); if(line.empty()) { continue; } auto split_line = String::split(line, ":"); if(split_line.size() != 2) { throw_on_invalid_line(line, "There should be exactly one colon per gene property line."); } auto property_name = String::remove_extra_whitespace(split_line[0]); auto property_data = String::remove_extra_whitespace(split_line[1]); if(property_name == "Name") { if(String::remove_extra_whitespace(property_data) == name()) { continue; } else { throw_on_invalid_line(line, "Reading data for wrong gene. Gene is " + name() + ", data is for " + property_data + "."); } } try { auto& current_value = properties.at(property_name); if(std::isnan(current_value)) { current_value = String::to_number<double>(property_data); } else { throw std::runtime_error("Duplicate parameter: " + property_name); } } catch(const std::out_of_range& e) { if(String::contains(e.what(), "at") || String::contains(e.what(), "invalid map<K, T> key")) { throw_on_invalid_line(line, "Unrecognized parameter name: " + property_name); } else if(String::contains(e.what(), "stod")) { throw_on_invalid_line(line, "Bad parameter value: " + property_data); } else { throw_on_invalid_line(line, e.what()); } } catch(const std::invalid_argument&) { throw_on_invalid_line(line, "Bad parameter value: " + property_data); } catch(const std::exception& e) { throw_on_invalid_line(line, e.what()); } } auto missing_data = std::accumulate(properties.begin(), properties.end(), std::string{}, [](const auto& so_far, const auto& key_value) { return so_far + (std::isnan(key_value.second) ? "\n" + key_value.first : ""); }); if( ! missing_data.empty()) { throw Genetic_AI_Creation_Error("Missing gene data for " + name() + ":" + missing_data); } load_properties(properties); } void Gene::read_from(const std::string& file_name) { auto ifs = std::ifstream(file_name); if( ! ifs) { throw Genetic_AI_Creation_Error("Could not open " + file_name + " to read."); } for(std::string line; std::getline(ifs, line);) { if(String::starts_with(line, "Name: ")) { auto gene_name = String::remove_extra_whitespace(String::split(line, ":", 1)[1]); if(gene_name == name()) { try { read_from(ifs); return; } catch(const std::exception& e) { throw Genetic_AI_Creation_Error("Error in reading data for " + name() + " from " + file_name + "\n" + e.what()); } } } } throw Genetic_AI_Creation_Error(name() + " not found in " + file_name); } void Gene::throw_on_invalid_line(const std::string& line, const std::string& reason) const { throw Genetic_AI_Creation_Error("Invalid line in while reading for " + name() + ": " + line + "\n" + reason); } void Gene::mutate() noexcept { auto properties = list_properties(); if(has_priority() && Random::success_probability(2, properties.size())) { (Random::coin_flip() ? opening_priority : endgame_priority) += Random::random_laplace(0.005); } else { gene_specific_mutation(); } } void Gene::gene_specific_mutation() noexcept { } double Gene::evaluate(const Board& board, Piece_Color perspective, size_t depth, double game_progress) const noexcept { auto scoring_priority = Math::interpolate(opening_priority, endgame_priority, game_progress); return scoring_priority*score_board(board, perspective, depth, game_progress); } void Gene::print(std::ostream& os) const noexcept { auto properties = list_properties(); os << "Name: " << name() << "\n"; for(const auto& [name, value] : properties) { os << name << ": " << value << "\n"; } os << "\n"; } void Gene::reset_piece_strength_gene(const Piece_Strength_Gene*) noexcept { } double Gene::priority(Game_Stage stage) const noexcept { return stage == Game_Stage::OPENING ? opening_priority : endgame_priority; } bool Gene::has_priority() const noexcept { return list_properties().count("Priority - Opening") != 0; } void Gene::scale_priority(Game_Stage stage, double k) noexcept { (stage == Game_Stage::OPENING ? opening_priority : endgame_priority) *= k; } void Gene::test(bool& test_variable, const Board& board, Piece_Color perspective, double expected_score) const noexcept { static auto test_number = 0; static auto last_gene_name = std::string{}; if(name() != last_gene_name) { test_number = 1; last_gene_name = name(); } else { ++test_number; } auto result = score_board(board, perspective, board.game_length(), 0.0); if(std::abs(result - expected_score) > 1e-6) { std::cerr << "Error in " << name() << " Test #" << test_number << ": Expected " << expected_score << ", Got: " << result << '\n'; test_variable = false; } } <|endoftext|>
<commit_before>/* * * Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker 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. * * Orion Context Broker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * fermin at tid dot es * * Author: Ken Zangelin */ #include "unittest.h" #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "rest/ConnectionInfo.h" extern int servicePathCheck(ConnectionInfo* ciP); /* **************************************************************************** * * rest.servicePathCheck - */ TEST(rest, servicePathCheck) { ConnectionInfo ci; int r; ci.servicePath = "/h1/_h2/h3/_h4/h5/_h6/h7/_h8/h9/_h10h10h10"; r = servicePathCheck(&ci); EXPECT_EQ(0, r); ci.servicePath = "/h1/h2/h3/h4/h5/h6/h7/h8/h9/h10/h11"; r = servicePathCheck(&ci); EXPECT_EQ(1, r); ci.servicePath = "/h0123456789"; r = servicePathCheck(&ci); EXPECT_EQ(2, r); ci.servicePath = "/h-0"; r = servicePathCheck(&ci); EXPECT_EQ(3, r); } <commit_msg>Comments in unit-test<commit_after>/* * * Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker 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. * * Orion Context Broker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * fermin at tid dot es * * Author: Ken Zangelin */ #include "unittest.h" #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "rest/ConnectionInfo.h" extern int servicePathCheck(ConnectionInfo* ciP); /* **************************************************************************** * * rest.servicePathCheck - */ TEST(rest, servicePathCheck) { ConnectionInfo ci; int r; // 1. OK ci.servicePath = "/h1/_h2/h3/_h4/h5/_h6/h7/_h8/h9/_h10h10h10"; r = servicePathCheck(&ci); EXPECT_EQ(0, r); // 2. More than 10 components in Service Path ci.servicePath = "/h1/h2/h3/h4/h5/h6/h7/h8/h9/h10/h11"; r = servicePathCheck(&ci); EXPECT_EQ(1, r); // More than 10 chars in path component of Service Path ci.servicePath = "/h0123456789"; r = servicePathCheck(&ci); EXPECT_EQ(2, r); // Bad character ('-') in Service Path ci.servicePath = "/h-0"; r = servicePathCheck(&ci); EXPECT_EQ(3, r); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AccessibleComponentBase.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2003-04-24 16:52:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "AccessibleComponentBase.hxx" #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_ #include <com/sun/star/accessibility/AccessibleRole.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_ #include <com/sun/star/drawing/XShapeDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_ #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::accessibility; namespace accessibility { //===== internal ============================================================ AccessibleComponentBase::AccessibleComponentBase (void) { } AccessibleComponentBase::~AccessibleComponentBase (void) { } //===== XAccessibleComponent ================================================ sal_Bool SAL_CALL AccessibleComponentBase::containsPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException) { awt::Size aSize (getSize()); return (aPoint.X >= 0) && (aPoint.X < aSize.Width) && (aPoint.Y >= 0) && (aPoint.Y < aSize.Height); } uno::Reference<XAccessible > SAL_CALL AccessibleComponentBase::getAccessibleAtPoint ( const awt::Point& aPoint) throw (uno::RuntimeException) { return uno::Reference<XAccessible>(); } awt::Rectangle SAL_CALL AccessibleComponentBase::getBounds (void) throw (uno::RuntimeException) { return awt::Rectangle(); } awt::Point SAL_CALL AccessibleComponentBase::getLocation (void) throw (::com::sun::star::uno::RuntimeException) { awt::Rectangle aBBox (getBounds()); return awt::Point (aBBox.X, aBBox.Y); } awt::Point SAL_CALL AccessibleComponentBase::getLocationOnScreen (void) throw (::com::sun::star::uno::RuntimeException) { return awt::Point(); } ::com::sun::star::awt::Size SAL_CALL AccessibleComponentBase::getSize (void) throw (::com::sun::star::uno::RuntimeException) { awt::Rectangle aBBox (getBounds()); return awt::Size (aBBox.Width, aBBox.Height); } void SAL_CALL AccessibleComponentBase::addFocusListener ( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener) throw (::com::sun::star::uno::RuntimeException) { // Ignored } void SAL_CALL AccessibleComponentBase::removeFocusListener (const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException) { // Ignored } void SAL_CALL AccessibleComponentBase::grabFocus (void) throw (::com::sun::star::uno::RuntimeException) { // Ignored } sal_Int32 SAL_CALL AccessibleComponentBase::getForeground (void) throw (::com::sun::star::uno::RuntimeException) { return Color(COL_BLACK).GetColor(); } sal_Int32 SAL_CALL AccessibleComponentBase::getBackground (void) throw (::com::sun::star::uno::RuntimeException) { return Color(COL_WHITE).GetColor(); } //===== XAccessibleExtendedComponent ======================================== ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL AccessibleComponentBase::getFont (void) throw (::com::sun::star::uno::RuntimeException) { return uno::Reference<awt::XFont>(); } ::rtl::OUString SAL_CALL AccessibleComponentBase::getTitledBorderText (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii (""); } ::rtl::OUString SAL_CALL AccessibleComponentBase::getToolTipText (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii (""); } //===== XTypeProvider =================================================== uno::Sequence<uno::Type> SAL_CALL AccessibleComponentBase::getTypes (void) throw (uno::RuntimeException) { // Get list of types from the context base implementation... uno::Sequence<uno::Type> aTypeList (2); // ...and add the additional type for the component. const uno::Type aComponentType = ::getCppuType((const uno::Reference<XAccessibleComponent>*)0); const uno::Type aExtendedComponentType = ::getCppuType((const uno::Reference<XAccessibleExtendedComponent>*)0); aTypeList[0] = aComponentType; aTypeList[1] = aExtendedComponentType; return aTypeList; } } // end of namespace accessibility <commit_msg>INTEGRATION: CWS draw12 (1.11.32); FILE MERGED 2003/05/19 08:50:37 af 1.11.32.1: #i14107# Doing single selection to grab focus to object.<commit_after>/************************************************************************* * * $RCSfile: AccessibleComponentBase.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: vg $ $Date: 2003-05-26 09:05:02 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "AccessibleComponentBase.hxx" #ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_ #include <com/sun/star/accessibility/AccessibleRole.hpp> #endif #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_SELECTION_HPP_ #include <com/sun/star/accessibility/XAccessibleSelection.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_ #include <com/sun/star/drawing/XShapeDescriptor.hpp> #endif #ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_ #include <com/sun/star/lang/IndexOutOfBoundsException.hpp> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::accessibility; namespace accessibility { //===== internal ============================================================ AccessibleComponentBase::AccessibleComponentBase (void) { } AccessibleComponentBase::~AccessibleComponentBase (void) { } //===== XAccessibleComponent ================================================ sal_Bool SAL_CALL AccessibleComponentBase::containsPoint ( const ::com::sun::star::awt::Point& aPoint) throw (::com::sun::star::uno::RuntimeException) { awt::Size aSize (getSize()); return (aPoint.X >= 0) && (aPoint.X < aSize.Width) && (aPoint.Y >= 0) && (aPoint.Y < aSize.Height); } uno::Reference<XAccessible > SAL_CALL AccessibleComponentBase::getAccessibleAtPoint ( const awt::Point& aPoint) throw (uno::RuntimeException) { return uno::Reference<XAccessible>(); } awt::Rectangle SAL_CALL AccessibleComponentBase::getBounds (void) throw (uno::RuntimeException) { return awt::Rectangle(); } awt::Point SAL_CALL AccessibleComponentBase::getLocation (void) throw (::com::sun::star::uno::RuntimeException) { awt::Rectangle aBBox (getBounds()); return awt::Point (aBBox.X, aBBox.Y); } awt::Point SAL_CALL AccessibleComponentBase::getLocationOnScreen (void) throw (::com::sun::star::uno::RuntimeException) { return awt::Point(); } ::com::sun::star::awt::Size SAL_CALL AccessibleComponentBase::getSize (void) throw (::com::sun::star::uno::RuntimeException) { awt::Rectangle aBBox (getBounds()); return awt::Size (aBBox.Width, aBBox.Height); } void SAL_CALL AccessibleComponentBase::addFocusListener ( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener) throw (::com::sun::star::uno::RuntimeException) { // Ignored } void SAL_CALL AccessibleComponentBase::removeFocusListener (const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException) { // Ignored } void SAL_CALL AccessibleComponentBase::grabFocus (void) throw (::com::sun::star::uno::RuntimeException) { uno::Reference<XAccessibleContext> xContext (this, uno::UNO_QUERY); uno::Reference<XAccessibleSelection> xSelection ( xContext->getAccessibleParent(), uno::UNO_QUERY); if (xSelection.is()) { // Do a single selection on this object. xSelection->clearAccessibleSelection(); xSelection->selectAccessibleChild (xContext->getAccessibleIndexInParent()); } } sal_Int32 SAL_CALL AccessibleComponentBase::getForeground (void) throw (::com::sun::star::uno::RuntimeException) { return Color(COL_BLACK).GetColor(); } sal_Int32 SAL_CALL AccessibleComponentBase::getBackground (void) throw (::com::sun::star::uno::RuntimeException) { return Color(COL_WHITE).GetColor(); } //===== XAccessibleExtendedComponent ======================================== ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL AccessibleComponentBase::getFont (void) throw (::com::sun::star::uno::RuntimeException) { return uno::Reference<awt::XFont>(); } ::rtl::OUString SAL_CALL AccessibleComponentBase::getTitledBorderText (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii (""); } ::rtl::OUString SAL_CALL AccessibleComponentBase::getToolTipText (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii (""); } //===== XTypeProvider =================================================== uno::Sequence<uno::Type> SAL_CALL AccessibleComponentBase::getTypes (void) throw (uno::RuntimeException) { // Get list of types from the context base implementation... uno::Sequence<uno::Type> aTypeList (2); // ...and add the additional type for the component. const uno::Type aComponentType = ::getCppuType((const uno::Reference<XAccessibleComponent>*)0); const uno::Type aExtendedComponentType = ::getCppuType((const uno::Reference<XAccessibleExtendedComponent>*)0); aTypeList[0] = aComponentType; aTypeList[1] = aExtendedComponentType; return aTypeList; } } // end of namespace accessibility <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2002, 2003 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ #include <tbytevectorlist.h> #include <id3v2tag.h> #include "textidentificationframe.h" using namespace TagLib; using namespace ID3v2; class TextIdentificationFrame::TextIdentificationFramePrivate { public: TextIdentificationFramePrivate() : textEncoding(String::Latin1) {} String::Type textEncoding; StringList fieldList; }; //////////////////////////////////////////////////////////////////////////////// // TextIdentificationFrame public members //////////////////////////////////////////////////////////////////////////////// TextIdentificationFrame::TextIdentificationFrame(const ByteVector &type, String::Type encoding) : Frame(type) { d = new TextIdentificationFramePrivate; d->textEncoding = encoding; } TextIdentificationFrame::TextIdentificationFrame(const ByteVector &data) : Frame(data) { d = new TextIdentificationFramePrivate; setData(data); } TextIdentificationFrame::~TextIdentificationFrame() { delete d; } void TextIdentificationFrame::setText(const StringList &l) { d->fieldList = l; } void TextIdentificationFrame::setText(const String &s) { d->fieldList = s; } String TextIdentificationFrame::toString() const { return d->fieldList.toString(); } StringList TextIdentificationFrame::fieldList() const { return d->fieldList; } String::Type TextIdentificationFrame::textEncoding() const { return d->textEncoding; } void TextIdentificationFrame::setTextEncoding(String::Type encoding) { d->textEncoding = encoding; } //////////////////////////////////////////////////////////////////////////////// // TextIdentificationFrame protected members //////////////////////////////////////////////////////////////////////////////// void TextIdentificationFrame::parseFields(const ByteVector &data) { // Don't try to parse invalid frames if(data.size() < 2) return; // read the string data type (the first byte of the field data) d->textEncoding = String::Type(data[0]); // split the byte array into chunks based on the string type (two byte delimiter // for unicode encodings) int byteAlign = d->textEncoding == String::Latin1 || d->textEncoding == String::UTF8 ? 1 : 2; // build a small counter to strip nulls off the end of the field int dataLength = data.size() - 1; while(dataLength > 0 && data[dataLength] == 0) dataLength--; while(dataLength % byteAlign != 0) dataLength++; ByteVectorList l = ByteVectorList::split(data.mid(1, dataLength), textDelimiter(d->textEncoding), byteAlign); d->fieldList.clear(); // append those split values to the list and make sure that the new string's // type is the same specified for this frame for(ByteVectorList::Iterator it = l.begin(); it != l.end(); it++) { String s(*it, d->textEncoding); d->fieldList.append(s); } } ByteVector TextIdentificationFrame::renderFields() const { ByteVector v; v.append(char(d->textEncoding)); for(StringList::ConstIterator it = d->fieldList.begin(); it != d->fieldList.end(); it++) { // Since the field list is null delimited, if this is not the first // element in the list, append the appropriate delimiter for this // encoding. if(it != d->fieldList.begin()) v.append(textDelimiter(d->textEncoding)); v.append((*it).data(d->textEncoding)); } return v; } //////////////////////////////////////////////////////////////////////////////// // TextIdentificationFrame private members //////////////////////////////////////////////////////////////////////////////// TextIdentificationFrame::TextIdentificationFrame(const ByteVector &data, Header *h) : Frame(h) { d = new TextIdentificationFramePrivate; parseFields(fieldData(data)); } //////////////////////////////////////////////////////////////////////////////// // UserTextIdentificationFrame public members //////////////////////////////////////////////////////////////////////////////// UserTextIdentificationFrame::UserTextIdentificationFrame(String::Type encoding) : TextIdentificationFrame("TXXX", encoding), d(0) { StringList l; l.append(String::null); l.append(String::null); setText(l); } UserTextIdentificationFrame::UserTextIdentificationFrame(const ByteVector &data) : TextIdentificationFrame(data) { checkFields(); } String UserTextIdentificationFrame::toString() const { return "[" + description() + "] " + fieldList().toString(); } String UserTextIdentificationFrame::description() const { return !TextIdentificationFrame::fieldList().isEmpty() ? TextIdentificationFrame::fieldList().front() : String::null; } StringList UserTextIdentificationFrame::fieldList() const { // TODO: remove this function return TextIdentificationFrame::fieldList(); } void UserTextIdentificationFrame::setText(const String &text) { if(description().isEmpty()) setDescription(String::null); TextIdentificationFrame::setText(StringList(description()).append(text)); } void UserTextIdentificationFrame::setText(const StringList &fields) { if(description().isEmpty()) setDescription(String::null); TextIdentificationFrame::setText(StringList(description()).append(fields)); } void UserTextIdentificationFrame::setDescription(const String &s) { StringList l = fieldList(); if(l.isEmpty()) l.append(s); else l[0] = s; TextIdentificationFrame::setText(l); } UserTextIdentificationFrame *UserTextIdentificationFrame::find( ID3v2::Tag *tag, const String &description) // static { FrameList l = tag->frameList("TXXX"); for(FrameList::Iterator it = l.begin(); it != l.end(); ++it) { UserTextIdentificationFrame *f = dynamic_cast<UserTextIdentificationFrame *>(*it); if(f && f->description() == description) return f; } return 0; } //////////////////////////////////////////////////////////////////////////////// // UserTextIdentificationFrame private members //////////////////////////////////////////////////////////////////////////////// UserTextIdentificationFrame::UserTextIdentificationFrame(const ByteVector &data, Header *h) : TextIdentificationFrame(data, h) { checkFields(); } void UserTextIdentificationFrame::checkFields() { int fields = fieldList().size(); if(fields == 0) setDescription(String::null); if(fields <= 1) setText(String::null); } <commit_msg>Don't include empty strings in the text field list. This is a slight deviation from the standard, but major editors (i.e. iTunes) mess up ID3v2 text frames with null termination (which technically indicates a field with content, plus an empty field).<commit_after>/*************************************************************************** copyright : (C) 2002, 2003 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ #include <tbytevectorlist.h> #include <id3v2tag.h> #include "textidentificationframe.h" using namespace TagLib; using namespace ID3v2; class TextIdentificationFrame::TextIdentificationFramePrivate { public: TextIdentificationFramePrivate() : textEncoding(String::Latin1) {} String::Type textEncoding; StringList fieldList; }; //////////////////////////////////////////////////////////////////////////////// // TextIdentificationFrame public members //////////////////////////////////////////////////////////////////////////////// TextIdentificationFrame::TextIdentificationFrame(const ByteVector &type, String::Type encoding) : Frame(type) { d = new TextIdentificationFramePrivate; d->textEncoding = encoding; } TextIdentificationFrame::TextIdentificationFrame(const ByteVector &data) : Frame(data) { d = new TextIdentificationFramePrivate; setData(data); } TextIdentificationFrame::~TextIdentificationFrame() { delete d; } void TextIdentificationFrame::setText(const StringList &l) { d->fieldList = l; } void TextIdentificationFrame::setText(const String &s) { d->fieldList = s; } String TextIdentificationFrame::toString() const { return d->fieldList.toString(); } StringList TextIdentificationFrame::fieldList() const { return d->fieldList; } String::Type TextIdentificationFrame::textEncoding() const { return d->textEncoding; } void TextIdentificationFrame::setTextEncoding(String::Type encoding) { d->textEncoding = encoding; } //////////////////////////////////////////////////////////////////////////////// // TextIdentificationFrame protected members //////////////////////////////////////////////////////////////////////////////// void TextIdentificationFrame::parseFields(const ByteVector &data) { // Don't try to parse invalid frames if(data.size() < 2) return; // read the string data type (the first byte of the field data) d->textEncoding = String::Type(data[0]); // split the byte array into chunks based on the string type (two byte delimiter // for unicode encodings) int byteAlign = d->textEncoding == String::Latin1 || d->textEncoding == String::UTF8 ? 1 : 2; // build a small counter to strip nulls off the end of the field int dataLength = data.size() - 1; while(dataLength > 0 && data[dataLength] == 0) dataLength--; while(dataLength % byteAlign != 0) dataLength++; ByteVectorList l = ByteVectorList::split(data.mid(1, dataLength), textDelimiter(d->textEncoding), byteAlign); d->fieldList.clear(); // append those split values to the list and make sure that the new string's // type is the same specified for this frame for(ByteVectorList::Iterator it = l.begin(); it != l.end(); it++) { if(!(*it).isEmpty()) { String s(*it, d->textEncoding); d->fieldList.append(s); } } } ByteVector TextIdentificationFrame::renderFields() const { ByteVector v; v.append(char(d->textEncoding)); for(StringList::ConstIterator it = d->fieldList.begin(); it != d->fieldList.end(); it++) { // Since the field list is null delimited, if this is not the first // element in the list, append the appropriate delimiter for this // encoding. if(it != d->fieldList.begin()) v.append(textDelimiter(d->textEncoding)); v.append((*it).data(d->textEncoding)); } return v; } //////////////////////////////////////////////////////////////////////////////// // TextIdentificationFrame private members //////////////////////////////////////////////////////////////////////////////// TextIdentificationFrame::TextIdentificationFrame(const ByteVector &data, Header *h) : Frame(h) { d = new TextIdentificationFramePrivate; parseFields(fieldData(data)); } //////////////////////////////////////////////////////////////////////////////// // UserTextIdentificationFrame public members //////////////////////////////////////////////////////////////////////////////// UserTextIdentificationFrame::UserTextIdentificationFrame(String::Type encoding) : TextIdentificationFrame("TXXX", encoding), d(0) { StringList l; l.append(String::null); l.append(String::null); setText(l); } UserTextIdentificationFrame::UserTextIdentificationFrame(const ByteVector &data) : TextIdentificationFrame(data) { checkFields(); } String UserTextIdentificationFrame::toString() const { return "[" + description() + "] " + fieldList().toString(); } String UserTextIdentificationFrame::description() const { return !TextIdentificationFrame::fieldList().isEmpty() ? TextIdentificationFrame::fieldList().front() : String::null; } StringList UserTextIdentificationFrame::fieldList() const { // TODO: remove this function return TextIdentificationFrame::fieldList(); } void UserTextIdentificationFrame::setText(const String &text) { if(description().isEmpty()) setDescription(String::null); TextIdentificationFrame::setText(StringList(description()).append(text)); } void UserTextIdentificationFrame::setText(const StringList &fields) { if(description().isEmpty()) setDescription(String::null); TextIdentificationFrame::setText(StringList(description()).append(fields)); } void UserTextIdentificationFrame::setDescription(const String &s) { StringList l = fieldList(); if(l.isEmpty()) l.append(s); else l[0] = s; TextIdentificationFrame::setText(l); } UserTextIdentificationFrame *UserTextIdentificationFrame::find( ID3v2::Tag *tag, const String &description) // static { FrameList l = tag->frameList("TXXX"); for(FrameList::Iterator it = l.begin(); it != l.end(); ++it) { UserTextIdentificationFrame *f = dynamic_cast<UserTextIdentificationFrame *>(*it); if(f && f->description() == description) return f; } return 0; } //////////////////////////////////////////////////////////////////////////////// // UserTextIdentificationFrame private members //////////////////////////////////////////////////////////////////////////////// UserTextIdentificationFrame::UserTextIdentificationFrame(const ByteVector &data, Header *h) : TextIdentificationFrame(data, h) { checkFields(); } void UserTextIdentificationFrame::checkFields() { int fields = fieldList().size(); if(fields == 0) setDescription(String::null); if(fields <= 1) setText(String::null); } <|endoftext|>
<commit_before>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <iostream> #include "SessionManager.h" #include "TcpSession.h" namespace nyx { TcpSession::TcpSession(tcp::socket&& socket) : socket_(std::move(socket)) , strand_(socket_.get_io_context()) , buffer_(1024) { } TcpSession::~TcpSession(void) { } void TcpSession::do_read(void) { auto self(shared_from_this()); socket_.async_read_some(asio::buffer(buffer_), [this, self](const std::error_code& ec, std::size_t n) { if (!ec) { handle_data(buffer_, n); do_read(); } else { disconnect(); } }); } void TcpSession::do_write(const std::string& buf) { auto self(shared_from_this()); strand_.post([this, self, buf] { asio::async_write(socket_, asio::buffer(buf), [this, self](const std::error_code& /*ec*/, std::size_t /*n*/) { }); }); } void TcpSession::disconnect(void) { if (closed_) return; closed_ = true; if (closed_fn_) closed_fn_(shared_from_this()); socket_.close(); SessionManager::get_instance().unreg_session(shared_from_this()); } void TcpSession::handle_data(std::vector<char>& buf, std::size_t n) { if (message_fn_) message_fn_(shared_from_this(), std::string(&buf[0], n)); } } <commit_msg>:construction: chore(session): updated the disconnection of tcp session<commit_after>// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <iostream> #include "SessionManager.h" #include "TcpSession.h" namespace nyx { TcpSession::TcpSession(tcp::socket&& socket) : socket_(std::move(socket)) , strand_(socket_.get_io_context()) , buffer_(1024) { } TcpSession::~TcpSession(void) { } void TcpSession::do_read(void) { auto self(shared_from_this()); socket_.async_read_some(asio::buffer(buffer_), [this, self](const std::error_code& ec, std::size_t n) { if (!ec) { handle_data(buffer_, n); do_read(); } else { disconnect(); } }); } void TcpSession::do_write(const std::string& buf) { auto self(shared_from_this()); strand_.post([this, self, buf] { asio::async_write(socket_, asio::buffer(buf), [this, self](const std::error_code& /*ec*/, std::size_t /*n*/) { }); }); } void TcpSession::disconnect(void) { auto self(shared_from_this()); strand_.post([this, self] { if (closed_) return; closed_ = true; if (closed_fn_) closed_fn_(shared_from_this()); socket_.close(); SessionManager::get_instance().unreg_session(shared_from_this()); }); } void TcpSession::handle_data(std::vector<char>& buf, std::size_t n) { if (message_fn_) message_fn_(shared_from_this(), std::string(&buf[0], n)); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 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. */ #include <gtest/gtest.h> #include "capu/util/ReadWriteLock.h" #include "capu/util/Runnable.h" #include "capu/os/Thread.h" class Reader: public capu::Runnable { public: bool& m_var; capu::ReadWriteLock& m_lock; Reader(bool& var, capu::ReadWriteLock& lock) : m_var(var) , m_lock(lock) { } inline void run() { m_lock.lockRead(); m_var = true; capu::Thread::Sleep(500); m_var = false; m_lock.unlockRead(); } }; class Writer: public capu::Runnable { public: bool& m_var; capu::ReadWriteLock& m_lock; Writer(bool& var, capu::ReadWriteLock& lock) : m_var(var) , m_lock(lock) { } inline void run() { m_lock.lockWrite(); EXPECT_FALSE(m_var); // no reader during write lock! m_lock.unlockWrite(); } }; TEST(ReadWriteLock, ReaderWriterLockTest) { capu::ReadWriteLock lock; bool readerIsInside = false; Reader r1(readerIsInside, lock); Reader r2(readerIsInside, lock); Reader r3(readerIsInside, lock); Writer w1(readerIsInside, lock); Writer w2(readerIsInside, lock); capu::Thread t1; capu::Thread t2; capu::Thread t3; capu::Thread t4; capu::Thread t5; t1.start(r1); t2.start(r2); t3.start(r3); t4.start(w1); t5.start(w2); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); } <commit_msg>Remove data race in ReadWriteLock test<commit_after>/* * Copyright (C) 2012 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. */ #include <gtest/gtest.h> #include "capu/util/ReadWriteLock.h" #include "capu/util/Runnable.h" #include "capu/os/Thread.h" class Reader: public capu::Runnable { public: capu::Atomic<bool>& m_var; capu::ReadWriteLock& m_lock; Reader(capu::Atomic<bool>& var, capu::ReadWriteLock& lock) : m_var(var) , m_lock(lock) { } inline void run() { m_lock.lockRead(); m_var = true; capu::Thread::Sleep(500); m_var = false; m_lock.unlockRead(); } }; class Writer: public capu::Runnable { public: capu::Atomic<bool>& m_var; capu::ReadWriteLock& m_lock; Writer(capu::Atomic<bool>& var, capu::ReadWriteLock& lock) : m_var(var) , m_lock(lock) { } inline void run() { m_lock.lockWrite(); EXPECT_FALSE(m_var); // no reader during write lock! m_lock.unlockWrite(); } }; TEST(ReadWriteLock, ReaderWriterLockTest) { capu::ReadWriteLock lock; capu::Atomic<bool> readerIsInside(false); Reader r1(readerIsInside, lock); Reader r2(readerIsInside, lock); Reader r3(readerIsInside, lock); Writer w1(readerIsInside, lock); Writer w2(readerIsInside, lock); capu::Thread t1; capu::Thread t2; capu::Thread t3; capu::Thread t4; capu::Thread t5; t1.start(r1); t2.start(r2); t3.start(r3); t4.start(w1); t5.start(w2); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); } <|endoftext|>
<commit_before>#include <sys/types.h> #include <sys/errno.h> #include <sys/event.h> #include <sys/time.h> #include <unistd.h> #include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> EventPoll::EventPoll(void) : log_("/event/poll"), read_poll_(), write_poll_(), kq_(kqueue()) { ASSERT(kq_ != -1); } EventPoll::~EventPoll() { ASSERT(read_poll_.empty()); ASSERT(write_poll_.empty()); } Action * EventPoll::poll(const Type& type, int fd, EventCallback *cb) { ASSERT(fd != -1); EventPoll::PollHandler *poll_handler; struct kevent kev; switch (type) { case EventPoll::Readable: ASSERT(read_poll_.find(fd) == read_poll_.end()); poll_handler = &read_poll_[fd]; EV_SET(&kev, fd, EVFILT_READ, EV_ADD, 0, 0, NULL); break; case EventPoll::Writable: ASSERT(write_poll_.find(fd) == write_poll_.end()); poll_handler = &write_poll_[fd]; EV_SET(&kev, fd, EVFILT_WRITE, EV_ADD, 0, 0, NULL); break; default: NOTREACHED(); } int evcnt = ::kevent(kq_, &kev, 1, NULL, 0, NULL); if (evcnt == -1) HALT(log_) << "Could not add event to kqueue."; ASSERT(evcnt == 0); ASSERT(poll_handler->action_ == NULL); poll_handler->callback_ = cb; Action *a = new EventPoll::PollAction(this, type, fd); return (a); } void EventPoll::cancel(const Type& type, int fd) { EventPoll::PollHandler *poll_handler; struct kevent kev; switch (type) { case EventPoll::Readable: ASSERT(read_poll_.find(fd) != read_poll_.end()); poll_handler = &read_poll_[fd]; poll_handler->cancel(); read_poll_.erase(fd); EV_SET(&kev, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); break; case EventPoll::Writable: ASSERT(write_poll_.find(fd) != write_poll_.end()); poll_handler = &write_poll_[fd]; poll_handler->cancel(); write_poll_.erase(fd); EV_SET(&kev, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); break; } int evcnt = ::kevent(kq_, &kev, 1, NULL, 0, NULL); if (evcnt == -1) HALT(log_) << "Could not delete event from kqueue."; ASSERT(evcnt == 0); } void EventPoll::wait(int ms) { static const unsigned kevcnt = 128; struct timespec ts; ts.tv_sec = ms / 1000; ts.tv_nsec = (ms % 1000) * 1000000; if (idle()) { if (ms != -1) { int rv; rv = nanosleep(&ts, NULL); ASSERT(rv != -1); } return; } struct kevent kev[kevcnt]; int evcnt = kevent(kq_, NULL, 0, kev, kevcnt, ms == -1 ? NULL : &ts); if (evcnt == -1) { if (errno == EINTR) { INFO(log_) << "Received interrupt, ceasing polling until stop handlers have run."; return; } HALT(log_) << "Could not poll kqueue."; } int i; for (i = 0; i < evcnt; i++) { struct kevent *ev = &kev[i]; EventPoll::PollHandler *poll_handler; switch (ev->filter) { case EVFILT_READ: ASSERT(read_poll_.find(ev->ident) != read_poll_.end()); poll_handler = &read_poll_[ev->ident]; break; case EVFILT_WRITE: ASSERT(write_poll_.find(ev->ident) != write_poll_.end()); poll_handler = &write_poll_[ev->ident]; break; default: NOTREACHED(); } if ((ev->flags & EV_ERROR) != 0) { poll_handler->callback(Event(Event::Error, ev->fflags)); continue; } if ((ev->flags & EV_EOF) != 0) { poll_handler->callback(Event(Event::EOS, ev->fflags)); continue; } poll_handler->callback(Event(Event::Done, ev->fflags)); } } <commit_msg>Assert that we are only generating EOS messages for read filters.<commit_after>#include <sys/types.h> #include <sys/errno.h> #include <sys/event.h> #include <sys/time.h> #include <unistd.h> #include <common/buffer.h> #include <event/action.h> #include <event/callback.h> #include <event/event_system.h> EventPoll::EventPoll(void) : log_("/event/poll"), read_poll_(), write_poll_(), kq_(kqueue()) { ASSERT(kq_ != -1); } EventPoll::~EventPoll() { ASSERT(read_poll_.empty()); ASSERT(write_poll_.empty()); } Action * EventPoll::poll(const Type& type, int fd, EventCallback *cb) { ASSERT(fd != -1); EventPoll::PollHandler *poll_handler; struct kevent kev; switch (type) { case EventPoll::Readable: ASSERT(read_poll_.find(fd) == read_poll_.end()); poll_handler = &read_poll_[fd]; EV_SET(&kev, fd, EVFILT_READ, EV_ADD, 0, 0, NULL); break; case EventPoll::Writable: ASSERT(write_poll_.find(fd) == write_poll_.end()); poll_handler = &write_poll_[fd]; EV_SET(&kev, fd, EVFILT_WRITE, EV_ADD, 0, 0, NULL); break; default: NOTREACHED(); } int evcnt = ::kevent(kq_, &kev, 1, NULL, 0, NULL); if (evcnt == -1) HALT(log_) << "Could not add event to kqueue."; ASSERT(evcnt == 0); ASSERT(poll_handler->action_ == NULL); poll_handler->callback_ = cb; Action *a = new EventPoll::PollAction(this, type, fd); return (a); } void EventPoll::cancel(const Type& type, int fd) { EventPoll::PollHandler *poll_handler; struct kevent kev; switch (type) { case EventPoll::Readable: ASSERT(read_poll_.find(fd) != read_poll_.end()); poll_handler = &read_poll_[fd]; poll_handler->cancel(); read_poll_.erase(fd); EV_SET(&kev, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); break; case EventPoll::Writable: ASSERT(write_poll_.find(fd) != write_poll_.end()); poll_handler = &write_poll_[fd]; poll_handler->cancel(); write_poll_.erase(fd); EV_SET(&kev, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); break; } int evcnt = ::kevent(kq_, &kev, 1, NULL, 0, NULL); if (evcnt == -1) HALT(log_) << "Could not delete event from kqueue."; ASSERT(evcnt == 0); } void EventPoll::wait(int ms) { static const unsigned kevcnt = 128; struct timespec ts; ts.tv_sec = ms / 1000; ts.tv_nsec = (ms % 1000) * 1000000; if (idle()) { if (ms != -1) { int rv; rv = nanosleep(&ts, NULL); ASSERT(rv != -1); } return; } struct kevent kev[kevcnt]; int evcnt = kevent(kq_, NULL, 0, kev, kevcnt, ms == -1 ? NULL : &ts); if (evcnt == -1) { if (errno == EINTR) { INFO(log_) << "Received interrupt, ceasing polling until stop handlers have run."; return; } HALT(log_) << "Could not poll kqueue."; } int i; for (i = 0; i < evcnt; i++) { struct kevent *ev = &kev[i]; EventPoll::PollHandler *poll_handler; switch (ev->filter) { case EVFILT_READ: ASSERT(read_poll_.find(ev->ident) != read_poll_.end()); poll_handler = &read_poll_[ev->ident]; break; case EVFILT_WRITE: ASSERT(write_poll_.find(ev->ident) != write_poll_.end()); poll_handler = &write_poll_[ev->ident]; break; default: NOTREACHED(); } if ((ev->flags & EV_ERROR) != 0) { poll_handler->callback(Event(Event::Error, ev->fflags)); continue; } if ((ev->flags & EV_EOF) != 0) { ASSERT(ev->filter == EVFILT_READ); poll_handler->callback(Event(Event::EOS, ev->fflags)); continue; } poll_handler->callback(Event(Event::Done, ev->fflags)); } } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * Simbody(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2011-12 Stanford University and the Authors. * * Authors: Peter Eastman * * Contributors: * * * * 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 "SimTKsimbody.h" #include "SimTKcommon/Testing.h" #include <vector> #include <map> using namespace SimTK; using namespace std; const Real TOL = 1e-10; #define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, "Assertion failed");} template <class T> void assertEqual(T val1, T val2) { ASSERT(abs(val1-val2) < TOL); } template <int N> void assertEqual(Vec<N> val1, Vec<N> val2) { for (int i = 0; i < N; ++i) ASSERT(abs(val1[i]-val2[i]) < TOL); } static void compareToTranslate(bool prescribe, Motion::Level level) { // Create a system of pairs of identical bodies, where half will be implemented with RBNodeLoneParticle // and half with RBNodeTranslate. MultibodySystem system; SimbodyMatterSubsystem matter(system); GeneralForceSubsystem force(system); Force::UniformGravity gravity(force, matter, Vec3(1.1, 1.2, 1.3)); Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1))); Random::Gaussian random(0.0, 3.0); const int numBodies = 10; for (int i = 0; i < numBodies; i++) { MobilizedBody::Translation body1(matter.updGround(), body); MobilizedBody::Translation body2(matter.updGround(), Vec3(0), body, Vec3(1e-100)); Vec3 station1(random.getValue(), random.getValue(), random.getValue()); Vec3 station2(random.getValue(), random.getValue(), random.getValue()); Real length = random.getValue(); Force::TwoPointLinearSpring(force, matter.updGround(), station1, body1, station2, 1.0, length); Force::TwoPointLinearSpring(force, matter.updGround(), station1, body2, station2, 1.0, length); if (prescribe) { Real phase = random.getValue(); Motion::Sinusoid(body1, level, 1.5, 1.1, phase); Motion::Sinusoid(body2, level, 1.5, 1.1, phase); } } // Initialize the state. State state = system.realizeTopology(); for (int i = 0; i < numBodies; i++) { Vec3 pos(random.getValue(), random.getValue(), random.getValue()); Vec3 vel(random.getValue(), random.getValue(), random.getValue()); const MobilizedBody& body1 = matter.getMobilizedBody(MobilizedBodyIndex(2*i+1)); const MobilizedBody& body2 = matter.getMobilizedBody(MobilizedBodyIndex(2*i+2)); body1.setQToFitTranslation(state, pos); body2.setQToFitTranslation(state, pos); body1.setUToFitLinearVelocity(state, vel); body2.setUToFitLinearVelocity(state, vel); } // Calculate lots of quantities from the MobilizedBodies. system.realize(state, Stage::Acceleration); Vector_<SpatialVec> reactionForces; matter.calcMobilizerReactionForces(state, reactionForces); Vector_<SpatialVec> reactionForcesFreebody; matter.calcMobilizerReactionForcesUsingFreebodyMethod(state, reactionForcesFreebody); // Both methods should produce the same results. SimTK_TEST_EQ(reactionForces, reactionForcesFreebody); Vector mv, minvv; matter.multiplyByM(state, state.getU(), mv); matter.multiplyByMInv(state, state.getU(), minvv); Vector appliedMobilityForces(matter.getNumMobilities()); Vector_<SpatialVec> appliedBodyForces(matter.getNumBodies()); for (int i = 0; i < numBodies; i++) { Vec3 mobilityForce; random.fillArray((Real*) &mobilityForce, 3); Vec3::updAs(&appliedMobilityForces[6*i]) = mobilityForce; Vec3::updAs(&appliedMobilityForces[6*i+3]) = mobilityForce; SpatialVec bodyForce; random.fillArray((Real*) &bodyForce, 6); appliedBodyForces[2*i+1] = bodyForce; appliedBodyForces[2*i+2] = bodyForce; } Vector knownUdot, residualMobilityForces; matter.calcResidualForceIgnoringConstraints(state, appliedMobilityForces, appliedBodyForces, knownUdot, residualMobilityForces); Vector dEdQ; matter.multiplyBySystemJacobianTranspose(state, appliedBodyForces, dEdQ); Array_<SpatialInertia,MobilizedBodyIndex> compositeInertias; matter.calcCompositeBodyInertias(state, compositeInertias); // See whether the RBNodeLoneParticles and the RBNodeTranslates produced identical results. for (int i = 0; i < numBodies; i++) { MobilizedBodyIndex index1(2*i+1); MobilizedBodyIndex index2(2*i+2); const MobilizedBody& body1 = matter.getMobilizedBody(index1); const MobilizedBody& body2 = matter.getMobilizedBody(index2); assertEqual(body1.getBodyOriginLocation(state), body2.getBodyOriginLocation(state)); assertEqual(body1.getBodyOriginVelocity(state), body2.getBodyOriginVelocity(state)); assertEqual(body1.getBodyOriginAcceleration(state), body2.getBodyOriginAcceleration(state)); assertEqual(reactionForces[index1][0], reactionForces[index2][0]); assertEqual(reactionForces[index1][1], reactionForces[index2][1]); assertEqual(Vec3::getAs(&mv[6*i]), Vec3::getAs(&mv[6*i+3])); if (!prescribe) assertEqual(Vec3::getAs(&minvv[6*i]), Vec3::getAs(&minvv[6*i+3])); assertEqual(Vec3::getAs(&residualMobilityForces[6*i]), Vec3::getAs(&residualMobilityForces[6*i+3])); assertEqual(Vec3::getAs(&dEdQ[6*i]), Vec3::getAs(&dEdQ[6*i+3])); assertEqual(compositeInertias[index1].getMass(), compositeInertias[index2].getMass()); assertEqual(compositeInertias[index1].getMassCenter(), compositeInertias[index2].getMassCenter()); assertEqual(compositeInertias[index1].getUnitInertia().getMoments(), compositeInertias[index2].getUnitInertia().getMoments()); assertEqual(compositeInertias[index1].getUnitInertia().getProducts(), compositeInertias[index2].getUnitInertia().getProducts()); } } static void testFree() { compareToTranslate(false, Motion::Position); } static void testPrescribePosition() { compareToTranslate(true, Motion::Position); } static void testPrescribeVelocity() { compareToTranslate(true, Motion::Velocity); } static void testPrescribeAcceleration() { compareToTranslate(true, Motion::Acceleration); } int main() { SimTK_START_TEST("TestLoneParticle"); SimTK_SUBTEST(testFree); SimTK_SUBTEST(testPrescribePosition); SimTK_SUBTEST(testPrescribeVelocity); SimTK_SUBTEST(testPrescribeAcceleration); SimTK_END_TEST(); } <commit_msg>Line endings.<commit_after>/* -------------------------------------------------------------------------- * * Simbody(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2011-12 Stanford University and the Authors. * * Authors: Peter Eastman * * Contributors: * * * * 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 "SimTKsimbody.h" #include "SimTKcommon/Testing.h" #include <vector> #include <map> using namespace SimTK; using namespace std; const Real TOL = 1e-10; #define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, "Assertion failed");} template <class T> void assertEqual(T val1, T val2) { ASSERT(abs(val1-val2) < TOL); } template <int N> void assertEqual(Vec<N> val1, Vec<N> val2) { for (int i = 0; i < N; ++i) ASSERT(abs(val1[i]-val2[i]) < TOL); } static void compareToTranslate(bool prescribe, Motion::Level level) { // Create a system of pairs of identical bodies, where half will be implemented with RBNodeLoneParticle // and half with RBNodeTranslate. MultibodySystem system; SimbodyMatterSubsystem matter(system); GeneralForceSubsystem force(system); Force::UniformGravity gravity(force, matter, Vec3(1.1, 1.2, 1.3)); Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1))); Random::Gaussian random(0.0, 3.0); const int numBodies = 10; for (int i = 0; i < numBodies; i++) { MobilizedBody::Translation body1(matter.updGround(), body); MobilizedBody::Translation body2(matter.updGround(), Vec3(0), body, Vec3(1e-100)); Vec3 station1(random.getValue(), random.getValue(), random.getValue()); Vec3 station2(random.getValue(), random.getValue(), random.getValue()); Real length = random.getValue(); Force::TwoPointLinearSpring(force, matter.updGround(), station1, body1, station2, 1.0, length); Force::TwoPointLinearSpring(force, matter.updGround(), station1, body2, station2, 1.0, length); if (prescribe) { Real phase = random.getValue(); Motion::Sinusoid(body1, level, 1.5, 1.1, phase); Motion::Sinusoid(body2, level, 1.5, 1.1, phase); } } // Initialize the state. State state = system.realizeTopology(); for (int i = 0; i < numBodies; i++) { Vec3 pos(random.getValue(), random.getValue(), random.getValue()); Vec3 vel(random.getValue(), random.getValue(), random.getValue()); const MobilizedBody& body1 = matter.getMobilizedBody(MobilizedBodyIndex(2*i+1)); const MobilizedBody& body2 = matter.getMobilizedBody(MobilizedBodyIndex(2*i+2)); body1.setQToFitTranslation(state, pos); body2.setQToFitTranslation(state, pos); body1.setUToFitLinearVelocity(state, vel); body2.setUToFitLinearVelocity(state, vel); } // Calculate lots of quantities from the MobilizedBodies. system.realize(state, Stage::Acceleration); Vector_<SpatialVec> reactionForces; matter.calcMobilizerReactionForces(state, reactionForces); Vector_<SpatialVec> reactionForcesFreebody; matter.calcMobilizerReactionForcesUsingFreebodyMethod(state, reactionForcesFreebody); // Both methods should produce the same results. SimTK_TEST_EQ(reactionForces, reactionForcesFreebody); Vector mv, minvv; matter.multiplyByM(state, state.getU(), mv); matter.multiplyByMInv(state, state.getU(), minvv); Vector appliedMobilityForces(matter.getNumMobilities()); Vector_<SpatialVec> appliedBodyForces(matter.getNumBodies()); for (int i = 0; i < numBodies; i++) { Vec3 mobilityForce; random.fillArray((Real*) &mobilityForce, 3); Vec3::updAs(&appliedMobilityForces[6*i]) = mobilityForce; Vec3::updAs(&appliedMobilityForces[6*i+3]) = mobilityForce; SpatialVec bodyForce; random.fillArray((Real*) &bodyForce, 6); appliedBodyForces[2*i+1] = bodyForce; appliedBodyForces[2*i+2] = bodyForce; } Vector knownUdot, residualMobilityForces; matter.calcResidualForceIgnoringConstraints(state, appliedMobilityForces, appliedBodyForces, knownUdot, residualMobilityForces); Vector dEdQ; matter.multiplyBySystemJacobianTranspose(state, appliedBodyForces, dEdQ); Array_<SpatialInertia,MobilizedBodyIndex> compositeInertias; matter.calcCompositeBodyInertias(state, compositeInertias); // See whether the RBNodeLoneParticles and the RBNodeTranslates produced identical results. for (int i = 0; i < numBodies; i++) { MobilizedBodyIndex index1(2*i+1); MobilizedBodyIndex index2(2*i+2); const MobilizedBody& body1 = matter.getMobilizedBody(index1); const MobilizedBody& body2 = matter.getMobilizedBody(index2); assertEqual(body1.getBodyOriginLocation(state), body2.getBodyOriginLocation(state)); assertEqual(body1.getBodyOriginVelocity(state), body2.getBodyOriginVelocity(state)); assertEqual(body1.getBodyOriginAcceleration(state), body2.getBodyOriginAcceleration(state)); assertEqual(reactionForces[index1][0], reactionForces[index2][0]); assertEqual(reactionForces[index1][1], reactionForces[index2][1]); assertEqual(Vec3::getAs(&mv[6*i]), Vec3::getAs(&mv[6*i+3])); if (!prescribe) assertEqual(Vec3::getAs(&minvv[6*i]), Vec3::getAs(&minvv[6*i+3])); assertEqual(Vec3::getAs(&residualMobilityForces[6*i]), Vec3::getAs(&residualMobilityForces[6*i+3])); assertEqual(Vec3::getAs(&dEdQ[6*i]), Vec3::getAs(&dEdQ[6*i+3])); assertEqual(compositeInertias[index1].getMass(), compositeInertias[index2].getMass()); assertEqual(compositeInertias[index1].getMassCenter(), compositeInertias[index2].getMassCenter()); assertEqual(compositeInertias[index1].getUnitInertia().getMoments(), compositeInertias[index2].getUnitInertia().getMoments()); assertEqual(compositeInertias[index1].getUnitInertia().getProducts(), compositeInertias[index2].getUnitInertia().getProducts()); } } static void testFree() { compareToTranslate(false, Motion::Position); } static void testPrescribePosition() { compareToTranslate(true, Motion::Position); } static void testPrescribeVelocity() { compareToTranslate(true, Motion::Velocity); } static void testPrescribeAcceleration() { compareToTranslate(true, Motion::Acceleration); } int main() { SimTK_START_TEST("TestLoneParticle"); SimTK_SUBTEST(testFree); SimTK_SUBTEST(testPrescribePosition); SimTK_SUBTEST(testPrescribeVelocity); SimTK_SUBTEST(testPrescribeAcceleration); SimTK_END_TEST(); } <|endoftext|>
<commit_before>template <> PetscErrorCode NavierStokesSolver<2>::writeGrid() { PetscErrorCode ierr; PetscInt rank; ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr); if(rank==0) { std::ofstream f(caseFolder+"/grid.txt"); for(std::vector<PetscReal>::const_iterator i=mesh->x.begin(); i!=mesh->x.end(); ++i) f << *i << '\n'; for(std::vector<PetscReal>::const_iterator i=mesh->y.begin(); i!=mesh->y.end(); ++i) f << *i << '\n'; f.close(); } return 0; } template <> PetscErrorCode NavierStokesSolver<3>::writeGrid() { PetscErrorCode ierr; PetscInt rank; ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr); if(rank==0) { std::ofstream f(caseFolder+"/grid.txt"); for(std::vector<PetscReal>::const_iterator i=mesh->x.begin(); i!=mesh->x.end(); ++i) f << *i << '\n'; for(std::vector<PetscReal>::const_iterator i=mesh->y.begin(); i!=mesh->y.end(); ++i) f << *i << '\n'; for(std::vector<PetscReal>::const_iterator i=mesh->z.begin(); i!=mesh->z.end(); ++i) f << *i << '\n'; f.close(); } return 0; }<commit_msg>Writes the number of points in each direction in grid file<commit_after>template <> PetscErrorCode NavierStokesSolver<2>::writeGrid() { PetscErrorCode ierr; PetscInt rank; ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr); if(rank==0) { std::ofstream f(caseFolder+"/grid.txt"); f << mesh->nx << '\t' << mesh->ny << '\n'; for(std::vector<PetscReal>::const_iterator i=mesh->x.begin(); i!=mesh->x.end(); ++i) f << *i << '\n'; for(std::vector<PetscReal>::const_iterator i=mesh->y.begin(); i!=mesh->y.end(); ++i) f << *i << '\n'; f.close(); } return 0; } template <> PetscErrorCode NavierStokesSolver<3>::writeGrid() { PetscErrorCode ierr; PetscInt rank; ierr = MPI_Comm_rank(PETSC_COMM_WORLD, &rank); CHKERRQ(ierr); if(rank==0) { std::ofstream f(caseFolder+"/grid.txt"); f << mesh->nx << '\t' << mesh->ny << '\t' << mesh->nz << '\n'; for(std::vector<PetscReal>::const_iterator i=mesh->x.begin(); i!=mesh->x.end(); ++i) f << *i << '\n'; for(std::vector<PetscReal>::const_iterator i=mesh->y.begin(); i!=mesh->y.end(); ++i) f << *i << '\n'; for(std::vector<PetscReal>::const_iterator i=mesh->z.begin(); i!=mesh->z.end(); ++i) f << *i << '\n'; f.close(); } return 0; }<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** 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. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgeopositioninfo.h" #include <QHash> #include <QDebug> #include <QDataStream> QT_BEGIN_NAMESPACE class QGeoPositionInfoPrivate { public: QDateTime timestamp; QGeoCoordinate coord; QHash<int, qreal> doubleAttribs; }; /*! \class QGeoPositionInfo \inmodule QtLocation \ingroup QtLocation-positioning \since Qt Location 5.0 \brief The QGeoPositionInfo class contains information gathered on a global position, direction and velocity at a particular point in time. A QGeoPositionInfo contains, at a minimum, a geographical coordinate and a timestamp. It may also have heading and speed measurements as well as estimates of the accuracy of the provided data. \sa QGeoPositionInfoSource */ /*! \enum QGeoPositionInfo::Attribute Defines the attributes for positional information. \value Direction The bearing to true north from the direction of travel, in degrees. \value GroundSpeed The ground speed, in meters/sec. \value VerticalSpeed The vertical speed, in meters/sec. \value MagneticVariation The angle between the horizontal component of the magnetic field and true north, in degrees. Also known as magnetic declination. A positive value indicates a clockwise direction from true north and a negative value indicates a counter-clockwise direction. \value HorizontalAccuracy The accuracy of the provided latitude-longitude value, in meters. \value VerticalAccuracy The accuracy of the provided altitude value, in meters. */ /*! Creates an invalid QGeoPositionInfo object. \sa isValid() */ QGeoPositionInfo::QGeoPositionInfo() : d(new QGeoPositionInfoPrivate) { } /*! Creates a QGeoPositionInfo for the given \a coordinate and \a timestamp. */ QGeoPositionInfo::QGeoPositionInfo(const QGeoCoordinate &coordinate, const QDateTime &timestamp) : d(new QGeoPositionInfoPrivate) { d->timestamp = timestamp; d->coord = coordinate; } /*! Creates a QGeoPositionInfo with the values of \a other. */ QGeoPositionInfo::QGeoPositionInfo(const QGeoPositionInfo &other) : d(new QGeoPositionInfoPrivate) { operator=(other); } /*! Destroys a QGeoPositionInfo object. */ QGeoPositionInfo::~QGeoPositionInfo() { delete d; } /*! Assigns the values from \a other to this QGeoPositionInfo. */ QGeoPositionInfo &QGeoPositionInfo::operator=(const QGeoPositionInfo & other) { if (this == &other) return *this; d->timestamp = other.d->timestamp; d->coord = other.d->coord; d->doubleAttribs = other.d->doubleAttribs; return *this; } /*! Returns true if all of this object's values are the same as those of \a other. */ bool QGeoPositionInfo::operator==(const QGeoPositionInfo &other) const { return d->timestamp == other.d->timestamp && d->coord == other.d->coord && d->doubleAttribs == other.d->doubleAttribs; } /*! \fn bool QGeoPositionInfo::operator!=(const QGeoPositionInfo &other) const Returns true if any of this object's values are not the same as those of \a other. */ /*! Returns true if the timestamp() and coordinate() values are both valid. \sa QGeoCoordinate::isValid(), QDateTime::isValid() */ bool QGeoPositionInfo::isValid() const { return d->timestamp.isValid() && d->coord.isValid(); } /*! Sets the date and time at which this position was reported to \a timestamp. The \a timestamp must be in UTC time. \sa timestamp() */ void QGeoPositionInfo::setTimestamp(const QDateTime &timestamp) { d->timestamp = timestamp; } /*! Returns the date and time at which this position was reported, in UTC time. Returns an invalid QDateTime if no date/time value has been set. \sa setTimestamp() */ QDateTime QGeoPositionInfo::timestamp() const { return d->timestamp; } /*! Sets the coordinate for this position to \a coordinate. \sa coordinate() */ void QGeoPositionInfo::setCoordinate(const QGeoCoordinate &coordinate) { d->coord = coordinate; } /*! Returns the coordinate for this position. Returns an invalid coordinate if no coordinate has been set. \sa setCoordinate() */ QGeoCoordinate QGeoPositionInfo::coordinate() const { return d->coord; } /*! Sets the value for \a attribute to \a value. \sa attribute() */ void QGeoPositionInfo::setAttribute(Attribute attribute, qreal value) { d->doubleAttribs[int(attribute)] = value; } /*! Returns the value of the specified \a attribute as a qreal value. Returns -1 if the value has not been set, although this may also be a legitimate value for some attributes. The function hasAttribute() should be used to determine whether or not a value has been set for an attribute. \sa hasAttribute(), setAttribute() */ qreal QGeoPositionInfo::attribute(Attribute attribute) const { if (d->doubleAttribs.contains(int(attribute))) return d->doubleAttribs[int(attribute)]; return -1; } /*! Removes the specified \a attribute and its value. */ void QGeoPositionInfo::removeAttribute(Attribute attribute) { d->doubleAttribs.remove(int(attribute)); } /*! Returns true if the specified \a attribute is present for this QGeoPositionInfo object. */ bool QGeoPositionInfo::hasAttribute(Attribute attribute) const { return d->doubleAttribs.contains(int(attribute)); } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QGeoPositionInfo &info) { dbg.nospace() << "QGeoPositionInfo(" << info.d->timestamp; dbg.nospace() << ", "; dbg.nospace() << info.d->coord; QList<int> attribs = info.d->doubleAttribs.keys(); qStableSort(attribs.begin(), attribs.end()); // Output a sorted list from an unsorted hash. for (int i = 0; i < attribs.count(); ++i) { dbg.nospace() << ", "; switch (attribs[i]) { case QGeoPositionInfo::Direction: dbg.nospace() << "Direction="; break; case QGeoPositionInfo::GroundSpeed: dbg.nospace() << "GroundSpeed="; break; case QGeoPositionInfo::VerticalSpeed: dbg.nospace() << "VerticalSpeed="; break; case QGeoPositionInfo::MagneticVariation: dbg.nospace() << "MagneticVariation="; break; case QGeoPositionInfo::HorizontalAccuracy: dbg.nospace() << "HorizontalAccuracy="; break; case QGeoPositionInfo::VerticalAccuracy: dbg.nospace() << "VerticalAccuracy="; break; } dbg.nospace() << info.d->doubleAttribs[attribs[i]]; } dbg.nospace() << ')'; return dbg; } #endif #ifndef QT_NO_DATASTREAM /*! \fn QDataStream &operator<<(QDataStream &stream, const QGeoPositionInfo &info) \relates QGeoPositionInfo Writes the given \a info to the specified \a stream. \sa {Serializing Qt Data Types} */ QDataStream &operator<<(QDataStream &stream, const QGeoPositionInfo &info) { stream << info.d->timestamp; stream << info.d->coord; stream << info.d->doubleAttribs; return stream; } #endif #ifndef QT_NO_DATASTREAM /*! \fn QDataStream &operator>>(QDataStream &stream, QGeoPositionInfo &info) \relates QGeoPositionInfo Reads a coordinate from the specified \a stream into the given \a info. \sa {Serializing Qt Data Types} */ QDataStream &operator>>(QDataStream &stream, QGeoPositionInfo &info) { stream >> info.d->timestamp; stream >> info.d->coord; stream >> info.d->doubleAttribs; return stream; } #endif QT_END_NAMESPACE <commit_msg>Update the documentation for the Direction attribute of QGeoPositionInfo. The definition is now unambiguous.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** 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. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgeopositioninfo.h" #include <QHash> #include <QDebug> #include <QDataStream> QT_BEGIN_NAMESPACE class QGeoPositionInfoPrivate { public: QDateTime timestamp; QGeoCoordinate coord; QHash<int, qreal> doubleAttribs; }; /*! \class QGeoPositionInfo \inmodule QtLocation \ingroup QtLocation-positioning \since Qt Location 5.0 \brief The QGeoPositionInfo class contains information gathered on a global position, direction and velocity at a particular point in time. A QGeoPositionInfo contains, at a minimum, a geographical coordinate and a timestamp. It may also have heading and speed measurements as well as estimates of the accuracy of the provided data. \sa QGeoPositionInfoSource */ /*! \enum QGeoPositionInfo::Attribute Defines the attributes for positional information. \value Direction The bearing measured in degrees clockwise from true north to the direction of travel. \value GroundSpeed The ground speed, in meters/sec. \value VerticalSpeed The vertical speed, in meters/sec. \value MagneticVariation The angle between the horizontal component of the magnetic field and true north, in degrees. Also known as magnetic declination. A positive value indicates a clockwise direction from true north and a negative value indicates a counter-clockwise direction. \value HorizontalAccuracy The accuracy of the provided latitude-longitude value, in meters. \value VerticalAccuracy The accuracy of the provided altitude value, in meters. */ /*! Creates an invalid QGeoPositionInfo object. \sa isValid() */ QGeoPositionInfo::QGeoPositionInfo() : d(new QGeoPositionInfoPrivate) { } /*! Creates a QGeoPositionInfo for the given \a coordinate and \a timestamp. */ QGeoPositionInfo::QGeoPositionInfo(const QGeoCoordinate &coordinate, const QDateTime &timestamp) : d(new QGeoPositionInfoPrivate) { d->timestamp = timestamp; d->coord = coordinate; } /*! Creates a QGeoPositionInfo with the values of \a other. */ QGeoPositionInfo::QGeoPositionInfo(const QGeoPositionInfo &other) : d(new QGeoPositionInfoPrivate) { operator=(other); } /*! Destroys a QGeoPositionInfo object. */ QGeoPositionInfo::~QGeoPositionInfo() { delete d; } /*! Assigns the values from \a other to this QGeoPositionInfo. */ QGeoPositionInfo &QGeoPositionInfo::operator=(const QGeoPositionInfo & other) { if (this == &other) return *this; d->timestamp = other.d->timestamp; d->coord = other.d->coord; d->doubleAttribs = other.d->doubleAttribs; return *this; } /*! Returns true if all of this object's values are the same as those of \a other. */ bool QGeoPositionInfo::operator==(const QGeoPositionInfo &other) const { return d->timestamp == other.d->timestamp && d->coord == other.d->coord && d->doubleAttribs == other.d->doubleAttribs; } /*! \fn bool QGeoPositionInfo::operator!=(const QGeoPositionInfo &other) const Returns true if any of this object's values are not the same as those of \a other. */ /*! Returns true if the timestamp() and coordinate() values are both valid. \sa QGeoCoordinate::isValid(), QDateTime::isValid() */ bool QGeoPositionInfo::isValid() const { return d->timestamp.isValid() && d->coord.isValid(); } /*! Sets the date and time at which this position was reported to \a timestamp. The \a timestamp must be in UTC time. \sa timestamp() */ void QGeoPositionInfo::setTimestamp(const QDateTime &timestamp) { d->timestamp = timestamp; } /*! Returns the date and time at which this position was reported, in UTC time. Returns an invalid QDateTime if no date/time value has been set. \sa setTimestamp() */ QDateTime QGeoPositionInfo::timestamp() const { return d->timestamp; } /*! Sets the coordinate for this position to \a coordinate. \sa coordinate() */ void QGeoPositionInfo::setCoordinate(const QGeoCoordinate &coordinate) { d->coord = coordinate; } /*! Returns the coordinate for this position. Returns an invalid coordinate if no coordinate has been set. \sa setCoordinate() */ QGeoCoordinate QGeoPositionInfo::coordinate() const { return d->coord; } /*! Sets the value for \a attribute to \a value. \sa attribute() */ void QGeoPositionInfo::setAttribute(Attribute attribute, qreal value) { d->doubleAttribs[int(attribute)] = value; } /*! Returns the value of the specified \a attribute as a qreal value. Returns -1 if the value has not been set, although this may also be a legitimate value for some attributes. The function hasAttribute() should be used to determine whether or not a value has been set for an attribute. \sa hasAttribute(), setAttribute() */ qreal QGeoPositionInfo::attribute(Attribute attribute) const { if (d->doubleAttribs.contains(int(attribute))) return d->doubleAttribs[int(attribute)]; return -1; } /*! Removes the specified \a attribute and its value. */ void QGeoPositionInfo::removeAttribute(Attribute attribute) { d->doubleAttribs.remove(int(attribute)); } /*! Returns true if the specified \a attribute is present for this QGeoPositionInfo object. */ bool QGeoPositionInfo::hasAttribute(Attribute attribute) const { return d->doubleAttribs.contains(int(attribute)); } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QGeoPositionInfo &info) { dbg.nospace() << "QGeoPositionInfo(" << info.d->timestamp; dbg.nospace() << ", "; dbg.nospace() << info.d->coord; QList<int> attribs = info.d->doubleAttribs.keys(); qStableSort(attribs.begin(), attribs.end()); // Output a sorted list from an unsorted hash. for (int i = 0; i < attribs.count(); ++i) { dbg.nospace() << ", "; switch (attribs[i]) { case QGeoPositionInfo::Direction: dbg.nospace() << "Direction="; break; case QGeoPositionInfo::GroundSpeed: dbg.nospace() << "GroundSpeed="; break; case QGeoPositionInfo::VerticalSpeed: dbg.nospace() << "VerticalSpeed="; break; case QGeoPositionInfo::MagneticVariation: dbg.nospace() << "MagneticVariation="; break; case QGeoPositionInfo::HorizontalAccuracy: dbg.nospace() << "HorizontalAccuracy="; break; case QGeoPositionInfo::VerticalAccuracy: dbg.nospace() << "VerticalAccuracy="; break; } dbg.nospace() << info.d->doubleAttribs[attribs[i]]; } dbg.nospace() << ')'; return dbg; } #endif #ifndef QT_NO_DATASTREAM /*! \fn QDataStream &operator<<(QDataStream &stream, const QGeoPositionInfo &info) \relates QGeoPositionInfo Writes the given \a info to the specified \a stream. \sa {Serializing Qt Data Types} */ QDataStream &operator<<(QDataStream &stream, const QGeoPositionInfo &info) { stream << info.d->timestamp; stream << info.d->coord; stream << info.d->doubleAttribs; return stream; } #endif #ifndef QT_NO_DATASTREAM /*! \fn QDataStream &operator>>(QDataStream &stream, QGeoPositionInfo &info) \relates QGeoPositionInfo Reads a coordinate from the specified \a stream into the given \a info. \sa {Serializing Qt Data Types} */ QDataStream &operator>>(QDataStream &stream, QGeoPositionInfo &info) { stream >> info.d->timestamp; stream >> info.d->coord; stream >> info.d->doubleAttribs; return stream; } #endif QT_END_NAMESPACE <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // 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 <vector.hpp> #include <string.hpp> #include "arp_layer.hpp" #include "arp_cache.hpp" #include "ip_layer.hpp" #include "logging.hpp" #include "kernel_utils.hpp" namespace { //TODO } //end of anonymous namespace void network::arp::decode(network::ethernet::packet& packet){ header* arp_header = reinterpret_cast<header*>(packet.payload + packet.index); logging::logf(logging::log_level::TRACE, "arp: Start ARP packet handling\n"); auto hw_type = switch_endian_16(arp_header->hw_type); auto protocol_type = switch_endian_16(arp_header->protocol_type); // We only support ethernet hardware frames if(hw_type != 0x1){ logging::logf(logging::log_level::ERROR, "arp: Unhandled hardware type %h\n", size_t(hw_type)); return; } // We only support IPV4 protocol if(protocol_type != 0x800){ logging::logf(logging::log_level::ERROR, "arp: Unhandled protocol type %h\n", size_t(protocol_type)); return; } auto hw_len = arp_header->hw_len; auto protocol_len = arp_header->protocol_len; auto operation = switch_endian_16(arp_header->operation); // This should never happen if(hw_len != 0x6 || protocol_len != 0x4){ logging::logf(logging::log_level::ERROR, "arp: Unable to process the given length hw:%h prot:%h\n", size_t(hw_len), size_t(protocol_len)); return; } if (operation != 0x1 && operation != 0x2) { logging::logf(logging::log_level::TRACE, "arp: Unhandled operation %h\n", size_t(operation)); return; } size_t source_hw = 0; size_t target_hw = 0; for(size_t i = 0; i < 3; ++i){ source_hw |= uint64_t(switch_endian_16(arp_header->source_hw_addr[i])) << ((2 - i) * 16); target_hw |= uint64_t(switch_endian_16(arp_header->target_hw_addr[i])) << ((2 - i) * 16); } logging::logf(logging::log_level::TRACE, "arp: Source HW Address %h \n", source_hw); logging::logf(logging::log_level::TRACE, "arp: Target HW Address %h \n", target_hw); network::ip::address source_prot; network::ip::address target_prot; for(size_t i = 0; i < 2; ++i){ auto source = switch_endian_16(arp_header->source_protocol_addr[i]); auto target = switch_endian_16(arp_header->target_protocol_addr[i]); source_prot.set_sub(2*i, source >> 8); source_prot.set_sub(2*i+1, source); target_prot.set_sub(2*i, target >> 8); target_prot.set_sub(2*i+1, target); } logging::logf(logging::log_level::TRACE, "arp: Source Protocol Address %u.%u.%u.%u \n", uint64_t(source_prot(0)), uint64_t(source_prot(1)), uint64_t(source_prot(2)), uint64_t(source_prot(3))); logging::logf(logging::log_level::TRACE, "arp: Target Protocol Address %u.%u.%u.%u \n", uint64_t(target_prot(0)), uint64_t(target_prot(1)), uint64_t(target_prot(2)), uint64_t(target_prot(3))); //TODO Only do that is not an ARP probe network::arp::update_cache(source_hw, source_prot); if(operation == 0x1){ logging::logf(logging::log_level::TRACE, "arp: Handle Request\n"); //TODO } else if(operation == 0x2){ logging::logf(logging::log_level::TRACE, "arp: Handle Reply\n"); //TODO } } <commit_msg>Prepare reply (WIP)<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // 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 <vector.hpp> #include <string.hpp> #include "arp_layer.hpp" #include "arp_cache.hpp" #include "ip_layer.hpp" #include "logging.hpp" #include "kernel_utils.hpp" namespace { //TODO } //end of anonymous namespace void network::arp::decode(network::ethernet::packet& packet){ header* arp_header = reinterpret_cast<header*>(packet.payload + packet.index); logging::logf(logging::log_level::TRACE, "arp: Start ARP packet handling\n"); auto hw_type = switch_endian_16(arp_header->hw_type); auto protocol_type = switch_endian_16(arp_header->protocol_type); // We only support ethernet hardware frames if(hw_type != 0x1){ logging::logf(logging::log_level::ERROR, "arp: Unhandled hardware type %h\n", size_t(hw_type)); return; } // We only support IPV4 protocol if(protocol_type != 0x800){ logging::logf(logging::log_level::ERROR, "arp: Unhandled protocol type %h\n", size_t(protocol_type)); return; } auto hw_len = arp_header->hw_len; auto protocol_len = arp_header->protocol_len; auto operation = switch_endian_16(arp_header->operation); // This should never happen if(hw_len != 0x6 || protocol_len != 0x4){ logging::logf(logging::log_level::ERROR, "arp: Unable to process the given length hw:%h prot:%h\n", size_t(hw_len), size_t(protocol_len)); return; } if (operation != 0x1 && operation != 0x2) { logging::logf(logging::log_level::TRACE, "arp: Unhandled operation %h\n", size_t(operation)); return; } size_t source_hw = 0; size_t target_hw = 0; for(size_t i = 0; i < 3; ++i){ source_hw |= uint64_t(switch_endian_16(arp_header->source_hw_addr[i])) << ((2 - i) * 16); target_hw |= uint64_t(switch_endian_16(arp_header->target_hw_addr[i])) << ((2 - i) * 16); } logging::logf(logging::log_level::TRACE, "arp: Source HW Address %h \n", source_hw); logging::logf(logging::log_level::TRACE, "arp: Target HW Address %h \n", target_hw); network::ip::address source_prot; network::ip::address target_prot; for(size_t i = 0; i < 2; ++i){ auto source = switch_endian_16(arp_header->source_protocol_addr[i]); auto target = switch_endian_16(arp_header->target_protocol_addr[i]); source_prot.set_sub(2*i, source >> 8); source_prot.set_sub(2*i+1, source); target_prot.set_sub(2*i, target >> 8); target_prot.set_sub(2*i+1, target); } logging::logf(logging::log_level::TRACE, "arp: Source Protocol Address %u.%u.%u.%u \n", uint64_t(source_prot(0)), uint64_t(source_prot(1)), uint64_t(source_prot(2)), uint64_t(source_prot(3))); logging::logf(logging::log_level::TRACE, "arp: Target Protocol Address %u.%u.%u.%u \n", uint64_t(target_prot(0)), uint64_t(target_prot(1)), uint64_t(target_prot(2)), uint64_t(target_prot(3))); //TODO Only do that is not an ARP probe network::arp::update_cache(source_hw, source_prot); if(operation == 0x1){ logging::logf(logging::log_level::TRACE, "arp: Handle Request\n"); // Ask the ethernet layer to craft a packet auto packet = network::ethernet::prepare_packet(sizeof(header), target_hw, ethernet::ether_type::ARP); //TODO } else if(operation == 0x2){ logging::logf(logging::log_level::TRACE, "arp: Handle Reply\n"); //TODO } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_download.h" #include <algorithm> #include "base/logging.h" #include "base/rand_util.h" #include "base/stl_util-inl.h" #include "chrome/browser/autofill/autofill_xml_parser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #include "net/http/http_response_headers.h" #define DISABLED_REQUEST_URL "http://disabled" #if defined(GOOGLE_CHROME_BUILD) #include "chrome/browser/autofill/internal/autofill_download_internal.h" #else #define AUTO_FILL_QUERY_SERVER_REQUEST_URL DISABLED_REQUEST_URL #define AUTO_FILL_UPLOAD_SERVER_REQUEST_URL DISABLED_REQUEST_URL #define AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER "SOMESERVER/" #endif AutoFillDownloadManager::AutoFillDownloadManager(Profile* profile) : profile_(profile), observer_(NULL), next_query_request_(base::Time::Now()), next_upload_request_(base::Time::Now()), positive_upload_rate_(0), negative_upload_rate_(0), fetcher_id_for_unittest_(0), is_testing_(false) { // |profile_| could be NULL in some unit-tests. if (profile_) { PrefService* preferences = profile_->GetPrefs(); positive_upload_rate_ = preferences->GetReal(prefs::kAutoFillPositiveUploadRate); negative_upload_rate_ = preferences->GetReal(prefs::kAutoFillNegativeUploadRate); } } AutoFillDownloadManager::~AutoFillDownloadManager() { STLDeleteContainerPairFirstPointers(url_fetchers_.begin(), url_fetchers_.end()); } void AutoFillDownloadManager::SetObserver( AutoFillDownloadManager::Observer *observer) { if (observer) { DCHECK(!observer_); observer_ = observer; } else { observer_ = NULL; } } bool AutoFillDownloadManager::StartQueryRequest( const ScopedVector<FormStructure>& forms) { if (next_query_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. return false; } std::string form_xml; FormStructure::EncodeQueryRequest(forms, &form_xml); FormRequestData request_data; request_data.form_signatures.reserve(forms.size()); for (ScopedVector<FormStructure>::const_iterator it = forms.begin(); it != forms.end(); ++it) { request_data.form_signatures.push_back((*it)->FormSignature()); } request_data.request_type = AutoFillDownloadManager::REQUEST_QUERY; return StartRequest(form_xml, request_data); } bool AutoFillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_matched) { if (next_upload_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. return false; } // Check if we need to upload form. double upload_rate = form_was_matched ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (base::RandDouble() > upload_rate) { LOG(INFO) << "AutoFillDownloadManager: Upload request is ignored"; // If we ever need notification that upload was skipped, add it here. return false; } std::string form_xml; form.EncodeUploadRequest(form_was_matched, &form_xml); FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutoFillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } bool AutoFillDownloadManager::CancelRequest( const std::string& form_signature, AutoFillDownloadManager::AutoFillRequestType request_type) { for (std::map<URLFetcher *, FormRequestData>::iterator it = url_fetchers_.begin(); it != url_fetchers_.end(); ++it) { if (std::find(it->second.form_signatures.begin(), it->second.form_signatures.end(), form_signature) != it->second.form_signatures.end() && it->second.request_type == request_type) { delete it->first; url_fetchers_.erase(it); return true; } } return false; } double AutoFillDownloadManager::GetPositiveUploadRate() const { return positive_upload_rate_; } double AutoFillDownloadManager::GetNegativeUploadRate() const { return negative_upload_rate_; } void AutoFillDownloadManager::SetPositiveUploadRate(double rate) { if (rate == positive_upload_rate_) return; positive_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); DCHECK(profile_); PrefService* preferences = profile_->GetPrefs(); preferences->SetReal(prefs::kAutoFillPositiveUploadRate, rate); } void AutoFillDownloadManager::SetNegativeUploadRate(double rate) { if (rate == negative_upload_rate_) return; negative_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); DCHECK(profile_); PrefService* preferences = profile_->GetPrefs(); preferences->SetReal(prefs::kAutoFillNegativeUploadRate, rate); } bool AutoFillDownloadManager::StartRequest( const std::string& form_xml, const FormRequestData& request_data) { std::string request_url; if (request_data.request_type == AutoFillDownloadManager::REQUEST_QUERY) request_url = AUTO_FILL_QUERY_SERVER_REQUEST_URL; else request_url = AUTO_FILL_UPLOAD_SERVER_REQUEST_URL; if (!request_url.compare(DISABLED_REQUEST_URL) && !is_testing_) { // We have it disabled - return true as if it succeeded, but do nothing. return true; } // Id is ignored for regular chrome, in unit test id's for fake fetcher // factory will be 0, 1, 2, ... URLFetcher *fetcher = URLFetcher::Create(fetcher_id_for_unittest_++, GURL(request_url), URLFetcher::POST, this); url_fetchers_[fetcher] = request_data; fetcher->set_automatcally_retry_on_5xx(false); fetcher->set_request_context(Profile::GetDefaultRequestContext()); fetcher->set_upload_data("text/plain", form_xml); fetcher->Start(); return true; } void AutoFillDownloadManager::OnURLFetchComplete(const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { std::map<URLFetcher *, FormRequestData>::iterator it = url_fetchers_.find(const_cast<URLFetcher*>(source)); DCHECK(it != url_fetchers_.end()); std::string type_of_request( it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY ? "query" : "upload"); const int kHttpResponseOk = 200; const int kHttpInternalServerError = 500; const int kHttpBadGateway = 502; const int kHttpServiceUnavailable = 503; DCHECK(it->second.form_signatures.size()); if (response_code != kHttpResponseOk) { bool back_off = false; std::string server_header; switch (response_code) { case kHttpBadGateway: if (!source->response_headers()->EnumerateHeader(NULL, "server", &server_header) || StartsWithASCII(server_header.c_str(), AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER, false) != 0) break; // Bad getaway was received from AutoFill servers. Fall through to back // off. case kHttpInternalServerError: case kHttpServiceUnavailable: back_off = true; break; } if (back_off) { base::Time back_off_time(base::Time::Now() + source->backoff_delay()); if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) { next_query_request_ = back_off_time; } else { next_upload_request_ = back_off_time; } } LOG(INFO) << "AutoFillDownloadManager: " << type_of_request << " request has failed with response" << response_code; if (observer_) { observer_->OnHeuristicsRequestError(it->second.form_signatures[0], it->second.request_type, response_code); } } else { LOG(INFO) << "AutoFillDownloadManager: " << type_of_request << " request has succeeded"; if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) { if (observer_) observer_->OnLoadedAutoFillHeuristics(it->second.form_signatures, data); } else { double new_positive_upload_rate = 0; double new_negative_upload_rate = 0; AutoFillUploadXmlParser parse_handler(&new_positive_upload_rate, &new_negative_upload_rate); buzz::XmlParser parser(&parse_handler); parser.Parse(data.data(), data.length(), true); if (parse_handler.succeeded()) { SetPositiveUploadRate(new_positive_upload_rate); SetNegativeUploadRate(new_negative_upload_rate); } if (observer_) observer_->OnUploadedAutoFillHeuristics(it->second.form_signatures[0]); } } delete it->first; url_fetchers_.erase(it); } <commit_msg>Possible fix for 40234 + changed one of the DCHECK to CHECK BUG=40234 TEST=Should not crash Review URL: http://codereview.chromium.org/1594019<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_download.h" #include <algorithm> #include "base/logging.h" #include "base/rand_util.h" #include "base/stl_util-inl.h" #include "chrome/browser/autofill/autofill_xml_parser.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #include "net/http/http_response_headers.h" #define DISABLED_REQUEST_URL "http://disabled" #if defined(GOOGLE_CHROME_BUILD) #include "chrome/browser/autofill/internal/autofill_download_internal.h" #else #define AUTO_FILL_QUERY_SERVER_REQUEST_URL DISABLED_REQUEST_URL #define AUTO_FILL_UPLOAD_SERVER_REQUEST_URL DISABLED_REQUEST_URL #define AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER "SOMESERVER/" #endif AutoFillDownloadManager::AutoFillDownloadManager(Profile* profile) : profile_(profile), observer_(NULL), next_query_request_(base::Time::Now()), next_upload_request_(base::Time::Now()), positive_upload_rate_(0), negative_upload_rate_(0), fetcher_id_for_unittest_(0), is_testing_(false) { // |profile_| could be NULL in some unit-tests. if (profile_) { PrefService* preferences = profile_->GetPrefs(); positive_upload_rate_ = preferences->GetReal(prefs::kAutoFillPositiveUploadRate); negative_upload_rate_ = preferences->GetReal(prefs::kAutoFillNegativeUploadRate); } } AutoFillDownloadManager::~AutoFillDownloadManager() { STLDeleteContainerPairFirstPointers(url_fetchers_.begin(), url_fetchers_.end()); } void AutoFillDownloadManager::SetObserver( AutoFillDownloadManager::Observer *observer) { if (observer) { DCHECK(!observer_); observer_ = observer; } else { observer_ = NULL; } } bool AutoFillDownloadManager::StartQueryRequest( const ScopedVector<FormStructure>& forms) { if (next_query_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. return false; } std::string form_xml; FormStructure::EncodeQueryRequest(forms, &form_xml); FormRequestData request_data; request_data.form_signatures.reserve(forms.size()); for (ScopedVector<FormStructure>::const_iterator it = forms.begin(); it != forms.end(); ++it) { request_data.form_signatures.push_back((*it)->FormSignature()); } request_data.request_type = AutoFillDownloadManager::REQUEST_QUERY; return StartRequest(form_xml, request_data); } bool AutoFillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_matched) { if (next_upload_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. return false; } // Check if we need to upload form. double upload_rate = form_was_matched ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (base::RandDouble() > upload_rate) { LOG(INFO) << "AutoFillDownloadManager: Upload request is ignored"; // If we ever need notification that upload was skipped, add it here. return false; } std::string form_xml; form.EncodeUploadRequest(form_was_matched, &form_xml); FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutoFillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } bool AutoFillDownloadManager::CancelRequest( const std::string& form_signature, AutoFillDownloadManager::AutoFillRequestType request_type) { for (std::map<URLFetcher *, FormRequestData>::iterator it = url_fetchers_.begin(); it != url_fetchers_.end(); ++it) { if (std::find(it->second.form_signatures.begin(), it->second.form_signatures.end(), form_signature) != it->second.form_signatures.end() && it->second.request_type == request_type) { delete it->first; url_fetchers_.erase(it); return true; } } return false; } double AutoFillDownloadManager::GetPositiveUploadRate() const { return positive_upload_rate_; } double AutoFillDownloadManager::GetNegativeUploadRate() const { return negative_upload_rate_; } void AutoFillDownloadManager::SetPositiveUploadRate(double rate) { if (rate == positive_upload_rate_) return; positive_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); DCHECK(profile_); PrefService* preferences = profile_->GetPrefs(); preferences->SetReal(prefs::kAutoFillPositiveUploadRate, rate); } void AutoFillDownloadManager::SetNegativeUploadRate(double rate) { if (rate == negative_upload_rate_) return; negative_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); DCHECK(profile_); PrefService* preferences = profile_->GetPrefs(); preferences->SetReal(prefs::kAutoFillNegativeUploadRate, rate); } bool AutoFillDownloadManager::StartRequest( const std::string& form_xml, const FormRequestData& request_data) { std::string request_url; if (request_data.request_type == AutoFillDownloadManager::REQUEST_QUERY) request_url = AUTO_FILL_QUERY_SERVER_REQUEST_URL; else request_url = AUTO_FILL_UPLOAD_SERVER_REQUEST_URL; if (!request_url.compare(DISABLED_REQUEST_URL) && !is_testing_) { // We have it disabled - return true as if it succeeded, but do nothing. return true; } // Id is ignored for regular chrome, in unit test id's for fake fetcher // factory will be 0, 1, 2, ... URLFetcher *fetcher = URLFetcher::Create(fetcher_id_for_unittest_++, GURL(request_url), URLFetcher::POST, this); url_fetchers_[fetcher] = request_data; fetcher->set_automatcally_retry_on_5xx(false); fetcher->set_request_context(Profile::GetDefaultRequestContext()); fetcher->set_upload_data("text/plain", form_xml); fetcher->Start(); return true; } void AutoFillDownloadManager::OnURLFetchComplete(const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { std::map<URLFetcher *, FormRequestData>::iterator it = url_fetchers_.find(const_cast<URLFetcher*>(source)); if (it == url_fetchers_.end()) { // Looks like crash on Mac is possibly caused with callback entering here // with unknown fetcher when network is refreshed. return; } std::string type_of_request( it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY ? "query" : "upload"); const int kHttpResponseOk = 200; const int kHttpInternalServerError = 500; const int kHttpBadGateway = 502; const int kHttpServiceUnavailable = 503; CHECK(it->second.form_signatures.size()); if (response_code != kHttpResponseOk) { bool back_off = false; std::string server_header; switch (response_code) { case kHttpBadGateway: if (!source->response_headers()->EnumerateHeader(NULL, "server", &server_header) || StartsWithASCII(server_header.c_str(), AUTO_FILL_QUERY_SERVER_NAME_START_IN_HEADER, false) != 0) break; // Bad getaway was received from AutoFill servers. Fall through to back // off. case kHttpInternalServerError: case kHttpServiceUnavailable: back_off = true; break; } if (back_off) { base::Time back_off_time(base::Time::Now() + source->backoff_delay()); if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) { next_query_request_ = back_off_time; } else { next_upload_request_ = back_off_time; } } LOG(INFO) << "AutoFillDownloadManager: " << type_of_request << " request has failed with response" << response_code; if (observer_) { observer_->OnHeuristicsRequestError(it->second.form_signatures[0], it->second.request_type, response_code); } } else { LOG(INFO) << "AutoFillDownloadManager: " << type_of_request << " request has succeeded"; if (it->second.request_type == AutoFillDownloadManager::REQUEST_QUERY) { if (observer_) observer_->OnLoadedAutoFillHeuristics(it->second.form_signatures, data); } else { double new_positive_upload_rate = 0; double new_negative_upload_rate = 0; AutoFillUploadXmlParser parse_handler(&new_positive_upload_rate, &new_negative_upload_rate); buzz::XmlParser parser(&parse_handler); parser.Parse(data.data(), data.length(), true); if (parse_handler.succeeded()) { SetPositiveUploadRate(new_positive_upload_rate); SetNegativeUploadRate(new_negative_upload_rate); } if (observer_) observer_->OnUploadedAutoFillHeuristics(it->second.form_signatures[0]); } } delete it->first; url_fetchers_.erase(it); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "optionsmodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "net.h" #include "txdb.h" // for -dbcache defaults #ifdef ENABLE_WALLET #include "wallet.h" #include "walletdb.h" #endif #include <QNetworkProxy> #include <QSettings> #include <QStringList> OptionsModel::OptionsModel(QObject *parent) : QAbstractListModel(parent) { Init(); } void OptionsModel::addOverriddenOption(const std::string &option) { strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(mapArgs[option]) + " "; } // Writes all missing QSettings with their default values void OptionsModel::Init() { QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool(); if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", BitcoinUnits::BTC); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("strThirdPartyTxUrls")) settings.setValue("strThirdPartyTxUrls", ""); strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If SoftSetArg() or SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS); if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); // Wallet #ifdef ENABLE_WALLET if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE); payTxFee = CFeeRate(settings.value("nTransactionFee").toLongLong()); // if -paytxfee is set, this will be overridden later in init.cpp if (mapArgs.count("-paytxfee")) addOverriddenOption("-paytxfee"); if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fListen")) settings.setValue("fListen", DEFAULT_LISTEN); if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool())) addOverriddenOption("-listen"); if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!SoftSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); } void OptionsModel::Reset() { QSettings settings; // Remove all entries from our QSettings object settings.clear(); // default setting for OptionsModel::StartAtStartup - disabled if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(false); } int OptionsModel::rowCount(const QModelIndex & parent) const { return OptionIDRowCount; } // read QSettings values and return them QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: return GUIUtil::GetStartOnSystemStartup(); case MinimizeToTray: return fMinimizeToTray; case MapPortUPnP: #ifdef USE_UPNP return settings.value("fUseUPnP"); #else return false; #endif case MinimizeOnClose: return fMinimizeOnClose; // default proxy case ProxyUse: return settings.value("fUseProxy", false); case ProxyIP: { // contains IP at index 0 and port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); return strlIpPort.at(0); } case ProxyPort: { // contains IP at index 0 and port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); return strlIpPort.at(1); } #ifdef ENABLE_WALLET case Fee: { // Attention: Init() is called before payTxFee is set in AppInit2()! // To ensure we can change the fee on-the-fly update our QSetting when // opening OptionsDialog, which queries Fee via the mapper. if (!(payTxFee == CFeeRate(settings.value("nTransactionFee").toLongLong(), 1000))) settings.setValue("nTransactionFee", (qint64)payTxFee.GetFeePerK()); // Todo: Consider to revert back to use just payTxFee here, if we don't want // -paytxfee to update our QSettings! return settings.value("nTransactionFee"); } case SpendZeroConfChange: return settings.value("bSpendZeroConfChange"); #endif case DisplayUnit: return nDisplayUnit; case ThirdPartyTxUrls: return strThirdPartyTxUrls; case Language: return settings.value("language"); case CoinControlFeatures: return fCoinControlFeatures; case DatabaseCache: return settings.value("nDatabaseCache"); case ThreadsScriptVerif: return settings.value("nThreadsScriptVerif"); case Listen: return settings.value("fListen"); default: return QVariant(); } } return QVariant(); } // write QSettings values bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: // core option - can be changed on-the-fly settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; // default proxy case ProxyUse: if (settings.value("fUseProxy") != value) { settings.setValue("fUseProxy", value.toBool()); setRestartRequired(true); } break; case ProxyIP: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed IP if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) { // construct new value from new IP and current port QString strNewValue = value.toString() + ":" + strlIpPort.at(1); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; case ProxyPort: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed port if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) { // construct new value from current IP and new port QString strNewValue = strlIpPort.at(0) + ":" + value.toString(); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; #ifdef ENABLE_WALLET case Fee: { // core option - can be changed on-the-fly // Todo: Add is valid check and warn via message, if not CAmount nTransactionFee(value.toLongLong()); payTxFee = CFeeRate(nTransactionFee, 1000); settings.setValue("nTransactionFee", qint64(nTransactionFee)); emit transactionFeeChanged(nTransactionFee); break; } case SpendZeroConfChange: if (settings.value("bSpendZeroConfChange") != value) { settings.setValue("bSpendZeroConfChange", value); setRestartRequired(true); } break; #endif case DisplayUnit: setDisplayUnit(value); break; case ThirdPartyTxUrls: if (strThirdPartyTxUrls != value.toString()) { strThirdPartyTxUrls = value.toString(); settings.setValue("strThirdPartyTxUrls", strThirdPartyTxUrls); setRestartRequired(true); } break; case Language: if (settings.value("language") != value) { settings.setValue("language", value); setRestartRequired(true); } break; case CoinControlFeatures: fCoinControlFeatures = value.toBool(); settings.setValue("fCoinControlFeatures", fCoinControlFeatures); emit coinControlFeaturesChanged(fCoinControlFeatures); break; case DatabaseCache: if (settings.value("nDatabaseCache") != value) { settings.setValue("nDatabaseCache", value); setRestartRequired(true); } break; case ThreadsScriptVerif: if (settings.value("nThreadsScriptVerif") != value) { settings.setValue("nThreadsScriptVerif", value); setRestartRequired(true); } break; case Listen: if (settings.value("fListen") != value) { settings.setValue("fListen", value); setRestartRequired(true); } break; default: break; } } emit dataChanged(index, index); return successful; } /** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */ void OptionsModel::setDisplayUnit(const QVariant &value) { if (!value.isNull()) { QSettings settings; nDisplayUnit = value.toInt(); settings.setValue("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(nDisplayUnit); } } bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const { // Directly query current base proxy, because // GUI settings can be overridden with -proxy. proxyType curProxy; if (GetProxy(NET_IPV4, curProxy)) { proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setHostName(QString::fromStdString(curProxy.ToStringIP())); proxy.setPort(curProxy.GetPort()); return true; } else proxy.setType(QNetworkProxy::NoProxy); return false; } void OptionsModel::setRestartRequired(bool fRequired) { QSettings settings; return settings.setValue("fRestartRequired", fRequired); } bool OptionsModel::isRestartRequired() { QSettings settings; return settings.value("fRestartRequired", false).toBool(); } <commit_msg>qt: add proxy to options overridden if necessary.<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "optionsmodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "net.h" #include "txdb.h" // for -dbcache defaults #ifdef ENABLE_WALLET #include "wallet.h" #include "walletdb.h" #endif #include <QNetworkProxy> #include <QSettings> #include <QStringList> OptionsModel::OptionsModel(QObject *parent) : QAbstractListModel(parent) { Init(); } void OptionsModel::addOverriddenOption(const std::string &option) { strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(mapArgs[option]) + " "; } // Writes all missing QSettings with their default values void OptionsModel::Init() { QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool(); if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", BitcoinUnits::BTC); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("strThirdPartyTxUrls")) settings.setValue("strThirdPartyTxUrls", ""); strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If SoftSetArg() or SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS); if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); // Wallet #ifdef ENABLE_WALLET if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE); payTxFee = CFeeRate(settings.value("nTransactionFee").toLongLong()); // if -paytxfee is set, this will be overridden later in init.cpp if (mapArgs.count("-paytxfee")) addOverriddenOption("-paytxfee"); if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fListen")) settings.setValue("fListen", DEFAULT_LISTEN); if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool())) addOverriddenOption("-listen"); if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); else if(!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty()) addOverriddenOption("-proxy"); // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!SoftSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); } void OptionsModel::Reset() { QSettings settings; // Remove all entries from our QSettings object settings.clear(); // default setting for OptionsModel::StartAtStartup - disabled if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(false); } int OptionsModel::rowCount(const QModelIndex & parent) const { return OptionIDRowCount; } // read QSettings values and return them QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: return GUIUtil::GetStartOnSystemStartup(); case MinimizeToTray: return fMinimizeToTray; case MapPortUPnP: #ifdef USE_UPNP return settings.value("fUseUPnP"); #else return false; #endif case MinimizeOnClose: return fMinimizeOnClose; // default proxy case ProxyUse: return settings.value("fUseProxy", false); case ProxyIP: { // contains IP at index 0 and port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); return strlIpPort.at(0); } case ProxyPort: { // contains IP at index 0 and port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); return strlIpPort.at(1); } #ifdef ENABLE_WALLET case Fee: { // Attention: Init() is called before payTxFee is set in AppInit2()! // To ensure we can change the fee on-the-fly update our QSetting when // opening OptionsDialog, which queries Fee via the mapper. if (!(payTxFee == CFeeRate(settings.value("nTransactionFee").toLongLong(), 1000))) settings.setValue("nTransactionFee", (qint64)payTxFee.GetFeePerK()); // Todo: Consider to revert back to use just payTxFee here, if we don't want // -paytxfee to update our QSettings! return settings.value("nTransactionFee"); } case SpendZeroConfChange: return settings.value("bSpendZeroConfChange"); #endif case DisplayUnit: return nDisplayUnit; case ThirdPartyTxUrls: return strThirdPartyTxUrls; case Language: return settings.value("language"); case CoinControlFeatures: return fCoinControlFeatures; case DatabaseCache: return settings.value("nDatabaseCache"); case ThreadsScriptVerif: return settings.value("nThreadsScriptVerif"); case Listen: return settings.value("fListen"); default: return QVariant(); } } return QVariant(); } // write QSettings values bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: // core option - can be changed on-the-fly settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; // default proxy case ProxyUse: if (settings.value("fUseProxy") != value) { settings.setValue("fUseProxy", value.toBool()); setRestartRequired(true); } break; case ProxyIP: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed IP if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) { // construct new value from new IP and current port QString strNewValue = value.toString() + ":" + strlIpPort.at(1); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; case ProxyPort: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed port if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) { // construct new value from current IP and new port QString strNewValue = strlIpPort.at(0) + ":" + value.toString(); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; #ifdef ENABLE_WALLET case Fee: { // core option - can be changed on-the-fly // Todo: Add is valid check and warn via message, if not CAmount nTransactionFee(value.toLongLong()); payTxFee = CFeeRate(nTransactionFee, 1000); settings.setValue("nTransactionFee", qint64(nTransactionFee)); emit transactionFeeChanged(nTransactionFee); break; } case SpendZeroConfChange: if (settings.value("bSpendZeroConfChange") != value) { settings.setValue("bSpendZeroConfChange", value); setRestartRequired(true); } break; #endif case DisplayUnit: setDisplayUnit(value); break; case ThirdPartyTxUrls: if (strThirdPartyTxUrls != value.toString()) { strThirdPartyTxUrls = value.toString(); settings.setValue("strThirdPartyTxUrls", strThirdPartyTxUrls); setRestartRequired(true); } break; case Language: if (settings.value("language") != value) { settings.setValue("language", value); setRestartRequired(true); } break; case CoinControlFeatures: fCoinControlFeatures = value.toBool(); settings.setValue("fCoinControlFeatures", fCoinControlFeatures); emit coinControlFeaturesChanged(fCoinControlFeatures); break; case DatabaseCache: if (settings.value("nDatabaseCache") != value) { settings.setValue("nDatabaseCache", value); setRestartRequired(true); } break; case ThreadsScriptVerif: if (settings.value("nThreadsScriptVerif") != value) { settings.setValue("nThreadsScriptVerif", value); setRestartRequired(true); } break; case Listen: if (settings.value("fListen") != value) { settings.setValue("fListen", value); setRestartRequired(true); } break; default: break; } } emit dataChanged(index, index); return successful; } /** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */ void OptionsModel::setDisplayUnit(const QVariant &value) { if (!value.isNull()) { QSettings settings; nDisplayUnit = value.toInt(); settings.setValue("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(nDisplayUnit); } } bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const { // Directly query current base proxy, because // GUI settings can be overridden with -proxy. proxyType curProxy; if (GetProxy(NET_IPV4, curProxy)) { proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setHostName(QString::fromStdString(curProxy.ToStringIP())); proxy.setPort(curProxy.GetPort()); return true; } else proxy.setType(QNetworkProxy::NoProxy); return false; } void OptionsModel::setRestartRequired(bool fRequired) { QSettings settings; return settings.setValue("fRestartRequired", fRequired); } bool OptionsModel::isRestartRequired() { QSettings settings; return settings.value("fRestartRequired", false).toBool(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "auth/common.hh" #include <seastar/core/shared_ptr.hh> #include "cql3/query_processor.hh" #include "cql3/statements/create_table_statement.hh" #include "database.hh" #include "schema_builder.hh" #include "service/migration_manager.hh" #include "timeout_config.hh" namespace auth { namespace meta { const sstring DEFAULT_SUPERUSER_NAME("cassandra"); const sstring AUTH_KS("system_auth"); const sstring USERS_CF("users"); const sstring AUTH_PACKAGE_NAME("org.apache.cassandra.auth."); } static logging::logger auth_log("auth"); // Func must support being invoked more than once. future<> do_after_system_ready(seastar::abort_source& as, seastar::noncopyable_function<future<>()> func) { struct empty_state { }; return delay_until_system_ready(as).then([&as, func = std::move(func)] () mutable { return exponential_backoff_retry::do_until_value(1s, 1min, as, [func = std::move(func)] { return func().then_wrapped([] (auto&& f) -> std::optional<empty_state> { if (f.failed()) { auth_log.info("Auth task failed with error, rescheduling: {}", f.get_exception()); return { }; } return { empty_state() }; }); }); }).discard_result(); } future<> create_metadata_table_if_missing( std::string_view table_name, cql3::query_processor& qp, std::string_view cql, ::service::migration_manager& mm) { auto& db = qp.db(); if (db.has_schema(meta::AUTH_KS, sstring(table_name))) { return make_ready_future<>(); } auto parsed_statement = static_pointer_cast<cql3::statements::raw::cf_statement>( cql3::query_processor::parse_statement(cql)); parsed_statement->prepare_keyspace(meta::AUTH_KS); auto statement = static_pointer_cast<cql3::statements::create_table_statement>( parsed_statement->prepare(db, qp.get_cql_stats())->statement); const auto schema = statement->get_cf_meta_data(qp.db()); const auto uuid = generate_legacy_id(schema->ks_name(), schema->cf_name()); schema_builder b(schema); b.set_uuid(uuid); return mm.announce_new_column_family(b.build(), false); } future<> wait_for_schema_agreement(::service::migration_manager& mm, const database& db, seastar::abort_source& as) { static const auto pause = [] { return sleep(std::chrono::milliseconds(500)); }; return do_until([&db, &as] { as.check(); return db.get_version() != database::empty_version; }, pause).then([&mm, &as] { return do_until([&mm, &as] { as.check(); return mm.have_schema_agreement(); }, pause); }); } const timeout_config& internal_distributed_timeout_config() noexcept { static const auto t = 5s; static const timeout_config tc{t, t, t, t, t, t, t}; return tc; } } <commit_msg>auth: Change the log level for async. retries<commit_after>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "auth/common.hh" #include <seastar/core/shared_ptr.hh> #include "cql3/query_processor.hh" #include "cql3/statements/create_table_statement.hh" #include "database.hh" #include "schema_builder.hh" #include "service/migration_manager.hh" #include "timeout_config.hh" namespace auth { namespace meta { const sstring DEFAULT_SUPERUSER_NAME("cassandra"); const sstring AUTH_KS("system_auth"); const sstring USERS_CF("users"); const sstring AUTH_PACKAGE_NAME("org.apache.cassandra.auth."); } static logging::logger auth_log("auth"); // Func must support being invoked more than once. future<> do_after_system_ready(seastar::abort_source& as, seastar::noncopyable_function<future<>()> func) { struct empty_state { }; return delay_until_system_ready(as).then([&as, func = std::move(func)] () mutable { return exponential_backoff_retry::do_until_value(1s, 1min, as, [func = std::move(func)] { return func().then_wrapped([] (auto&& f) -> std::optional<empty_state> { if (f.failed()) { auth_log.debug("Auth task failed with error, rescheduling: {}", f.get_exception()); return { }; } return { empty_state() }; }); }); }).discard_result(); } future<> create_metadata_table_if_missing( std::string_view table_name, cql3::query_processor& qp, std::string_view cql, ::service::migration_manager& mm) { auto& db = qp.db(); if (db.has_schema(meta::AUTH_KS, sstring(table_name))) { return make_ready_future<>(); } auto parsed_statement = static_pointer_cast<cql3::statements::raw::cf_statement>( cql3::query_processor::parse_statement(cql)); parsed_statement->prepare_keyspace(meta::AUTH_KS); auto statement = static_pointer_cast<cql3::statements::create_table_statement>( parsed_statement->prepare(db, qp.get_cql_stats())->statement); const auto schema = statement->get_cf_meta_data(qp.db()); const auto uuid = generate_legacy_id(schema->ks_name(), schema->cf_name()); schema_builder b(schema); b.set_uuid(uuid); return mm.announce_new_column_family(b.build(), false); } future<> wait_for_schema_agreement(::service::migration_manager& mm, const database& db, seastar::abort_source& as) { static const auto pause = [] { return sleep(std::chrono::milliseconds(500)); }; return do_until([&db, &as] { as.check(); return db.get_version() != database::empty_version; }, pause).then([&mm, &as] { return do_until([&mm, &as] { as.check(); return mm.have_schema_agreement(); }, pause); }); } const timeout_config& internal_distributed_timeout_config() noexcept { static const auto t = 5s; static const timeout_config tc{t, t, t, t, t, t, t}; return tc; } } <|endoftext|>
<commit_before><commit_msg>allow user to specify max beam for aligning retries<commit_after><|endoftext|>
<commit_before>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*- // // Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // Copyright (C) 2002-2003 Zack Rusin <zack@kde.org> // // gaducontact.cpp // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. #include <klocale.h> #include <kaction.h> #include <kdebug.h> #include <kfiledialog.h> #include "gaduaccount.h" #include "gaduprotocol.h" #include "gaducontact.h" #include "gadupubdir.h" #include "gadueditcontact.h" #include "gaducontactlist.h" #include "gadusession.h" #include "kopetemessagemanagerfactory.h" #include "kopetegroup.h" #include "kopetemetacontact.h" #include "kopetestdaction.h" #include "kopeteuiglobal.h" #include "userinfodialog.h" using Kopete::UserInfoDialog; GaduContact::GaduContact( uin_t uin, const QString& name, KopeteAccount* account, KopeteMetaContact* parent ) : KopeteContact( account, QString::number( uin ), parent ), uin_( uin ) { msgManager_ = 0L; account_ = static_cast<GaduAccount*>( account ); remote_ip = 0; remote_port = 0; version = 0; image_size = 0; thisContact_.append( this ); initActions(); // don't call libkopete functions like these until the object is fully // constructed. all GaduContact construction must be above this point. setFileCapable( false ); //offline setOnlineStatus( GaduProtocol::protocol()->convertStatus( 0 ) ); setDisplayName( name ); } QString GaduContact::identityId() const { return parentIdentity_; } void GaduContact::setParentIdentity( const QString& id) { parentIdentity_ = id; } uin_t GaduContact::uin() const { return uin_; } void GaduContact::sendFile( const KURL &sourceURL, const QString &fileName, uint fileSize ) { QString filePath; if ( !sourceURL.isValid () ) { filePath = KFileDialog::getOpenFileName( QString::null , "*", 0L, i18n ( "Kopete File Transfer" ) ); } else { filePath = sourceURL.path( -1 ); } QFile file ( filePath ); if ( file.exists () ) { // transfer the bastard } } void GaduContact::changedStatus( KGaduNotify* newstatus ) { if ( newstatus->description.isNull() ) { setOnlineStatus( GaduProtocol::protocol()->convertStatus( newstatus->status ) ); removeProperty( GaduProtocol::protocol()->propAwayMessage ); } else { setOnlineStatus( GaduProtocol::protocol()->convertStatus( newstatus->status ) ); setProperty( GaduProtocol::protocol()->propAwayMessage, newstatus->description ); } remote_ip = newstatus->remote_ip; remote_port = newstatus->remote_port; version = newstatus->version; image_size = newstatus->image_size; setFileCapable( newstatus->fileCap ); kdDebug(14100) << "uin:" << uin() << " port: " << remote_port << " remote ip: " << remote_ip << " image size: " << image_size << " version: " << version << endl; } unsigned int GaduContact::contactIp() { return remote_ip; } unsigned short GaduContact::contactPort() { return remote_port; } KopeteMessageManager* GaduContact::manager( bool canCreate ) { if ( !msgManager_ && canCreate ) { msgManager_ = KopeteMessageManagerFactory::factory()->create( account_->myself(), thisContact_, GaduProtocol::protocol() ); connect( msgManager_, SIGNAL( messageSent( KopeteMessage&, KopeteMessageManager*) ), this, SLOT( messageSend( KopeteMessage&, KopeteMessageManager*) ) ); connect( msgManager_, SIGNAL( destroyed() ), this, SLOT( slotMessageManagerDestroyed() ) ); } return msgManager_; } void GaduContact::slotMessageManagerDestroyed() { msgManager_ = 0L; } void GaduContact::initActions() { actionSendMessage_ = KopeteStdAction::sendMessage( this, SLOT( execute() ), this, "actionMessage" ); actionInfo_ = KopeteStdAction::contactInfo( this, SLOT( slotUserInfo() ), this, "actionInfo" ); } void GaduContact::messageReceived( KopeteMessage& msg ) { manager()->appendMessage( msg ); } void GaduContact::messageSend( KopeteMessage& msg, KopeteMessageManager* mgr ) { if ( msg.plainBody().isEmpty() ) { return; } mgr->appendMessage( msg ); account_->sendMessage( uin_, msg ); } bool GaduContact::isReachable() { return account_->isConnected(); } QPtrList<KAction>* GaduContact::customContextMenuActions() { QPtrList<KAction> *fakeCollection = new QPtrList<KAction>(); //show profile KAction* actionShowProfile = new KAction( i18n("Show Profile") , "info", 0, this, SLOT( slotShowPublicProfile() ), this, "actionShowPublicProfile" ); fakeCollection->append( actionShowProfile ); KAction* actionEditContact = new KAction( i18n("Edit...") , "edit", 0, this, SLOT( slotEditContact() ), this, "actionEditContact" ); fakeCollection->append( actionEditContact ); return fakeCollection; } void GaduContact::slotEditContact() { new GaduEditContact( static_cast<GaduAccount*>(account()), this, Kopete::UI::Global::mainWidget() ); } void GaduContact::slotShowPublicProfile() { account_->slotSearch( uin_ ); } void GaduContact::slotUserInfo() { /// FIXME: use more decent information here UserInfoDialog *dlg = new UserInfoDialog( i18n( "Gadu contact" ) ); dlg->setName( metaContact()->displayName() ); dlg->setId( QString::number( uin_ ) ); dlg->setStatus( onlineStatus().description() ); dlg->setAwayMessage( description_ ); dlg->show(); } void GaduContact::slotDeleteContact() { account_->removeContact( this ); deleteLater(); } void GaduContact::serialize( QMap<QString, QString>& serializedData, QMap<QString, QString>& ) { serializedData[ "email" ] = property( GaduProtocol::protocol()->propEmail ).value().toString(); serializedData[ "FirstName" ] = property( GaduProtocol::protocol()->propFirstName ).value().toString(); serializedData[ "SecondName" ] = property( GaduProtocol::protocol()->propLastName ).value().toString(); serializedData[ "telephone" ] = property( GaduProtocol::protocol()->propPhoneNr ).value().toString(); serializedData[ "ignored" ] = ignored_ ? "true" : "false"; } bool GaduContact::setContactDetails( const GaduContactsList::ContactLine* cl ) { setProperty( GaduProtocol::protocol()->propEmail, cl->email ); setProperty( GaduProtocol::protocol()->propFirstName, cl->firstname ); setProperty( GaduProtocol::protocol()->propLastName, cl->surname ); setProperty( GaduProtocol::protocol()->propPhoneNr, cl->phonenr ); //setProperty( "ignored", i18n( "ignored" ), cl->ignored ? "true" : "false" ); ignored_ = cl->ignored; //setProperty( "nickName", i18n( "nick name" ), cl->nickname ); return true; } GaduContactsList::ContactLine* GaduContact::contactDetails() { KopeteGroupList groupList; QString groups; GaduContactsList::ContactLine* cl = new GaduContactsList::ContactLine; cl->firstname = property( GaduProtocol::protocol()->propFirstName ).value().toString(); cl->surname = property( GaduProtocol::protocol()->propLastName ).value().toString(); //cl->nickname = property( "nickName" ).value().toString(); cl->email = property( GaduProtocol::protocol()->propEmail ).value().toString(); cl->phonenr = property( GaduProtocol::protocol()->propPhoneNr ).value().toString(); cl->ignored = ignored_; //( property( "ignored" ).value().toString() == "true" ); cl->uin = QString::number( uin_ ); cl->displayname = metaContact()->displayName(); groupList = metaContact()->groups(); KopeteGroup* gr; for ( gr = groupList.first (); gr ; gr = groupList.next () ) { // if present in any group, don't export to top level // FIXME: again, probably bug in libkopete // in case of topLevel group, KopeteGroup::displayName() returns "TopLevel" ineasted of just " " or "/" // imo TopLevel group should be detected like i am doing that below if ( gr!=KopeteGroup::topLevel() ) { groups += gr->displayName()+","; } } if ( groups.length() ) { groups.truncate( groups.length()-1 ); } cl->group = groups; return cl; } QString GaduContact::findBestContactName( const GaduContactsList::ContactLine* cl ) { QString name; if ( cl == NULL ) { return name; } if ( cl->uin.isEmpty() ) { return name; } name = cl->uin; if ( cl->displayname.length() ) { name = cl->displayname; } else { // no name either if ( cl->nickname.isEmpty() ) { // maybe we can use fistname + surname ? if ( cl->firstname.isEmpty() && cl->surname.isEmpty() ) { name = cl->uin; } // what a shame, i have to use UIN than :/ else { if ( cl->firstname.isEmpty() ) { name = cl->surname; } else { if ( cl->surname.isEmpty() ) { name = cl->firstname; } else { name = cl->firstname + " " + cl->surname; } } } } else { name = cl->nickname; } } return name; } void GaduContact::messageAck() { manager()->messageSucceeded(); } void GaduContact::setIgnored( bool val ) { ignored_ = val; } bool GaduContact::ignored() { return ignored_; } #include "gaducontact.moc" <commit_msg>canCreate is false by default, causing loads of issues. don't crash anymore... (argentina)<commit_after>// -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*- // // Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl> // Copyright (C) 2002-2003 Zack Rusin <zack@kde.org> // // gaducontact.cpp // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. #include <klocale.h> #include <kaction.h> #include <kdebug.h> #include <kfiledialog.h> #include "gaduaccount.h" #include "gaduprotocol.h" #include "gaducontact.h" #include "gadupubdir.h" #include "gadueditcontact.h" #include "gaducontactlist.h" #include "gadusession.h" #include "kopetemessagemanagerfactory.h" #include "kopetegroup.h" #include "kopetemetacontact.h" #include "kopetestdaction.h" #include "kopeteuiglobal.h" #include "userinfodialog.h" using Kopete::UserInfoDialog; GaduContact::GaduContact( uin_t uin, const QString& name, KopeteAccount* account, KopeteMetaContact* parent ) : KopeteContact( account, QString::number( uin ), parent ), uin_( uin ) { msgManager_ = 0L; account_ = static_cast<GaduAccount*>( account ); remote_ip = 0; remote_port = 0; version = 0; image_size = 0; thisContact_.append( this ); initActions(); // don't call libkopete functions like these until the object is fully // constructed. all GaduContact construction must be above this point. setFileCapable( false ); //offline setOnlineStatus( GaduProtocol::protocol()->convertStatus( 0 ) ); setDisplayName( name ); } QString GaduContact::identityId() const { return parentIdentity_; } void GaduContact::setParentIdentity( const QString& id) { parentIdentity_ = id; } uin_t GaduContact::uin() const { return uin_; } void GaduContact::sendFile( const KURL &sourceURL, const QString &fileName, uint fileSize ) { QString filePath; if ( !sourceURL.isValid () ) { filePath = KFileDialog::getOpenFileName( QString::null , "*", 0L, i18n ( "Kopete File Transfer" ) ); } else { filePath = sourceURL.path( -1 ); } QFile file ( filePath ); if ( file.exists () ) { // transfer the bastard } } void GaduContact::changedStatus( KGaduNotify* newstatus ) { if ( newstatus->description.isNull() ) { setOnlineStatus( GaduProtocol::protocol()->convertStatus( newstatus->status ) ); removeProperty( GaduProtocol::protocol()->propAwayMessage ); } else { setOnlineStatus( GaduProtocol::protocol()->convertStatus( newstatus->status ) ); setProperty( GaduProtocol::protocol()->propAwayMessage, newstatus->description ); } remote_ip = newstatus->remote_ip; remote_port = newstatus->remote_port; version = newstatus->version; image_size = newstatus->image_size; setFileCapable( newstatus->fileCap ); kdDebug(14100) << "uin:" << uin() << " port: " << remote_port << " remote ip: " << remote_ip << " image size: " << image_size << " version: " << version << endl; } unsigned int GaduContact::contactIp() { return remote_ip; } unsigned short GaduContact::contactPort() { return remote_port; } KopeteMessageManager* GaduContact::manager( bool /* canCreate */ ) { if ( !msgManager_ ) { msgManager_ = KopeteMessageManagerFactory::factory()->create( account_->myself(), thisContact_, GaduProtocol::protocol() ); connect( msgManager_, SIGNAL( messageSent( KopeteMessage&, KopeteMessageManager*) ), this, SLOT( messageSend( KopeteMessage&, KopeteMessageManager*) ) ); connect( msgManager_, SIGNAL( destroyed() ), this, SLOT( slotMessageManagerDestroyed() ) ); } kdDebug(14100) << "GaduContact::manager returning: " << msgManager_ << endl; return msgManager_; } void GaduContact::slotMessageManagerDestroyed() { msgManager_ = 0L; } void GaduContact::initActions() { actionSendMessage_ = KopeteStdAction::sendMessage( this, SLOT( execute() ), this, "actionMessage" ); actionInfo_ = KopeteStdAction::contactInfo( this, SLOT( slotUserInfo() ), this, "actionInfo" ); } void GaduContact::messageReceived( KopeteMessage& msg ) { manager()->appendMessage( msg ); } void GaduContact::messageSend( KopeteMessage& msg, KopeteMessageManager* mgr ) { if ( msg.plainBody().isEmpty() ) { return; } mgr->appendMessage( msg ); account_->sendMessage( uin_, msg ); } bool GaduContact::isReachable() { return account_->isConnected(); } QPtrList<KAction>* GaduContact::customContextMenuActions() { QPtrList<KAction> *fakeCollection = new QPtrList<KAction>(); //show profile KAction* actionShowProfile = new KAction( i18n("Show Profile") , "info", 0, this, SLOT( slotShowPublicProfile() ), this, "actionShowPublicProfile" ); fakeCollection->append( actionShowProfile ); KAction* actionEditContact = new KAction( i18n("Edit...") , "edit", 0, this, SLOT( slotEditContact() ), this, "actionEditContact" ); fakeCollection->append( actionEditContact ); return fakeCollection; } void GaduContact::slotEditContact() { new GaduEditContact( static_cast<GaduAccount*>(account()), this, Kopete::UI::Global::mainWidget() ); } void GaduContact::slotShowPublicProfile() { account_->slotSearch( uin_ ); } void GaduContact::slotUserInfo() { /// FIXME: use more decent information here UserInfoDialog *dlg = new UserInfoDialog( i18n( "Gadu contact" ) ); dlg->setName( metaContact()->displayName() ); dlg->setId( QString::number( uin_ ) ); dlg->setStatus( onlineStatus().description() ); dlg->setAwayMessage( description_ ); dlg->show(); } void GaduContact::slotDeleteContact() { account_->removeContact( this ); deleteLater(); } void GaduContact::serialize( QMap<QString, QString>& serializedData, QMap<QString, QString>& ) { serializedData[ "email" ] = property( GaduProtocol::protocol()->propEmail ).value().toString(); serializedData[ "FirstName" ] = property( GaduProtocol::protocol()->propFirstName ).value().toString(); serializedData[ "SecondName" ] = property( GaduProtocol::protocol()->propLastName ).value().toString(); serializedData[ "telephone" ] = property( GaduProtocol::protocol()->propPhoneNr ).value().toString(); serializedData[ "ignored" ] = ignored_ ? "true" : "false"; } bool GaduContact::setContactDetails( const GaduContactsList::ContactLine* cl ) { setProperty( GaduProtocol::protocol()->propEmail, cl->email ); setProperty( GaduProtocol::protocol()->propFirstName, cl->firstname ); setProperty( GaduProtocol::protocol()->propLastName, cl->surname ); setProperty( GaduProtocol::protocol()->propPhoneNr, cl->phonenr ); //setProperty( "ignored", i18n( "ignored" ), cl->ignored ? "true" : "false" ); ignored_ = cl->ignored; //setProperty( "nickName", i18n( "nick name" ), cl->nickname ); return true; } GaduContactsList::ContactLine* GaduContact::contactDetails() { KopeteGroupList groupList; QString groups; GaduContactsList::ContactLine* cl = new GaduContactsList::ContactLine; cl->firstname = property( GaduProtocol::protocol()->propFirstName ).value().toString(); cl->surname = property( GaduProtocol::protocol()->propLastName ).value().toString(); //cl->nickname = property( "nickName" ).value().toString(); cl->email = property( GaduProtocol::protocol()->propEmail ).value().toString(); cl->phonenr = property( GaduProtocol::protocol()->propPhoneNr ).value().toString(); cl->ignored = ignored_; //( property( "ignored" ).value().toString() == "true" ); cl->uin = QString::number( uin_ ); cl->displayname = metaContact()->displayName(); groupList = metaContact()->groups(); KopeteGroup* gr; for ( gr = groupList.first (); gr ; gr = groupList.next () ) { // if present in any group, don't export to top level // FIXME: again, probably bug in libkopete // in case of topLevel group, KopeteGroup::displayName() returns "TopLevel" ineasted of just " " or "/" // imo TopLevel group should be detected like i am doing that below if ( gr!=KopeteGroup::topLevel() ) { groups += gr->displayName()+","; } } if ( groups.length() ) { groups.truncate( groups.length()-1 ); } cl->group = groups; return cl; } QString GaduContact::findBestContactName( const GaduContactsList::ContactLine* cl ) { QString name; if ( cl == NULL ) { return name; } if ( cl->uin.isEmpty() ) { return name; } name = cl->uin; if ( cl->displayname.length() ) { name = cl->displayname; } else { // no name either if ( cl->nickname.isEmpty() ) { // maybe we can use fistname + surname ? if ( cl->firstname.isEmpty() && cl->surname.isEmpty() ) { name = cl->uin; } // what a shame, i have to use UIN than :/ else { if ( cl->firstname.isEmpty() ) { name = cl->surname; } else { if ( cl->surname.isEmpty() ) { name = cl->firstname; } else { name = cl->firstname + " " + cl->surname; } } } } else { name = cl->nickname; } } return name; } void GaduContact::messageAck() { manager()->messageSucceeded(); } void GaduContact::setIgnored( bool val ) { ignored_ = val; } bool GaduContact::ignored() { return ignored_; } #include "gaducontact.moc" <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2016 Kim Kulling 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 <cppcore/Random/RandomGenerator.h> #include <stdlib.h> #include <time.h> #include <cassert> namespace CPPCore { static const unsigned int N = 624; static const unsigned int M = 397; static void mersenne_twister_vector_init( unsigned int *seedPoints, size_t len ) { assert( nullptr != seedPoints ); const unsigned int mult = 1812433253ul; unsigned int seed = 5489ul; for (unsigned int i = 0; i < len; ++i) { seedPoints[ i ] = seed; seed = mult * (seed ^ (seed >> 30)) + (i + 1); } } static void mersenne_twister_vector_update(unsigned int* const p) { static const unsigned int A[ 2 ] = { 0, 0x9908B0DF }; unsigned int i; for (; i < N - M; i++) p[i] = p[i + (M)] ^ (((p[i] & 0x80000000) | (p[i + 1] & 0x7FFFFFFF)) >> 1) ^ A[p[i + 1] & 1]; for (; i < N - 1; i++) p[i] = p[i + (M - N)] ^ (((p[i] & 0x80000000) | (p[i + 1] & 0x7FFFFFFF)) >> 1) ^ A[p[i + 1] & 1]; p[N - 1] = p[M - 1] ^ (((p[N - 1] & 0x80000000) | (p[0] & 0x7FFFFFFF)) >> 1) ^ A[p[0] & 1]; } unsigned int mersenne_twister() { static unsigned int vector[ N ]; /* Zustandsvektor */ static int idx = N + 1; /* Auslese-Index; idx>N: neuer Vektor mu berechnet werden, idx=N+1: Vektor mu berhaupt erst mal initialisiert werden */ if (idx >= N) { if (idx > N) { mersenne_twister_vector_init(vector, N); } mersenne_twister_vector_update(vector); idx = 0; } unsigned int e = vector[ idx++ ]; // Tempering e ^= (e >> 11); e ^= (e << 7) & 0x9D2C5680; e ^= (e << 15) & 0xEFC60000; e ^= (e >> 18); return e; } RandomGenerator::RandomGenerator( GeneratorType type ) noexcept : m_type( type ) { ::srand( static_cast< unsigned int >( time( NULL ) ) ); } RandomGenerator::~RandomGenerator() { // empty } int RandomGenerator::get( int lower, int upper ) { int ret( 0 ); if ( GeneratorType::Standard == m_type ) { ret = ::rand() % upper + lower; } else if (GeneratorType::MersenneTwister == m_type) { ret = mersenne_twister() % upper + lower; } return ret; } } // Namespace CPPCore <commit_msg>RAndomGenerator: fix compiler warnings.<commit_after>/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2016 Kim Kulling 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 <cppcore/Random/RandomGenerator.h> #include <stdlib.h> #include <time.h> #include <cassert> namespace CPPCore { static const unsigned int N = 624; static const unsigned int M = 397; static void mersenne_twister_vector_init( unsigned int *seedPoints, size_t len ) { assert( nullptr != seedPoints ); const unsigned int mult = 1812433253ul; unsigned int seed = 5489ul; for (unsigned int i = 0; i < len; ++i) { seedPoints[ i ] = seed; seed = mult * (seed ^ (seed >> 30)) + (i + 1); } } static void mersenne_twister_vector_update(unsigned int* const p) { static const unsigned int A[ 2 ] = { 0, 0x9908B0DF }; unsigned int i=0; for (; i < N - M; i++) p[i] = p[i + (M)] ^ (((p[i] & 0x80000000) | (p[i + 1] & 0x7FFFFFFF)) >> 1) ^ A[p[i + 1] & 1]; for (; i < N - 1; i++) p[i] = p[i + (M - N)] ^ (((p[i] & 0x80000000) | (p[i + 1] & 0x7FFFFFFF)) >> 1) ^ A[p[i + 1] & 1]; p[N - 1] = p[M - 1] ^ (((p[N - 1] & 0x80000000) | (p[0] & 0x7FFFFFFF)) >> 1) ^ A[p[0] & 1]; } unsigned int mersenne_twister() { static unsigned int vector[ N ]; /* Zustandsvektor */ static int idx = N + 1; /* Auslese-Index; idx>N: neuer Vektor mu berechnet werden, idx=N+1: Vektor mu berhaupt erst mal initialisiert werden */ if (static_cast<unsigned int>(idx) >= N) { if (static_cast<unsigned int>(idx) > N) { mersenne_twister_vector_init(vector, N); } mersenne_twister_vector_update(vector); idx = 0; } unsigned int e = vector[ idx++ ]; // Tempering e ^= (e >> 11); e ^= (e << 7) & 0x9D2C5680; e ^= (e << 15) & 0xEFC60000; e ^= (e >> 18); return e; } RandomGenerator::RandomGenerator( GeneratorType type ) noexcept : m_type( type ) { ::srand( static_cast< unsigned int >( time( NULL ) ) ); } RandomGenerator::~RandomGenerator() { // empty } int RandomGenerator::get( int lower, int upper ) { int ret( 0 ); if ( GeneratorType::Standard == m_type ) { ret = ::rand() % upper + lower; } else if (GeneratorType::MersenneTwister == m_type) { ret = mersenne_twister() % upper + lower; } return ret; } } // Namespace CPPCore <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // aggregate_test.cpp // // Identification: tests/executor/aggregate_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <set> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "backend/common/types.h" #include "backend/common/value.h" #include "backend/executor/logical_tile.h" #include "backend/executor/aggregate_executor.h" #include "backend/executor/logical_tile_factory.h" #include "backend/expression/expression_util.h" #include "backend/planner/abstract_plan_node.h" #include "backend/planner/aggregateV2_node.h" #include "backend/storage/data_table.h" #include "executor/executor_tests_util.h" #include "executor/mock_executor.h" #include "harness.h" using ::testing::NotNull; using ::testing::Return; namespace peloton { namespace test { TEST(AggregateTests, DistinctTest) { /* * SELECT d, a, b, c FROM table GROUP BY a, b, c, d; */ const int tuple_count = TESTS_TUPLES_PER_TILEGROUP; // Create a table and wrap it in logical tiles std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tuple_count, false)); ExecutorTestsUtil::PopulateTable(data_table.get(), 2*tuple_count, false, false, true); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> source_logical_tile2( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1))); // (1-5) Setup plan node // 1) Set up group-by columns std::vector<oid_t> group_by_columns = { 0, 1, 2, 3 }; // 2) Set up project info planner::ProjectInfo::DirectMapList direct_map_list = { { 0, { 0, 3 } }, { 1, { 0, 0 } }, { 2, { 0, 1 } }, { 3, { 0, 2 } } }; auto proj_info = new planner::ProjectInfo(planner::ProjectInfo::TargetList(), std::move(direct_map_list)); // 3) Set up unique aggregates (empty) std::vector<planner::AggregateV2Node::AggTerm> agg_terms; // 4) Set up predicate (empty) expression::AbstractExpression* predicate = nullptr; // 5) Create output table schema auto data_table_schema = data_table.get()->GetSchema(); std::vector<oid_t> set = { 3, 0, 1, 2 }; std::vector<catalog::Column> columns; for (auto column_index : set) { columns.push_back(data_table_schema->GetColumn(column_index)); } auto output_table_schema = new catalog::Schema(columns); // OK) Create the plan node planner::AggregateV2Node node(proj_info, predicate, std::move(agg_terms), std::move(group_by_columns), output_table_schema); // Create and set up executor auto &txn_manager = concurrency::TransactionManager::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); executor::AggregateExecutor executor(&node, context.get()); MockExecutor child_executor; executor.AddChild(&child_executor); EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()).WillOnce(Return(true)).WillOnce( Return(true)).WillOnce(Return(false)); EXPECT_CALL(child_executor, GetOutput()).WillOnce( Return(source_logical_tile1.release())).WillOnce( Return(source_logical_tile2.release())); EXPECT_TRUE(executor.Init()); EXPECT_TRUE(executor.Execute()); txn_manager.CommitTransaction(txn); } TEST(AggregateTests, SumGroupByTest) { /* * SELECT a, SUM(b) from table GROUP BY a; */ const int tuple_count = TESTS_TUPLES_PER_TILEGROUP; // Create a table and wrap it in logical tiles std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tuple_count, false)); ExecutorTestsUtil::PopulateTable(data_table.get(), 2*tuple_count, false, false, true); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> source_logical_tile2( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1))); // (1-5) Setup plan node // 1) Set up group-by columns std::vector<oid_t> group_by_columns = { 0 }; // 2) Set up project info planner::ProjectInfo::DirectMapList direct_map_list = { { 0, { 0, 0 } }, { 1, { 1, 0 } } }; auto proj_info = new planner::ProjectInfo(planner::ProjectInfo::TargetList(), std::move(direct_map_list)); // 3) Set up unique aggregates std::vector<planner::AggregateV2Node::AggTerm> agg_terms; planner::AggregateV2Node::AggTerm sumb = std::make_pair( EXPRESSION_TYPE_AGGREGATE_SUM, expression::TupleValueFactory(0, 1)); agg_terms.push_back(sumb); // 4) Set up predicate (empty) expression::AbstractExpression* predicate = nullptr; // 5) Create output table schema auto data_table_schema = data_table.get()->GetSchema(); std::vector<oid_t> set = { 0, 1 }; std::vector<catalog::Column> columns; for (auto column_index : set) { columns.push_back(data_table_schema->GetColumn(column_index)); } auto output_table_schema = new catalog::Schema(columns); // OK) Create the plan node planner::AggregateV2Node node(proj_info, predicate, std::move(agg_terms), std::move(group_by_columns), output_table_schema); // Create and set up executor auto &txn_manager = concurrency::TransactionManager::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); executor::AggregateExecutor executor(&node, context.get()); MockExecutor child_executor; executor.AddChild(&child_executor); EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()).WillOnce(Return(true)).WillOnce( Return(true)).WillOnce(Return(false)); EXPECT_CALL(child_executor, GetOutput()).WillOnce( Return(source_logical_tile1.release())).WillOnce( Return(source_logical_tile2.release())); EXPECT_TRUE(executor.Init()); EXPECT_TRUE(executor.Execute()); txn_manager.CommitTransaction(txn); } TEST(AggregateTests, SumMaxGroupByTest) { /* * SELECT a, SUM(b), MAX(c) from table GROUP BY a; */ const int tuple_count = TESTS_TUPLES_PER_TILEGROUP; // Create a table and wrap it in logical tiles std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tuple_count, false)); ExecutorTestsUtil::PopulateTable(data_table.get(), 2 * tuple_count, false, false, true); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> source_logical_tile2( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1))); // (1-5) Setup plan node // 1) Set up group-by columns std::vector<oid_t> group_by_columns = { 0 }; // 2) Set up project info planner::ProjectInfo::DirectMapList direct_map_list = { { 0, { 0, 0 } }, { 1, { 1, 0 } }, { 2, { 1, 1 } } }; auto proj_info = new planner::ProjectInfo(planner::ProjectInfo::TargetList(), std::move(direct_map_list)); // 3) Set up unique aggregates std::vector<planner::AggregateV2Node::AggTerm> agg_terms; planner::AggregateV2Node::AggTerm sumb = std::make_pair( EXPRESSION_TYPE_AGGREGATE_SUM, expression::TupleValueFactory(0, 1)); planner::AggregateV2Node::AggTerm maxc = std::make_pair( EXPRESSION_TYPE_AGGREGATE_MAX, expression::TupleValueFactory(0, 2)); agg_terms.push_back(sumb); agg_terms.push_back(maxc); // 4) Set up predicate (empty) expression::AbstractExpression* predicate = nullptr; // 5) Create output table schema auto data_table_schema = data_table.get()->GetSchema(); std::vector<oid_t> set = { 0, 1, 2 }; std::vector<catalog::Column> columns; for (auto column_index : set) { columns.push_back(data_table_schema->GetColumn(column_index)); } auto output_table_schema = new catalog::Schema(columns); // OK) Create the plan node planner::AggregateV2Node node(proj_info, predicate, std::move(agg_terms), std::move(group_by_columns), output_table_schema); // Create and set up executor auto &txn_manager = concurrency::TransactionManager::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); executor::AggregateExecutor executor(&node, context.get()); MockExecutor child_executor; executor.AddChild(&child_executor); EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()).WillOnce(Return(true)).WillOnce( Return(true)).WillOnce(Return(false)); EXPECT_CALL(child_executor, GetOutput()).WillOnce( Return(source_logical_tile1.release())).WillOnce( Return(source_logical_tile2.release())); EXPECT_TRUE(executor.Init()); EXPECT_TRUE(executor.Execute()); txn_manager.CommitTransaction(txn); } /* TEST(AggregateTests, AggregateTest) { const int tuple_count = TESTS_TUPLES_PER_TILEGROUP; // Create a table and wrap it in logical tiles std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tuple_count, false)); ExecutorTestsUtil::PopulateTable(data_table.get(), 2 * tuple_count, false, false, true); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> source_logical_tile2( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1))); // Setup plan node std::vector<oid_t> group_by_columns = {0, 1}; std::map<oid_t, oid_t> pass_through_columns_map; // Input tuple column index -> Output tuple column index pass_through_columns_map[0] = 0; pass_through_columns_map[1] = 1; // Aggregates std::vector<oid_t> aggregate_columns = {2, 2}; std::map<oid_t, oid_t> aggregate_columns_map; // Input tuple column index -> Output tuple column index aggregate_columns_map[0] = 2; aggregate_columns_map[1] = 3; std::vector<ExpressionType> aggregate_types; aggregate_types.push_back(EXPRESSION_TYPE_AGGREGATE_SUM); aggregate_types.push_back(EXPRESSION_TYPE_AGGREGATE_AVG); // More complex schema construction auto data_table_schema = data_table.get()->GetSchema(); std::vector<oid_t> set = {0, 1, 2, 2}; std::vector<catalog::Column> columns; for (auto column_index : set) { columns.push_back(data_table_schema->GetColumn(column_index)); } auto output_table_schema = new catalog::Schema(columns); // Create the plan node planner::AggregateNode node( aggregate_columns, aggregate_columns_map, group_by_columns, nullptr, pass_through_columns_map, aggregate_types, output_table_schema); // Create and set up executor auto &txn_manager = concurrency::TransactionManager::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); executor::AggregateExecutor executor(&node, context.get()); MockExecutor child_executor; executor.AddChild(&child_executor); EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_CALL(child_executor, GetOutput()) .WillOnce(Return(source_logical_tile1.release())) .WillOnce(Return(source_logical_tile2.release())); EXPECT_TRUE(executor.Init()); EXPECT_TRUE(executor.Execute()); std::unique_ptr<executor::LogicalTile> logical_tile(executor.GetOutput()); EXPECT_TRUE(logical_tile.get() != nullptr); EXPECT_TRUE(logical_tile.get()->GetValue(0, 2) == ValueFactory::GetDoubleValue(110)); EXPECT_TRUE(logical_tile.get()->GetValue(1, 2) == ValueFactory::GetDoubleValue(360)); EXPECT_TRUE(logical_tile.get()->GetValue(0, 3) == ValueFactory::GetDoubleValue(22)); EXPECT_TRUE(logical_tile.get()->GetValue(1, 3) == ValueFactory::GetDoubleValue(72)); txn_manager.CommitTransaction(txn); } */ } // namespace test } // namespace peloton <commit_msg>Add EXPECT_TRUE in aggregate_test.<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // aggregate_test.cpp // // Identification: tests/executor/aggregate_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include <set> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "backend/common/types.h" #include "backend/common/value.h" #include "backend/executor/logical_tile.h" #include "backend/executor/aggregate_executor.h" #include "backend/executor/logical_tile_factory.h" #include "backend/expression/expression_util.h" #include "backend/planner/abstract_plan_node.h" #include "backend/planner/aggregateV2_node.h" #include "backend/storage/data_table.h" #include "executor/executor_tests_util.h" #include "executor/mock_executor.h" #include "harness.h" using ::testing::NotNull; using ::testing::Return; namespace peloton { namespace test { TEST(AggregateTests, DistinctTest) { /* * SELECT d, a, b, c FROM table GROUP BY a, b, c, d; */ const int tuple_count = TESTS_TUPLES_PER_TILEGROUP; // Create a table and wrap it in logical tiles std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tuple_count, false)); ExecutorTestsUtil::PopulateTable(data_table.get(), 2*tuple_count, false, false, true); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> source_logical_tile2( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1))); // (1-5) Setup plan node // 1) Set up group-by columns std::vector<oid_t> group_by_columns = { 0, 1, 2, 3 }; // 2) Set up project info planner::ProjectInfo::DirectMapList direct_map_list = { { 0, { 0, 3 } }, { 1, { 0, 0 } }, { 2, { 0, 1 } }, { 3, { 0, 2 } } }; auto proj_info = new planner::ProjectInfo(planner::ProjectInfo::TargetList(), std::move(direct_map_list)); // 3) Set up unique aggregates (empty) std::vector<planner::AggregateV2Node::AggTerm> agg_terms; // 4) Set up predicate (empty) expression::AbstractExpression* predicate = nullptr; // 5) Create output table schema auto data_table_schema = data_table.get()->GetSchema(); std::vector<oid_t> set = { 3, 0, 1, 2 }; std::vector<catalog::Column> columns; for (auto column_index : set) { columns.push_back(data_table_schema->GetColumn(column_index)); } auto output_table_schema = new catalog::Schema(columns); // OK) Create the plan node planner::AggregateV2Node node(proj_info, predicate, std::move(agg_terms), std::move(group_by_columns), output_table_schema); // Create and set up executor auto &txn_manager = concurrency::TransactionManager::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); executor::AggregateExecutor executor(&node, context.get()); MockExecutor child_executor; executor.AddChild(&child_executor); EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()).WillOnce(Return(true)).WillOnce( Return(true)).WillOnce(Return(false)); EXPECT_CALL(child_executor, GetOutput()).WillOnce( Return(source_logical_tile1.release())).WillOnce( Return(source_logical_tile2.release())); EXPECT_TRUE(executor.Init()); EXPECT_TRUE(executor.Execute()); txn_manager.CommitTransaction(txn); /* Verify result */ std::unique_ptr<executor::LogicalTile> result_tile(executor.GetOutput()); EXPECT_TRUE(result_tile.get() != nullptr); EXPECT_TRUE(result_tile->GetValue(0, 2).OpEquals(ValueFactory::GetIntegerValue(1)).IsTrue()); EXPECT_TRUE(result_tile->GetValue(0, 3).OpEquals(ValueFactory::GetDoubleValue(2)).IsTrue()); EXPECT_TRUE(result_tile->GetValue(5, 2).OpEquals(ValueFactory::GetIntegerValue(51)).IsTrue()); EXPECT_TRUE(result_tile->GetValue(5, 3).OpEquals(ValueFactory::GetDoubleValue(52)).IsTrue()); } TEST(AggregateTests, SumGroupByTest) { /* * SELECT a, SUM(b) from table GROUP BY a; */ const int tuple_count = TESTS_TUPLES_PER_TILEGROUP; // Create a table and wrap it in logical tiles std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tuple_count, false)); ExecutorTestsUtil::PopulateTable(data_table.get(), 2*tuple_count, false, false, true); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> source_logical_tile2( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1))); // (1-5) Setup plan node // 1) Set up group-by columns std::vector<oid_t> group_by_columns = { 0 }; // 2) Set up project info planner::ProjectInfo::DirectMapList direct_map_list = { { 0, { 0, 0 } }, { 1, { 1, 0 } } }; auto proj_info = new planner::ProjectInfo(planner::ProjectInfo::TargetList(), std::move(direct_map_list)); // 3) Set up unique aggregates std::vector<planner::AggregateV2Node::AggTerm> agg_terms; planner::AggregateV2Node::AggTerm sumb = std::make_pair( EXPRESSION_TYPE_AGGREGATE_SUM, expression::TupleValueFactory(0, 1)); agg_terms.push_back(sumb); // 4) Set up predicate (empty) expression::AbstractExpression* predicate = nullptr; // 5) Create output table schema auto data_table_schema = data_table.get()->GetSchema(); std::vector<oid_t> set = { 0, 1 }; std::vector<catalog::Column> columns; for (auto column_index : set) { columns.push_back(data_table_schema->GetColumn(column_index)); } auto output_table_schema = new catalog::Schema(columns); // OK) Create the plan node planner::AggregateV2Node node(proj_info, predicate, std::move(agg_terms), std::move(group_by_columns), output_table_schema); // Create and set up executor auto &txn_manager = concurrency::TransactionManager::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); executor::AggregateExecutor executor(&node, context.get()); MockExecutor child_executor; executor.AddChild(&child_executor); EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()).WillOnce(Return(true)).WillOnce( Return(true)).WillOnce(Return(false)); EXPECT_CALL(child_executor, GetOutput()).WillOnce( Return(source_logical_tile1.release())).WillOnce( Return(source_logical_tile2.release())); EXPECT_TRUE(executor.Init()); EXPECT_TRUE(executor.Execute()); txn_manager.CommitTransaction(txn); /* Verify result */ std::unique_ptr<executor::LogicalTile> result_tile(executor.GetOutput()); EXPECT_TRUE(result_tile.get() != nullptr); EXPECT_TRUE(result_tile->GetValue(0, 0).OpEquals(ValueFactory::GetIntegerValue(0)).IsTrue()); EXPECT_TRUE(result_tile->GetValue(0, 1).OpEquals(ValueFactory::GetIntegerValue(460)).IsTrue()); } TEST(AggregateTests, SumMaxGroupByTest) { /* * SELECT a, SUM(b), MAX(c) from table GROUP BY a; */ const int tuple_count = TESTS_TUPLES_PER_TILEGROUP; // Create a table and wrap it in logical tiles std::unique_ptr<storage::DataTable> data_table( ExecutorTestsUtil::CreateTable(tuple_count, false)); ExecutorTestsUtil::PopulateTable(data_table.get(), 2 * tuple_count, false, false, true); std::unique_ptr<executor::LogicalTile> source_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> source_logical_tile2( executor::LogicalTileFactory::WrapTileGroup(data_table->GetTileGroup(1))); // (1-5) Setup plan node // 1) Set up group-by columns std::vector<oid_t> group_by_columns = { 0 }; // 2) Set up project info planner::ProjectInfo::DirectMapList direct_map_list = { { 0, { 0, 0 } }, { 1, { 1, 0 } }, { 2, { 1, 1 } } }; auto proj_info = new planner::ProjectInfo(planner::ProjectInfo::TargetList(), std::move(direct_map_list)); // 3) Set up unique aggregates std::vector<planner::AggregateV2Node::AggTerm> agg_terms; planner::AggregateV2Node::AggTerm sumb = std::make_pair( EXPRESSION_TYPE_AGGREGATE_SUM, expression::TupleValueFactory(0, 1)); planner::AggregateV2Node::AggTerm maxc = std::make_pair( EXPRESSION_TYPE_AGGREGATE_MAX, expression::TupleValueFactory(0, 2)); agg_terms.push_back(sumb); agg_terms.push_back(maxc); // 4) Set up predicate (empty) expression::AbstractExpression* predicate = nullptr; // 5) Create output table schema auto data_table_schema = data_table.get()->GetSchema(); std::vector<oid_t> set = { 0, 1, 2 }; std::vector<catalog::Column> columns; for (auto column_index : set) { columns.push_back(data_table_schema->GetColumn(column_index)); } auto output_table_schema = new catalog::Schema(columns); // OK) Create the plan node planner::AggregateV2Node node(proj_info, predicate, std::move(agg_terms), std::move(group_by_columns), output_table_schema); // Create and set up executor auto &txn_manager = concurrency::TransactionManager::GetInstance(); auto txn = txn_manager.BeginTransaction(); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); executor::AggregateExecutor executor(&node, context.get()); MockExecutor child_executor; executor.AddChild(&child_executor); EXPECT_CALL(child_executor, DInit()).WillOnce(Return(true)); EXPECT_CALL(child_executor, DExecute()).WillOnce(Return(true)).WillOnce( Return(true)).WillOnce(Return(false)); EXPECT_CALL(child_executor, GetOutput()).WillOnce( Return(source_logical_tile1.release())).WillOnce( Return(source_logical_tile2.release())); EXPECT_TRUE(executor.Init()); EXPECT_TRUE(executor.Execute()); txn_manager.CommitTransaction(txn); /* Verify result */ std::unique_ptr<executor::LogicalTile> result_tile(executor.GetOutput()); EXPECT_TRUE(result_tile.get() != nullptr); EXPECT_TRUE(result_tile->GetValue(0, 0).OpEquals(ValueFactory::GetIntegerValue(0)).IsTrue()); EXPECT_TRUE(result_tile->GetValue(0, 1).OpEquals(ValueFactory::GetIntegerValue(460)).IsTrue()); EXPECT_TRUE(result_tile->GetValue(0, 2).OpEquals(ValueFactory::GetDoubleValue(92)).IsTrue()); } } // namespace test } // namespace peloton <|endoftext|>
<commit_before>#include "overviewpage.h" #include "ui_overviewpage.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "optionsmodel.h" #include "transactiontablemodel.h" #include "transactionfilterproxy.h" #include "guiutil.h" #include "guiconstants.h" #include "askpassphrasedialog.h" #include "updatecheck.h" #include "../version.h" #include <vector> #include <QAbstractItemDelegate> #include <QPainter> #include <QDesktopServices> //Added for openURL() #include <QTimer> //Added for update timer #include <QUrl> #define DECORATION_SIZE 64 #define NUM_ITEMS 6 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); #if QT_VERSION < 0x050000 if(qVariantCanConvert<QColor>(value)) { foreground = qvariant_cast<QColor>(value); } #else if(value.canConvert<QBrush>()) { QBrush brush = qvariant_cast<QBrush>(value); foreground = brush.color(); } #endif painter->setPen(foreground); painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; }; #include "overviewpage.moc" OverviewPage::OverviewPage(QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), currentBalance(-1), currentStake(0), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), txdelegate(new TxViewDelegate()), filter(0) { ui->setupUi(this); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); ui->labelUpdateStatus->setText("(" + tr("checking for updates") + ")"); ui->labelUpdateStatus->setTextFormat(Qt::RichText); ui->labelUpdateStatus->setTextInteractionFlags(Qt::TextBrowserInteraction); ui->labelUpdateStatus->setOpenExternalLinks(true); // Setup a timer to regularly check for updates to the wallet // Have it trigger once, immediately, then set it to check once ever 24 hours // The update timer conversion factor (_UPDATE_MS_TO_HOURS) is located in // updatecheck.h timerUpdate(); updateTimer = new QTimer(this); connect(updateTimer, SIGNAL(timeout()), this, SLOT(timerUpdate())); updateTimer->start(_UPDATE_INTERVAL*_UPDATE_MS_TO_HOURS); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // show the "checking for updates" warning showUpdateWarning(true); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) emit transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { int unit = model->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentStake = stake; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); ui->labelStake->setText(BitcoinUnits::formatWithUnit(unit, stake)); ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, (balance + stake + unconfirmedBalance))); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); } void OverviewPage::setNumTransactions(int count) { ui->labelNumTransactions->setText(QLocale::system().toString(count)); } void OverviewPage::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->sort(TransactionTableModel::Date, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); setNumTransactions(model->getNumTransactions()); connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } // update the display unit, to not use the default ("XMG") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(model && model->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = model->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } void OverviewPage::showUpdateWarning(bool fShow) { ui->labelUpdateStatus->setVisible(fShow); } void OverviewPage::showUpdateLayout(bool fShow) { ui->labelUpdateStatic->setVisible(fShow); ui->labelUpdateStatus->setVisible(fShow); } void OverviewPage::timerUpdate() { // Create a connection to the website to check for updates QUrl updateUrl(_UPDATE_VERSION_URL); m_pUpdCtrl = new UpdateCheck(updateUrl, this); connect(m_pUpdCtrl, SIGNAL (downloaded()), this, SLOT (checkForUpdates())); } void OverviewPage::checkForUpdates() { // Grab the internal wallet version and the online version string QString siteVersion(m_pUpdCtrl->downloadedData()); QString internalVersion; internalVersion = QString::number(DISPLAY_VERSION_MAJOR); internalVersion = internalVersion + "." + QString::number(DISPLAY_VERSION_MINOR); internalVersion = internalVersion + "." + QString::number(DISPLAY_VERSION_REVISION); internalVersion = internalVersion + "." + QString::number(DISPLAY_VERSION_BUILD); QString report = QString("The wallet is up to date"); // Split the online version string and compare it against the internal version // If at any point we find that the internal version is less than the online // version, exit without setting bool isUpToDate. If the internal version is // equal to or greater than the online version, set isUpToDate = true. bool isUpToDate = true; unsigned int nVersion = m_pUpdCtrl->parseClientVersion(siteVersion.toStdString(), '.'); if (nVersion > CLIENT_VERSION * 10) isUpToDate = false; // If versions are the same, remove the update section, otherwise make sure // it is visible and show a link to the wallet download site if (isUpToDate) { showUpdateLayout(false); } else { report = QString(_UPDATE_DOWNLOAD_URL); report = QString("<a href=\"" + report + "\">Wallet version " + siteVersion + " available!</a>"); showUpdateLayout(true); } // Set the update label text and exit ui->labelUpdateStatus->setText(report); } <commit_msg>Changed client update info<commit_after>#include "overviewpage.h" #include "ui_overviewpage.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "optionsmodel.h" #include "transactiontablemodel.h" #include "transactionfilterproxy.h" #include "guiutil.h" #include "guiconstants.h" #include "askpassphrasedialog.h" #include "updatecheck.h" #include "../version.h" #include <vector> #include <QAbstractItemDelegate> #include <QPainter> #include <QDesktopServices> //Added for openURL() #include <QTimer> //Added for update timer #include <QUrl> #define DECORATION_SIZE 64 #define NUM_ITEMS 6 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); #if QT_VERSION < 0x050000 if(qVariantCanConvert<QColor>(value)) { foreground = qvariant_cast<QColor>(value); } #else if(value.canConvert<QBrush>()) { QBrush brush = qvariant_cast<QBrush>(value); foreground = brush.color(); } #endif painter->setPen(foreground); painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; }; #include "overviewpage.moc" OverviewPage::OverviewPage(QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), currentBalance(-1), currentStake(0), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), txdelegate(new TxViewDelegate()), filter(0) { ui->setupUi(this); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); ui->labelUpdateStatus->setText("(" + tr("checking for updates") + ")"); ui->labelUpdateStatus->setTextFormat(Qt::RichText); ui->labelUpdateStatus->setTextInteractionFlags(Qt::TextBrowserInteraction); ui->labelUpdateStatus->setOpenExternalLinks(true); // Setup a timer to regularly check for updates to the wallet // Have it trigger once, immediately, then set it to check once ever 24 hours // The update timer conversion factor (_UPDATE_MS_TO_HOURS) is located in // updatecheck.h timerUpdate(); updateTimer = new QTimer(this); connect(updateTimer, SIGNAL(timeout()), this, SLOT(timerUpdate())); updateTimer->start(_UPDATE_INTERVAL*_UPDATE_MS_TO_HOURS); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // show the "checking for updates" warning showUpdateWarning(true); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) emit transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { int unit = model->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentStake = stake; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); ui->labelStake->setText(BitcoinUnits::formatWithUnit(unit, stake)); ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, (balance + stake + unconfirmedBalance))); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); } void OverviewPage::setNumTransactions(int count) { ui->labelNumTransactions->setText(QLocale::system().toString(count)); } void OverviewPage::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->sort(TransactionTableModel::Date, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); setNumTransactions(model->getNumTransactions()); connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } // update the display unit, to not use the default ("XMG") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(model && model->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = model->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } void OverviewPage::showUpdateWarning(bool fShow) { ui->labelUpdateStatus->setVisible(fShow); } void OverviewPage::showUpdateLayout(bool fShow) { ui->labelUpdateStatic->setVisible(fShow); ui->labelUpdateStatus->setVisible(fShow); } void OverviewPage::timerUpdate() { // Create a connection to the website to check for updates QUrl updateUrl(_UPDATE_VERSION_URL); m_pUpdCtrl = new UpdateCheck(updateUrl, this); connect(m_pUpdCtrl, SIGNAL (downloaded()), this, SLOT (checkForUpdates())); } void OverviewPage::checkForUpdates() { // Grab the internal wallet version and the online version string QString siteVersion(m_pUpdCtrl->downloadedData()); QString internalVersion; internalVersion = QString::number(DISPLAY_VERSION_MAJOR); internalVersion = internalVersion + "." + QString::number(DISPLAY_VERSION_MINOR); internalVersion = internalVersion + "." + QString::number(DISPLAY_VERSION_REVISION); internalVersion = internalVersion + "." + QString::number(DISPLAY_VERSION_BUILD); QString report = QString("The wallet is up to date"); // Split the online version string and compare it against the internal version // If at any point we find that the internal version is less than the online // version, exit without setting bool isUpToDate. If the internal version is // equal to or greater than the online version, set isUpToDate = true. bool isUpToDate = true; unsigned int nVersion = m_pUpdCtrl->parseClientVersion(siteVersion.toStdString(), '.'); if (nVersion > CLIENT_VERSION * 10) isUpToDate = false; // If versions are the same, remove the update section, otherwise make sure // it is visible and show a link to the wallet download site if (isUpToDate) { showUpdateLayout(false); } else { report = QString(_UPDATE_DOWNLOAD_URL); report = QString("<a href=\"" + report + "\">v" + siteVersion + " available</a>"); showUpdateLayout(true); } // Set the update label text and exit ui->labelUpdateStatus->setText(report); } <|endoftext|>
<commit_before>/* * RWLock * Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net> * Copyright (C) 2011 by NeoSmart Technologies * This code is released under the terms of the MIT License */ #include "stdafx.h" #include "RWLock.h" #define MAX_SPIN 50000 #include <tchar.h> #include <assert.h> #include <stdlib.h> __forceinline __int16 ReaderCount(unsigned __int32 lock) { return lock & 0x00007FFF; } __forceinline __int32 SetReaders(unsigned __int32 lock, unsigned __int16 readers) { return (lock & ~0x00007FFF) | readers; } __forceinline __int16 WaitingCount(unsigned __int32 lock) { return (lock & 0x3FFF8000) >> 15; } __forceinline __int32 SetWaiting(unsigned __int32 lock, unsigned __int16 waiting) { return (lock & ~0x3FFF8000) | (waiting << 15); } __forceinline bool Writer(unsigned __int32 lock) { return (lock & 0x40000000) != 0; } __forceinline __int32 SetWriter(unsigned __int32 lock, bool writer) { if(writer) return lock | 0x40000000; else return lock & ~0x40000000; } __forceinline bool AllClear(unsigned __int32 lock) { return (lock & 0x40007FFF) == 0; } __forceinline bool Initialized(unsigned __int32 lock) { return (lock & 0x80000000) != 0; } __forceinline __int32 SetInitialized(unsigned __int32 lock, bool initialized) { if(initialized) return lock | 0x80000000; else return lock & ~0x80000000; } RWLockIPC::RWLockIPC(unsigned __int32 *lock, LPCTSTR guid) { SECURITY_ATTRIBUTES sa; SECURITY_DESCRIPTOR sd; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = &sd; InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE); _lock = lock; _event = CreateEvent(&sa, FALSE, FALSE, guid); if(!Initialized(*_lock)) { HANDLE hMutex = CreateMutex(&sa, FALSE, guid); WaitForSingleObject(hMutex, INFINITE); if(!Initialized(*_lock)) { *_lock = 0; *_lock = SetInitialized(*_lock, true); } ReleaseMutex(hMutex); CloseHandle(hMutex); } } RWLockIPC::~RWLockIPC() { CloseHandle(_event); } void RWLockIPC::StartRead() { for(int i = 0; ; ++i) { __int32 temp = *_lock; if(!Writer(temp)) { if(InterlockedCompareExchange((LONG*)_lock, SetReaders(temp, ReaderCount(temp) + 1), temp) == temp) return; else continue; } else { if(i < MAX_SPIN) continue; //The pending write operation is taking too long, so we'll drop to the kernel and wait if(InterlockedCompareExchange((LONG*)_lock, SetWaiting(temp, WaitingCount(temp) + 1), temp) != temp) continue; i = 0; //reset the spincount for the next time WaitForSingleObject(_event, INFINITE); do { temp = *_lock; } while(InterlockedCompareExchange((LONG*)_lock, SetWaiting(temp, WaitingCount(temp) - 1), temp) != temp); } } } void RWLockIPC::StartWrite() { for(int i = 0; ; ++i) { __int32 temp = *_lock; if(AllClear(temp)) { if(InterlockedCompareExchange((LONG*)_lock, SetWriter(temp, true), temp) == temp) return; else continue; } else { if(i < MAX_SPIN) continue; //The pending read operations are taking too long, so we'll drop to the kernel and wait if(InterlockedCompareExchange((LONG*)_lock, SetWaiting(temp, WaitingCount(temp) + 1), temp) != temp) continue; i = 0; //reset the spincount for the next time WaitForSingleObject(_event, INFINITE); do { temp = *_lock; } while(InterlockedCompareExchange((LONG*)_lock, SetWaiting(temp, WaitingCount(temp) - 1), temp) != temp); } } } void RWLockIPC::EndRead() { while(true) { __int32 temp = *_lock; assert(ReaderCount(temp) > 0); if(ReaderCount(temp) == 1 && WaitingCount(temp) != 0) { //Note: this isn't nor has to be thread-safe //We're the last reader and there's a pending write //Wake one waiting writer SetEvent(_event); } //Decrement reader count if(InterlockedCompareExchange((LONG*)_lock, SetReaders(temp, ReaderCount(temp) - 1), temp) == temp) break; } } void RWLockIPC::EndWrite() { while(true) { __int32 temp; while(true) { temp = *_lock; assert(Writer(temp)); __int16 waitingCount = WaitingCount(temp); if(waitingCount == 0) break; //Note: This is thread-safe (there's guaranteed not to be another EndWrite simultaneously) //Wake all waiting readers or writers SetEvent(_event); } //Decrement writer count if(InterlockedCompareExchange((LONG*)_lock, SetWriter(temp, false), temp) == temp) break; } } RWLock::RWLock() : _rwLock(&(*(_lock = (new unsigned int)) = RWLOCK_INIT), NULL) { } RWLock::~RWLock() { delete _lock; } void RWLock::StartRead() { _rwLock.StartRead(); } void RWLock::StartWrite() { _rwLock.StartWrite(); } void RWLock::EndRead() { _rwLock.EndRead(); } void RWLock::EndWrite() { _rwLock.EndWrite(); } struct THREAD_ENTRY { SLIST_ENTRY ItemEntry; unsigned int* ThreadPointer; }; RWLockIPCReentrant::RWLockIPCReentrant(unsigned __int32 *lock, LPCTSTR guid) : _rwLock(lock, guid) { _tlsIndex = TlsAlloc(); _threadPointers = (PSLIST_HEADER)_aligned_malloc(sizeof(SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT); InitializeSListHead(_threadPointers); } RWLockIPCReentrant::~RWLockIPCReentrant() { THREAD_ENTRY *entry; while((entry = (THREAD_ENTRY*) InterlockedPopEntrySList(_threadPointers)) != NULL) { _aligned_free(entry); } _aligned_free(_threadPointers); TlsFree(_tlsIndex); } void RWLockIPCReentrant::StartRead() { unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex); if(threadCounter == NULL) { threadCounter = new unsigned int; *threadCounter = 0; TlsSetValue(_tlsIndex, threadCounter); THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT); InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry)); } if(InterlockedIncrement((LONG*)threadCounter) == 1) _rwLock.StartRead(); } void RWLockIPCReentrant::StartWrite() { unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex); if(threadCounter == NULL) { threadCounter = new unsigned int; *threadCounter = 0; TlsSetValue(_tlsIndex, threadCounter); THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT); InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry)); } if(InterlockedIncrement((LONG*)threadCounter) == 1) _rwLock.StartWrite(); } void RWLockIPCReentrant::EndRead() { unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex); if(threadCounter == NULL) { threadCounter = new unsigned int; *threadCounter = 0; TlsSetValue(_tlsIndex, threadCounter); THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT); InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry)); } assert(*threadCounter > 0); if(InterlockedDecrement((LONG*)threadCounter) == 0) _rwLock.EndRead(); } void RWLockIPCReentrant::EndWrite() { unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex); if(threadCounter == NULL) { threadCounter = new unsigned int; *threadCounter = 0; TlsSetValue(_tlsIndex, threadCounter); THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT); InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry)); } assert(*threadCounter > 0); if(InterlockedDecrement((LONG*)threadCounter) == 0) _rwLock.EndWrite(); } RWLockReentrant::RWLockReentrant() : _rwLock(&(*(_lock = (new unsigned int)) = RWLOCK_INIT), NULL) { } RWLockReentrant::~RWLockReentrant() { delete _lock; } void RWLockReentrant::StartRead() { _rwLock.StartRead(); } void RWLockReentrant::StartWrite() { _rwLock.StartWrite(); } void RWLockReentrant::EndRead() { _rwLock.EndRead(); } void RWLockReentrant::EndWrite() { _rwLock.EndWrite(); } <commit_msg>* Added rep nop to spin sequence<commit_after>/* * RWLock * Author: Mahmoud Al-Qudsi <mqudsi@neosmart.net> * Copyright (C) 2011 by NeoSmart Technologies * This code is released under the terms of the MIT License */ #include "stdafx.h" #include "RWLock.h" #define MAX_SPIN 50000 #include <tchar.h> #include <assert.h> #include <stdlib.h> __forceinline __int16 ReaderCount(unsigned __int32 lock) { return lock & 0x00007FFF; } __forceinline __int32 SetReaders(unsigned __int32 lock, unsigned __int16 readers) { return (lock & ~0x00007FFF) | readers; } __forceinline __int16 WaitingCount(unsigned __int32 lock) { return (lock & 0x3FFF8000) >> 15; } __forceinline __int32 SetWaiting(unsigned __int32 lock, unsigned __int16 waiting) { return (lock & ~0x3FFF8000) | (waiting << 15); } __forceinline bool Writer(unsigned __int32 lock) { return (lock & 0x40000000) != 0; } __forceinline __int32 SetWriter(unsigned __int32 lock, bool writer) { if(writer) return lock | 0x40000000; else return lock & ~0x40000000; } __forceinline bool AllClear(unsigned __int32 lock) { return (lock & 0x40007FFF) == 0; } __forceinline bool Initialized(unsigned __int32 lock) { return (lock & 0x80000000) != 0; } __forceinline __int32 SetInitialized(unsigned __int32 lock, bool initialized) { if(initialized) return lock | 0x80000000; else return lock & ~0x80000000; } RWLockIPC::RWLockIPC(unsigned __int32 *lock, LPCTSTR guid) { SECURITY_ATTRIBUTES sa; SECURITY_DESCRIPTOR sd; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = &sd; InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE); _lock = lock; _event = CreateEvent(&sa, FALSE, FALSE, guid); if(!Initialized(*_lock)) { HANDLE hMutex = CreateMutex(&sa, FALSE, guid); WaitForSingleObject(hMutex, INFINITE); if(!Initialized(*_lock)) { *_lock = 0; *_lock = SetInitialized(*_lock, true); } ReleaseMutex(hMutex); CloseHandle(hMutex); } } RWLockIPC::~RWLockIPC() { CloseHandle(_event); } void RWLockIPC::StartRead() { for(int i = 0; ; ++i) { __int32 temp = *_lock; if(!Writer(temp)) { if(InterlockedCompareExchange((LONG*)_lock, SetReaders(temp, ReaderCount(temp) + 1), temp) == temp) return; else continue; } else { if(i < MAX_SPIN) { YieldProcessor(); continue; } //The pending write operation is taking too long, so we'll drop to the kernel and wait if(InterlockedCompareExchange((LONG*)_lock, SetWaiting(temp, WaitingCount(temp) + 1), temp) != temp) continue; i = 0; //reset the spincount for the next time WaitForSingleObject(_event, INFINITE); do { temp = *_lock; } while(InterlockedCompareExchange((LONG*)_lock, SetWaiting(temp, WaitingCount(temp) - 1), temp) != temp); } } } void RWLockIPC::StartWrite() { for(int i = 0; ; ++i) { __int32 temp = *_lock; if(AllClear(temp)) { if(InterlockedCompareExchange((LONG*)_lock, SetWriter(temp, true), temp) == temp) return; else continue; } else { if(i < MAX_SPIN) { YieldProcessor(); continue; } //The pending read operations are taking too long, so we'll drop to the kernel and wait if(InterlockedCompareExchange((LONG*)_lock, SetWaiting(temp, WaitingCount(temp) + 1), temp) != temp) continue; i = 0; //reset the spincount for the next time WaitForSingleObject(_event, INFINITE); do { temp = *_lock; } while(InterlockedCompareExchange((LONG*)_lock, SetWaiting(temp, WaitingCount(temp) - 1), temp) != temp); } } } void RWLockIPC::EndRead() { while(true) { __int32 temp = *_lock; assert(ReaderCount(temp) > 0); if(ReaderCount(temp) == 1 && WaitingCount(temp) != 0) { //Note: this isn't nor has to be thread-safe //We're the last reader and there's a pending write //Wake one waiting writer SetEvent(_event); } //Decrement reader count if(InterlockedCompareExchange((LONG*)_lock, SetReaders(temp, ReaderCount(temp) - 1), temp) == temp) break; } } void RWLockIPC::EndWrite() { while(true) { __int32 temp; while(true) { temp = *_lock; assert(Writer(temp)); __int16 waitingCount = WaitingCount(temp); if(waitingCount == 0) break; //Note: This is thread-safe (there's guaranteed not to be another EndWrite simultaneously) //Wake all waiting readers or writers SetEvent(_event); } //Decrement writer count if(InterlockedCompareExchange((LONG*)_lock, SetWriter(temp, false), temp) == temp) break; } } RWLock::RWLock() : _rwLock(&(*(_lock = (new unsigned int)) = RWLOCK_INIT), NULL) { } RWLock::~RWLock() { delete _lock; } void RWLock::StartRead() { _rwLock.StartRead(); } void RWLock::StartWrite() { _rwLock.StartWrite(); } void RWLock::EndRead() { _rwLock.EndRead(); } void RWLock::EndWrite() { _rwLock.EndWrite(); } struct THREAD_ENTRY { SLIST_ENTRY ItemEntry; unsigned int* ThreadPointer; }; RWLockIPCReentrant::RWLockIPCReentrant(unsigned __int32 *lock, LPCTSTR guid) : _rwLock(lock, guid) { _tlsIndex = TlsAlloc(); _threadPointers = (PSLIST_HEADER)_aligned_malloc(sizeof(SLIST_HEADER), MEMORY_ALLOCATION_ALIGNMENT); InitializeSListHead(_threadPointers); } RWLockIPCReentrant::~RWLockIPCReentrant() { THREAD_ENTRY *entry; while((entry = (THREAD_ENTRY*) InterlockedPopEntrySList(_threadPointers)) != NULL) { _aligned_free(entry); } _aligned_free(_threadPointers); TlsFree(_tlsIndex); } void RWLockIPCReentrant::StartRead() { unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex); if(threadCounter == NULL) { threadCounter = new unsigned int; *threadCounter = 0; TlsSetValue(_tlsIndex, threadCounter); THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT); InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry)); } if(InterlockedIncrement((LONG*)threadCounter) == 1) _rwLock.StartRead(); } void RWLockIPCReentrant::StartWrite() { unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex); if(threadCounter == NULL) { threadCounter = new unsigned int; *threadCounter = 0; TlsSetValue(_tlsIndex, threadCounter); THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT); InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry)); } if(InterlockedIncrement((LONG*)threadCounter) == 1) _rwLock.StartWrite(); } void RWLockIPCReentrant::EndRead() { unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex); if(threadCounter == NULL) { threadCounter = new unsigned int; *threadCounter = 0; TlsSetValue(_tlsIndex, threadCounter); THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT); InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry)); } assert(*threadCounter > 0); if(InterlockedDecrement((LONG*)threadCounter) == 0) _rwLock.EndRead(); } void RWLockIPCReentrant::EndWrite() { unsigned int *threadCounter = (unsigned int*)TlsGetValue(_tlsIndex); if(threadCounter == NULL) { threadCounter = new unsigned int; *threadCounter = 0; TlsSetValue(_tlsIndex, threadCounter); THREAD_ENTRY *entry = (THREAD_ENTRY*)_aligned_malloc(sizeof(THREAD_ENTRY), MEMORY_ALLOCATION_ALIGNMENT); InterlockedPushEntrySList(_threadPointers, &(entry->ItemEntry)); } assert(*threadCounter > 0); if(InterlockedDecrement((LONG*)threadCounter) == 0) _rwLock.EndWrite(); } RWLockReentrant::RWLockReentrant() : _rwLock(&(*(_lock = (new unsigned int)) = RWLOCK_INIT), NULL) { } RWLockReentrant::~RWLockReentrant() { delete _lock; } void RWLockReentrant::StartRead() { _rwLock.StartRead(); } void RWLockReentrant::StartWrite() { _rwLock.StartWrite(); } void RWLockReentrant::EndRead() { _rwLock.EndRead(); } void RWLockReentrant::EndWrite() { _rwLock.EndWrite(); } <|endoftext|>
<commit_before>#include "remote_executor_impl.h" using namespace Wuild; RemoteExecutor::RemoteExecutor(ConfiguredApplication &app) : m_app(app) { bool silent = !Syslogger::IsLogLevelEnabled(LOG_DEBUG); IInvocationRewriter::Config compilerConfig; if (!m_app.GetInvocationRewriterConfig(compilerConfig, silent)) return; RemoteToolClient::Config remoteToolConfig; if (!m_app.GetRemoteToolClientConfig(remoteToolConfig, silent)) return; m_minimalRemoteTasks = remoteToolConfig.m_minimalRemoteTasks; m_invocationRewruiter = InvocationRewriter::Create(compilerConfig); m_remoteService.reset(new RemoteToolClient(m_invocationRewruiter)); if (!m_remoteService->SetConfig(remoteToolConfig)) return; #ifdef TEST_CLIENT m_localExecutor = LocalExecutor::Create(m_invocationRewruiter, m_app.m_tempDir); m_app.m_remoteToolServerConfig.m_threadCount = 2; m_app.m_remoteToolServerConfig.m_listenHost = "localhost"; m_app.m_remoteToolServerConfig.m_listenPort = 12345; m_app.m_remoteToolServerConfig.m_coordinator.m_enabled = false; m_toolServer.reset(new RemoteToolServer(m_localExecutor)); if (!m_toolServer->SetConfig(m_app.m_remoteToolServerConfig)) return; ToolServerInfo toolServerInfo; toolServerInfo.m_connectionHost = "localhost"; toolServerInfo.m_connectionPort = 12345; toolServerInfo.m_toolIds = m_compiler->GetConfig().m_toolIds; toolServerInfo.m_totalThreads = 2; m_remoteService->AddClient(toolServerInfo); remoteToolConfig.m_coordinator.m_enabled = false; m_remoteService->SetConfig(remoteToolConfig); #endif m_remoteEnabled = true; } void RemoteExecutor::SetVerbose(bool verbose) { if (!verbose || Syslogger::IsLogLevelEnabled(LOG_INFO)) return; m_app.m_loggerConfig.m_maxLogLevel = LOG_INFO; m_app.InitLogging(m_app.m_loggerConfig); } bool RemoteExecutor::PreprocessCode(const std::vector<std::string> &originalRule, const std::vector<std::string> &ignoredArgs, std::string &toolId, std::vector<std::string> &preprocessRule, std::vector<std::string> &compileRule) const { if (!m_remoteEnabled || originalRule.size() < 3) return false; std::vector<std::string> args = originalRule; std::string srcExecutable = StringUtils::Trim(args[0]); args.erase(args.begin()); auto space = srcExecutable.find(' '); if (space != std::string::npos) { args.insert(args.begin(), srcExecutable.substr(space + 1)); srcExecutable = srcExecutable.substr(0, space); } ToolInvocation original, pp, cc; original.m_id.m_toolExecutable = srcExecutable; original.m_args = args; original.m_ignoredArgs = ignoredArgs; if (!m_invocationRewruiter->SplitInvocation(original, pp, cc)) return false; toolId = pp.m_id.m_toolId; preprocessRule.push_back(srcExecutable + " "); preprocessRule.insert(preprocessRule.end(), pp.m_args.begin(), pp.m_args.end()); compileRule.push_back(srcExecutable + " "); compileRule.insert(compileRule.end(), cc.m_args.begin(), cc.m_args.end()); return true; } std::string RemoteExecutor::GetPreprocessedPath(const std::string &sourcePath, const std::string &objectPath) const { if (!m_remoteEnabled) return ""; return m_invocationRewruiter->GetPreprocessedPath(sourcePath, objectPath); } std::string RemoteExecutor::FilterPreprocessorFlags(const std::string &toolId, const std::string &flags) const { if (!m_remoteEnabled) return flags; return m_invocationRewruiter->FilterFlags(ToolInvocation(flags, ToolInvocation::InvokeType::Preprocess).SetId(toolId)).GetArgsString(false); } std::string RemoteExecutor::FilterCompilerFlags(const std::string &toolId, const std::string &flags) const { if (!m_remoteEnabled) return flags; return m_invocationRewruiter->FilterFlags(ToolInvocation(flags, ToolInvocation::InvokeType::Compile).SetId(toolId)).GetArgsString(false); } void RemoteExecutor::RunIfNeeded(const std::vector<std::string> &toolIds) { if (!m_remoteEnabled || m_hasStart) return; m_hasStart = true; m_remoteService->Start(toolIds); #ifdef TEST_CLIENT m_toolServer->Start(); #endif } void RemoteExecutor::SleepSome() const { usleep(1000); } int RemoteExecutor::GetMinimalRemoteTasks() const { if (!m_remoteEnabled) return -1; return m_minimalRemoteTasks; } bool RemoteExecutor::CanRunMore() { if (!m_remoteEnabled) return false; return m_remoteService->GetFreeRemoteThreads() > 0; } bool RemoteExecutor::StartCommand(void *userData, const std::string &command) { if (!m_remoteEnabled) return false; const auto space = command.find(' '); ToolInvocation invocation(command.substr(space + 1)); invocation.SetExecutable(command.substr(0, space)); invocation = m_invocationRewruiter->CompleteInvocation(invocation); auto outputFilename = invocation.GetOutput(); auto callback = [this, userData, outputFilename]( const RemoteToolClient::TaskExecutionInfo & info) { bool result = info.m_result; Syslogger() << outputFilename<< " -> " << result << ", " << info.GetProfilingStr() ; std::lock_guard<std::mutex> lock(m_resultsMutex); m_results.emplace_back(userData, result, info.m_stdOutput); }; m_remoteService->InvokeTool(invocation, callback); return true; } bool RemoteExecutor::WaitForCommand(IRemoteExecutor::Result *result) { if (!m_remoteEnabled) return false; std::lock_guard<std::mutex> lock(m_resultsMutex); if (!m_results.empty()) { *result = std::move(m_results[0]); m_results.pop_front(); return true; } return false; } RemoteExecutor::~RemoteExecutor() { if (!m_remoteEnabled) return; m_remoteService->FinishSession(); Syslogger(LOG_NOTICE) << m_remoteService->GetSessionInformation(); } <commit_msg>Missing copyright.<commit_after>/* * Copyright (C) 2017 Smirnov Vladimir mapron1@gmail.com * Source code 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 or in file COPYING-APACHE-2.0.txt * * 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.h */ #include "remote_executor_impl.h" using namespace Wuild; RemoteExecutor::RemoteExecutor(ConfiguredApplication &app) : m_app(app) { bool silent = !Syslogger::IsLogLevelEnabled(LOG_DEBUG); IInvocationRewriter::Config compilerConfig; if (!m_app.GetInvocationRewriterConfig(compilerConfig, silent)) return; RemoteToolClient::Config remoteToolConfig; if (!m_app.GetRemoteToolClientConfig(remoteToolConfig, silent)) return; m_minimalRemoteTasks = remoteToolConfig.m_minimalRemoteTasks; m_invocationRewruiter = InvocationRewriter::Create(compilerConfig); m_remoteService.reset(new RemoteToolClient(m_invocationRewruiter)); if (!m_remoteService->SetConfig(remoteToolConfig)) return; #ifdef TEST_CLIENT m_localExecutor = LocalExecutor::Create(m_invocationRewruiter, m_app.m_tempDir); m_app.m_remoteToolServerConfig.m_threadCount = 2; m_app.m_remoteToolServerConfig.m_listenHost = "localhost"; m_app.m_remoteToolServerConfig.m_listenPort = 12345; m_app.m_remoteToolServerConfig.m_coordinator.m_enabled = false; m_toolServer.reset(new RemoteToolServer(m_localExecutor)); if (!m_toolServer->SetConfig(m_app.m_remoteToolServerConfig)) return; ToolServerInfo toolServerInfo; toolServerInfo.m_connectionHost = "localhost"; toolServerInfo.m_connectionPort = 12345; toolServerInfo.m_toolIds = m_compiler->GetConfig().m_toolIds; toolServerInfo.m_totalThreads = 2; m_remoteService->AddClient(toolServerInfo); remoteToolConfig.m_coordinator.m_enabled = false; m_remoteService->SetConfig(remoteToolConfig); #endif m_remoteEnabled = true; } void RemoteExecutor::SetVerbose(bool verbose) { if (!verbose || Syslogger::IsLogLevelEnabled(LOG_INFO)) return; m_app.m_loggerConfig.m_maxLogLevel = LOG_INFO; m_app.InitLogging(m_app.m_loggerConfig); } bool RemoteExecutor::PreprocessCode(const std::vector<std::string> &originalRule, const std::vector<std::string> &ignoredArgs, std::string &toolId, std::vector<std::string> &preprocessRule, std::vector<std::string> &compileRule) const { if (!m_remoteEnabled || originalRule.size() < 3) return false; std::vector<std::string> args = originalRule; std::string srcExecutable = StringUtils::Trim(args[0]); args.erase(args.begin()); auto space = srcExecutable.find(' '); if (space != std::string::npos) { args.insert(args.begin(), srcExecutable.substr(space + 1)); srcExecutable = srcExecutable.substr(0, space); } ToolInvocation original, pp, cc; original.m_id.m_toolExecutable = srcExecutable; original.m_args = args; original.m_ignoredArgs = ignoredArgs; if (!m_invocationRewruiter->SplitInvocation(original, pp, cc)) return false; toolId = pp.m_id.m_toolId; preprocessRule.push_back(srcExecutable + " "); preprocessRule.insert(preprocessRule.end(), pp.m_args.begin(), pp.m_args.end()); compileRule.push_back(srcExecutable + " "); compileRule.insert(compileRule.end(), cc.m_args.begin(), cc.m_args.end()); return true; } std::string RemoteExecutor::GetPreprocessedPath(const std::string &sourcePath, const std::string &objectPath) const { if (!m_remoteEnabled) return ""; return m_invocationRewruiter->GetPreprocessedPath(sourcePath, objectPath); } std::string RemoteExecutor::FilterPreprocessorFlags(const std::string &toolId, const std::string &flags) const { if (!m_remoteEnabled) return flags; return m_invocationRewruiter->FilterFlags(ToolInvocation(flags, ToolInvocation::InvokeType::Preprocess).SetId(toolId)).GetArgsString(false); } std::string RemoteExecutor::FilterCompilerFlags(const std::string &toolId, const std::string &flags) const { if (!m_remoteEnabled) return flags; return m_invocationRewruiter->FilterFlags(ToolInvocation(flags, ToolInvocation::InvokeType::Compile).SetId(toolId)).GetArgsString(false); } void RemoteExecutor::RunIfNeeded(const std::vector<std::string> &toolIds) { if (!m_remoteEnabled || m_hasStart) return; m_hasStart = true; m_remoteService->Start(toolIds); #ifdef TEST_CLIENT m_toolServer->Start(); #endif } void RemoteExecutor::SleepSome() const { usleep(1000); } int RemoteExecutor::GetMinimalRemoteTasks() const { if (!m_remoteEnabled) return -1; return m_minimalRemoteTasks; } bool RemoteExecutor::CanRunMore() { if (!m_remoteEnabled) return false; return m_remoteService->GetFreeRemoteThreads() > 0; } bool RemoteExecutor::StartCommand(void *userData, const std::string &command) { if (!m_remoteEnabled) return false; const auto space = command.find(' '); ToolInvocation invocation(command.substr(space + 1)); invocation.SetExecutable(command.substr(0, space)); invocation = m_invocationRewruiter->CompleteInvocation(invocation); auto outputFilename = invocation.GetOutput(); auto callback = [this, userData, outputFilename]( const RemoteToolClient::TaskExecutionInfo & info) { bool result = info.m_result; Syslogger() << outputFilename<< " -> " << result << ", " << info.GetProfilingStr() ; std::lock_guard<std::mutex> lock(m_resultsMutex); m_results.emplace_back(userData, result, info.m_stdOutput); }; m_remoteService->InvokeTool(invocation, callback); return true; } bool RemoteExecutor::WaitForCommand(IRemoteExecutor::Result *result) { if (!m_remoteEnabled) return false; std::lock_guard<std::mutex> lock(m_resultsMutex); if (!m_results.empty()) { *result = std::move(m_results[0]); m_results.pop_front(); return true; } return false; } RemoteExecutor::~RemoteExecutor() { if (!m_remoteEnabled) return; m_remoteService->FinishSession(); Syslogger(LOG_NOTICE) << m_remoteService->GetSessionInformation(); } <|endoftext|>
<commit_before>// // sync_client.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <istream> #include <ostream> #include <string> #include <regex> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <fc/variant.hpp> #include <fc/io/json.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/http_plugin/http_plugin.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include "httpc.hpp" using boost::asio::ip::tcp; namespace eosio { namespace client { namespace http { namespace detail { class http_context_impl { public: boost::asio::io_service ios; }; void http_context_deleter::operator()(http_context_impl* p) const { delete p; } } http_context create_http_context() { return http_context(new detail::http_context_impl, detail::http_context_deleter()); } void do_connect(tcp::socket& sock, const resolved_url& url) { // Get a list of endpoints corresponding to the server name. vector<tcp::endpoint> endpoints; endpoints.reserve(url.resolved_addresses.size()); for (const auto& addr: url.resolved_addresses) { endpoints.emplace_back(boost::asio::ip::make_address(addr), url.resolved_port); } boost::asio::connect(sock, endpoints); } template<class T> std::string do_txrx(T& socket, boost::asio::streambuf& request_buff, unsigned int& status_code) { // Send the request. boost::asio::write(socket, request_buff); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); // Check that response is OK. std::istream response_stream(&response); std::string http_version; response_stream >> http_version; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); FC_ASSERT( !(!response_stream || http_version.substr(0, 5) != "HTTP/"), "Invalid Response" ); // Read the response headers, which are terminated by a blank line. boost::asio::read_until(socket, response, "\r\n\r\n"); // Process the response headers. std::string header; int response_content_length = -1; std::regex clregex(R"xx(^content-length:\s+(\d+))xx", std::regex_constants::icase); while (std::getline(response_stream, header) && header != "\r") { std::smatch match; if(std::regex_search(header, match, clregex)) response_content_length = std::stoi(match[1]); } FC_ASSERT(response_content_length >= 0, "Invalid content-length response"); std::stringstream re; // Write whatever content we already have to output. response_content_length -= response.size(); if (response.size() > 0) re << &response; boost::asio::read(socket, response, boost::asio::transfer_exactly(response_content_length)); re << &response; return re.str(); } parsed_url parse_url( const string& server_url ) { parsed_url res; //via rfc3986 and modified a bit to suck out the port number //Sadly this doesn't work for ipv6 addresses std::regex rgx(R"xx(^(([^:/?#]+):)?(//([^:/?#]*)(:(\d+))?)?([^?#]*)(\?([^#]*))?(#(.*))?)xx"); std::smatch match; if(std::regex_search(server_url.begin(), server_url.end(), match, rgx)) { res.scheme = match[2]; res.server = match[4]; res.port = match[6]; res.path = match[7]; } if(res.scheme != "http" && res.scheme != "https") FC_THROW("Unrecognized URL scheme (${s}) in URL \"${u}\"", ("s", res.scheme)("u", server_url)); if(res.server.empty()) FC_THROW("No server parsed from URL \"${u}\"", ("u", server_url)); if(res.port.empty()) res.port = res.scheme == "http" ? "80" : "443"; boost::trim_right_if(res.path, boost::is_any_of("/")); return res; } resolved_url resolve_url( const http_context& context, const parsed_url& url ) { tcp::resolver resolver(context->ios); boost::system::error_code ec; auto result = resolver.resolve(tcp::v4(), url.server, url.port, ec); if (ec) { FC_THROW("Error resolving \"${server}:${url}\" : ${m}", ("server", url.server)("port",url.port)("m",ec.message())); } // non error results are guaranteed to return a non-empty range vector<string> resolved_addresses; resolved_addresses.reserve(result.size()); optional<uint16_t> resolved_port; bool is_loopback = true; for(const auto& r : result) { const auto& addr = r.endpoint().address(); uint16_t port = r.endpoint().port(); resolved_addresses.emplace_back(addr.to_string()); is_loopback = is_loopback && addr.is_loopback(); if (resolved_port) { FC_ASSERT(*resolved_port == port, "Service name \"${port}\" resolved to multiple ports and this is not supported!", ("port",url.port)); } else { resolved_port = port; } } return resolved_url(url, std::move(resolved_addresses), *resolved_port, is_loopback); } fc::variant do_http_call( const connection_param& cp, const fc::variant& postdata, bool print_request, bool print_response ) { std::string postjson; if( !postdata.is_null() ) { postjson = print_request ? fc::json::to_pretty_string( postdata ) : fc::json::to_string( postdata ); } const auto& url = cp.url; boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "POST " << url.path << " HTTP/1.0\r\n"; request_stream << "Host: " << url.server << "\r\n"; request_stream << "content-length: " << postjson.size() << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Connection: close\r\n"; request_stream << "\r\n"; // append more customized headers std::vector<string>::iterator itr; for (itr = cp.headers.begin(); itr != cp.headers.end(); itr++) { request_stream << *itr << "\r\n"; } request_stream << postjson; if ( print_request ) { string s(request.size(), '\0'); buffer_copy(boost::asio::buffer(s), request.data()); std::cerr << "REQUEST:" << std::endl << "---------------------" << std::endl << s << std::endl << "---------------------" << std::endl; } unsigned int status_code; std::string re; if(url.scheme == "http") { tcp::socket socket(cp.context->ios); do_connect(socket, url); re = do_txrx(socket, request, status_code); } else { //https boost::asio::ssl::context ssl_context(boost::asio::ssl::context::sslv23_client); #if defined( __APPLE__ ) //TODO: this is undocumented/not supported; fix with keychain based approach ssl_context.load_verify_file("/private/etc/ssl/cert.pem"); #elif defined( _WIN32 ) FC_THROW("HTTPS on Windows not supported"); #else ssl_context.set_default_verify_paths(); #endif boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket(cp.context->ios, ssl_context); SSL_set_tlsext_host_name(socket.native_handle(), url.server.c_str()); if(cp.verify_cert) socket.set_verify_mode(boost::asio::ssl::verify_peer); do_connect(socket.next_layer(), url); socket.handshake(boost::asio::ssl::stream_base::client); re = do_txrx(socket, request, status_code); //try and do a clean shutdown; but swallow if this fails (other side could have already gave TCP the ax) try {socket.shutdown();} catch(...) {} } const auto response_result = fc::json::from_string(re); if( print_response ) { std::cerr << "RESPONSE:" << std::endl << "---------------------" << std::endl << fc::json::to_pretty_string( response_result ) << std::endl << "---------------------" << std::endl; } if( status_code == 200 || status_code == 201 || status_code == 202 ) { return response_result; } else if( status_code == 404 ) { // Unknown endpoint if (url.path.compare(0, chain_func_base.size(), chain_func_base) == 0) { throw chain::missing_chain_api_plugin_exception(FC_LOG_MESSAGE(error, "Chain API plugin is not enabled")); } else if (url.path.compare(0, wallet_func_base.size(), wallet_func_base) == 0) { throw chain::missing_wallet_api_plugin_exception(FC_LOG_MESSAGE(error, "Wallet is not available")); } else if (url.path.compare(0, account_history_func_base.size(), account_history_func_base) == 0) { throw chain::missing_history_api_plugin_exception(FC_LOG_MESSAGE(error, "History API plugin is not enabled")); } else if (url.path.compare(0, net_func_base.size(), net_func_base) == 0) { throw chain::missing_net_api_plugin_exception(FC_LOG_MESSAGE(error, "Net API plugin is not enabled")); } } else { auto &&error_info = response_result.as<eosio::error_results>().error; // Construct fc exception from error const auto &error_details = error_info.details; fc::log_messages logs; for (auto itr = error_details.begin(); itr != error_details.end(); itr++) { const auto& context = fc::log_context(fc::log_level::error, itr->file.data(), itr->line_number, itr->method.data()); logs.emplace_back(fc::log_message(context, itr->message)); } throw fc::exception(logs, error_info.code, error_info.name, error_info.what); } FC_ASSERT( status_code == 200, "Error code ${c}\n: ${msg}\n", ("c", status_code)("msg", re) ); return response_result; } }}} <commit_msg>unrelated change reverted #4196<commit_after>// // sync_client.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <istream> #include <ostream> #include <string> #include <regex> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <fc/variant.hpp> #include <fc/io/json.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/http_plugin/http_plugin.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include "httpc.hpp" using boost::asio::ip::tcp; namespace eosio { namespace client { namespace http { namespace detail { class http_context_impl { public: boost::asio::io_service ios; }; void http_context_deleter::operator()(http_context_impl* p) const { delete p; } } http_context create_http_context() { return http_context(new detail::http_context_impl, detail::http_context_deleter()); } void do_connect(tcp::socket& sock, const resolved_url& url) { // Get a list of endpoints corresponding to the server name. vector<tcp::endpoint> endpoints; endpoints.reserve(url.resolved_addresses.size()); for (const auto& addr: url.resolved_addresses) { endpoints.emplace_back(boost::asio::ip::make_address(addr), url.resolved_port); } boost::asio::connect(sock, endpoints); } template<class T> std::string do_txrx(T& socket, boost::asio::streambuf& request_buff, unsigned int& status_code) { // Send the request. boost::asio::write(socket, request_buff); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); // Check that response is OK. std::istream response_stream(&response); std::string http_version; response_stream >> http_version; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); FC_ASSERT( !(!response_stream || http_version.substr(0, 5) != "HTTP/"), "Invalid Response" ); // Read the response headers, which are terminated by a blank line. boost::asio::read_until(socket, response, "\r\n\r\n"); // Process the response headers. std::string header; int response_content_length = -1; std::regex clregex(R"xx(^content-length:\s+(\d+))xx", std::regex_constants::icase); while (std::getline(response_stream, header) && header != "\r") { std::smatch match; if(std::regex_search(header, match, clregex)) response_content_length = std::stoi(match[1]); } FC_ASSERT(response_content_length >= 0, "Invalid content-length response"); std::stringstream re; // Write whatever content we already have to output. response_content_length -= response.size(); if (response.size() > 0) re << &response; boost::asio::read(socket, response, boost::asio::transfer_exactly(response_content_length)); re << &response; return re.str(); } parsed_url parse_url( const string& server_url ) { parsed_url res; //via rfc3986 and modified a bit to suck out the port number //Sadly this doesn't work for ipv6 addresses std::regex rgx(R"xx(^(([^:/?#]+):)?(//([^:/?#]*)(:(\d+))?)?([^?#]*)(\?([^#]*))?(#(.*))?)xx"); std::smatch match; if(std::regex_search(server_url.begin(), server_url.end(), match, rgx)) { res.scheme = match[2]; res.server = match[4]; res.port = match[6]; res.path = match[7]; } if(res.scheme != "http" && res.scheme != "https") FC_THROW("Unrecognized URL scheme (${s}) in URL \"${u}\"", ("s", res.scheme)("u", server_url)); if(res.server.empty()) FC_THROW("No server parsed from URL \"${u}\"", ("u", server_url)); if(res.port.empty()) res.port = res.scheme == "http" ? "80" : "443"; boost::trim_right_if(res.path, boost::is_any_of("/")); return res; } resolved_url resolve_url( const http_context& context, const parsed_url& url ) { tcp::resolver resolver(context->ios); boost::system::error_code ec; auto result = resolver.resolve(url.server, url.port, ec); if (ec) { FC_THROW("Error resolving \"${server}:${url}\" : ${m}", ("server", url.server)("port",url.port)("m",ec.message())); } // non error results are guaranteed to return a non-empty range vector<string> resolved_addresses; resolved_addresses.reserve(result.size()); optional<uint16_t> resolved_port; bool is_loopback = true; for(const auto& r : result) { const auto& addr = r.endpoint().address(); uint16_t port = r.endpoint().port(); resolved_addresses.emplace_back(addr.to_string()); is_loopback = is_loopback && addr.is_loopback(); if (resolved_port) { FC_ASSERT(*resolved_port == port, "Service name \"${port}\" resolved to multiple ports and this is not supported!", ("port",url.port)); } else { resolved_port = port; } } return resolved_url(url, std::move(resolved_addresses), *resolved_port, is_loopback); } fc::variant do_http_call( const connection_param& cp, const fc::variant& postdata, bool print_request, bool print_response ) { std::string postjson; if( !postdata.is_null() ) { postjson = print_request ? fc::json::to_pretty_string( postdata ) : fc::json::to_string( postdata ); } const auto& url = cp.url; boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "POST " << url.path << " HTTP/1.0\r\n"; request_stream << "Host: " << url.server << "\r\n"; request_stream << "content-length: " << postjson.size() << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Connection: close\r\n"; request_stream << "\r\n"; // append more customized headers std::vector<string>::iterator itr; for (itr = cp.headers.begin(); itr != cp.headers.end(); itr++) { request_stream << *itr << "\r\n"; } request_stream << postjson; if ( print_request ) { string s(request.size(), '\0'); buffer_copy(boost::asio::buffer(s), request.data()); std::cerr << "REQUEST:" << std::endl << "---------------------" << std::endl << s << std::endl << "---------------------" << std::endl; } unsigned int status_code; std::string re; if(url.scheme == "http") { tcp::socket socket(cp.context->ios); do_connect(socket, url); re = do_txrx(socket, request, status_code); } else { //https boost::asio::ssl::context ssl_context(boost::asio::ssl::context::sslv23_client); #if defined( __APPLE__ ) //TODO: this is undocumented/not supported; fix with keychain based approach ssl_context.load_verify_file("/private/etc/ssl/cert.pem"); #elif defined( _WIN32 ) FC_THROW("HTTPS on Windows not supported"); #else ssl_context.set_default_verify_paths(); #endif boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket(cp.context->ios, ssl_context); SSL_set_tlsext_host_name(socket.native_handle(), url.server.c_str()); if(cp.verify_cert) socket.set_verify_mode(boost::asio::ssl::verify_peer); do_connect(socket.next_layer(), url); socket.handshake(boost::asio::ssl::stream_base::client); re = do_txrx(socket, request, status_code); //try and do a clean shutdown; but swallow if this fails (other side could have already gave TCP the ax) try {socket.shutdown();} catch(...) {} } const auto response_result = fc::json::from_string(re); if( print_response ) { std::cerr << "RESPONSE:" << std::endl << "---------------------" << std::endl << fc::json::to_pretty_string( response_result ) << std::endl << "---------------------" << std::endl; } if( status_code == 200 || status_code == 201 || status_code == 202 ) { return response_result; } else if( status_code == 404 ) { // Unknown endpoint if (url.path.compare(0, chain_func_base.size(), chain_func_base) == 0) { throw chain::missing_chain_api_plugin_exception(FC_LOG_MESSAGE(error, "Chain API plugin is not enabled")); } else if (url.path.compare(0, wallet_func_base.size(), wallet_func_base) == 0) { throw chain::missing_wallet_api_plugin_exception(FC_LOG_MESSAGE(error, "Wallet is not available")); } else if (url.path.compare(0, account_history_func_base.size(), account_history_func_base) == 0) { throw chain::missing_history_api_plugin_exception(FC_LOG_MESSAGE(error, "History API plugin is not enabled")); } else if (url.path.compare(0, net_func_base.size(), net_func_base) == 0) { throw chain::missing_net_api_plugin_exception(FC_LOG_MESSAGE(error, "Net API plugin is not enabled")); } } else { auto &&error_info = response_result.as<eosio::error_results>().error; // Construct fc exception from error const auto &error_details = error_info.details; fc::log_messages logs; for (auto itr = error_details.begin(); itr != error_details.end(); itr++) { const auto& context = fc::log_context(fc::log_level::error, itr->file.data(), itr->line_number, itr->method.data()); logs.emplace_back(fc::log_message(context, itr->message)); } throw fc::exception(logs, error_info.code, error_info.name, error_info.what); } FC_ASSERT( status_code == 200, "Error code ${c}\n: ${msg}\n", ("c", status_code)("msg", re) ); return response_result; } }}} <|endoftext|>
<commit_before>/* * JailCGI integration. * * author: Max Kellermann <mk@cm4all.com> */ #include "JailParams.hxx" #include "exec.hxx" #include "pool.hxx" #include "util/CharUtil.hxx" #include <glib.h> #include <string.h> gcc_const static GQuark jail_quark(void) { return g_quark_from_static_string("jail"); } void JailParams::Init() { memset(this, 0, sizeof(*this)); } bool JailParams::Check(GError **error_r) const { if (!enabled) return true; if (home_directory == nullptr) { g_set_error(error_r, jail_quark(), 0, "No JailCGI home directory"); return false; } return true; } JailParams::JailParams(struct pool *pool, const JailParams &src) :enabled(src.enabled), account_id(p_strdup_checked(pool, src.account_id)), site_id(p_strdup_checked(pool, src.site_id)), user_name(p_strdup_checked(pool, src.user_name)), host_name(p_strdup_checked(pool, src.host_name)), home_directory(p_strdup_checked(pool, src.home_directory)) { } void JailParams::CopyFrom(struct pool &pool, const JailParams &src) { enabled = src.enabled; account_id = p_strdup_checked(&pool, src.account_id); site_id = p_strdup_checked(&pool, src.site_id); user_name = p_strdup_checked(&pool, src.user_name); host_name = p_strdup_checked(&pool, src.host_name); home_directory = p_strdup_checked(&pool, src.home_directory); } char * JailParams::MakeId(char *p) const { if (enabled) { p = (char *)mempcpy(p, ";j=", 3); p = stpcpy(p, home_directory); } return p; } void JailParams::InsertWrapper(Exec &e, const char *document_root) const { if (!enabled) return; e.Append("/usr/lib/cm4all/jailcgi/bin/wrapper"); if (document_root != nullptr) { e.Append("-d"); e.Append(document_root); } if (account_id != nullptr) { e.Append("--account"); e.Append(account_id); } if (site_id != nullptr) { e.Append("--site"); e.Append(site_id); } if (user_name != nullptr) { e.Append("--name"); e.Append(user_name); } if (host_name != nullptr) e.SetEnv("JAILCGI_SERVERNAME", host_name); if (home_directory != nullptr) { e.Append("--home"); e.Append(home_directory); } e.Append("--"); } <commit_msg>JailParams: implement Init() without memset()<commit_after>/* * JailCGI integration. * * author: Max Kellermann <mk@cm4all.com> */ #include "JailParams.hxx" #include "exec.hxx" #include "pool.hxx" #include "util/CharUtil.hxx" #include <glib.h> #include <string.h> gcc_const static GQuark jail_quark(void) { return g_quark_from_static_string("jail"); } void JailParams::Init() { enabled = false; account_id = nullptr; site_id = nullptr; user_name = nullptr; host_name = nullptr; home_directory = nullptr; host_name = nullptr; } bool JailParams::Check(GError **error_r) const { if (!enabled) return true; if (home_directory == nullptr) { g_set_error(error_r, jail_quark(), 0, "No JailCGI home directory"); return false; } return true; } JailParams::JailParams(struct pool *pool, const JailParams &src) :enabled(src.enabled), account_id(p_strdup_checked(pool, src.account_id)), site_id(p_strdup_checked(pool, src.site_id)), user_name(p_strdup_checked(pool, src.user_name)), host_name(p_strdup_checked(pool, src.host_name)), home_directory(p_strdup_checked(pool, src.home_directory)) { } void JailParams::CopyFrom(struct pool &pool, const JailParams &src) { enabled = src.enabled; account_id = p_strdup_checked(&pool, src.account_id); site_id = p_strdup_checked(&pool, src.site_id); user_name = p_strdup_checked(&pool, src.user_name); host_name = p_strdup_checked(&pool, src.host_name); home_directory = p_strdup_checked(&pool, src.home_directory); } char * JailParams::MakeId(char *p) const { if (enabled) { p = (char *)mempcpy(p, ";j=", 3); p = stpcpy(p, home_directory); } return p; } void JailParams::InsertWrapper(Exec &e, const char *document_root) const { if (!enabled) return; e.Append("/usr/lib/cm4all/jailcgi/bin/wrapper"); if (document_root != nullptr) { e.Append("-d"); e.Append(document_root); } if (account_id != nullptr) { e.Append("--account"); e.Append(account_id); } if (site_id != nullptr) { e.Append("--site"); e.Append(site_id); } if (user_name != nullptr) { e.Append("--name"); e.Append(user_name); } if (host_name != nullptr) e.SetEnv("JAILCGI_SERVERNAME", host_name); if (home_directory != nullptr) { e.Append("--home"); e.Append(home_directory); } e.Append("--"); } <|endoftext|>
<commit_before>#include <NfcAdapter.h> NfcAdapter::NfcAdapter(void) { shield = new Adafruit_NFCShield_I2C(IRQ, RESET); } NfcAdapter::~NfcAdapter(void) { delete shield; } void NfcAdapter::begin() { shield->begin(); uint32_t versiondata = shield->getFirmwareVersion(); if (! versiondata) { Serial.print(F("Didn't find PN53x board")); while (1); // halt } // Got ok data, print it out! Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX); Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC); Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); // configure board to read RFID tags shield->SAMConfig(); } boolean NfcAdapter::tagPresent() { uint8_t success; uidLength = 0; success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); // if (success) // { // Serial.println("Found an ISO14443A card"); // Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes"); // Serial.print(" UID Value: "); // shield->PrintHex(uid, uidLength); // Serial.println(""); // } return success; } NfcTag NfcAdapter::read() { uint8_t type = guessTagType(); // TODO need and abstraction of Driver if (type == TAG_TYPE_MIFARE_CLASSIC) { Serial.println(F("Mifare Classic")); MifareClassic mifareClassic = MifareClassic(*shield); return mifareClassic.read(uid, uidLength); } else if (type == TAG_TYPE_2) { Serial.println(F("Mifare Ultralight")); MifareUltralight ultralight = MifareUltralight(*shield); return ultralight.read(uid, uidLength); } else if (type = TAG_TYPE_UNKNOWN) { Serial.print(F("Can not determine tag type")); //Serial.print(F("Can not determine tag type for ATQA 0x")); //Serial.print(atqa, HEX);Serial.print(" SAK 0x");Serial.println(sak, HEX); return NfcTag(uid, uidLength); } else { Serial.print(F("No driver for card type "));Serial.println(type); // TODO should set type here return NfcTag(uid, uidLength); } } boolean NfcAdapter::write(NdefMessage& ndefMessage) { boolean success; if (uidLength == 4) { MifareClassic mifareClassic = MifareClassic(*shield); success = mifareClassic.write(ndefMessage, uid, uidLength); } else { Serial.println(F("Unsupported Tag")); success = false; } return success; } // TODO this should return a Driver MifareClassic, MifareUltralight, Type 4, Unknown // Guess Tag Type by looking at the ATQA and SAK values // Need to follow spec for Card Identification. Maybe AN1303, AN1305 and ??? uint8_t NfcAdapter::guessTagType() { // 4 byte id - Mifare Classic // - ATQA 0x4 && SAK 0x8 // 7 byte id // - ATQA 0x44 && SAK 0x8 - Mifare Classic // - ATQA 0x44 && SAK 0x0 - Mifare Ultralight NFC Forum Type 2 // - ATQA 0x344 && SAK 0x20 - NFC Forum Type 4 if (uidLength == 4) { return TAG_TYPE_MIFARE_CLASSIC; } else { return TAG_TYPE_2; } }<commit_msg>cleanup<commit_after>#include <NfcAdapter.h> NfcAdapter::NfcAdapter(void) { shield = new Adafruit_NFCShield_I2C(IRQ, RESET); } NfcAdapter::~NfcAdapter(void) { delete shield; } void NfcAdapter::begin() { shield->begin(); uint32_t versiondata = shield->getFirmwareVersion(); if (! versiondata) { Serial.print(F("Didn't find PN53x board")); while (1); // halt } Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX); Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC); Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); // configure board to read RFID tags shield->SAMConfig(); } boolean NfcAdapter::tagPresent() { uint8_t success; uidLength = 0; success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); // if (success) // { // Serial.println("Found an ISO14443A card"); // Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes"); // Serial.print(" UID Value: "); // shield->PrintHex(uid, uidLength); // Serial.println(""); // } return success; } NfcTag NfcAdapter::read() { uint8_t type = guessTagType(); // TODO need an abstraction of Driver if (type == TAG_TYPE_MIFARE_CLASSIC) { Serial.println(F("Mifare Classic")); MifareClassic mifareClassic = MifareClassic(*shield); return mifareClassic.read(uid, uidLength); } else if (type == TAG_TYPE_2) { Serial.println(F("Mifare Ultralight")); MifareUltralight ultralight = MifareUltralight(*shield); return ultralight.read(uid, uidLength); } else if (type = TAG_TYPE_UNKNOWN) { Serial.print(F("Can not determine tag type")); //Serial.print(F("Can not determine tag type for ATQA 0x")); //Serial.print(atqa, HEX);Serial.print(" SAK 0x");Serial.println(sak, HEX); return NfcTag(uid, uidLength); } else { Serial.print(F("No driver for card type "));Serial.println(type); // TODO should set type here return NfcTag(uid, uidLength); } } boolean NfcAdapter::write(NdefMessage& ndefMessage) { boolean success; if (uidLength == 4) { MifareClassic mifareClassic = MifareClassic(*shield); success = mifareClassic.write(ndefMessage, uid, uidLength); } else { Serial.println(F("Unsupported Tag")); success = false; } return success; } // TODO this should return a Driver MifareClassic, MifareUltralight, Type 4, Unknown // Guess Tag Type by looking at the ATQA and SAK values // Need to follow spec for Card Identification. Maybe AN1303, AN1305 and ??? uint8_t NfcAdapter::guessTagType() { // 4 byte id - Mifare Classic // - ATQA 0x4 && SAK 0x8 // 7 byte id // - ATQA 0x44 && SAK 0x8 - Mifare Classic // - ATQA 0x44 && SAK 0x0 - Mifare Ultralight NFC Forum Type 2 // - ATQA 0x344 && SAK 0x20 - NFC Forum Type 4 if (uidLength == 4) { return TAG_TYPE_MIFARE_CLASSIC; } else { return TAG_TYPE_2; } }<|endoftext|>
<commit_before>/* * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include <cfloat> #include "particle_filter.h" using namespace std; default_random_engine gen; void ParticleFilter::init(double x, double y, double theta, double std[]) { // TODO: Set the number of particles. Initialize all particles to first position (based on estimates of // x, y, theta and their uncertainties from GPS) and all weights to 1. // Add random Gaussian noise to each particle. // NOTE: Consult particle_filter.h for more information about this method (and othe[rs in this file). normal_distribution<double> dist_x(x, std[0]) normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); particles = vector<Particle>(100); int id = 0; for (auto &p: particles) { //c11 loop for vector p.id = id; p.x = dist_x(gen); p.y = dist_y(gen); p.theta = dist_theta(gen); p.weight = 1/100; id += 1; } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // TODO: Add measurements to each particle and add random Gaussian noise. // NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful. // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution // http://www.cplusplus.com/reference/random/default_random_engine/ normal_distribution<double> dist_x(x, std_pos[0]) normal_distribution<double> dist_y(y, std_pos[1]); normal_distribution<double> dist_theta(theta, std_pos[2]); for (auto &p: particles) { p.x = p.x + (velocity/yaw_rate)(sin(p.theta + yaw_rate * delta_t) - sin(p.theta)) + dist_x(gen); p.y = p.y + (velocity/yaw_rate)(cos(p.theta) - cos(theta + yaw_rate * delta_t)) + dist_y(gen); p.theta += p.theta * yaw_rate + dist_theta(gen); } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. // NOTE: this method will NOT be called by the grading code. But you will probably find it useful to // implement this method and use it as a helper during the updateWeights phase. for (auto &obs : observations) { double distance = DBL_MAX; for (auto &pred: predicted) { double temp = dist(obs.x, obs.y, pred.x, pred.y); if (diff > temp) { diff = temp; } } } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { // TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read // more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution // NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located // according to the MAP'S coordinate system. You will need to transform between the two systems. // Keep in mind that this transformation requires both rotation AND translation (but no scaling). // The following is a good resource for the theory: // https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm // and the following is a good resource for the actual equation to implement (look at equation // 3.33 // http://planning.cs.uiuc.edu/node99.html gaussian_norm = 1/(2 * M_PI * std_landmark[0] * std_landmark[1]); // x_map= x_part + (np.cos(theta) * x_obs) - (np.sin(theta) * y_obs) for (auto &p: particles) { vector<LandmarkObs> landmark_in_range; int i= 0; for (auto &landmark: map_landmarks.landmark_list) { if(dist(landmark.x_f, landmark.y_f, p.x,p.y) <= sensor_range) { LandmarkObs landmarkObs; landmarkObs.id = i; landmarkObs.x = double(landmark.x_f); landmarkObs.y = double(landmark.y_f); landmark_in_range.push_back(landmarkObs); } } std::vector<LandmarkObs> transformed_obs = transform(observations, p); dataAssociation(landmark_in_range, transformed_obs); exponent = pow(x_obs - mu[0],2)/(2 * std_landmark[0]) + pow(y_obs-mu_y, 2)/(2*std_landmark[1]); weights[i] = gaussian_norm * exp(exponent) ; } } void ParticleFilter::resample() { // TODO: Resample particles with replacement with probability proportional to their weight. // NOTE: You may find std::discrete_distribution helpful here. // http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { //particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } <commit_msg>Update kidnapped vehicle project<commit_after>/* * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include <cfloat> #include "particle_filter.h" using namespace std; default_random_engine gen; void ParticleFilter::init(double x, double y, double theta, double std[]) { // TODO: Set the number of particles. Initialize all particles to first position (based on estimates of // x, y, theta and their uncertainties from GPS) and all weights to 1. // Add random Gaussian noise to each particle. // NOTE: Consult particle_filter.h for more information about this method (and othe[rs in this file). normal_distribution<double> dist_x(x, std[0]) normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); num_particles = 100 particles = vector<Particle>(num_particles); int id = 0; for (auto &p: particles) { //c11 loop for vector p.id = id; p.x = dist_x(gen); p.y = dist_y(gen); p.theta = dist_theta(gen); p.weight = 1/100; id += 1; } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // TODO: Add measurements to each particle and add random Gaussian noise. // NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful. // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution // http://www.cplusplus.com/reference/random/default_random_engine/ normal_distribution<double> dist_x(x, std_pos[0]) normal_distribution<double> dist_y(y, std_pos[1]); normal_distribution<double> dist_theta(theta, std_pos[2]); for (auto &p: particles) { p.x = p.x + (velocity/yaw_rate)(sin(p.theta + yaw_rate * delta_t) - sin(p.theta)) + dist_x(gen); p.y = p.y + (velocity/yaw_rate)(cos(p.theta) - cos(theta + yaw_rate * delta_t)) + dist_y(gen); p.theta += p.theta * yaw_rate + dist_theta(gen); } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. // NOTE: this method will NOT be called by the grading code. But you will probably find it useful to // implement this method and use it as a helper during the updateWeights phase. for (auto &obs : observations) { double distance = DBL_MAX; for (auto &pred: predicted) { double temp = dist(obs.x, obs.y, pred.x, pred.y); if (diff > temp) { diff = temp; obs.id = landmark.id; } } } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { // TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read // more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution // NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located // according to the MAP'S coordinate system. You will need to transform between the two systems. // Keep in mind that this transformation requires both rotation AND translation (but no scaling). // The following is a good resource for the theory: // https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm // and the following is a good resource for the actual equation to implement (look at equation // 3.33 // http://planning.cs.uiuc.edu/node99.html // x_map= x_part + (np.cos(theta) * x_obs) - (np.sin(theta) * y_obs) for (auto &p: particles) { vector<LandmarkObs> landmark_in_range; int i= 0; for (auto &landmark: map_landmarks.landmark_list) { if(dist(landmark.x_f, landmark.y_f, p.x,p.y) <= sensor_range) { LandmarkObs landmarkObs; landmarkObs.id = i; landmarkObs.x = double(landmark.x_f); landmarkObs.y = double(landmark.y_f); landmark_in_range.push_back(landmarkObs); } } // coverting from vehicle to map system std::vector<LandmarkObs> transformed_obs = transform(observations, p); vector<LandmarkObs> transformed_obs; for (auto &obs: observations) { x_map = obs.x + (cos(p.theta) * obs.x) - (sin(p.theta) * obs.y); y_map= obs.y + (sin(theta) * obs.x) + (cos(theta) * obs.y) transformed_obs.x = x_map; transformed_obs.y = y_map; } dataAssociation(landmark_in_range, transformed_obs); double sum_sqr_x_diff = 0.0; double sum_sqr_y_diff = 0.0; for (auto &obs: transformed_obs) { double x_diff = obs.x - landmark_in_range[obs.id].x; double y_diff = obs.y - landmark_in_range[obs.id].y; sum_sqr_x_diff += x_diff * x_diff; sum_sqr_y_diff += y_diff * y_diff; } double std_x = std_landmark[0]; double std_y = std_landmark[1]; gaussian_norm = 1/(2 * M_PI * std_x * std_y); exponent = sum_sqr_x_diff/(2 * std_x * std_x) + sum_sqr_y_diff/(2 * std_y * std_y); p.weight = gaussian_norm * (exp(-exponent)) ; } if (weights.size() != num_particles) { weights = std::vector<double>(num_particles); } for (int i =0; i < num_particles; i++) { weights[i] = particles[i].weight; } } void ParticleFilter::resample() { // TODO: Resample particles with replacement with probability proportional to their weight. // NOTE: You may find std::discrete_distribution helpful here. // http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution std::discrete_distribution<int> dist_particles(weights.begin(), weights.end()); std::vector<Particle> resampled_particles; for (int i = 0; i <num_particles; i++) { resampled_particles.push_back(particles[dist_particles(gen)]); } particles = resampled_particles; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { //particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } <|endoftext|>
<commit_before>#ifndef STAN__MATH__PRIM__SCAL__FUN__DIVIDE_HPP #define STAN__MATH__PRIM__SCAL__FUN__DIVIDE_HPP #include <vector> #include <cstddef> #include <cstdlib> namespace stan { namespace math { inline int divide(const int x, const int y) { return std::div(x, y).quot; } } } #endif <commit_msg>removed header from divide.hpp<commit_after>#ifndef STAN__MATH__PRIM__SCAL__FUN__DIVIDE_HPP #define STAN__MATH__PRIM__SCAL__FUN__DIVIDE_HPP #include <cstddef> #include <cstdlib> namespace stan { namespace math { inline int divide(const int x, const int y) { return std::div(x, y).quot; } } } #endif <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ua_server_internal.h" #include "ua_config_default.h" #include "ua_log_stdout.h" #include "ua_plugin_log.h" #include "testing_networklayers.h" /* ** Main entry point. The fuzzer invokes this function with each ** fuzzed input. */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { UA_ByteString sentData; UA_Connection c = createDummyConnection(&sentData); UA_ServerConfig *config = UA_ServerConfig_new_default(); UA_Server *server = UA_Server_new(config); // we need to copy the message because it will be freed in the processing function UA_ByteString msg = UA_ByteString(); UA_StatusCode retval = UA_ByteString_allocBuffer(&msg, size); if(retval != UA_STATUSCODE_GOOD) return (int)retval; memcpy(msg.data, data, size); UA_Server_processBinaryMessage(server, &c, &msg); // if we got an invalid chunk, the message is not deleted, so delete it here UA_ByteString_deleteMembers(&msg); UA_Server_run_shutdown(server); UA_Server_delete(server); UA_ServerConfig_delete(config); UA_Connection_deleteMembers(&c); return 0; } <commit_msg>fix a unasigned memory problem in the fuzzer<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ua_server_internal.h" #include "ua_config_default.h" #include "ua_log_stdout.h" #include "ua_plugin_log.h" #include "testing_networklayers.h" /* ** Main entry point. The fuzzer invokes this function with each ** fuzzed input. */ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { UA_ByteString sentData = UA_BYTESTRING_NULL; UA_Connection c = createDummyConnection(&sentData); UA_ServerConfig *config = UA_ServerConfig_new_default(); UA_Server *server = UA_Server_new(config); // we need to copy the message because it will be freed in the processing function UA_ByteString msg = UA_ByteString(); UA_StatusCode retval = UA_ByteString_allocBuffer(&msg, size); if(retval != UA_STATUSCODE_GOOD) return (int)retval; memcpy(msg.data, data, size); UA_Server_processBinaryMessage(server, &c, &msg); // if we got an invalid chunk, the message is not deleted, so delete it here UA_ByteString_deleteMembers(&msg); UA_Server_run_shutdown(server); UA_Server_delete(server); UA_ServerConfig_delete(config); c.close(&c); UA_Connection_deleteMembers(&c); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2007 Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messageactions.h" #include "globalsettings.h" #include "kmfolder.h" #include "kmmessage.h" #include "kmreaderwin.h" #include <kaction.h> #include <kactionmenu.h> #include <kactioncollection.h> #include <ktoggleaction.h> #include <kdebug.h> #include <klocale.h> #include <qwidget.h> using namespace KMail; MessageActions::MessageActions( KActionCollection *ac, QWidget * parent ) : QObject( parent ), mParent( parent ), mActionCollection( ac ), mCurrentMessage( 0 ), mMessageView( 0 ) { mReplyActionMenu = new KActionMenu( KIcon("mail-reply-sender"), i18nc("Message->","&Reply"), this ); mActionCollection->addAction( "message_reply_menu", mReplyActionMenu ); connect( mReplyActionMenu, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyAction = new KAction( KIcon("mail-reply-sender"), i18n("&Reply..."), this ); mActionCollection->addAction( "reply", mReplyAction ); mReplyAction->setShortcut(Qt::Key_R); connect( mReplyAction, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyActionMenu->addAction( mReplyAction ); mReplyAuthorAction = new KAction( KIcon("mail-reply-sender"), i18n("Reply to A&uthor..."), this ); mActionCollection->addAction( "reply_author", mReplyAuthorAction ); mReplyAuthorAction->setShortcut(Qt::SHIFT+Qt::Key_A); connect( mReplyAuthorAction, SIGNAL(activated()), this, SLOT(slotReplyAuthorToMsg()) ); mReplyActionMenu->addAction( mReplyAuthorAction ); mReplyAllAction = new KAction( KIcon("mail-reply-all"), i18n("Reply to &All..."), this ); mActionCollection->addAction( "reply_all", mReplyAllAction ); mReplyAllAction->setShortcut( Qt::Key_A ); connect( mReplyAllAction, SIGNAL(activated()), this, SLOT(slotReplyAllToMsg()) ); mReplyActionMenu->addAction( mReplyAllAction ); mReplyListAction = new KAction( KIcon("mail-reply-list"), i18n("Reply to Mailing-&List..."), this ); mActionCollection->addAction( "reply_list", mReplyListAction ); mReplyListAction->setShortcut( Qt::Key_L ); connect( mReplyListAction, SIGNAL(activated()), this, SLOT(slotReplyListToMsg()) ); mReplyActionMenu->addAction( mReplyListAction ); mNoQuoteReplyAction = new KAction( i18n("Reply Without &Quote..."), this ); mActionCollection->addAction( "noquotereply", mNoQuoteReplyAction ); mNoQuoteReplyAction->setShortcut( Qt::SHIFT+Qt::Key_R ); connect( mNoQuoteReplyAction, SIGNAL(activated()), this, SLOT(slotNoQuoteReplyToMsg()) ); mCreateTodoAction = new KAction( KIcon("view-pim-tasks"), i18n("Create Task..."), this ); mActionCollection->addAction( "create_todo", mCreateTodoAction ); connect( mCreateTodoAction, SIGNAL(activated()), this, SLOT(slotCreateTodo()) ); mStatusMenu = new KActionMenu ( i18n( "Mar&k Message" ), this ); mActionCollection->addAction( "set_status", mStatusMenu ); KAction *action; action = new KAction( KIcon("kmmsgread"), i18n("Mark Message as &Read"), this ); action->setToolTip( i18n("Mark selected messages as read") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusRead()) ); mActionCollection->addAction( "status_read", action ); mStatusMenu->addAction( action ); action = new KAction( KIcon("kmmsgnew"), i18n("Mark Message as &New"), this ); action->setToolTip( i18n("Mark selected messages as new") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusNew()) ); mActionCollection->addAction( "status_new" , action ); mStatusMenu->addAction( action ); action = new KAction( KIcon("kmmsgunseen"), i18n("Mark Message as &Unread"), this ); action->setToolTip( i18n("Mark selected messages as unread") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusUnread()) ); mActionCollection->addAction( "status_unread", action ); mStatusMenu->addAction( action ); mStatusMenu->addSeparator(); mToggleFlagAction = new KToggleAction( KIcon("mail-flag"), i18n("Mark Message as &Important"), this ); connect( mToggleFlagAction, SIGNAL(activated()), this, SLOT(slotSetMsgStatusFlag()) ); mToggleFlagAction->setCheckedState( KGuiItem(i18n("Remove &Important Message Mark")) ); mActionCollection->addAction( "status_flag", mToggleFlagAction ); mStatusMenu->addAction( mToggleFlagAction ); mToggleTodoAction = new KToggleAction( KIcon("view-pim-tasks"), i18n("Mark Message as &Action Item"), this ); connect( mToggleTodoAction, SIGNAL(activated()), this, SLOT(slotSetMsgStatusTodo()) ); mToggleTodoAction->setCheckedState( KGuiItem(i18n("Remove &Action Item Message Mark")) ); mActionCollection->addAction( "status_todo", mToggleTodoAction ); mStatusMenu->addAction( mToggleTodoAction ); mEditAction = new KAction( KIcon("edit"), i18n("&Edit Message"), this ); mActionCollection->addAction( "edit", mEditAction ); connect( mEditAction, SIGNAL(activated()), this, SLOT(editCurrentMessage()) ); mEditAction->setShortcut( Qt::Key_T ); updateActions(); } void MessageActions::setCurrentMessage(KMMessage * msg) { mCurrentMessage = msg; if ( !msg ) { mSelectedSernums.clear(); mVisibleSernums.clear(); } updateActions(); } void MessageActions::setSelectedSernums(const QList< Q_UINT32 > & sernums) { mSelectedSernums = sernums; updateActions(); } void MessageActions::setSelectedVisibleSernums(const QList< Q_UINT32 > & sernums) { mVisibleSernums = sernums; updateActions(); } void MessageActions::updateActions() { const bool singleMsg = (mCurrentMessage != 0 && mSelectedSernums.count() <= 1); const bool multiVisible = mVisibleSernums.count() > 0 || mCurrentMessage; const bool flagsAvailable = GlobalSettings::self()->allowLocalFlags() || !((mCurrentMessage && mCurrentMessage->parent()) ? mCurrentMessage->parent()->isReadOnly() : true); mCreateTodoAction->setEnabled( singleMsg ); mReplyActionMenu->setEnabled( singleMsg ); mReplyAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mReplyAuthorAction->setEnabled( singleMsg ); mReplyAllAction->setEnabled( singleMsg ); mReplyListAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mStatusMenu->setEnabled( multiVisible ); mToggleFlagAction->setEnabled( flagsAvailable ); mToggleTodoAction->setEnabled( flagsAvailable ); if ( mCurrentMessage ) { mToggleTodoAction->setChecked( mCurrentMessage->status().isTodo() ); mToggleFlagAction->setChecked( mCurrentMessage->status().isImportant() ); } mEditAction->setEnabled( singleMsg ); } void MessageActions::slotCreateTodo() { if ( !mCurrentMessage ) return; KMCommand *command = new CreateTodoCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::setMessageView(KMReaderWin * msgView) { mMessageView = msgView; } void MessageActions::slotReplyToMsg() { replyCommand<KMReplyToCommand>(); } void MessageActions::slotReplyAuthorToMsg() { replyCommand<KMReplyAuthorCommand>(); } void MessageActions::slotReplyListToMsg() { replyCommand<KMReplyListCommand>(); } void MessageActions::slotReplyAllToMsg() { replyCommand<KMReplyToAllCommand>(); } void MessageActions::slotNoQuoteReplyToMsg() { if ( !mCurrentMessage ) return; KMCommand *command = new KMNoQuoteReplyToCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::slotSetMsgStatusNew() { setMessageStatus( KPIM::MessageStatus::statusNew() ); } void MessageActions::slotSetMsgStatusUnread() { setMessageStatus( KPIM::MessageStatus::statusUnread() ); } void MessageActions::slotSetMsgStatusRead() { setMessageStatus( KPIM::MessageStatus::statusRead() ); } void MessageActions::slotSetMsgStatusFlag() { setMessageStatus( KPIM::MessageStatus::statusImportant(), true ); } void MessageActions::slotSetMsgStatusTodo() { setMessageStatus( KPIM::MessageStatus::statusTodo(), true ); } void MessageActions::setMessageStatus( KPIM::MessageStatus status, bool toggle ) { QList<Q_UINT32> serNums = mVisibleSernums; if ( serNums.isEmpty() && mCurrentMessage ) serNums.append( mCurrentMessage->getMsgSerNum() ); if ( serNums.empty() ) return; KMCommand *command = new KMSetStatusCommand( status, serNums, toggle ); command->start(); } void MessageActions::editCurrentMessage() { if ( !mCurrentMessage ) return; KMCommand *command = 0; KMFolder *folder = mCurrentMessage->parent(); // edit, unlike send again, removes the message from the folder // we only want that for templates and drafts folders if ( folder && ( kmkernel->folderIsDraftOrOutbox( folder ) || kmkernel->folderIsTemplates( folder ) ) ) command = new KMEditMsgCommand( mParent, mCurrentMessage ); else command = new KMResendMessageCommand( mParent, mCurrentMessage ); command->start(); } #include "messageactions.moc" <commit_msg>Use an icon that actually exists. Thanks to Thomas for spotting this one.<commit_after>/* Copyright (c) 2007 Volker Krause <vkrause@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messageactions.h" #include "globalsettings.h" #include "kmfolder.h" #include "kmmessage.h" #include "kmreaderwin.h" #include <kaction.h> #include <kactionmenu.h> #include <kactioncollection.h> #include <ktoggleaction.h> #include <kdebug.h> #include <klocale.h> #include <qwidget.h> using namespace KMail; MessageActions::MessageActions( KActionCollection *ac, QWidget * parent ) : QObject( parent ), mParent( parent ), mActionCollection( ac ), mCurrentMessage( 0 ), mMessageView( 0 ) { mReplyActionMenu = new KActionMenu( KIcon("mail-reply-sender"), i18nc("Message->","&Reply"), this ); mActionCollection->addAction( "message_reply_menu", mReplyActionMenu ); connect( mReplyActionMenu, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyAction = new KAction( KIcon("mail-reply-sender"), i18n("&Reply..."), this ); mActionCollection->addAction( "reply", mReplyAction ); mReplyAction->setShortcut(Qt::Key_R); connect( mReplyAction, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyActionMenu->addAction( mReplyAction ); mReplyAuthorAction = new KAction( KIcon("mail-reply-sender"), i18n("Reply to A&uthor..."), this ); mActionCollection->addAction( "reply_author", mReplyAuthorAction ); mReplyAuthorAction->setShortcut(Qt::SHIFT+Qt::Key_A); connect( mReplyAuthorAction, SIGNAL(activated()), this, SLOT(slotReplyAuthorToMsg()) ); mReplyActionMenu->addAction( mReplyAuthorAction ); mReplyAllAction = new KAction( KIcon("mail-reply-all"), i18n("Reply to &All..."), this ); mActionCollection->addAction( "reply_all", mReplyAllAction ); mReplyAllAction->setShortcut( Qt::Key_A ); connect( mReplyAllAction, SIGNAL(activated()), this, SLOT(slotReplyAllToMsg()) ); mReplyActionMenu->addAction( mReplyAllAction ); mReplyListAction = new KAction( KIcon("mail-reply-list"), i18n("Reply to Mailing-&List..."), this ); mActionCollection->addAction( "reply_list", mReplyListAction ); mReplyListAction->setShortcut( Qt::Key_L ); connect( mReplyListAction, SIGNAL(activated()), this, SLOT(slotReplyListToMsg()) ); mReplyActionMenu->addAction( mReplyListAction ); mNoQuoteReplyAction = new KAction( i18n("Reply Without &Quote..."), this ); mActionCollection->addAction( "noquotereply", mNoQuoteReplyAction ); mNoQuoteReplyAction->setShortcut( Qt::SHIFT+Qt::Key_R ); connect( mNoQuoteReplyAction, SIGNAL(activated()), this, SLOT(slotNoQuoteReplyToMsg()) ); mCreateTodoAction = new KAction( KIcon("view-pim-tasks"), i18n("Create Task..."), this ); mActionCollection->addAction( "create_todo", mCreateTodoAction ); connect( mCreateTodoAction, SIGNAL(activated()), this, SLOT(slotCreateTodo()) ); mStatusMenu = new KActionMenu ( i18n( "Mar&k Message" ), this ); mActionCollection->addAction( "set_status", mStatusMenu ); KAction *action; action = new KAction( KIcon("kmmsgread"), i18n("Mark Message as &Read"), this ); action->setToolTip( i18n("Mark selected messages as read") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusRead()) ); mActionCollection->addAction( "status_read", action ); mStatusMenu->addAction( action ); action = new KAction( KIcon("kmmsgnew"), i18n("Mark Message as &New"), this ); action->setToolTip( i18n("Mark selected messages as new") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusNew()) ); mActionCollection->addAction( "status_new" , action ); mStatusMenu->addAction( action ); action = new KAction( KIcon("kmmsgunseen"), i18n("Mark Message as &Unread"), this ); action->setToolTip( i18n("Mark selected messages as unread") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusUnread()) ); mActionCollection->addAction( "status_unread", action ); mStatusMenu->addAction( action ); mStatusMenu->addSeparator(); mToggleFlagAction = new KToggleAction( KIcon("mail-flag"), i18n("Mark Message as &Important"), this ); connect( mToggleFlagAction, SIGNAL(activated()), this, SLOT(slotSetMsgStatusFlag()) ); mToggleFlagAction->setCheckedState( KGuiItem(i18n("Remove &Important Message Mark")) ); mActionCollection->addAction( "status_flag", mToggleFlagAction ); mStatusMenu->addAction( mToggleFlagAction ); mToggleTodoAction = new KToggleAction( KIcon("view-pim-tasks"), i18n("Mark Message as &Action Item"), this ); connect( mToggleTodoAction, SIGNAL(activated()), this, SLOT(slotSetMsgStatusTodo()) ); mToggleTodoAction->setCheckedState( KGuiItem(i18n("Remove &Action Item Message Mark")) ); mActionCollection->addAction( "status_todo", mToggleTodoAction ); mStatusMenu->addAction( mToggleTodoAction ); mEditAction = new KAction( KIcon("accessories-text-editor"), i18n("&Edit Message"), this ); mActionCollection->addAction( "edit", mEditAction ); connect( mEditAction, SIGNAL(activated()), this, SLOT(editCurrentMessage()) ); mEditAction->setShortcut( Qt::Key_T ); updateActions(); } void MessageActions::setCurrentMessage(KMMessage * msg) { mCurrentMessage = msg; if ( !msg ) { mSelectedSernums.clear(); mVisibleSernums.clear(); } updateActions(); } void MessageActions::setSelectedSernums(const QList< Q_UINT32 > & sernums) { mSelectedSernums = sernums; updateActions(); } void MessageActions::setSelectedVisibleSernums(const QList< Q_UINT32 > & sernums) { mVisibleSernums = sernums; updateActions(); } void MessageActions::updateActions() { const bool singleMsg = (mCurrentMessage != 0 && mSelectedSernums.count() <= 1); const bool multiVisible = mVisibleSernums.count() > 0 || mCurrentMessage; const bool flagsAvailable = GlobalSettings::self()->allowLocalFlags() || !((mCurrentMessage && mCurrentMessage->parent()) ? mCurrentMessage->parent()->isReadOnly() : true); mCreateTodoAction->setEnabled( singleMsg ); mReplyActionMenu->setEnabled( singleMsg ); mReplyAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mReplyAuthorAction->setEnabled( singleMsg ); mReplyAllAction->setEnabled( singleMsg ); mReplyListAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mStatusMenu->setEnabled( multiVisible ); mToggleFlagAction->setEnabled( flagsAvailable ); mToggleTodoAction->setEnabled( flagsAvailable ); if ( mCurrentMessage ) { mToggleTodoAction->setChecked( mCurrentMessage->status().isTodo() ); mToggleFlagAction->setChecked( mCurrentMessage->status().isImportant() ); } mEditAction->setEnabled( singleMsg ); } void MessageActions::slotCreateTodo() { if ( !mCurrentMessage ) return; KMCommand *command = new CreateTodoCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::setMessageView(KMReaderWin * msgView) { mMessageView = msgView; } void MessageActions::slotReplyToMsg() { replyCommand<KMReplyToCommand>(); } void MessageActions::slotReplyAuthorToMsg() { replyCommand<KMReplyAuthorCommand>(); } void MessageActions::slotReplyListToMsg() { replyCommand<KMReplyListCommand>(); } void MessageActions::slotReplyAllToMsg() { replyCommand<KMReplyToAllCommand>(); } void MessageActions::slotNoQuoteReplyToMsg() { if ( !mCurrentMessage ) return; KMCommand *command = new KMNoQuoteReplyToCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::slotSetMsgStatusNew() { setMessageStatus( KPIM::MessageStatus::statusNew() ); } void MessageActions::slotSetMsgStatusUnread() { setMessageStatus( KPIM::MessageStatus::statusUnread() ); } void MessageActions::slotSetMsgStatusRead() { setMessageStatus( KPIM::MessageStatus::statusRead() ); } void MessageActions::slotSetMsgStatusFlag() { setMessageStatus( KPIM::MessageStatus::statusImportant(), true ); } void MessageActions::slotSetMsgStatusTodo() { setMessageStatus( KPIM::MessageStatus::statusTodo(), true ); } void MessageActions::setMessageStatus( KPIM::MessageStatus status, bool toggle ) { QList<Q_UINT32> serNums = mVisibleSernums; if ( serNums.isEmpty() && mCurrentMessage ) serNums.append( mCurrentMessage->getMsgSerNum() ); if ( serNums.empty() ) return; KMCommand *command = new KMSetStatusCommand( status, serNums, toggle ); command->start(); } void MessageActions::editCurrentMessage() { if ( !mCurrentMessage ) return; KMCommand *command = 0; KMFolder *folder = mCurrentMessage->parent(); // edit, unlike send again, removes the message from the folder // we only want that for templates and drafts folders if ( folder && ( kmkernel->folderIsDraftOrOutbox( folder ) || kmkernel->folderIsTemplates( folder ) ) ) command = new KMEditMsgCommand( mParent, mCurrentMessage ); else command = new KMResendMessageCommand( mParent, mCurrentMessage ); command->start(); } #include "messageactions.moc" <|endoftext|>
<commit_before>#include "Alpha.h" #include <QKeyEvent> #include <cmath> // Config const float TURN_SPEED = 1; const float PLAYER_FWD = 50; const float PLAYER_BWD = 30; // end Config Alpha::Alpha(QWidget* const parent) : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), timer(this) { setFocusPolicy(Qt::ClickFocus); // allows keypresses to passed to the rendered window connect(&timer, SIGNAL(timeout(const float&)), this, SLOT(tick(const float&))); connect(&timer, SIGNAL(timeout(const float&)), this, SLOT(updateGL())); timer.startOnShow(this); player.pos.setZ(10); } void Alpha::tick(const float& elapsed) { float velocity_init = player.velocity; // for position calculation purposes if (pad.forward) { player.velocity = PLAYER_FWD; } else if (pad.backward) { player.velocity = -PLAYER_BWD; } else { player.velocity = 0; } if (pad.yawleft && !pad.yawright) { player.yaw -= M_PI * elapsed * TURN_SPEED; } if (pad.yawright && !pad.yawleft) { player.yaw += M_PI * elapsed * TURN_SPEED; } if (pad.pitchup && !pad.pitchdown) { player.pitch += M_PI * elapsed * TURN_SPEED; } if (pad.pitchdown && !pad.pitchup) { player.pitch -= M_PI * elapsed * TURN_SPEED; } if ( player.yaw >= 2 * M_PI ) { player.yaw -= 2 * M_PI; } // TODO: turn this into 1 normalize function else if (player.yaw <= 0 ) { player.yaw += 2 * M_PI; } // keeps our angles within 1 revolution if ( player.pitch >= 2 * M_PI ) { player.pitch -= 2 * M_PI; } // TODO: turn this into 1 normalize function else if (player.pitch <= 0 ) { player.pitch += 2 * M_PI; } // keeps our angles within 1 revolution // S = Sinit + (1/2) * (V + Vinit) * deltaT float x = player.pos.x() + 0.5 * (player.velocity + velocity_init) * elapsed * cos(player.yaw); float y = player.pos.y() + 0.5 * (player.velocity + velocity_init) * elapsed * sin(player.yaw); float z; // TODO: use this; player.pos.setX(x); player.pos.setY(y); } void Alpha::initializeGL() { glClearColor(0.4,0.6,1,0); // background: r,g,b,a setXRotation(130); setYRotation(0); setZRotation(0); } void Alpha::resizeGL(int width, int height) { glViewport(0, 0, width, height); // viewport: (startx,starty, width, height) const float aspectRatio = (float) height / (float) width; const float range = 100.0; // do not do anything with GL_PROJECTION besides set glOrtho glMatrixMode(GL_PROJECTION); // determines how the the world is viewed by the user glLoadIdentity(); // set the matrix to an unmodified state if (width <= height) { glOrtho( // clips everything drawn outside the params -range, // left range, // right -range * aspectRatio, // bottom range * aspectRatio, // top 2 * -range, // back 2 * range); // front } else { glOrtho( -range / aspectRatio, range / aspectRatio, -range, range, 2 * -range, 2 * range); } glMatrixMode(GL_MODELVIEW); // the world and where it is viewed from glLoadIdentity(); // set the matrix to an unmodified state } void Alpha::paintGL() { glClear(GL_COLOR_BUFFER_BIT); // Clears the view glMatrixMode(GL_MODELVIEW); glLoadIdentity(); applyRotation(); //glEnable(GL_DEPTH_TEST); // XXX: figure out why this causes flickering //glDepthMask(GL_TRUE); glEnable(GL_CULL_FACE); //glCullFace(GL_FRONT); // draw the player's cube glRotatef(player.yaw * 180 / M_PI, 0, 0, 1); glRotatef(player.pitch * 180 /M_PI, 0,1,0); glBegin(GL_QUADS); { // TOP is BLACK glColor3f(0.0f,0.0f,0.0f); glVertex3f( 4.0f, 4.0f, 4.0f); // Top Right glVertex3f(-4.0f, 4.0f, 4.0f); // Top Left glVertex3f(-4.0f,-4.0f, 4.0f); // Bottom Left glVertex3f( 4.0f,-4.0f, 4.0f); // Bottom Right // BOTTOM is WHITE glColor3f(1.0f,1.0f,1.0f); glVertex3f(-4.0f, 4.0f, -4.0f); // Top Right glVertex3f( 4.0f, 4.0f, -4.0f); // Top Left glVertex3f( 4.0f,-4.0f, -4.0f); // Bottom Left glVertex3f(-4.0f,-4.0f, -4.0f); // Bottom Right // BACK is RED glColor3f(1.0f,0.0f,0.0f); glVertex3f(-4.0f,-4.0f, 4.0f); // Top Right glVertex3f(-4.0f, 4.0f, 4.0f); // Top Left glVertex3f(-4.0f, 4.0f,-4.0f); // Bottom Left glVertex3f(-4.0f,-4.0f,-4.0f); // Bottom Right // FRONT is GREEN glColor3f(0.0f,1.0f,0.0f); glVertex3f( 4.0f, 4.0f, 4.0f); // Top Right glVertex3f( 4.0f,-4.0f, 4.0f); // Top Left glVertex3f( 4.0f,-4.0f,-4.0f); // Bottom Left glVertex3f( 4.0f, 4.0f,-4.0f); // Bottom Right // LEFT is BLUE glColor3f(0.0f,0.0f,1.0f); glVertex3f(-4.0f, 4.0f, 4.0f); // Top Right glVertex3f( 4.0f, 4.0f, 4.0f); // Top Left glVertex3f( 4.0f, 4.0f,-4.0f); // Bottom Left glVertex3f(-4.0f, 4.0f,-4.0f); // Bottom Right // RIGHT is BLUE glVertex3f( 4.0f,-4.0f, 4.0f); // Top Right glVertex3f(-4.0f,-4.0f, 4.0f); // Top Left glVertex3f(-4.0f,-4.0f,-4.0f); // Bottom Left glVertex3f( 4.0f,-4.0f,-4.0f); // Bottom Right } glEnd(); // draw the ground glPushMatrix(); { glTranslatef(player.pos.x(), player.pos.y(), player.pos.z()); // move the world, not the camera glBegin(GL_QUADS); { glColor3f(0.1f, 0.65f, 0.1f); // XXX: This is all backwards glVertex3f(-80.0f, 80.0f, 0.0f); // Top Left glVertex3f( 80.0f, 80.0f, 0.0f); // Top Right glVertex3f( 80.0f,-80.0f, 0.0f); // Bottom Right glVertex3f(-80.0f,-80.0f, 0.0f); // Bottom Left } glEnd(); } glPopMatrix(); } void Alpha::keyPressEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_W: pad.forward = true; break; case Qt::Key_S: pad.backward = true; break; case Qt::Key_A: pad.yawleft = true; break; case Qt::Key_D: pad.yawright = true; break; case Qt::Key_Space: pad.up = true; break; case Qt::Key_X: pad.down = true; break; case Qt::Key_Q: pad.pitchup = true; break; case Qt::Key_E: pad.pitchdown = true; break; default: // TODO: have frito explain where the esc key is bound to close() QGLWidget::keyPressEvent(event); } } void Alpha::keyReleaseEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_W: pad.forward = false; break; case Qt::Key_S: pad.backward = false; break; case Qt::Key_A: pad.yawleft = false; break; case Qt::Key_D: pad.yawright = false; break; case Qt::Key_Space: pad.up = false; break; case Qt::Key_X: pad.down = false; break; case Qt::Key_Q: pad.pitchup = false; break; case Qt::Key_E: pad.pitchdown = false; break; default: QGLWidget::keyPressEvent(event); } } void Alpha::mousePressEvent(QMouseEvent *event) { lastPos = event->pos(); } /** * Interpret the mouse event to rotate the camera around the scene. */ void Alpha::mouseMoveEvent(QMouseEvent *event) { int dx = event->x() - lastPos.x(); int dy = event->y() - lastPos.y(); if (event->buttons() & Qt::LeftButton) { setScaledXRotation(xRot + dy * Alpha::ROTATION_SCALE / 2); setScaledYRotation(yRot + dx * Alpha::ROTATION_SCALE / 2); } else if (event->buttons() & Qt::RightButton) { setScaledXRotation(xRot + dy * Alpha::ROTATION_SCALE / 2); setScaledZRotation(zRot + dx * Alpha::ROTATION_SCALE / 2); } lastPos = event->pos(); } void Alpha::setScaledXRotation(int angle) { qNormalizeAngle(angle); if (angle != xRot) { xRot = angle; emit xRotationChanged(angle); updateGL(); } } void Alpha::setScaledYRotation(int angle) { qNormalizeAngle(angle); if (angle != yRot) { yRot = angle; emit yRotationChanged(angle); updateGL(); } } void Alpha::setScaledZRotation(int angle) { qNormalizeAngle(angle); if (angle != zRot) { zRot = angle; emit zRotationChanged(angle); updateGL(); } } void Alpha::applyRotation() const { static const float ROTATION_DENOM = 1 / (float)Alpha::ROTATION_SCALE; glRotatef((float)(xRot) * ROTATION_DENOM, 1.0, 0.0, 0.0); glRotatef((float)(yRot) * ROTATION_DENOM, 0.0, 1.0, 0.0); glRotatef((float)(zRot) * ROTATION_DENOM, 0.0, 0.0, 1.0); } <commit_msg>Fixed flickering with depth test<commit_after>#include "Alpha.h" #include <QKeyEvent> #include <cmath> // Config const float TURN_SPEED = 1; const float PLAYER_FWD = 50; const float PLAYER_BWD = 30; // end Config Alpha::Alpha(QWidget* const parent) : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), timer(this) { setFocusPolicy(Qt::ClickFocus); // allows keypresses to passed to the rendered window connect(&timer, SIGNAL(timeout(const float&)), this, SLOT(tick(const float&))); connect(&timer, SIGNAL(timeout(const float&)), this, SLOT(updateGL())); timer.startOnShow(this); player.pos.setZ(10); } void Alpha::tick(const float& elapsed) { float velocity_init = player.velocity; // for position calculation purposes if (pad.forward) { player.velocity = PLAYER_FWD; } else if (pad.backward) { player.velocity = -PLAYER_BWD; } else { player.velocity = 0; } if (pad.yawleft && !pad.yawright) { player.yaw -= M_PI * elapsed * TURN_SPEED; } if (pad.yawright && !pad.yawleft) { player.yaw += M_PI * elapsed * TURN_SPEED; } if (pad.pitchup && !pad.pitchdown) { player.pitch += M_PI * elapsed * TURN_SPEED; } if (pad.pitchdown && !pad.pitchup) { player.pitch -= M_PI * elapsed * TURN_SPEED; } if ( player.yaw >= 2 * M_PI ) { player.yaw -= 2 * M_PI; } // TODO: turn this into 1 normalize function else if (player.yaw <= 0 ) { player.yaw += 2 * M_PI; } // keeps our angles within 1 revolution if ( player.pitch >= 2 * M_PI ) { player.pitch -= 2 * M_PI; } // TODO: turn this into 1 normalize function else if (player.pitch <= 0 ) { player.pitch += 2 * M_PI; } // keeps our angles within 1 revolution // S = Sinit + (1/2) * (V + Vinit) * deltaT float x = player.pos.x() + 0.5 * (player.velocity + velocity_init) * elapsed * cos(player.yaw); float y = player.pos.y() + 0.5 * (player.velocity + velocity_init) * elapsed * sin(player.yaw); float z; // TODO: use this; player.pos.setX(x); player.pos.setY(y); } void Alpha::initializeGL() { glClearColor(0.4,0.6,1,0); // background: r,g,b,a setXRotation(130); setYRotation(0); setZRotation(0); } void Alpha::resizeGL(int width, int height) { glViewport(0, 0, width, height); // viewport: (startx,starty, width, height) const float aspectRatio = (float) height / (float) width; const float range = 100.0; // do not do anything with GL_PROJECTION besides set glOrtho glMatrixMode(GL_PROJECTION); // determines how the the world is viewed by the user glLoadIdentity(); // set the matrix to an unmodified state if (width <= height) { glOrtho( // clips everything drawn outside the params -range, // left range, // right -range * aspectRatio, // bottom range * aspectRatio, // top 2 * -range, // back 2 * range); // front } else { glOrtho( -range / aspectRatio, range / aspectRatio, -range, range, 2 * -range, 2 * range); } glMatrixMode(GL_MODELVIEW); // the world and where it is viewed from glLoadIdentity(); // set the matrix to an unmodified state } void Alpha::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clears the view glMatrixMode(GL_MODELVIEW); glLoadIdentity(); applyRotation(); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glEnable(GL_CULL_FACE); // draw the player's cube glRotatef(player.yaw * 180 / M_PI, 0, 0, 1); glRotatef(player.pitch * 180 /M_PI, 0,1,0); glBegin(GL_QUADS); { // TOP is BLACK glColor3f(0.0f,0.0f,0.0f); glVertex3f( 4.0f, 4.0f, 4.0f); // Top Right glVertex3f(-4.0f, 4.0f, 4.0f); // Top Left glVertex3f(-4.0f,-4.0f, 4.0f); // Bottom Left glVertex3f( 4.0f,-4.0f, 4.0f); // Bottom Right // BOTTOM is WHITE glColor3f(1.0f,1.0f,1.0f); glVertex3f(-4.0f, 4.0f, -4.0f); // Top Right glVertex3f( 4.0f, 4.0f, -4.0f); // Top Left glVertex3f( 4.0f,-4.0f, -4.0f); // Bottom Left glVertex3f(-4.0f,-4.0f, -4.0f); // Bottom Right // BACK is RED glColor3f(1.0f,0.0f,0.0f); glVertex3f(-4.0f,-4.0f, 4.0f); // Top Right glVertex3f(-4.0f, 4.0f, 4.0f); // Top Left glVertex3f(-4.0f, 4.0f,-4.0f); // Bottom Left glVertex3f(-4.0f,-4.0f,-4.0f); // Bottom Right // FRONT is GREEN glColor3f(0.0f,1.0f,0.0f); glVertex3f( 4.0f, 4.0f, 4.0f); // Top Right glVertex3f( 4.0f,-4.0f, 4.0f); // Top Left glVertex3f( 4.0f,-4.0f,-4.0f); // Bottom Left glVertex3f( 4.0f, 4.0f,-4.0f); // Bottom Right // LEFT is BLUE glColor3f(0.0f,0.0f,1.0f); glVertex3f(-4.0f, 4.0f, 4.0f); // Top Right glVertex3f( 4.0f, 4.0f, 4.0f); // Top Left glVertex3f( 4.0f, 4.0f,-4.0f); // Bottom Left glVertex3f(-4.0f, 4.0f,-4.0f); // Bottom Right // RIGHT is BLUE glVertex3f( 4.0f,-4.0f, 4.0f); // Top Right glVertex3f(-4.0f,-4.0f, 4.0f); // Top Left glVertex3f(-4.0f,-4.0f,-4.0f); // Bottom Left glVertex3f( 4.0f,-4.0f,-4.0f); // Bottom Right } glEnd(); // draw the ground glPushMatrix(); { glTranslatef(player.pos.x(), player.pos.y(), player.pos.z()); // move the world, not the camera glBegin(GL_QUADS); { glColor3f(0.1f, 0.65f, 0.1f); // XXX: This is all backwards glVertex3f(-80.0f, 80.0f, 0.0f); // Top Left glVertex3f( 80.0f, 80.0f, 0.0f); // Top Right glVertex3f( 80.0f,-80.0f, 0.0f); // Bottom Right glVertex3f(-80.0f,-80.0f, 0.0f); // Bottom Left } glEnd(); } glPopMatrix(); } void Alpha::keyPressEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_W: pad.forward = true; break; case Qt::Key_S: pad.backward = true; break; case Qt::Key_A: pad.yawleft = true; break; case Qt::Key_D: pad.yawright = true; break; case Qt::Key_Space: pad.up = true; break; case Qt::Key_X: pad.down = true; break; case Qt::Key_Q: pad.pitchup = true; break; case Qt::Key_E: pad.pitchdown = true; break; default: // TODO: have frito explain where the esc key is bound to close() QGLWidget::keyPressEvent(event); } } void Alpha::keyReleaseEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_W: pad.forward = false; break; case Qt::Key_S: pad.backward = false; break; case Qt::Key_A: pad.yawleft = false; break; case Qt::Key_D: pad.yawright = false; break; case Qt::Key_Space: pad.up = false; break; case Qt::Key_X: pad.down = false; break; case Qt::Key_Q: pad.pitchup = false; break; case Qt::Key_E: pad.pitchdown = false; break; default: QGLWidget::keyPressEvent(event); } } void Alpha::mousePressEvent(QMouseEvent *event) { lastPos = event->pos(); } /** * Interpret the mouse event to rotate the camera around the scene. */ void Alpha::mouseMoveEvent(QMouseEvent *event) { int dx = event->x() - lastPos.x(); int dy = event->y() - lastPos.y(); if (event->buttons() & Qt::LeftButton) { setScaledXRotation(xRot + dy * Alpha::ROTATION_SCALE / 2); setScaledYRotation(yRot + dx * Alpha::ROTATION_SCALE / 2); } else if (event->buttons() & Qt::RightButton) { setScaledXRotation(xRot + dy * Alpha::ROTATION_SCALE / 2); setScaledZRotation(zRot + dx * Alpha::ROTATION_SCALE / 2); } lastPos = event->pos(); } void Alpha::setScaledXRotation(int angle) { qNormalizeAngle(angle); if (angle != xRot) { xRot = angle; emit xRotationChanged(angle); updateGL(); } } void Alpha::setScaledYRotation(int angle) { qNormalizeAngle(angle); if (angle != yRot) { yRot = angle; emit yRotationChanged(angle); updateGL(); } } void Alpha::setScaledZRotation(int angle) { qNormalizeAngle(angle); if (angle != zRot) { zRot = angle; emit zRotationChanged(angle); updateGL(); } } void Alpha::applyRotation() const { static const float ROTATION_DENOM = 1 / (float)Alpha::ROTATION_SCALE; glRotatef((float)(xRot) * ROTATION_DENOM, 1.0, 0.0, 0.0); glRotatef((float)(yRot) * ROTATION_DENOM, 0.0, 1.0, 0.0); glRotatef((float)(zRot) * ROTATION_DENOM, 0.0, 0.0, 1.0); } <|endoftext|>
<commit_before>#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("bitcoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } } <commit_msg>qr code fix<commit_after>#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("myriadcoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } } <|endoftext|>
<commit_before>#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QtQml/qqml.h> #include <QColor> #include <QPalette> #include "models/DialogsModel.hpp" #include "models/MessagesModel.hpp" #ifdef QT_WIDGETS_LIB #include <QApplication> #endif #include <QDebug> class Theme : public QObject { Q_OBJECT Q_PROPERTY(qreal horizontalPageMargin MEMBER m_horizontalPageMargin CONSTANT) Q_PROPERTY(qreal paddingLarge MEMBER m_paddingLarge CONSTANT) Q_PROPERTY(qreal paddingMedium MEMBER m_paddingMedium CONSTANT) Q_PROPERTY(qreal paddingSmall MEMBER m_paddingSmall CONSTANT) Q_PROPERTY(int fontSizeTiny MEMBER m_fontSizeTiny CONSTANT) Q_PROPERTY(int fontSizeExtraSmall MEMBER m_fontSizeExtraSmall CONSTANT) Q_PROPERTY(int fontSizeSmall MEMBER m_fontSizeSmall CONSTANT) Q_PROPERTY(int fontSizeMedium MEMBER m_fontSizeMedium CONSTANT) Q_PROPERTY(int fontSizeLarge MEMBER m_fontSizeLarge CONSTANT) Q_PROPERTY(QColor primaryColor MEMBER m_primaryColor CONSTANT) Q_PROPERTY(QColor secondaryColor MEMBER m_secondaryColor CONSTANT) Q_PROPERTY(QColor backgroundColor MEMBER m_backgroundColor CONSTANT) Q_PROPERTY(QColor highlightColor MEMBER m_highlightColor CONSTANT) Q_PROPERTY(QColor highlightBackgroundColor MEMBER m_highlightBackgroundColor CONSTANT) Q_PROPERTY(QColor highlightDimmerColor MEMBER m_highlightDimmerColor CONSTANT) Q_PROPERTY(qreal itemSizeExtraSmall MEMBER m_itemSizeExtraSmall CONSTANT) Q_PROPERTY(qreal itemSizeSmall MEMBER m_itemSizeSmall CONSTANT) Q_PROPERTY(qreal itemSizeMedium MEMBER m_itemSizeMedium CONSTANT) Q_PROPERTY(qreal itemSizeLarge MEMBER m_itemSizeLarge CONSTANT) Q_PROPERTY(qreal itemSizeExtraLarge MEMBER m_itemSizeExtraLarge CONSTANT) Q_PROPERTY(qreal iconSizeSmall MEMBER m_iconSizeSmall CONSTANT) Q_PROPERTY(qreal buttonWidthSmall MEMBER m_buttonWidthSmall CONSTANT) Q_PROPERTY(qreal buttonWidthMedium MEMBER m_buttonWidthMedium CONSTANT) Q_PROPERTY(int longDuration MEMBER m_longDuration CONSTANT) public: explicit Theme(QObject *parent = nullptr) : QObject(parent), m_fontSizeTiny(20), m_fontSizeExtraSmall(24), m_fontSizeSmall(28), m_fontSizeMedium(32), m_fontSizeLarge(40), m_fontSizeExtraLarge(50), m_fontSizeHuge(64), m_fontSizeTinyBase(20), m_fontSizeExtraSmallBase(24), m_fontSizeSmallBase(28), m_fontSizeMediumBase(32), m_fontSizeLargeBase(40), m_fontSizeExtraLargeBase(50), m_fontSizeHugeBase(64), m_itemSizeExtraSmall(70), m_itemSizeSmall(80), m_itemSizeMedium(100), m_itemSizeLarge(110), m_itemSizeExtraLarge(135), m_itemSizeHuge(180), m_iconSizeExtraSmall(24), m_iconSizeSmall(32), m_iconSizeSmallPlus(48), m_iconSizeMedium(64), m_iconSizeLarge(96), m_iconSizeExtraLarge(128), m_iconSizeLauncher(86), m_buttonWidthSmall(234), m_buttonWidthMedium(292), m_buttonWidthLarge(444), m_coverSizeSmall(148, 237), m_coverSizeLarge(234, 374), m_paddingSmall(6), m_paddingMedium(12), m_paddingLarge(24), m_horizontalPageMargin(m_paddingLarge), m_flickDeceleration(1500), m_maximumFlickVelocity(5000), m_pageStackIndicatorWidth(37), m_highlightBackgroundOpacity(0.3), m_longDuration(800) { const QPalette pal = QGuiApplication::palette(); // const QMetaEnum colorEnum = QMetaEnum::fromType<QPalette::ColorRole>(); // for (int i = 0; i < colorEnum.keyCount(); ++i) { // qDebug() << colorEnum.key(i) << pal.color((QPalette::ColorRole)colorEnum.value(i)).name(); // } m_highlightColor = pal.color(QPalette::Highlight); m_highlightDimmerColor = QStringLiteral("#bdc3c7"); m_backgroundColor = pal.color(QPalette::AlternateBase); m_highlightBackgroundColor = pal.color(QPalette::Highlight); } QString m_fontFamilyHeading; QString m_fontFamily; QStringList m_launcherIconDirectories; int m_fontSizeTiny; int m_fontSizeExtraSmall; int m_fontSizeSmall; int m_fontSizeMedium; int m_fontSizeLarge; int m_fontSizeExtraLarge; int m_fontSizeHuge; int m_fontSizeTinyBase; int m_fontSizeExtraSmallBase; int m_fontSizeSmallBase; int m_fontSizeMediumBase; int m_fontSizeLargeBase; int m_fontSizeExtraLargeBase; int m_fontSizeHugeBase; qreal m_itemSizeExtraSmall; qreal m_itemSizeSmall; qreal m_itemSizeMedium; qreal m_itemSizeLarge; qreal m_itemSizeExtraLarge; qreal m_itemSizeHuge; qreal m_iconSizeExtraSmall; qreal m_iconSizeSmall; qreal m_iconSizeSmallPlus; qreal m_iconSizeMedium; qreal m_iconSizeLarge; qreal m_iconSizeExtraLarge; qreal m_iconSizeLauncher; qreal m_buttonWidthSmall; qreal m_buttonWidthMedium; qreal m_buttonWidthLarge; QSize m_coverSizeSmall; QSize m_coverSizeLarge; qreal m_paddingSmall; qreal m_paddingMedium; qreal m_paddingLarge; qreal m_horizontalPageMargin; qreal m_flickDeceleration; qreal m_maximumFlickVelocity; float m_pageStackIndicatorWidth; float m_highlightBackgroundOpacity; qreal m_pixelRatio; qreal m_webviewCustomLayoutWidthScalingFactor; int m_minimumPressHighlightTime; QColor m_highlightColor; QColor m_primaryColor; QColor m_secondaryColor; QColor m_secondaryHighlightColor; QColor m_backgroundColor; QColor m_highlightBackgroundColor; QColor m_highlightDimmerColor; int m_longDuration; }; // Second, define the singleton type provider function (callback). static QObject *theme_type_provider(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) Theme *theme = new Theme(); return theme; } #include <QQuickStyle> int main(int argc, char *argv[]) { QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); app.setApplicationName("TelegramQt"); app.setApplicationVersion(QStringLiteral("0.2")); QQuickStyle::setStyle("Material"); qmlRegisterType<Telegram::Client::DialogsModel>("Client", 1, 0, "DialogsModel"); qmlRegisterType<Telegram::Client::MessagesModel>("Client", 1, 0, "MessagesModel"); qmlRegisterUncreatableType<Telegram::Client::Event>("Client", 1, 0, "Event", QStringLiteral("Event can be created only from C++")); QQmlApplicationEngine engine; qmlRegisterSingletonType<Theme>("TelegramQtTheme", 1, 0, "Theme", theme_type_provider); engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); return app.exec(); } #include "main.moc" <commit_msg>QmlClient: Print a comprehensive message on startup failed<commit_after>#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QtQml/qqml.h> #include <QColor> #include <QPalette> #include "models/DialogsModel.hpp" #include "models/MessagesModel.hpp" #ifdef QT_WIDGETS_LIB #include <QApplication> #endif #include <QDebug> class Theme : public QObject { Q_OBJECT Q_PROPERTY(qreal horizontalPageMargin MEMBER m_horizontalPageMargin CONSTANT) Q_PROPERTY(qreal paddingLarge MEMBER m_paddingLarge CONSTANT) Q_PROPERTY(qreal paddingMedium MEMBER m_paddingMedium CONSTANT) Q_PROPERTY(qreal paddingSmall MEMBER m_paddingSmall CONSTANT) Q_PROPERTY(int fontSizeTiny MEMBER m_fontSizeTiny CONSTANT) Q_PROPERTY(int fontSizeExtraSmall MEMBER m_fontSizeExtraSmall CONSTANT) Q_PROPERTY(int fontSizeSmall MEMBER m_fontSizeSmall CONSTANT) Q_PROPERTY(int fontSizeMedium MEMBER m_fontSizeMedium CONSTANT) Q_PROPERTY(int fontSizeLarge MEMBER m_fontSizeLarge CONSTANT) Q_PROPERTY(QColor primaryColor MEMBER m_primaryColor CONSTANT) Q_PROPERTY(QColor secondaryColor MEMBER m_secondaryColor CONSTANT) Q_PROPERTY(QColor backgroundColor MEMBER m_backgroundColor CONSTANT) Q_PROPERTY(QColor highlightColor MEMBER m_highlightColor CONSTANT) Q_PROPERTY(QColor highlightBackgroundColor MEMBER m_highlightBackgroundColor CONSTANT) Q_PROPERTY(QColor highlightDimmerColor MEMBER m_highlightDimmerColor CONSTANT) Q_PROPERTY(qreal itemSizeExtraSmall MEMBER m_itemSizeExtraSmall CONSTANT) Q_PROPERTY(qreal itemSizeSmall MEMBER m_itemSizeSmall CONSTANT) Q_PROPERTY(qreal itemSizeMedium MEMBER m_itemSizeMedium CONSTANT) Q_PROPERTY(qreal itemSizeLarge MEMBER m_itemSizeLarge CONSTANT) Q_PROPERTY(qreal itemSizeExtraLarge MEMBER m_itemSizeExtraLarge CONSTANT) Q_PROPERTY(qreal iconSizeSmall MEMBER m_iconSizeSmall CONSTANT) Q_PROPERTY(qreal buttonWidthSmall MEMBER m_buttonWidthSmall CONSTANT) Q_PROPERTY(qreal buttonWidthMedium MEMBER m_buttonWidthMedium CONSTANT) Q_PROPERTY(int longDuration MEMBER m_longDuration CONSTANT) public: explicit Theme(QObject *parent = nullptr) : QObject(parent), m_fontSizeTiny(20), m_fontSizeExtraSmall(24), m_fontSizeSmall(28), m_fontSizeMedium(32), m_fontSizeLarge(40), m_fontSizeExtraLarge(50), m_fontSizeHuge(64), m_fontSizeTinyBase(20), m_fontSizeExtraSmallBase(24), m_fontSizeSmallBase(28), m_fontSizeMediumBase(32), m_fontSizeLargeBase(40), m_fontSizeExtraLargeBase(50), m_fontSizeHugeBase(64), m_itemSizeExtraSmall(70), m_itemSizeSmall(80), m_itemSizeMedium(100), m_itemSizeLarge(110), m_itemSizeExtraLarge(135), m_itemSizeHuge(180), m_iconSizeExtraSmall(24), m_iconSizeSmall(32), m_iconSizeSmallPlus(48), m_iconSizeMedium(64), m_iconSizeLarge(96), m_iconSizeExtraLarge(128), m_iconSizeLauncher(86), m_buttonWidthSmall(234), m_buttonWidthMedium(292), m_buttonWidthLarge(444), m_coverSizeSmall(148, 237), m_coverSizeLarge(234, 374), m_paddingSmall(6), m_paddingMedium(12), m_paddingLarge(24), m_horizontalPageMargin(m_paddingLarge), m_flickDeceleration(1500), m_maximumFlickVelocity(5000), m_pageStackIndicatorWidth(37), m_highlightBackgroundOpacity(0.3), m_longDuration(800) { const QPalette pal = QGuiApplication::palette(); // const QMetaEnum colorEnum = QMetaEnum::fromType<QPalette::ColorRole>(); // for (int i = 0; i < colorEnum.keyCount(); ++i) { // qDebug() << colorEnum.key(i) << pal.color((QPalette::ColorRole)colorEnum.value(i)).name(); // } m_highlightColor = pal.color(QPalette::Highlight); m_highlightDimmerColor = QStringLiteral("#bdc3c7"); m_backgroundColor = pal.color(QPalette::AlternateBase); m_highlightBackgroundColor = pal.color(QPalette::Highlight); } QString m_fontFamilyHeading; QString m_fontFamily; QStringList m_launcherIconDirectories; int m_fontSizeTiny; int m_fontSizeExtraSmall; int m_fontSizeSmall; int m_fontSizeMedium; int m_fontSizeLarge; int m_fontSizeExtraLarge; int m_fontSizeHuge; int m_fontSizeTinyBase; int m_fontSizeExtraSmallBase; int m_fontSizeSmallBase; int m_fontSizeMediumBase; int m_fontSizeLargeBase; int m_fontSizeExtraLargeBase; int m_fontSizeHugeBase; qreal m_itemSizeExtraSmall; qreal m_itemSizeSmall; qreal m_itemSizeMedium; qreal m_itemSizeLarge; qreal m_itemSizeExtraLarge; qreal m_itemSizeHuge; qreal m_iconSizeExtraSmall; qreal m_iconSizeSmall; qreal m_iconSizeSmallPlus; qreal m_iconSizeMedium; qreal m_iconSizeLarge; qreal m_iconSizeExtraLarge; qreal m_iconSizeLauncher; qreal m_buttonWidthSmall; qreal m_buttonWidthMedium; qreal m_buttonWidthLarge; QSize m_coverSizeSmall; QSize m_coverSizeLarge; qreal m_paddingSmall; qreal m_paddingMedium; qreal m_paddingLarge; qreal m_horizontalPageMargin; qreal m_flickDeceleration; qreal m_maximumFlickVelocity; float m_pageStackIndicatorWidth; float m_highlightBackgroundOpacity; qreal m_pixelRatio; qreal m_webviewCustomLayoutWidthScalingFactor; int m_minimumPressHighlightTime; QColor m_highlightColor; QColor m_primaryColor; QColor m_secondaryColor; QColor m_secondaryHighlightColor; QColor m_backgroundColor; QColor m_highlightBackgroundColor; QColor m_highlightDimmerColor; int m_longDuration; }; // Second, define the singleton type provider function (callback). static QObject *theme_type_provider(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) Theme *theme = new Theme(); return theme; } #include <QQuickStyle> int main(int argc, char *argv[]) { QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); app.setApplicationName("TelegramQt"); app.setApplicationVersion(QStringLiteral("0.2")); QQuickStyle::setStyle("Material"); qmlRegisterType<Telegram::Client::DialogsModel>("Client", 1, 0, "DialogsModel"); qmlRegisterType<Telegram::Client::MessagesModel>("Client", 1, 0, "MessagesModel"); qmlRegisterUncreatableType<Telegram::Client::Event>("Client", 1, 0, "Event", QStringLiteral("Event can be created only from C++")); QQmlApplicationEngine engine; QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, [](QObject *object) { if (object) { return; } qCritical() << "Unable to instantiate the root component."; qCritical() << "Ensure that the application is installed correctly and double check" " that QML2_IMPORT_PATH environment variable is set to the correct" " installation directory with TelegramQt inside."; qCritical() << "If you built the project from CMake then ensure that you did\n" " cmake --build <your_build_directory> --target install\n" "and also follow the hint about QML2_IMPORT_PATH from CMake" " configure output."; exit(1); }); qmlRegisterSingletonType<Theme>("TelegramQtTheme", 1, 0, "Theme", theme_type_provider); engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); return app.exec(); } #include "main.moc" <|endoftext|>
<commit_before>#include <list> #include <iostream> #include <algorithm> using namespace std; const char * ones[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char * ten_scale[] = { "N/A", "N/A", // 0, 10 "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; const char * thousand_scale[] = { "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", /* "sextillion" */ }; const char * hundred = "hundred"; const char * negative = "negative"; const char * comma = ","; const char * space = " "; const char * and = "and"; const char * dash = "-"; typedef list<const char*> num_list_t; void engnum_99(int64_t n, num_list_t & num_list) { if (n < 20) { num_list.push_back(ones[n]); } else { num_list.push_back(ten_scale[n / 10]); if (n % 10 > 0) { num_list.push_back(dash); num_list.push_back(ones[n % 10]); } } } void engnum_999(int64_t n, num_list_t & num_list) { if (n >= 100) { num_list.push_back(ones[n / 100]); num_list.push_back(space); num_list.push_back(hundred); if (n % 100 > 0) { num_list.push_back(space); num_list.push_back(and); num_list.push_back(space); } } if (n % 100 > 0) { engnum_99(n % 100, num_list); } } void engnum(int64_t n, num_list_t & num_list) { if (n == 0) { num_list.push_back(ones[0]); return; } int bias_one = 0; if (n < 0) { num_list.push_back(negative); num_list.push_back(space); // INT64_MIN is not addressable by the positive number. if (n == INT64_MIN) { bias_one = 1; n = -(n + 1); } else { n = -n; } } bool first = true; for (int i = _countof(thousand_scale) - 1; i >= 0; --i) { int64_t scale = pow(1000, i + 1); int64_t hundreds = n / scale; n %= scale; if (hundreds > 0) { if (!first) { num_list.push_back(space); } engnum_999(hundreds, num_list); num_list.push_back(space); num_list.push_back(thousand_scale[i]); if (n > 0) { num_list.push_back(comma); } first = false; } } if (n > 0) { if (!first) { num_list.push_back(space); } engnum_999(n + bias_one, num_list); } } string engnum(int64_t n) { string numstr; num_list_t nums; engnum(n, nums); for_each(nums.begin(), nums.end(), [&numstr] (const char * s) { numstr += s; }); return numstr; } void print_engnum(int64_t n) { cout << n << " \"" << engnum(n).c_str() << "\"" << endl; } int main(int argc, char** argv) { cout.imbue(locale("en-US")); if (argc > 1) { int64_t lower = atoll(argv[1]); int count = 1; if (argc > 2) { count = atoi(argv[2]); } for (int64_t i = 0; i < count; ++i) { print_engnum(lower + i); } } else { print_engnum(INT64_MAX); print_engnum(INT64_MIN); print_engnum(UINT64_MAX); print_engnum(INT32_MAX); print_engnum(INT32_MIN); print_engnum(UINT32_MAX); print_engnum(INT16_MAX); print_engnum(INT16_MIN); print_engnum(UINT16_MAX); } } <commit_msg>use stringstream<commit_after>#include <list> #include <iostream> #include <sstream> #include <algorithm> using namespace std; const char * ones[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char * ten_scale[] = { "N/A", "N/A", // 0, 10 "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; const char * thousand_scale[] = { "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", /* "sextillion" */ }; const char * hundred = "hundred"; const char * negative = "negative"; const char * comma = ","; const char * space = " "; const char * and = "and"; const char * dash = "-"; typedef list<const char*> num_list_t; void engnum_99(int64_t n, stringstream & s) { if (n < 20) { s << ones[n]; } else { s << ten_scale[n / 10]; if (n % 10 > 0) { s << dash << ones[n % 10]; } } } void engnum_999(int64_t n, stringstream & s) { if (n >= 100) { s << ones[n / 100] << space << hundred; if (n % 100 > 0) { s << space << and << space; } } if (n % 100 > 0) { engnum_99(n % 100, s); } } void engnum(int64_t n, stringstream & s) { if (n == 0) { s << ones[0]; return; } int bias_one = 0; if (n < 0) { s << negative << space; // INT64_MIN is not addressable by the positive number. if (n == INT64_MIN) { bias_one = 1; n = -(n + 1); } else { n = -n; } } bool first = true; for (int i = _countof(thousand_scale) - 1; i >= 0; --i) { int64_t scale = pow(1000, i + 1); int64_t hundreds = n / scale; n %= scale; if (hundreds > 0) { if (!first) { s << space; } engnum_999(hundreds, s); s << space << thousand_scale[i]; if (n > 0) { s << comma; } first = false; } } if (n > 0) { if (!first) { s << space; } engnum_999(n + bias_one, s); } } string engnum(int64_t n) { stringstream ss; engnum(n, ss); return ss.str(); } void print_engnum(int64_t n) { cout << n << " \"" << engnum(n).c_str() << "\"" << endl; } int main(int argc, char** argv) { cout.imbue(locale("en-US")); if (argc > 1) { int64_t lower = atoll(argv[1]); int count = 1; if (argc > 2) { count = atoi(argv[2]); } for (int64_t i = 0; i < count; ++i) { print_engnum(lower + i); } } else { print_engnum(INT64_MAX); print_engnum(INT64_MIN); print_engnum(UINT64_MAX); print_engnum(INT32_MAX); print_engnum(INT32_MIN); print_engnum(UINT32_MAX); print_engnum(INT16_MAX); print_engnum(INT16_MIN); print_engnum(UINT16_MAX); } } <|endoftext|>
<commit_before>/* Copyright (c) 2014, Dilyan Rusev All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the {organization} nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "stdafx.h" #ifdef WIN32 #include "Game.h" #include"Board.h" #include <cassert> #include <algorithm> using namespace std; using Microsoft::WRL::ComPtr; struct Game::Impl { Impl(); ~Impl(); void CreateAppWindow(); void InitGraphicsSystems(); void RunMainLoop(); void Initialize(); static LRESULT CALLBACK GameProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam); LRESULT OnDestroy(); LRESULT OnClose(); LRESULT OnPaint(); LRESULT OnKeyDown(int vk); LRESULT OnKeyUp(int vk); void Update(float ms); void Render(); void CreateDeviceResources(); void CleanDeviceResources(); ComPtr<ID2D1Bitmap> LoadImage(const wchar_t* fileName) const; const wchar_t* APP_TITLE; const wchar_t* APP_CLASS; const int WINDOW_WIDTH; const int WINDOW_HEIGHT; const int BLOCK_WIDTH; const int BLOCK_HEIGHT; RECT m_clientRect; bool m_isClassRegistered; HWND m_window; HINSTANCE m_instance; LARGE_INTEGER m_perfFrequency; Board m_board; D2D1_POINT_2F m_boardPos; ComPtr<ID2D1Factory> m_drawFactory; ComPtr<IDWriteFactory> m_writeFactory; ComPtr<IWICImagingFactory> m_imageFactory; ComPtr<ID2D1HwndRenderTarget> m_renderTarget; ComPtr<ID2D1Brush> m_testBrush; ComPtr<ID2D1Bitmap> m_terimonoBitmaps[Count_Tetrimonos]; }; Game::Impl::Impl() : APP_TITLE(L"Falling Blocks") , APP_CLASS(L"FallingBlocks") , WINDOW_WIDTH(1280) , WINDOW_HEIGHT(720) , BLOCK_WIDTH(35) , BLOCK_HEIGHT(35) , m_isClassRegistered(false) , m_window(nullptr) , m_instance(nullptr) { } Game::Impl::~Impl() { if (m_isClassRegistered && m_instance) { ::UnregisterClass(APP_CLASS, m_instance); } } Game::Game() : m_impl(new Impl()) { } Game::~Game() { } void Game::Initialize() { m_impl->Initialize(); } void Game::Impl::Initialize() { m_instance = static_cast<HINSTANCE>(::GetModuleHandle(nullptr)); assert(::QueryPerformanceFrequency(&m_perfFrequency)); CreateAppWindow(); InitGraphicsSystems(); CreateDeviceResources(); } void Game::Impl::InitGraphicsSystems() { HRESULT hr = ::CoCreateInstance(CLSID_WICImagingFactory1, nullptr, CLSCTX_INPROC_SERVER, __uuidof(m_imageFactory), reinterpret_cast<void**>(m_imageFactory.GetAddressOf())); assert(SUCCEEDED(hr)); hr = ::DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(m_writeFactory), reinterpret_cast<IUnknown**>(m_writeFactory.GetAddressOf())); assert(SUCCEEDED(hr)); hr = ::D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, IID_PPV_ARGS(&m_drawFactory)); assert(SUCCEEDED(hr)); } void Game::Impl::CreateAppWindow() { assert(m_instance != nullptr); WNDCLASSEX wc; wc.cbSize = sizeof(wc); wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = nullptr; wc.hCursor = ::LoadCursor(nullptr, IDC_ARROW); wc.hIcon = ::LoadIcon(nullptr, IDI_APPLICATION); wc.hIconSm = ::LoadIcon(nullptr, IDI_APPLICATION); wc.hInstance = m_instance; wc.lpfnWndProc = &GameProc; wc.lpszClassName = APP_CLASS; wc.lpszMenuName = nullptr; wc.style = 0; assert(::RegisterClassEx(&wc)); m_isClassRegistered = true; DWORD windowStyle = WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU; DWORD exStyle = 0; RECT windowSize = { 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT }; assert(::AdjustWindowRectEx(&windowSize, windowStyle, FALSE, exStyle)); int width = windowSize.right - windowSize.left; int height = windowSize.bottom - windowSize.top; int x = (::GetSystemMetrics(SM_CXSCREEN) - width) / 2; int y = (::GetSystemMetrics(SM_CYSCREEN) - height) / 2; m_window = ::CreateWindowExW(exStyle, APP_CLASS, APP_TITLE, windowStyle, x, y, width, height, HWND_DESKTOP, nullptr, m_instance, reinterpret_cast<void*>(this)); assert(m_window != nullptr); m_clientRect.left = 0; m_clientRect.right = WINDOW_WIDTH; m_clientRect.top = 0; m_clientRect.bottom = WINDOW_HEIGHT; m_boardPos.x = (WINDOW_WIDTH - m_board.WIDTH * BLOCK_WIDTH) / 2.0f; m_boardPos.y = (WINDOW_HEIGHT - m_board.HEIGHT * BLOCK_HEIGHT) / 2.0f; } void Game::RunMainLoop() { m_impl->RunMainLoop(); } void Game::Impl::RunMainLoop() { assert(m_instance); assert(m_window); ::ShowWindow(m_window, SW_SHOW); ::UpdateWindow(m_window); MSG msg; msg.message = WM_NULL; LARGE_INTEGER before, now; float elapsedInMs; ::QueryPerformanceCounter(&before); while (msg.message != WM_QUIT) { while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::QueryPerformanceCounter(&now); elapsedInMs = static_cast<float>((now.QuadPart - before.QuadPart) * 1000 / m_perfFrequency.QuadPart); Update(elapsedInMs); Render(); before = now; } } void Game::Impl::Update(float ms) { m_board.Update(ms); } void Game::Impl::Render() { m_renderTarget->BeginDraw(); m_renderTarget->Clear(D2D1::ColorF(D2D1::ColorF::AliceBlue)); D2D1_RECT_F dest; for (int y = 0; y < m_board.HEIGHT; y++) { for (int x = 0; x < m_board.WIDTH; x++) { auto t = m_board.GetAt(x, y); auto& bitmap = m_terimonoBitmaps[t]; dest.left = m_boardPos.x + static_cast<float>(x * BLOCK_WIDTH); dest.top = m_boardPos.y + static_cast<float>(y * BLOCK_HEIGHT); dest.right = dest.left + BLOCK_WIDTH; dest.bottom = dest.top + BLOCK_HEIGHT; m_renderTarget->DrawBitmap(bitmap.Get(), &dest, 1.0f, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR); } } D2D1_POINT_2F nextOffset = D2D1::Point2F(m_boardPos.x + m_board.WIDTH * BLOCK_WIDTH + 30, m_boardPos.y); for (int y = 0; y < m_board.MAX_TETRIMONO_HEIGHT; y++) { for (int x = 0; x < m_board.MAX_TETRIMONO_WIDTH; x++) { auto t = m_board.GetNextAt(x, y); auto& bitmap = m_terimonoBitmaps[t]; dest.left = nextOffset.x + static_cast<float>(x * BLOCK_WIDTH); dest.top = nextOffset.y + static_cast<float>(y * BLOCK_HEIGHT); dest.right = dest.left + BLOCK_WIDTH; dest.bottom = dest.top + BLOCK_HEIGHT; m_renderTarget->DrawBitmap(bitmap.Get(), &dest, 1.0f, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR); } } if (m_renderTarget->EndDraw() == D2DERR_RECREATE_TARGET) { CleanDeviceResources(); CreateDeviceResources(); } } void Game::Impl::CreateDeviceResources() { HRESULT hr; hr = m_drawFactory->CreateHwndRenderTarget( D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(), 96.0f, 96.0f), D2D1::HwndRenderTargetProperties(m_window, D2D1::SizeU(WINDOW_WIDTH, WINDOW_HEIGHT)), m_renderTarget.ReleaseAndGetAddressOf()); assert(SUCCEEDED(hr)); Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> solidBrush; assert(SUCCEEDED( m_renderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &solidBrush) )); solidBrush.As(&m_testBrush); m_terimonoBitmaps[Tetrimono_Empty] = LoadImage(L"Assets/block_empty.png"); m_terimonoBitmaps[Tetrimono_I] = LoadImage(L"Assets/block_blue.png"); m_terimonoBitmaps[Tetrimono_J] = LoadImage(L"Assets/block_cyan.png"); m_terimonoBitmaps[Tetrimono_L] = LoadImage(L"Assets/block_green.png"); m_terimonoBitmaps[Tetrimono_O] = LoadImage(L"Assets/block_orange.png"); m_terimonoBitmaps[Tetrimono_S] = LoadImage(L"Assets/block_red.png"); m_terimonoBitmaps[Tetrimono_T] = LoadImage(L"Assets/block_violet.png"); m_terimonoBitmaps[Tetrimono_Z] = LoadImage(L"Assets/block_yellow.png"); } ComPtr<ID2D1Bitmap> Game::Impl::LoadImage(const wchar_t* fileName) const { ComPtr<IWICBitmapDecoder> decoder; assert(SUCCEEDED( m_imageFactory->CreateDecoderFromFilename(fileName, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &decoder) )); ComPtr<IWICBitmapFrameDecode> frame; assert(SUCCEEDED( decoder->GetFrame(0, &frame) )); ComPtr<IWICFormatConverter> formatConverter; assert(SUCCEEDED( m_imageFactory->CreateFormatConverter(&formatConverter) )); assert(SUCCEEDED( formatConverter->Initialize(frame.Get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0.0f, WICBitmapPaletteTypeCustom) )); ComPtr<ID2D1Bitmap> bitmap; assert(SUCCEEDED( m_renderTarget->CreateBitmapFromWicBitmap(formatConverter.Get(), &bitmap) )); return bitmap; } void Game::Impl::CleanDeviceResources() { m_testBrush = nullptr; m_renderTarget = nullptr; } LRESULT Game::Impl::GameProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_CREATE) { CREATESTRUCT* createData = reinterpret_cast<CREATESTRUCT*>(lparam); Game* game = reinterpret_cast<Game*>(createData->lpCreateParams); ::SetWindowLongPtr(window, GWLP_USERDATA, #ifdef _WIN64 reinterpret_cast<LONG_PTR>(game) #else reinterpret_cast<LONG>(game) #endif ); return 0; } else { Game* game = reinterpret_cast<Game*>(::GetWindowLongPtr(window, GWLP_USERDATA)); std::unique_ptr<Game::Impl>& impl = game->m_impl; switch (message) { case WM_PAINT: return impl->OnPaint(); case WM_CLOSE: return impl->OnClose(); case WM_DESTROY: return impl->OnDestroy(); case WM_KEYDOWN: return impl->OnKeyDown(static_cast<int>(wparam)); case WM_KEYUP: return impl->OnKeyUp(static_cast<int>(wparam)); default: return ::DefWindowProc(window, message, wparam, lparam); } } } LRESULT Game::Impl::OnKeyDown(int vk) { switch (vk) { case VK_LEFT: m_board.MoveCurrent(-1, 0); break; case VK_RIGHT: m_board.MoveCurrent(1, 0); break; case VK_UP: m_board.RotateAntiClockwize(); break; case VK_DOWN: m_board.RotateClockwize(); break; case VK_SPACE: m_board.FallDown(); break; case VK_ESCAPE: ::PostQuitMessage(0); break; } return 0; } LRESULT Game::Impl::OnKeyUp(int vk) { UNREFERENCED_PARAMETER(vk); return 0; } LRESULT Game::Impl::OnDestroy() { ::PostQuitMessage(0); return 0; } LRESULT Game::Impl::OnClose() { ::DestroyWindow(m_window); return 0; } LRESULT Game::Impl::OnPaint() { ::ValidateRect(m_window, &m_clientRect); return 0; } #endif<commit_msg>fix windows bug (passing Impl instead of Game)<commit_after>/* Copyright (c) 2014, Dilyan Rusev All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the {organization} nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "stdafx.h" #ifdef WIN32 #include "Game.h" #include"Board.h" #include <cassert> #include <algorithm> using namespace std; using Microsoft::WRL::ComPtr; struct Game::Impl { Impl(Game* parent); ~Impl(); void CreateAppWindow(); void InitGraphicsSystems(); void RunMainLoop(); void Initialize(); static LRESULT CALLBACK GameProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam); LRESULT OnDestroy(); LRESULT OnClose(); LRESULT OnPaint(); LRESULT OnKeyDown(int vk); LRESULT OnKeyUp(int vk); void Update(float ms); void Render(); void CreateDeviceResources(); void CleanDeviceResources(); ComPtr<ID2D1Bitmap> LoadImage(const wchar_t* fileName) const; const wchar_t* APP_TITLE; const wchar_t* APP_CLASS; const int WINDOW_WIDTH; const int WINDOW_HEIGHT; const int BLOCK_WIDTH; const int BLOCK_HEIGHT; Game* m_parent; RECT m_clientRect; bool m_isClassRegistered; HWND m_window; HINSTANCE m_instance; LARGE_INTEGER m_perfFrequency; Board m_board; D2D1_POINT_2F m_boardPos; ComPtr<ID2D1Factory> m_drawFactory; ComPtr<IDWriteFactory> m_writeFactory; ComPtr<IWICImagingFactory> m_imageFactory; ComPtr<ID2D1HwndRenderTarget> m_renderTarget; ComPtr<ID2D1Brush> m_testBrush; ComPtr<ID2D1Bitmap> m_terimonoBitmaps[Count_Tetrimonos]; }; Game::Impl::Impl(Game* parent) : APP_TITLE(L"Falling Blocks") , APP_CLASS(L"FallingBlocks") , WINDOW_WIDTH(1280) , WINDOW_HEIGHT(720) , BLOCK_WIDTH(35) , BLOCK_HEIGHT(35) , m_parent(parent) , m_isClassRegistered(false) , m_window(nullptr) , m_instance(nullptr) { } Game::Impl::~Impl() { if (m_isClassRegistered && m_instance) { ::UnregisterClass(APP_CLASS, m_instance); } } Game::Game() : m_impl(new Impl(this)) { } Game::~Game() { } void Game::Initialize() { m_impl->Initialize(); } void Game::Impl::Initialize() { m_instance = static_cast<HINSTANCE>(::GetModuleHandle(nullptr)); assert(::QueryPerformanceFrequency(&m_perfFrequency)); CreateAppWindow(); InitGraphicsSystems(); CreateDeviceResources(); } void Game::Impl::InitGraphicsSystems() { HRESULT hr = ::CoCreateInstance(CLSID_WICImagingFactory1, nullptr, CLSCTX_INPROC_SERVER, __uuidof(m_imageFactory), reinterpret_cast<void**>(m_imageFactory.GetAddressOf())); assert(SUCCEEDED(hr)); hr = ::DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(m_writeFactory), reinterpret_cast<IUnknown**>(m_writeFactory.GetAddressOf())); assert(SUCCEEDED(hr)); hr = ::D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, IID_PPV_ARGS(&m_drawFactory)); assert(SUCCEEDED(hr)); } void Game::Impl::CreateAppWindow() { assert(m_instance != nullptr); WNDCLASSEX wc; wc.cbSize = sizeof(wc); wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = nullptr; wc.hCursor = ::LoadCursor(nullptr, IDC_ARROW); wc.hIcon = ::LoadIcon(nullptr, IDI_APPLICATION); wc.hIconSm = ::LoadIcon(nullptr, IDI_APPLICATION); wc.hInstance = m_instance; wc.lpfnWndProc = &GameProc; wc.lpszClassName = APP_CLASS; wc.lpszMenuName = nullptr; wc.style = 0; assert(::RegisterClassEx(&wc)); m_isClassRegistered = true; DWORD windowStyle = WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU; DWORD exStyle = 0; RECT windowSize = { 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT }; assert(::AdjustWindowRectEx(&windowSize, windowStyle, FALSE, exStyle)); int width = windowSize.right - windowSize.left; int height = windowSize.bottom - windowSize.top; int x = (::GetSystemMetrics(SM_CXSCREEN) - width) / 2; int y = (::GetSystemMetrics(SM_CYSCREEN) - height) / 2; m_window = ::CreateWindowExW(exStyle, APP_CLASS, APP_TITLE, windowStyle, x, y, width, height, HWND_DESKTOP, nullptr, m_instance, reinterpret_cast<void*>(m_parent)); assert(m_window != nullptr); m_clientRect.left = 0; m_clientRect.right = WINDOW_WIDTH; m_clientRect.top = 0; m_clientRect.bottom = WINDOW_HEIGHT; m_boardPos.x = (WINDOW_WIDTH - m_board.WIDTH * BLOCK_WIDTH) / 2.0f; m_boardPos.y = (WINDOW_HEIGHT - m_board.HEIGHT * BLOCK_HEIGHT) / 2.0f; } void Game::RunMainLoop() { m_impl->RunMainLoop(); } void Game::Impl::RunMainLoop() { assert(m_instance); assert(m_window); ::ShowWindow(m_window, SW_SHOW); ::UpdateWindow(m_window); MSG msg; msg.message = WM_NULL; LARGE_INTEGER before, now; float elapsedInMs; ::QueryPerformanceCounter(&before); while (msg.message != WM_QUIT) { while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::QueryPerformanceCounter(&now); elapsedInMs = static_cast<float>((now.QuadPart - before.QuadPart) * 1000 / m_perfFrequency.QuadPart); Update(elapsedInMs); Render(); before = now; } } void Game::Impl::Update(float ms) { m_board.Update(ms); } void Game::Impl::Render() { m_renderTarget->BeginDraw(); m_renderTarget->Clear(D2D1::ColorF(D2D1::ColorF::AliceBlue)); D2D1_RECT_F dest; for (int y = 0; y < m_board.HEIGHT; y++) { for (int x = 0; x < m_board.WIDTH; x++) { auto t = m_board.GetAt(x, y); auto& bitmap = m_terimonoBitmaps[t]; dest.left = m_boardPos.x + static_cast<float>(x * BLOCK_WIDTH); dest.top = m_boardPos.y + static_cast<float>(y * BLOCK_HEIGHT); dest.right = dest.left + BLOCK_WIDTH; dest.bottom = dest.top + BLOCK_HEIGHT; m_renderTarget->DrawBitmap(bitmap.Get(), &dest, 1.0f, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR); } } D2D1_POINT_2F nextOffset = D2D1::Point2F(m_boardPos.x + m_board.WIDTH * BLOCK_WIDTH + 30, m_boardPos.y); for (int y = 0; y < m_board.MAX_TETRIMONO_HEIGHT; y++) { for (int x = 0; x < m_board.MAX_TETRIMONO_WIDTH; x++) { auto t = m_board.GetNextAt(x, y); auto& bitmap = m_terimonoBitmaps[t]; dest.left = nextOffset.x + static_cast<float>(x * BLOCK_WIDTH); dest.top = nextOffset.y + static_cast<float>(y * BLOCK_HEIGHT); dest.right = dest.left + BLOCK_WIDTH; dest.bottom = dest.top + BLOCK_HEIGHT; m_renderTarget->DrawBitmap(bitmap.Get(), &dest, 1.0f, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR); } } if (m_renderTarget->EndDraw() == D2DERR_RECREATE_TARGET) { CleanDeviceResources(); CreateDeviceResources(); } } void Game::Impl::CreateDeviceResources() { HRESULT hr; hr = m_drawFactory->CreateHwndRenderTarget( D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(), 96.0f, 96.0f), D2D1::HwndRenderTargetProperties(m_window, D2D1::SizeU(WINDOW_WIDTH, WINDOW_HEIGHT)), m_renderTarget.ReleaseAndGetAddressOf()); assert(SUCCEEDED(hr)); Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> solidBrush; assert(SUCCEEDED( m_renderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &solidBrush) )); solidBrush.As(&m_testBrush); m_terimonoBitmaps[Tetrimono_Empty] = LoadImage(L"Assets/block_empty.png"); m_terimonoBitmaps[Tetrimono_I] = LoadImage(L"Assets/block_blue.png"); m_terimonoBitmaps[Tetrimono_J] = LoadImage(L"Assets/block_cyan.png"); m_terimonoBitmaps[Tetrimono_L] = LoadImage(L"Assets/block_green.png"); m_terimonoBitmaps[Tetrimono_O] = LoadImage(L"Assets/block_orange.png"); m_terimonoBitmaps[Tetrimono_S] = LoadImage(L"Assets/block_red.png"); m_terimonoBitmaps[Tetrimono_T] = LoadImage(L"Assets/block_violet.png"); m_terimonoBitmaps[Tetrimono_Z] = LoadImage(L"Assets/block_yellow.png"); } ComPtr<ID2D1Bitmap> Game::Impl::LoadImage(const wchar_t* fileName) const { ComPtr<IWICBitmapDecoder> decoder; assert(SUCCEEDED( m_imageFactory->CreateDecoderFromFilename(fileName, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &decoder) )); ComPtr<IWICBitmapFrameDecode> frame; assert(SUCCEEDED( decoder->GetFrame(0, &frame) )); ComPtr<IWICFormatConverter> formatConverter; assert(SUCCEEDED( m_imageFactory->CreateFormatConverter(&formatConverter) )); assert(SUCCEEDED( formatConverter->Initialize(frame.Get(), GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nullptr, 0.0f, WICBitmapPaletteTypeCustom) )); ComPtr<ID2D1Bitmap> bitmap; assert(SUCCEEDED( m_renderTarget->CreateBitmapFromWicBitmap(formatConverter.Get(), &bitmap) )); return bitmap; } void Game::Impl::CleanDeviceResources() { m_testBrush = nullptr; m_renderTarget = nullptr; } LRESULT Game::Impl::GameProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_CREATE) { CREATESTRUCT* createData = reinterpret_cast<CREATESTRUCT*>(lparam); Game* game = reinterpret_cast<Game*>(createData->lpCreateParams); ::SetWindowLongPtr(window, GWLP_USERDATA, #ifdef _WIN64 reinterpret_cast<LONG_PTR>(game) #else reinterpret_cast<LONG>(game) #endif ); return 0; } else { Game* game = reinterpret_cast<Game*>(::GetWindowLongPtr(window, GWLP_USERDATA)); std::unique_ptr<Game::Impl>& impl = game->m_impl; switch (message) { case WM_PAINT: return impl->OnPaint(); case WM_CLOSE: return impl->OnClose(); case WM_DESTROY: return impl->OnDestroy(); case WM_KEYDOWN: return impl->OnKeyDown(static_cast<int>(wparam)); case WM_KEYUP: return impl->OnKeyUp(static_cast<int>(wparam)); default: return ::DefWindowProc(window, message, wparam, lparam); } } } LRESULT Game::Impl::OnKeyDown(int vk) { switch (vk) { case VK_LEFT: m_board.MoveCurrent(-1, 0); break; case VK_RIGHT: m_board.MoveCurrent(1, 0); break; case VK_UP: m_board.RotateAntiClockwize(); break; case VK_DOWN: m_board.RotateClockwize(); break; case VK_SPACE: m_board.FallDown(); break; case VK_ESCAPE: ::PostQuitMessage(0); break; } return 0; } LRESULT Game::Impl::OnKeyUp(int vk) { UNREFERENCED_PARAMETER(vk); return 0; } LRESULT Game::Impl::OnDestroy() { ::PostQuitMessage(0); return 0; } LRESULT Game::Impl::OnClose() { ::DestroyWindow(m_window); return 0; } LRESULT Game::Impl::OnPaint() { ::ValidateRect(m_window, &m_clientRect); return 0; } #endif<|endoftext|>
<commit_before>#include <appbase/application.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include <eosio/http_plugin/http_plugin.hpp> #include <eosio/net_plugin/net_plugin.hpp> #include <eosio/producer_plugin/producer_plugin.hpp> #include <fc/log/logger_config.hpp> #include <fc/log/appender.hpp> #include <fc/exception/exception.hpp> #include <boost/dll/runtime_symbol_info.hpp> #include <boost/exception/diagnostic_information.hpp> #include "config.hpp" using namespace appbase; using namespace eosio; namespace detail { void configure_logging(const bfs::path& config_path) { try { try { if( fc::exists( config_path ) ) { fc::configure_logging( config_path ); } else { fc::configure_logging( fc::logging_config::default_config() ); } } catch (...) { elog("Error reloading logging.json"); throw; } } catch (const fc::exception& e) { elog("${e}", ("e",e.to_detail_string())); } catch (const boost::exception& e) { elog("${e}", ("e",boost::diagnostic_information(e))); } catch (const std::exception& e) { elog("${e}", ("e",e.what())); } catch (...) { // empty } } } // namespace detail void logging_conf_handler() { auto config_path = app().get_logging_conf(); if( fc::exists( config_path ) ) { ilog( "Received HUP. Reloading logging configuration from ${p}.", ("p", config_path.string()) ); } else { ilog( "Received HUP. No log config found at ${p}, setting to default.", ("p", config_path.string()) ); } ::detail::configure_logging( config_path ); fc::log_config::initialize_appenders( app().get_io_service() ); } void initialize_logging() { auto config_path = app().get_logging_conf(); if(fc::exists(config_path)) fc::configure_logging(config_path); // intentionally allowing exceptions to escape fc::log_config::initialize_appenders( app().get_io_service() ); app().set_sighup_callback(logging_conf_handler); } enum return_codes { OTHER_FAIL = -2, INITIALIZE_FAIL = -1, SUCCESS = 0, BAD_ALLOC = 1, DATABASE_DIRTY = 2, FIXED_REVERSIBLE = SUCCESS, EXTRACTED_GENESIS = SUCCESS, NODE_MANAGEMENT_SUCCESS = 5 }; int main(int argc, char** argv) { try { app().set_version(eosio::nodeos::config::version); auto root = fc::app_path(); app().set_default_data_dir(root / "eosio" / nodeos::config::node_executable_name / "data" ); app().set_default_config_dir(root / "eosio" / nodeos::config::node_executable_name / "config" ); http_plugin::set_defaults({ .default_unix_socket_path = "", .default_http_port = 8888 }); if(!app().initialize<chain_plugin, net_plugin, producer_plugin>(argc, argv)) { if(app().get_options().count("help") || app().get_options().count("version")) { return SUCCESS; } return INITIALIZE_FAIL; } initialize_logging(); ilog("${name} version ${ver}", ("name", nodeos::config::node_executable_name)("ver", app().version_string())); ilog("${name} using configuration file ${c}", ("name", nodeos::config::node_executable_name)("c", app().full_config_file_path().string())); ilog("${name} data directory is ${d}", ("name", nodeos::config::node_executable_name)("d", app().data_dir().string())); app().startup(); app().set_thread_priority_max(); app().exec(); } catch( const extract_genesis_state_exception& e ) { return EXTRACTED_GENESIS; } catch( const fixed_reversible_db_exception& e ) { return FIXED_REVERSIBLE; } catch( const node_management_success& e ) { return NODE_MANAGEMENT_SUCCESS; } catch( const fc::exception& e ) { if( e.code() == fc::std_exception_code ) { if( e.top_message().find( "database dirty flag set" ) != std::string::npos ) { elog( "database dirty flag set (likely due to unclean shutdown): replay required" ); return DATABASE_DIRTY; } } elog( "${e}", ("e", e.to_detail_string())); return OTHER_FAIL; } catch( const boost::interprocess::bad_alloc& e ) { elog("bad alloc"); return BAD_ALLOC; } catch( const boost::exception& e ) { elog("${e}", ("e",boost::diagnostic_information(e))); return OTHER_FAIL; } catch( const std::runtime_error& e ) { if( std::string(e.what()).find("database dirty flag set") != std::string::npos ) { elog( "database dirty flag set (likely due to unclean shutdown): replay required" ); return DATABASE_DIRTY; } else { elog( "${e}", ("e",e.what())); } return OTHER_FAIL; } catch( const std::exception& e ) { elog("${e}", ("e",e.what())); return OTHER_FAIL; } catch( ... ) { elog("unknown exception"); return OTHER_FAIL; } ilog("${name} successfully exiting", ("name", nodeos::config::node_executable_name)); return SUCCESS; } <commit_msg>modified code to handle db_runtime_exception<commit_after>#include <appbase/application.hpp> #include <eosio/chain_plugin/chain_plugin.hpp> #include <eosio/http_plugin/http_plugin.hpp> #include <eosio/net_plugin/net_plugin.hpp> #include <eosio/producer_plugin/producer_plugin.hpp> #include <fc/log/logger_config.hpp> #include <fc/log/appender.hpp> #include <fc/exception/exception.hpp> #include <boost/dll/runtime_symbol_info.hpp> #include <boost/exception/diagnostic_information.hpp> #include "config.hpp" using namespace appbase; using namespace eosio; namespace detail { void configure_logging(const bfs::path& config_path) { try { try { if( fc::exists( config_path ) ) { fc::configure_logging( config_path ); } else { fc::configure_logging( fc::logging_config::default_config() ); } } catch (...) { elog("Error reloading logging.json"); throw; } } catch (const fc::exception& e) { elog("${e}", ("e",e.to_detail_string())); } catch (const boost::exception& e) { elog("${e}", ("e",boost::diagnostic_information(e))); } catch (const std::exception& e) { elog("${e}", ("e",e.what())); } catch (...) { // empty } } } // namespace detail void logging_conf_handler() { auto config_path = app().get_logging_conf(); if( fc::exists( config_path ) ) { ilog( "Received HUP. Reloading logging configuration from ${p}.", ("p", config_path.string()) ); } else { ilog( "Received HUP. No log config found at ${p}, setting to default.", ("p", config_path.string()) ); } ::detail::configure_logging( config_path ); fc::log_config::initialize_appenders( app().get_io_service() ); } void initialize_logging() { auto config_path = app().get_logging_conf(); if(fc::exists(config_path)) fc::configure_logging(config_path); // intentionally allowing exceptions to escape fc::log_config::initialize_appenders( app().get_io_service() ); app().set_sighup_callback(logging_conf_handler); } enum return_codes { OTHER_FAIL = -2, INITIALIZE_FAIL = -1, SUCCESS = 0, BAD_ALLOC = 1, DATABASE_DIRTY = 2, FIXED_REVERSIBLE = SUCCESS, EXTRACTED_GENESIS = SUCCESS, NODE_MANAGEMENT_SUCCESS = 5 }; int main(int argc, char** argv) { try { app().set_version(eosio::nodeos::config::version); auto root = fc::app_path(); app().set_default_data_dir(root / "eosio" / nodeos::config::node_executable_name / "data" ); app().set_default_config_dir(root / "eosio" / nodeos::config::node_executable_name / "config" ); http_plugin::set_defaults({ .default_unix_socket_path = "", .default_http_port = 8888 }); if(!app().initialize<chain_plugin, net_plugin, producer_plugin>(argc, argv)) { if(app().get_options().count("help") || app().get_options().count("version")) { return SUCCESS; } return INITIALIZE_FAIL; } initialize_logging(); ilog("${name} version ${ver}", ("name", nodeos::config::node_executable_name)("ver", app().version_string())); ilog("${name} using configuration file ${c}", ("name", nodeos::config::node_executable_name)("c", app().full_config_file_path().string())); ilog("${name} data directory is ${d}", ("name", nodeos::config::node_executable_name)("d", app().data_dir().string())); app().startup(); app().set_thread_priority_max(); app().exec(); } catch( const extract_genesis_state_exception& e ) { return EXTRACTED_GENESIS; } catch( const fixed_reversible_db_exception& e ) { return FIXED_REVERSIBLE; } catch( const node_management_success& e ) { return NODE_MANAGEMENT_SUCCESS; } catch( const fc::exception& e ) { if( e.code() == fc::std_exception_code ) { if( e.top_message().find( "database dirty flag set" ) != std::string::npos ) { elog( "database dirty flag set (likely due to unclean shutdown): replay required" ); return DATABASE_DIRTY; } } elog( "${e}", ("e", e.to_detail_string())); return OTHER_FAIL; } catch( const boost::interprocess::bad_alloc& e ) { elog("bad alloc"); return BAD_ALLOC; } catch( const boost::exception& e ) { elog("${e}", ("e",boost::diagnostic_information(e))); return OTHER_FAIL; } catch (const chainbase::db_runtime_error& e) { if (chainbase::db_runtime_error::error_code::dirty == e.what_code()) { elog( "database dirty flag set (likely due to unclean shutdown): replay required" ); return DATABASE_DIRTY; } elog( "${e}", ("e",e.what())); return OTHER_FAIL; } catch( const std::runtime_error& e ) { elog( "${e}", ("e",e.what())); return OTHER_FAIL; } catch( const std::exception& e ) { elog("${e}", ("e",e.what())); return OTHER_FAIL; } catch( ... ) { elog("unknown exception"); return OTHER_FAIL; } ilog("${name} successfully exiting", ("name", nodeos::config::node_executable_name)); return SUCCESS; } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #define CAF_SUITE fused_downstream_manager #include "caf/fused_downstream_manager.hpp" #include "caf/test/dsl.hpp" #include <memory> #include <numeric> #include "caf/actor_system.hpp" #include "caf/actor_system_config.hpp" #include "caf/attach_stream_sink.hpp" #include "caf/event_based_actor.hpp" #include "caf/stateful_actor.hpp" using std::string; using namespace caf; namespace { TESTEE_SETUP(); using int_downstream_manager = broadcast_downstream_manager<int>; using string_downstream_manager = broadcast_downstream_manager<string>; using ints_atom = atom_constant<atom("ints")>; using strings_atom = atom_constant<atom("strings")>; template <class T> void push(std::deque<T>& xs, downstream<T>& out, size_t num) { auto n = std::min(num, xs.size()); CAF_MESSAGE("push " << n << " messages downstream"); for (size_t i = 0; i < n; ++i) out.push(xs[i]); xs.erase(xs.begin(), xs.begin() + static_cast<ptrdiff_t>(n)); } VARARGS_TESTEE(int_file_reader, size_t buf_size) { using buf = std::deque<int32_t>; return {[=](string& fname) -> result<stream<int32_t>> { CAF_CHECK_EQUAL(fname, "numbers.txt"); return attach_stream_source( self, // initialize state [=](buf& xs) { xs.resize(buf_size); std::iota(xs.begin(), xs.end(), 1); }, // get next element [](buf& xs, downstream<int32_t>& out, size_t num) { push(xs, out, num); }, // check whether we reached the end [=](const buf& xs) { return xs.empty(); }); }}; } VARARGS_TESTEE(string_file_reader, size_t buf_size) { using buf = std::deque<string>; return {[=](string& fname) -> result<stream<string>> { CAF_CHECK_EQUAL(fname, "strings.txt"); return attach_stream_source( self, // initialize state [=](buf& xs) { for (size_t i = 0; i < buf_size; ++i) xs.emplace_back("some string data"); }, // get next element [](buf& xs, downstream<string>& out, size_t num) { push(xs, out, num); }, // check whether we reached the end [=](const buf& xs) { return xs.empty(); }); }}; } TESTEE_STATE(sum_up) { int x = 0; }; TESTEE(sum_up) { using intptr = int*; return {[=](stream<int32_t>& in) { return attach_stream_sink( self, // input stream in, // initialize state [=](intptr& x) { x = &self->state.x; }, // processing step [](intptr& x, int32_t y) { *x += y; }, // cleanup and produce result message [=](intptr&, const error&) { CAF_MESSAGE(self->name() << " is done"); }); }, [=](join_atom, actor src) { CAF_MESSAGE(self->name() << " joins a stream"); self->send(self * src, join_atom::value, ints_atom::value); }}; } TESTEE_STATE(collect) { std::vector<string> strings; }; TESTEE(collect) { return {[=](stream<string>& in) { return attach_stream_sink( self, // input stream in, // initialize state [](unit_t&) { // nop }, // processing step [=](unit_t&, string y) { self->state.strings.emplace_back(std::move(y)); }, // cleanup and produce result message [=](unit_t&, const error&) { CAF_MESSAGE(self->name() << " is done"); }); }, [=](join_atom, actor src) { CAF_MESSAGE(self->name() << " joins a stream"); self->send(self * src, join_atom::value, strings_atom::value); }}; } using int_downstream_manager = broadcast_downstream_manager<int>; using string_downstream_manager = broadcast_downstream_manager<string>; using fused_manager = fused_downstream_manager<int_downstream_manager, string_downstream_manager>; class fused_stage : public stream_manager { public: using super = stream_manager; fused_stage(scheduled_actor* self) : stream_manager(self), out_(this) { continuous(true); } bool done() const override { return !continuous() && pending_handshakes_ == 0 && inbound_paths_.empty() && out_.clean(); } bool idle() const noexcept override { return inbound_paths_idle() && out_.stalled(); } void handle(inbound_path*, downstream_msg::batch& batch) override { using std::make_move_iterator; using int_vec = std::vector<int>; using string_vec = std::vector<string>; if (batch.xs.match_elements<int_vec>()) { CAF_MESSAGE("handle an integer batch"); auto& xs = batch.xs.get_mutable_as<int_vec>(0); auto& buf = out_.get<int_downstream_manager>().buf(); buf.insert(buf.end(), xs.begin(), xs.end()); return; } if (batch.xs.match_elements<string_vec>()) { CAF_MESSAGE("handle a string batch"); auto& xs = batch.xs.get_mutable_as<string_vec>(0); auto& buf = out_.get<string_downstream_manager>().buf(); buf.insert(buf.end(), xs.begin(), xs.end()); return; } CAF_LOG_ERROR("received unexpected batch type (dropped)"); } bool congested() const noexcept override { return out_.capacity() == 0; } fused_manager& out() noexcept override { return out_; } private: fused_manager out_; }; TESTEE_STATE(stream_multiplexer) { intrusive_ptr<fused_stage> stage; }; TESTEE(stream_multiplexer) { self->state.stage = make_counted<fused_stage>(self); return {[=](join_atom, ints_atom) { auto& stg = self->state.stage; CAF_MESSAGE("received 'join' request for integers"); auto result = stg->add_unchecked_outbound_path<int>(); stg->out().assign<int_downstream_manager>(result); return result; }, [=](join_atom, strings_atom) { auto& stg = self->state.stage; CAF_MESSAGE("received 'join' request for strings"); auto result = stg->add_unchecked_outbound_path<string>(); stg->out().assign<string_downstream_manager>(result); return result; }, [=](const stream<int32_t>& in) { CAF_MESSAGE("received handshake for integers"); return self->state.stage->add_unchecked_inbound_path(in); }, [=](const stream<string>& in) { CAF_MESSAGE("received handshake for strings"); return self->state.stage->add_unchecked_inbound_path(in); }}; } struct config : actor_system_config { config() { add_message_type<std::deque<std::string>>("deque<string>"); } }; using fixture = test_coordinator_fixture<>; } // namespace // -- unit tests --------------------------------------------------------------- CAF_TEST_FIXTURE_SCOPE(fused_downstream_manager_tests, fixture) CAF_TEST(depth_3_pipeline_with_fork) { auto src1 = sys.spawn(int_file_reader, 50u); auto src2 = sys.spawn(string_file_reader, 50u); auto stg = sys.spawn(stream_multiplexer); auto snk1 = sys.spawn(sum_up); auto snk2 = sys.spawn(collect); auto& st = deref<stream_multiplexer_actor>(stg).state; CAF_MESSAGE("connect sinks to the fused stage"); self->send(snk1, join_atom::value, stg); self->send(snk2, join_atom::value, stg); sched.run(); CAF_CHECK_EQUAL(st.stage->out().num_paths(), 2u); CAF_CHECK_EQUAL(st.stage->inbound_paths().size(), 0u); CAF_MESSAGE("connect sources to the fused stage"); self->send(stg * src1, "numbers.txt"); self->send(stg * src2, "strings.txt"); sched.run(); CAF_CHECK_EQUAL(st.stage->out().num_paths(), 2u); CAF_CHECK_EQUAL(st.stage->inbound_paths().size(), 2u); run_until([&] { return st.stage->inbound_paths().empty() && st.stage->out().clean(); }); CAF_CHECK_EQUAL(st.stage->out().num_paths(), 2u); CAF_CHECK_EQUAL(st.stage->inbound_paths().size(), 0u); CAF_CHECK_EQUAL(deref<sum_up_actor>(snk1).state.x, 1275); CAF_CHECK_EQUAL(deref<collect_actor>(snk2).state.strings.size(), 50u); self->send_exit(stg, exit_reason::kill); } CAF_TEST_FIXTURE_SCOPE_END() <commit_msg>Add trailing commas for nicer formatting<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #define CAF_SUITE fused_downstream_manager #include "caf/fused_downstream_manager.hpp" #include "caf/test/dsl.hpp" #include <memory> #include <numeric> #include "caf/actor_system.hpp" #include "caf/actor_system_config.hpp" #include "caf/attach_stream_sink.hpp" #include "caf/event_based_actor.hpp" #include "caf/stateful_actor.hpp" using std::string; using namespace caf; namespace { TESTEE_SETUP(); using int_downstream_manager = broadcast_downstream_manager<int>; using string_downstream_manager = broadcast_downstream_manager<string>; using ints_atom = atom_constant<atom("ints")>; using strings_atom = atom_constant<atom("strings")>; template <class T> void push(std::deque<T>& xs, downstream<T>& out, size_t num) { auto n = std::min(num, xs.size()); CAF_MESSAGE("push " << n << " messages downstream"); for (size_t i = 0; i < n; ++i) out.push(xs[i]); xs.erase(xs.begin(), xs.begin() + static_cast<ptrdiff_t>(n)); } VARARGS_TESTEE(int_file_reader, size_t buf_size) { using buf = std::deque<int32_t>; return { [=](string& fname) -> result<stream<int32_t>> { CAF_CHECK_EQUAL(fname, "numbers.txt"); return attach_stream_source( self, // initialize state [=](buf& xs) { xs.resize(buf_size); std::iota(xs.begin(), xs.end(), 1); }, // get next element [](buf& xs, downstream<int32_t>& out, size_t num) { push(xs, out, num); }, // check whether we reached the end [=](const buf& xs) { return xs.empty(); }); }, }; } VARARGS_TESTEE(string_file_reader, size_t buf_size) { using buf = std::deque<string>; return { [=](string& fname) -> result<stream<string>> { CAF_CHECK_EQUAL(fname, "strings.txt"); return attach_stream_source( self, // initialize state [=](buf& xs) { for (size_t i = 0; i < buf_size; ++i) xs.emplace_back("some string data"); }, // get next element [](buf& xs, downstream<string>& out, size_t num) { push(xs, out, num); }, // check whether we reached the end [=](const buf& xs) { return xs.empty(); }); }, }; } TESTEE_STATE(sum_up) { int x = 0; }; TESTEE(sum_up) { using intptr = int*; return { [=](stream<int32_t>& in) { return attach_stream_sink( self, // input stream in, // initialize state [=](intptr& x) { x = &self->state.x; }, // processing step [](intptr& x, int32_t y) { *x += y; }, // cleanup and produce result message [=](intptr&, const error&) { CAF_MESSAGE(self->name() << " is done"); }); }, [=](join_atom, actor src) { CAF_MESSAGE(self->name() << " joins a stream"); self->send(self * src, join_atom::value, ints_atom::value); }, }; } TESTEE_STATE(collect) { std::vector<string> strings; }; TESTEE(collect) { return { [=](stream<string>& in) { return attach_stream_sink( self, // input stream in, // initialize state [](unit_t&) { // nop }, // processing step [=](unit_t&, string y) { self->state.strings.emplace_back(std::move(y)); }, // cleanup and produce result message [=](unit_t&, const error&) { CAF_MESSAGE(self->name() << " is done"); }); }, [=](join_atom, actor src) { CAF_MESSAGE(self->name() << " joins a stream"); self->send(self * src, join_atom::value, strings_atom::value); }, }; } using int_downstream_manager = broadcast_downstream_manager<int>; using string_downstream_manager = broadcast_downstream_manager<string>; using fused_manager = fused_downstream_manager<int_downstream_manager, string_downstream_manager>; class fused_stage : public stream_manager { public: using super = stream_manager; fused_stage(scheduled_actor* self) : stream_manager(self), out_(this) { continuous(true); } bool done() const override { return !continuous() && pending_handshakes_ == 0 && inbound_paths_.empty() && out_.clean(); } bool idle() const noexcept override { return inbound_paths_idle() && out_.stalled(); } void handle(inbound_path*, downstream_msg::batch& batch) override { using std::make_move_iterator; using int_vec = std::vector<int>; using string_vec = std::vector<string>; if (batch.xs.match_elements<int_vec>()) { CAF_MESSAGE("handle an integer batch"); auto& xs = batch.xs.get_mutable_as<int_vec>(0); auto& buf = out_.get<int_downstream_manager>().buf(); buf.insert(buf.end(), xs.begin(), xs.end()); return; } if (batch.xs.match_elements<string_vec>()) { CAF_MESSAGE("handle a string batch"); auto& xs = batch.xs.get_mutable_as<string_vec>(0); auto& buf = out_.get<string_downstream_manager>().buf(); buf.insert(buf.end(), xs.begin(), xs.end()); return; } CAF_LOG_ERROR("received unexpected batch type (dropped)"); } bool congested() const noexcept override { return out_.capacity() == 0; } fused_manager& out() noexcept override { return out_; } private: fused_manager out_; }; TESTEE_STATE(stream_multiplexer) { intrusive_ptr<fused_stage> stage; }; TESTEE(stream_multiplexer) { self->state.stage = make_counted<fused_stage>(self); return { [=](join_atom, ints_atom) { auto& stg = self->state.stage; CAF_MESSAGE("received 'join' request for integers"); auto result = stg->add_unchecked_outbound_path<int>(); stg->out().assign<int_downstream_manager>(result); return result; }, [=](join_atom, strings_atom) { auto& stg = self->state.stage; CAF_MESSAGE("received 'join' request for strings"); auto result = stg->add_unchecked_outbound_path<string>(); stg->out().assign<string_downstream_manager>(result); return result; }, [=](const stream<int32_t>& in) { CAF_MESSAGE("received handshake for integers"); return self->state.stage->add_unchecked_inbound_path(in); }, [=](const stream<string>& in) { CAF_MESSAGE("received handshake for strings"); return self->state.stage->add_unchecked_inbound_path(in); }, }; } struct config : actor_system_config { config() { add_message_type<std::deque<std::string>>("deque<string>"); } }; using fixture = test_coordinator_fixture<>; } // namespace // -- unit tests --------------------------------------------------------------- CAF_TEST_FIXTURE_SCOPE(fused_downstream_manager_tests, fixture) CAF_TEST(depth_3_pipeline_with_fork) { auto src1 = sys.spawn(int_file_reader, 50u); auto src2 = sys.spawn(string_file_reader, 50u); auto stg = sys.spawn(stream_multiplexer); auto snk1 = sys.spawn(sum_up); auto snk2 = sys.spawn(collect); auto& st = deref<stream_multiplexer_actor>(stg).state; CAF_MESSAGE("connect sinks to the fused stage"); self->send(snk1, join_atom::value, stg); self->send(snk2, join_atom::value, stg); sched.run(); CAF_CHECK_EQUAL(st.stage->out().num_paths(), 2u); CAF_CHECK_EQUAL(st.stage->inbound_paths().size(), 0u); CAF_MESSAGE("connect sources to the fused stage"); self->send(stg * src1, "numbers.txt"); self->send(stg * src2, "strings.txt"); sched.run(); CAF_CHECK_EQUAL(st.stage->out().num_paths(), 2u); CAF_CHECK_EQUAL(st.stage->inbound_paths().size(), 2u); run_until([&] { return st.stage->inbound_paths().empty() && st.stage->out().clean(); }); CAF_CHECK_EQUAL(st.stage->out().num_paths(), 2u); CAF_CHECK_EQUAL(st.stage->inbound_paths().size(), 0u); CAF_CHECK_EQUAL(deref<sum_up_actor>(snk1).state.x, 1275); CAF_CHECK_EQUAL(deref<collect_actor>(snk2).state.strings.size(), 50u); self->send_exit(stg, exit_reason::kill); } CAF_TEST_FIXTURE_SCOPE_END() <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////// /* * Routines to write data in Nrrd format * Currently handles: raw, gzip and ascii encodings */ ///////////////////////////////////////////////////////////////// #include <hxNrrdIO/hxNrrdIOAPI.h> #include <hxcore/HxData.h> #include <hxcore/HxMessage.h> #include <hxfield/HxUniformScalarField3.h> #include <teem/nrrd.h> int NrrdWriter(HxUniformScalarField3* field, const char* filename, int encoding) { // Identify data type int nrrdType = nrrdTypeUnknown; switch ( field->primType() ) { case McPrimType::MC_UINT8: nrrdType = nrrdTypeUChar; break; case McPrimType::MC_INT8: nrrdType = nrrdTypeChar; break; case McPrimType::MC_UINT16: nrrdType = nrrdTypeUShort; break; case McPrimType::MC_INT16: nrrdType = nrrdTypeShort; break; case McPrimType::MC_INT32: nrrdType = nrrdTypeInt; break; case McPrimType::MC_FLOAT: nrrdType = nrrdTypeFloat; break; case McPrimType::MC_DOUBLE: nrrdType = nrrdTypeDouble; break; default: break; } if(nrrdType == nrrdTypeUnknown) { theMsg->printf("ERROR: unsupported output type: %s for nrrd",field->primType().getName()); return 0; } void* data = field->lattice().dataPtr(); Nrrd *nrrd = nrrdNew(); NrrdIoState *nios = nrrdIoStateNew(); if ( encoding == nrrdEncodingTypeGzip) { if (nrrdEncodingGzip->available() ) { nrrdIoStateEncodingSet( nios, nrrdEncodingGzip ); nrrdIoStateSet( nios, nrrdIoStateZlibLevel, 9 ); } else theMsg->printf("WARNING: Nrrd library does not support Gzip compression encoding.\n Make sure Teem_ZLIB is on in CMAKE when building Nrrd library.\n"); } else if ( encoding == nrrdEncodingTypeBzip2) { if (nrrdEncodingBzip2->available() ) { nrrdIoStateEncodingSet( nios, nrrdEncodingBzip2 ); // nrrdIoStateSet( nios, nrrdIoStateBzip2BlockSize, 9 ); } else theMsg->printf("WARNING: Nrrd library does not support Bzip2 compression encoding.\n Make sure Teem_BZIP2 is on in CMAKE when building Nrrd library.\n"); } else if ( encoding == nrrdEncodingTypeAscii) { nrrdIoStateEncodingSet( nios, nrrdEncodingAscii ); } else { theMsg->printf("ERROR: Unimplemented nrrd encoding type: %d\n",encoding); return 0; } try { McDim3l dims = field->lattice().getDims(); if ( nrrdWrap_va( nrrd, data, nrrdType, (size_t)3, (size_t)dims[0], (size_t)dims[1], (size_t)dims[2] ) ) { throw( biffGetDone(NRRD) ); } nrrdSpaceDimensionSet( nrrd, 3 ); // TODO: Would be nice to set space units. How does Amira store this? // if ( writeVolume->MetaKeyExists(CMTK_META_SPACE_UNITS_STRING) ) // { // nrrd->spaceUnits[0] = strdup( writeVolume->m_MetaInformation[CMTK_META_SPACE_UNITS_STRING].c_str() ); // nrrd->spaceUnits[1] = strdup( writeVolume->m_MetaInformation[CMTK_META_SPACE_UNITS_STRING].c_str() ); // nrrd->spaceUnits[2] = strdup( writeVolume->m_MetaInformation[CMTK_META_SPACE_UNITS_STRING].c_str() ); // } int kind[NRRD_DIM_MAX] = { nrrdKindDomain, nrrdKindDomain, nrrdKindDomain }; nrrdAxisInfoSet_nva( nrrd, nrrdAxisInfoKind, kind ); // TODO: Would be nice to write some kind of space if this exists // Fetch bounding box information and voxel size McBox3f bbox = field->getBoundingBox(); McVec3f voxelSize = field->getVoxelSize(); // Just deal with space directions orthogonal to data axes // TODO: Fetch transformation and use that double spaceDir[NRRD_DIM_MAX][NRRD_SPACE_DIM_MAX]; for ( int i = 0; i < 3; ++i ) { for ( int j = 0; j < 3; ++j ) { if (i == j) spaceDir[i][j] = (double) voxelSize[i]; else spaceDir[i][j] = 0.0; // Can't assume that memory is zeroed } } nrrdAxisInfoSet_nva( nrrd, nrrdAxisInfoSpaceDirection, spaceDir ); double origin[NRRD_DIM_MAX] = { bbox[0], bbox[2], bbox[4] }; if ( nrrdSpaceOriginSet( nrrd, origin ) ) { throw( biffGetDone(NRRD) ); } nrrdAxisInfoSet_va( nrrd, nrrdAxisInfoLabel, "x", "y", "z" ); if ( nrrdSave( filename, nrrd, nios ) ) { throw( biffGetDone(NRRD) ); } } catch ( char* err ) { theMsg->printf("ERROR: hxNrrdIO library returned error '%s'\n", err); free( err ); return 0; } nrrdIoStateNix( nios ); nrrdNix(nrrd); return 1; } HXNRRDIO_API int NrrdWriterRaw(HxUniformScalarField3* field, const char* filename) { return NrrdWriter(field, filename, nrrdEncodingTypeRaw); } HXNRRDIO_API int NrrdWriterGzip(HxUniformScalarField3* field, const char* filename) { return NrrdWriter(field, filename, nrrdEncodingTypeGzip); } HXNRRDIO_API int NrrdWriterAscii(HxUniformScalarField3* field, const char* filename) { return NrrdWriter(field, filename, nrrdEncodingTypeAscii); } <commit_msg>Fix bug in writing plain nrrd<commit_after>///////////////////////////////////////////////////////////////// /* * Routines to write data in Nrrd format * Currently handles: raw, gzip and ascii encodings */ ///////////////////////////////////////////////////////////////// #include <hxNrrdIO/hxNrrdIOAPI.h> #include <hxcore/HxData.h> #include <hxcore/HxMessage.h> #include <hxfield/HxUniformScalarField3.h> #include <teem/nrrd.h> int NrrdWriter(HxUniformScalarField3* field, const char* filename, int encoding) { // Identify data type int nrrdType = nrrdTypeUnknown; switch ( field->primType() ) { case McPrimType::MC_UINT8: nrrdType = nrrdTypeUChar; break; case McPrimType::MC_INT8: nrrdType = nrrdTypeChar; break; case McPrimType::MC_UINT16: nrrdType = nrrdTypeUShort; break; case McPrimType::MC_INT16: nrrdType = nrrdTypeShort; break; case McPrimType::MC_INT32: nrrdType = nrrdTypeInt; break; case McPrimType::MC_FLOAT: nrrdType = nrrdTypeFloat; break; case McPrimType::MC_DOUBLE: nrrdType = nrrdTypeDouble; break; default: break; } if(nrrdType == nrrdTypeUnknown) { theMsg->printf("ERROR: unsupported output type: %s for nrrd",field->primType().getName()); return 0; } void* data = field->lattice().dataPtr(); Nrrd *nrrd = nrrdNew(); NrrdIoState *nios = nrrdIoStateNew(); if ( encoding == nrrdEncodingTypeGzip) { if (nrrdEncodingGzip->available() ) { nrrdIoStateEncodingSet( nios, nrrdEncodingGzip ); nrrdIoStateSet( nios, nrrdIoStateZlibLevel, 9 ); } else theMsg->printf("WARNING: Nrrd library does not support Gzip compression encoding.\n Make sure Teem_ZLIB is on in CMAKE when building Nrrd library.\n"); } else if ( encoding == nrrdEncodingTypeBzip2) { if (nrrdEncodingBzip2->available() ) { nrrdIoStateEncodingSet( nios, nrrdEncodingBzip2 ); // nrrdIoStateSet( nios, nrrdIoStateBzip2BlockSize, 9 ); } else theMsg->printf("WARNING: Nrrd library does not support Bzip2 compression encoding.\n Make sure Teem_BZIP2 is on in CMAKE when building Nrrd library.\n"); } else if ( encoding == nrrdEncodingTypeRaw) { // Do nothing (the default) } else if ( encoding == nrrdEncodingTypeAscii) { nrrdIoStateEncodingSet( nios, nrrdEncodingAscii ); } else { theMsg->printf("ERROR: Unimplemented nrrd encoding type: %d\n",encoding); return 0; } try { McDim3l dims = field->lattice().getDims(); if ( nrrdWrap_va( nrrd, data, nrrdType, (size_t)3, (size_t)dims[0], (size_t)dims[1], (size_t)dims[2] ) ) { throw( biffGetDone(NRRD) ); } nrrdSpaceDimensionSet( nrrd, 3 ); // TODO: Would be nice to set space units. How does Amira store this? // if ( writeVolume->MetaKeyExists(CMTK_META_SPACE_UNITS_STRING) ) // { // nrrd->spaceUnits[0] = strdup( writeVolume->m_MetaInformation[CMTK_META_SPACE_UNITS_STRING].c_str() ); // nrrd->spaceUnits[1] = strdup( writeVolume->m_MetaInformation[CMTK_META_SPACE_UNITS_STRING].c_str() ); // nrrd->spaceUnits[2] = strdup( writeVolume->m_MetaInformation[CMTK_META_SPACE_UNITS_STRING].c_str() ); // } int kind[NRRD_DIM_MAX] = { nrrdKindDomain, nrrdKindDomain, nrrdKindDomain }; nrrdAxisInfoSet_nva( nrrd, nrrdAxisInfoKind, kind ); // TODO: Would be nice to write some kind of space if this exists // Fetch bounding box information and voxel size McBox3f bbox = field->getBoundingBox(); McVec3f voxelSize = field->getVoxelSize(); // Just deal with space directions orthogonal to data axes // TODO: Fetch transformation and use that double spaceDir[NRRD_DIM_MAX][NRRD_SPACE_DIM_MAX]; for ( int i = 0; i < 3; ++i ) { for ( int j = 0; j < 3; ++j ) { if (i == j) spaceDir[i][j] = (double) voxelSize[i]; else spaceDir[i][j] = 0.0; // Can't assume that memory is zeroed } } nrrdAxisInfoSet_nva( nrrd, nrrdAxisInfoSpaceDirection, spaceDir ); double origin[NRRD_DIM_MAX] = { bbox[0], bbox[2], bbox[4] }; if ( nrrdSpaceOriginSet( nrrd, origin ) ) { throw( biffGetDone(NRRD) ); } nrrdAxisInfoSet_va( nrrd, nrrdAxisInfoLabel, "x", "y", "z" ); if ( nrrdSave( filename, nrrd, nios ) ) { throw( biffGetDone(NRRD) ); } } catch ( char* err ) { theMsg->printf("ERROR: hxNrrdIO library returned error '%s'\n", err); free( err ); return 0; } nrrdIoStateNix( nios ); nrrdNix(nrrd); return 1; } HXNRRDIO_API int NrrdWriterRaw(HxUniformScalarField3* field, const char* filename) { return NrrdWriter(field, filename, nrrdEncodingTypeRaw); } HXNRRDIO_API int NrrdWriterGzip(HxUniformScalarField3* field, const char* filename) { return NrrdWriter(field, filename, nrrdEncodingTypeGzip); } HXNRRDIO_API int NrrdWriterAscii(HxUniformScalarField3* field, const char* filename) { return NrrdWriter(field, filename, nrrdEncodingTypeAscii); } <|endoftext|>
<commit_before>/*! * This file is part of CameraPlus. * * Copyright (C) 2012 Mohammed Sameer <msameer@foolab.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) 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 */ #include "qtcamdevice.h" #include "qtcamviewfinder.h" #include "qtcamconfig.h" #include "qtcamdevice_p.h" #include <QDebug> #include <gst/gst.h> #include "qtcamgstreamermessagelistener.h" #include "qtcammode.h" #include "qtcamimagemode.h" #include "qtcamvideomode.h" #include "qtcamnotifications.h" QtCamDevice::QtCamDevice(QtCamConfig *config, const QString& name, const QVariant& id, QObject *parent) : QObject(parent), d_ptr(new QtCamDevicePrivate) { d_ptr->q_ptr = this; d_ptr->name = name; d_ptr->id = id; d_ptr->conf = config; d_ptr->cameraBin = gst_element_factory_make("camerabin2", "QtCameraCameraBin"); if (!d_ptr->cameraBin) { qCritical() << "Failed to create camerabin"; return; } d_ptr->createAndAddElement(d_ptr->conf->audioSource(), "audio-source", "QtCameraAudioSrc"); d_ptr->createAndAddVideoSource(); int flags = 0x00000001 /* no-audio-conversion - Do not use audio conversion elements */ | 0x00000002 /* no-video-conversion - Do not use video conversion elements */ | 0x00000004 /* no-viewfinder-conversion - Do not use viewfinder conversion elements */ | 0x00000008; /* no-image-conversion - Do not use image conversion elements */ g_object_set(d_ptr->cameraBin, "flags", flags, NULL); d_ptr->setAudioCaptureCaps(); // TODO: audio bitrate // TODO: video bitrate // TODO: filters // TODO: custom properties for jifmux, mp4mux, audio encoder, video encoder, sink & video source d_ptr->listener = new QtCamGStreamerMessageListener(gst_element_get_bus(d_ptr->cameraBin), d_ptr, this); QObject::connect(d_ptr->listener, SIGNAL(error(const QString&, int, const QString&)), this, SLOT(_d_error(const QString&, int, const QString&))); QObject::connect(d_ptr->listener, SIGNAL(started()), this, SLOT(_d_started())); QObject::connect(d_ptr->listener, SIGNAL(stopped()), this, SLOT(_d_stopped())); QObject::connect(d_ptr->listener, SIGNAL(stopping()), this, SLOT(_d_stopping())); g_signal_connect(d_ptr->cameraBin, "notify::idle", G_CALLBACK(QtCamDevicePrivate::on_idle_changed), d_ptr); g_signal_connect(d_ptr->wrapperVideoSource, "notify::ready-for-capture", G_CALLBACK(QtCamDevicePrivate::on_ready_for_capture_changed), d_ptr); d_ptr->image = new QtCamImageMode(d_ptr, this); d_ptr->video = new QtCamVideoMode(d_ptr, this); d_ptr->notifications = new QtCamNotifications(this, this); } QtCamDevice::~QtCamDevice() { stop(true); d_ptr->image->deactivate(); d_ptr->video->deactivate(); delete d_ptr->image; d_ptr->image = 0; delete d_ptr->video; d_ptr->video = 0; if (d_ptr->cameraBin) { gst_object_unref(d_ptr->cameraBin); } delete d_ptr; d_ptr = 0; } bool QtCamDevice::setViewfinder(QtCamViewfinder *viewfinder) { if (isRunning()) { qWarning() << "QtCamDevice: pipeline must be stopped before setting a viewfinder"; return false; } if (d_ptr->viewfinder == viewfinder) { return true; } if (!viewfinder) { qWarning() << "QtCamDevice: viewfinder cannot be unset."; return false; } if (d_ptr->viewfinder) { qWarning() << "QtCamDevice: viewfinder cannot be replaced."; return false; } if (!viewfinder->setDevice(this)) { return false; } d_ptr->viewfinder = viewfinder; return true; } bool QtCamDevice::start() { if (d_ptr->error) { qWarning() << "Pipeline must be stopped first because of an error."; return false; } if (!d_ptr->cameraBin) { qWarning() << "Missing camerabin"; return false; } if (!d_ptr->viewfinder) { qWarning() << "Viewfinder not set"; return false; } if (isRunning()) { return true; } if (!d_ptr->active) { d_ptr->image->activate(); } else { d_ptr->active->applySettings(); } // Set sink. if (!d_ptr->setViewfinderSink()) { return false; } GstStateChangeReturn err = gst_element_set_state(d_ptr->cameraBin, GST_STATE_PLAYING); if (err == GST_STATE_CHANGE_FAILURE) { qWarning() << "Failed to start camera pipeline"; return false; } // We need to wait for startup to complet. There's a race condition somewhere in the pipeline. // If we set the scene mode to night and update the resolution while starting up // then subdevsrc2 barfs: // streaming task paused, reason not-negotiated (-4) GstState state; if (err != GST_STATE_CHANGE_ASYNC) { return true; } if (gst_element_get_state(d_ptr->cameraBin, &state, 0, GST_CLOCK_TIME_NONE) != GST_STATE_CHANGE_SUCCESS) { // We are seriously screwed up :( return false; } if (state != GST_STATE_PLAYING) { // Huh ? Is this even possible ?? return false; } return true; } bool QtCamDevice::stop(bool force) { if (!d_ptr->cameraBin) { return true; } if (d_ptr->error) { gst_element_set_state(d_ptr->cameraBin, GST_STATE_NULL); d_ptr->error = false; d_ptr->viewfinder->stop(); return true; } GstState state; gst_element_get_state(d_ptr->cameraBin, &state, 0, GST_CLOCK_TIME_NONE); if (state == GST_STATE_NULL) { // Nothing to do. return true; } if (!isIdle()) { if (!force) { return false; } } d_ptr->viewfinder->stop(); d_ptr->stopping = true; // First we go to ready: GstStateChangeReturn st = gst_element_set_state(d_ptr->cameraBin, GST_STATE_READY); if (st != GST_STATE_CHANGE_FAILURE) { // Flush the bus: d_ptr->listener->flushMessages(); } // Now to NULL gst_element_set_state(d_ptr->cameraBin, GST_STATE_NULL); d_ptr->stopping = false; return true; } bool QtCamDevice::isRunning() { if (!d_ptr->cameraBin) { return false; } GstState state; GstStateChangeReturn err = gst_element_get_state(d_ptr->cameraBin, &state, 0, GST_CLOCK_TIME_NONE); if (err == GST_STATE_CHANGE_FAILURE || state != GST_STATE_PLAYING) { return false; } return true; } bool QtCamDevice::isIdle() { if (!d_ptr->cameraBin) { return true; } gboolean idle = FALSE; g_object_get(d_ptr->cameraBin, "idle", &idle, NULL); return idle == TRUE; } QtCamImageMode *QtCamDevice::imageMode() const { return d_ptr->image; } QtCamVideoMode *QtCamDevice::videoMode() const { return d_ptr->video; } QtCamMode *QtCamDevice::activeMode() const { return d_ptr->active; } QString QtCamDevice::name() const { return d_ptr->name; } QVariant QtCamDevice::id() const { return d_ptr->id; } QtCamConfig *QtCamDevice::config() const { return d_ptr->conf; } QtCamGStreamerMessageListener *QtCamDevice::listener() const { return d_ptr->listener; } QtCamNotifications *QtCamDevice::notifications() const { return d_ptr->notifications; } #include "moc_qtcamdevice.cpp" <commit_msg>Stop viewfinder after the pipeline reaches idle state.<commit_after>/*! * This file is part of CameraPlus. * * Copyright (C) 2012 Mohammed Sameer <msameer@foolab.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) 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 */ #include "qtcamdevice.h" #include "qtcamviewfinder.h" #include "qtcamconfig.h" #include "qtcamdevice_p.h" #include <QDebug> #include <gst/gst.h> #include "qtcamgstreamermessagelistener.h" #include "qtcammode.h" #include "qtcamimagemode.h" #include "qtcamvideomode.h" #include "qtcamnotifications.h" QtCamDevice::QtCamDevice(QtCamConfig *config, const QString& name, const QVariant& id, QObject *parent) : QObject(parent), d_ptr(new QtCamDevicePrivate) { d_ptr->q_ptr = this; d_ptr->name = name; d_ptr->id = id; d_ptr->conf = config; d_ptr->cameraBin = gst_element_factory_make("camerabin2", "QtCameraCameraBin"); if (!d_ptr->cameraBin) { qCritical() << "Failed to create camerabin"; return; } d_ptr->createAndAddElement(d_ptr->conf->audioSource(), "audio-source", "QtCameraAudioSrc"); d_ptr->createAndAddVideoSource(); int flags = 0x00000001 /* no-audio-conversion - Do not use audio conversion elements */ | 0x00000002 /* no-video-conversion - Do not use video conversion elements */ | 0x00000004 /* no-viewfinder-conversion - Do not use viewfinder conversion elements */ | 0x00000008; /* no-image-conversion - Do not use image conversion elements */ g_object_set(d_ptr->cameraBin, "flags", flags, NULL); d_ptr->setAudioCaptureCaps(); // TODO: audio bitrate // TODO: video bitrate // TODO: filters // TODO: custom properties for jifmux, mp4mux, audio encoder, video encoder, sink & video source d_ptr->listener = new QtCamGStreamerMessageListener(gst_element_get_bus(d_ptr->cameraBin), d_ptr, this); QObject::connect(d_ptr->listener, SIGNAL(error(const QString&, int, const QString&)), this, SLOT(_d_error(const QString&, int, const QString&))); QObject::connect(d_ptr->listener, SIGNAL(started()), this, SLOT(_d_started())); QObject::connect(d_ptr->listener, SIGNAL(stopped()), this, SLOT(_d_stopped())); QObject::connect(d_ptr->listener, SIGNAL(stopping()), this, SLOT(_d_stopping())); g_signal_connect(d_ptr->cameraBin, "notify::idle", G_CALLBACK(QtCamDevicePrivate::on_idle_changed), d_ptr); g_signal_connect(d_ptr->wrapperVideoSource, "notify::ready-for-capture", G_CALLBACK(QtCamDevicePrivate::on_ready_for_capture_changed), d_ptr); d_ptr->image = new QtCamImageMode(d_ptr, this); d_ptr->video = new QtCamVideoMode(d_ptr, this); d_ptr->notifications = new QtCamNotifications(this, this); } QtCamDevice::~QtCamDevice() { stop(true); d_ptr->image->deactivate(); d_ptr->video->deactivate(); delete d_ptr->image; d_ptr->image = 0; delete d_ptr->video; d_ptr->video = 0; if (d_ptr->cameraBin) { gst_object_unref(d_ptr->cameraBin); } delete d_ptr; d_ptr = 0; } bool QtCamDevice::setViewfinder(QtCamViewfinder *viewfinder) { if (isRunning()) { qWarning() << "QtCamDevice: pipeline must be stopped before setting a viewfinder"; return false; } if (d_ptr->viewfinder == viewfinder) { return true; } if (!viewfinder) { qWarning() << "QtCamDevice: viewfinder cannot be unset."; return false; } if (d_ptr->viewfinder) { qWarning() << "QtCamDevice: viewfinder cannot be replaced."; return false; } if (!viewfinder->setDevice(this)) { return false; } d_ptr->viewfinder = viewfinder; return true; } bool QtCamDevice::start() { if (d_ptr->error) { qWarning() << "Pipeline must be stopped first because of an error."; return false; } if (!d_ptr->cameraBin) { qWarning() << "Missing camerabin"; return false; } if (!d_ptr->viewfinder) { qWarning() << "Viewfinder not set"; return false; } if (isRunning()) { return true; } if (!d_ptr->active) { d_ptr->image->activate(); } else { d_ptr->active->applySettings(); } // Set sink. if (!d_ptr->setViewfinderSink()) { return false; } GstStateChangeReturn err = gst_element_set_state(d_ptr->cameraBin, GST_STATE_PLAYING); if (err == GST_STATE_CHANGE_FAILURE) { qWarning() << "Failed to start camera pipeline"; return false; } // We need to wait for startup to complet. There's a race condition somewhere in the pipeline. // If we set the scene mode to night and update the resolution while starting up // then subdevsrc2 barfs: // streaming task paused, reason not-negotiated (-4) GstState state; if (err != GST_STATE_CHANGE_ASYNC) { return true; } if (gst_element_get_state(d_ptr->cameraBin, &state, 0, GST_CLOCK_TIME_NONE) != GST_STATE_CHANGE_SUCCESS) { // We are seriously screwed up :( return false; } if (state != GST_STATE_PLAYING) { // Huh ? Is this even possible ?? return false; } return true; } bool QtCamDevice::stop(bool force) { if (!d_ptr->cameraBin) { return true; } if (d_ptr->error) { gst_element_set_state(d_ptr->cameraBin, GST_STATE_NULL); d_ptr->error = false; d_ptr->viewfinder->stop(); return true; } GstState state; gst_element_get_state(d_ptr->cameraBin, &state, 0, GST_CLOCK_TIME_NONE); if (state == GST_STATE_NULL) { // Nothing to do. return true; } if (!isIdle()) { if (!force) { return false; } } d_ptr->stopping = true; // First we go to ready: GstStateChangeReturn st = gst_element_set_state(d_ptr->cameraBin, GST_STATE_READY); if (st != GST_STATE_CHANGE_FAILURE) { // Flush the bus: d_ptr->listener->flushMessages(); } // Now to NULL gst_element_set_state(d_ptr->cameraBin, GST_STATE_NULL); d_ptr->viewfinder->stop(); d_ptr->stopping = false; return true; } bool QtCamDevice::isRunning() { if (!d_ptr->cameraBin) { return false; } GstState state; GstStateChangeReturn err = gst_element_get_state(d_ptr->cameraBin, &state, 0, GST_CLOCK_TIME_NONE); if (err == GST_STATE_CHANGE_FAILURE || state != GST_STATE_PLAYING) { return false; } return true; } bool QtCamDevice::isIdle() { if (!d_ptr->cameraBin) { return true; } gboolean idle = FALSE; g_object_get(d_ptr->cameraBin, "idle", &idle, NULL); return idle == TRUE; } QtCamImageMode *QtCamDevice::imageMode() const { return d_ptr->image; } QtCamVideoMode *QtCamDevice::videoMode() const { return d_ptr->video; } QtCamMode *QtCamDevice::activeMode() const { return d_ptr->active; } QString QtCamDevice::name() const { return d_ptr->name; } QVariant QtCamDevice::id() const { return d_ptr->id; } QtCamConfig *QtCamDevice::config() const { return d_ptr->conf; } QtCamGStreamerMessageListener *QtCamDevice::listener() const { return d_ptr->listener; } QtCamNotifications *QtCamDevice::notifications() const { return d_ptr->notifications; } #include "moc_qtcamdevice.cpp" <|endoftext|>
<commit_before>/******************************************************************************\ * File: appl.cpp * Purpose: Implementation of classes for syncodbcquery * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2008, Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/aboutdlg.h> #include <wx/tokenzr.h> #include <wx/extension/grid.h> #include <wx/extension/shell.h> #include "appl.h" #include "appl.xpm" const wxString Quoted(const wxString& text) { return "'" + text + "'"; } IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { SetAppName("syncodbcquery"); wxExApp::OnInit(); MyFrame *frame = new MyFrame("syncodbcquery"); frame->Show(true); SetTopWindow(frame); return true; } BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory) EVT_CLOSE(MyFrame::OnClose) EVT_MENU(wxID_EXECUTE, MyFrame::OnCommand) EVT_MENU(wxID_PREFERENCES, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand) EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand) EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand) EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI) END_EVENT_TABLE() MyFrame::MyFrame(const wxString& title) : wxExFrameWithHistory(NULL, wxID_ANY, title) , m_Running(false) , m_Stopped(false) { SetIcon(appl_xpm); wxExMenu* menuFile = new wxExMenu; menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENTFILE_MENU, menuFile); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu* menuDatabase = new wxExMenu; menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open"))); menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close")); wxExMenu* menuQuery = new wxExMenu; menuQuery->Append(wxID_EXECUTE); menuQuery->Append(wxID_STOP); wxMenu* menuOptions = new wxMenu(); menuOptions->Append(wxID_PREFERENCES); wxMenu* menuView = new wxMenu(); menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar")); menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query")); menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results")); menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics")); wxMenu* menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar *menubar = new wxMenuBar; menubar->Append(menuFile, _("&File")); menubar->Append(menuView, _("&View")); menubar->Append(menuDatabase, _("&Database")); menubar->Append(menuQuery, _("&Query")); menubar->Append(menuOptions, _("&Options")); menubar->Append(menuHelp, _("&Help")); SetMenuBar(menubar); m_Query = new wxExSTCWithFrame(this, wxExSTC::STC_MENU_SIMPLE | wxExSTC::STC_MENU_FIND | wxExSTC::STC_MENU_REPLACE | wxExSTC::STC_MENU_INSERT); m_Query->SetLexer("sql"); m_Results = new wxExGrid(this); m_Results->CreateGrid(0, 0); m_Results->EnableEditing(false); // this is a read-only grid m_Shell = new wxExSTCShell(this, ">", ";", true, 50); m_Shell->SetFocus(); m_Shell->DocumentEnd(); m_Shell->SetLexer(); GetManager().AddPane(m_Shell, wxAuiPaneInfo(). Name("CONSOLE"). CenterPane()); GetManager().AddPane(m_Results, wxAuiPaneInfo(). Name("RESULTS"). Caption(_("Results")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Query, wxAuiPaneInfo(). Name("QUERY"). Caption(_("Query")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Statistics.Show(this), wxAuiPaneInfo().Left(). MaximizeButton(true). Caption(_("Statistics")). Name("STATISTICS")); GetManager().LoadPerspective(wxExApp::GetConfig("Perspective")); GetManager().GetPane("QUERY").Show(false); GetManager().Update(); std::vector<wxExPane> panes; panes.push_back(wxExPane("PaneText", -3)); panes.push_back(wxExPane("PaneLines", 100, _("Lines in window"))); SetupStatusBar(panes); CreateToolBar(); m_ToolBar->AddTool(wxID_NEW); m_ToolBar->AddTool(wxID_OPEN); m_ToolBar->AddTool(wxID_SAVE); #ifdef __WXGTK__ m_ToolBar->AddTool(wxID_EXECUTE); #endif m_ToolBar->Realize(); otl_connect::otl_initialize(); } void MyFrame::ConfigDialogApplied(wxWindowID dialogid) { m_Query->ConfigGet(); m_Shell->ConfigGet(); } void MyFrame::OnClose(wxCloseEvent& event) { if (!m_Query->Continue()) { return; } wxExApp::SetConfig("Perspective", GetManager().SavePerspective()); m_db.logoff(); event.Skip(); } void MyFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_ABOUT: { wxAboutDialogInfo info; info.SetIcon(GetIcon()); info.SetDescription(_("This program offers a general ODBC query.")); info.SetVersion("v1.0"); info.SetCopyright("(c) 2008, Anton van Wezenbeek"); info.AddDeveloper(wxVERSION_STRING); info.AddDeveloper(wxEX_VERSION_STRING); info.AddDeveloper(wxExOTLVersion()); wxAboutBox(info); } break; case wxID_EXECUTE: m_Stopped = false; RunQueries(m_Query->GetText()); break; case wxID_EXIT: Close(true); break; case wxID_NEW: if (m_Query->FileNew()) { m_Query->SetLexer("sql"); m_Query->SetFocus(); GetManager().GetPane("QUERY").Show(); GetManager().Update(); } break; case wxID_OPEN: DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true); break; case wxID_SAVE: m_Query->FileSave(); break; case wxID_SAVEAS: m_Query->FileSaveAs(); break; case wxID_STOP: m_Running = false; m_Stopped = true; break; case ID_DATABASE_CLOSE: m_db.logoff(); m_Shell->SetPrompt(">"); break; case ID_DATABASE_OPEN: wxExOTLDialog(wxExApp::GetConfig(), &m_db); m_Shell->SetPrompt((m_db.connected ? wxExApp::GetConfig(_("Datasource")): "") + ">"); break; case wxID_PREFERENCES: wxExSTC::ConfigDialog(_("Editor Options"), wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_MODELESS); break; case ID_SHELL_COMMAND: if (m_db.connected) { try { const wxString query = event.GetString().substr( 0, event.GetString().length() - 1); m_Stopped = false; RunQuery(query, true); } catch (otl_exception& p) { if (m_Results->IsShown()) { m_Results->EndBatch(); } m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg)); } } else { m_Shell->AppendText(_("\nnot connected")); } m_Shell->Prompt(); break; case ID_SHELL_COMMAND_STOP: m_Stopped = true; m_Shell->Prompt("Cancelled"); break; case ID_VIEW_QUERY: TogglePane("QUERY"); break; case ID_VIEW_RESULTS: TogglePane("RESULTS"); break; case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break; default: event.Skip(); } } void MyFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case wxID_EXECUTE: // If we have a query, you can hide it, but still run it. event.Enable(m_Query->GetLength() > 0 && m_db.connected); break; case wxID_SAVE: event.Enable(m_Query->GetModify()); break; case wxID_SAVEAS: event.Enable(m_Query->GetLength() > 0); break; case wxID_STOP: event.Enable(m_Running); break; case ID_DATABASE_CLOSE: event.Enable(m_db.connected); break; case ID_DATABASE_OPEN: event.Enable(!m_db.connected); break; case ID_RECENTFILE_MENU: event.Enable(!GetRecentFile().empty()); break; case ID_VIEW_QUERY: event.Check(GetManager().GetPane("QUERY").IsShown()); break; case ID_VIEW_RESULTS: event.Check(GetManager().GetPane("RESULTS").IsShown()); break; case ID_VIEW_STATISTICS: event.Check(GetManager().GetPane("STATISTICS").IsShown()); break; default: wxFAIL; } } bool MyFrame::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { GetManager().GetPane("QUERY").Show(true); GetManager().Update(); // Take care that DialogFileOpen always results in opening in the query. // Otherwise if results are focused, the file is opened in the results. return m_Query->Open(filename, line_number, match, flags); } void MyFrame::RunQuery(const wxString& query, bool empty_results) { wxStopWatch sw; const wxString query_lower = query.Lower(); // Query functions supported by ODBC // $SQLTables, $SQLColumns, etc. // $SQLTables $1:'%' // allow you to get database schema. if (query_lower.StartsWith("select") || query_lower.StartsWith("describe") || query_lower.StartsWith("show") || query_lower.StartsWith("explain") || query_lower.StartsWith("$sql")) { long rpc; if (m_Results->IsShown()) { rpc = wxExOTLQueryToGrid(&m_db, query, m_Results, m_Stopped, empty_results); } else { rpc = wxExOTLQueryToSTC(&m_db, query, m_Shell, m_Stopped); } sw.Pause(); UpdateStatistics(sw, rpc); } else { const long rpc = otl_cursor::direct_exec(m_db, query.c_str()); sw.Pause(); UpdateStatistics(sw, rpc); } m_Shell->DocumentEnd(); } void MyFrame::RunQueries(const wxString& text) { if (m_Results->IsShown()) { m_Results->ClearGrid(); } // Skip sql comments. wxString output = text; wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, ""); // Queries are seperated by ; character. wxStringTokenizer tkz(output, ";"); int no_queries = 0; wxStopWatch sw; m_Running = true; // Run all queries. while (tkz.HasMoreTokens() && !m_Stopped) { wxString query = tkz.GetNextToken(); query.Trim(true); query.Trim(false); if (!query.empty()) { try { RunQuery(query, no_queries == 0); no_queries++; wxYield(); } catch (otl_exception& p) { m_Statistics.Inc(_("Number of query errors")); m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg) + _(" in: ") + Quoted(query)); } } } m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"), no_queries, (float)sw.Time() / (float)1000)); m_Running = false; } void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc) { m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"), rpc, (float)sw.Time() / (float)1000)); m_Statistics.Set(_("Rows processed"), rpc); m_Statistics.Set(_("Query runtime"), sw.Time()); m_Statistics.Inc(_("Total number of queries run")); m_Statistics.Inc(_("Total query runtime"), sw.Time()); m_Statistics.Inc(_("Total rows processed"), rpc); } <commit_msg>reordered commands<commit_after>/******************************************************************************\ * File: appl.cpp * Purpose: Implementation of classes for syncodbcquery * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2008, Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/aboutdlg.h> #include <wx/tokenzr.h> #include <wx/extension/grid.h> #include <wx/extension/shell.h> #include "appl.h" #include "appl.xpm" const wxString Quoted(const wxString& text) { return "'" + text + "'"; } IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { SetAppName("syncodbcquery"); wxExApp::OnInit(); MyFrame *frame = new MyFrame("syncodbcquery"); frame->Show(true); SetTopWindow(frame); return true; } BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory) EVT_CLOSE(MyFrame::OnClose) EVT_MENU(wxID_EXECUTE, MyFrame::OnCommand) EVT_MENU(wxID_PREFERENCES, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand) EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand) EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand) EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI) END_EVENT_TABLE() MyFrame::MyFrame(const wxString& title) : wxExFrameWithHistory(NULL, wxID_ANY, title) , m_Running(false) , m_Stopped(false) { SetIcon(appl_xpm); wxExMenu* menuFile = new wxExMenu; menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENTFILE_MENU, menuFile); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu* menuDatabase = new wxExMenu; menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open"))); menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close")); wxExMenu* menuQuery = new wxExMenu; menuQuery->Append(wxID_EXECUTE); menuQuery->Append(wxID_STOP); wxMenu* menuOptions = new wxMenu(); menuOptions->Append(wxID_PREFERENCES); wxMenu* menuView = new wxMenu(); menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar")); menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query")); menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results")); menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics")); wxMenu* menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar *menubar = new wxMenuBar; menubar->Append(menuFile, _("&File")); menubar->Append(menuView, _("&View")); menubar->Append(menuDatabase, _("&Database")); menubar->Append(menuQuery, _("&Query")); menubar->Append(menuOptions, _("&Options")); menubar->Append(menuHelp, _("&Help")); SetMenuBar(menubar); m_Query = new wxExSTCWithFrame(this, wxExSTC::STC_MENU_SIMPLE | wxExSTC::STC_MENU_FIND | wxExSTC::STC_MENU_REPLACE | wxExSTC::STC_MENU_INSERT); m_Query->SetLexer("sql"); m_Results = new wxExGrid(this); m_Results->CreateGrid(0, 0); m_Results->EnableEditing(false); // this is a read-only grid m_Shell = new wxExSTCShell(this, ">", ";", true, 50); m_Shell->SetFocus(); m_Shell->DocumentEnd(); m_Shell->SetLexer(); GetManager().AddPane(m_Shell, wxAuiPaneInfo(). Name("CONSOLE"). CenterPane()); GetManager().AddPane(m_Results, wxAuiPaneInfo(). Name("RESULTS"). Caption(_("Results")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Query, wxAuiPaneInfo(). Name("QUERY"). Caption(_("Query")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Statistics.Show(this), wxAuiPaneInfo().Left(). MaximizeButton(true). Caption(_("Statistics")). Name("STATISTICS")); GetManager().LoadPerspective(wxExApp::GetConfig("Perspective")); GetManager().GetPane("QUERY").Show(false); GetManager().Update(); std::vector<wxExPane> panes; panes.push_back(wxExPane("PaneText", -3)); panes.push_back(wxExPane("PaneLines", 100, _("Lines in window"))); SetupStatusBar(panes); CreateToolBar(); m_ToolBar->AddTool(wxID_NEW); m_ToolBar->AddTool(wxID_OPEN); m_ToolBar->AddTool(wxID_SAVE); #ifdef __WXGTK__ m_ToolBar->AddTool(wxID_EXECUTE); #endif m_ToolBar->Realize(); otl_connect::otl_initialize(); } void MyFrame::ConfigDialogApplied(wxWindowID dialogid) { m_Query->ConfigGet(); m_Shell->ConfigGet(); } void MyFrame::OnClose(wxCloseEvent& event) { if (!m_Query->Continue()) { return; } wxExApp::SetConfig("Perspective", GetManager().SavePerspective()); m_db.logoff(); event.Skip(); } void MyFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_ABOUT: { wxAboutDialogInfo info; info.SetIcon(GetIcon()); info.SetDescription(_("This program offers a general ODBC query.")); info.SetVersion("v1.0"); info.SetCopyright("(c) 2008, Anton van Wezenbeek"); info.AddDeveloper(wxVERSION_STRING); info.AddDeveloper(wxEX_VERSION_STRING); info.AddDeveloper(wxExOTLVersion()); wxAboutBox(info); } break; case wxID_EXECUTE: m_Stopped = false; RunQueries(m_Query->GetText()); break; case wxID_EXIT: Close(true); break; case wxID_NEW: if (m_Query->FileNew()) { m_Query->SetLexer("sql"); m_Query->SetFocus(); GetManager().GetPane("QUERY").Show(); GetManager().Update(); } break; case wxID_OPEN: DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true); break; case wxID_PREFERENCES: wxExSTC::ConfigDialog(_("Editor Options"), wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_MODELESS); break; case wxID_SAVE: m_Query->FileSave(); break; case wxID_SAVEAS: m_Query->FileSaveAs(); break; case wxID_STOP: m_Running = false; m_Stopped = true; break; case ID_DATABASE_CLOSE: m_db.logoff(); m_Shell->SetPrompt(">"); break; case ID_DATABASE_OPEN: wxExOTLDialog(wxExApp::GetConfig(), &m_db); m_Shell->SetPrompt((m_db.connected ? wxExApp::GetConfig(_("Datasource")): "") + ">"); break; case ID_SHELL_COMMAND: if (m_db.connected) { try { const wxString query = event.GetString().substr( 0, event.GetString().length() - 1); m_Stopped = false; RunQuery(query, true); } catch (otl_exception& p) { if (m_Results->IsShown()) { m_Results->EndBatch(); } m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg)); } } else { m_Shell->AppendText(_("\nnot connected")); } m_Shell->Prompt(); break; case ID_SHELL_COMMAND_STOP: m_Stopped = true; m_Shell->Prompt("Cancelled"); break; case ID_VIEW_QUERY: TogglePane("QUERY"); break; case ID_VIEW_RESULTS: TogglePane("RESULTS"); break; case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break; default: event.Skip(); } } void MyFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case wxID_EXECUTE: // If we have a query, you can hide it, but still run it. event.Enable(m_Query->GetLength() > 0 && m_db.connected); break; case wxID_SAVE: event.Enable(m_Query->GetModify()); break; case wxID_SAVEAS: event.Enable(m_Query->GetLength() > 0); break; case wxID_STOP: event.Enable(m_Running); break; case ID_DATABASE_CLOSE: event.Enable(m_db.connected); break; case ID_DATABASE_OPEN: event.Enable(!m_db.connected); break; case ID_RECENTFILE_MENU: event.Enable(!GetRecentFile().empty()); break; case ID_VIEW_QUERY: event.Check(GetManager().GetPane("QUERY").IsShown()); break; case ID_VIEW_RESULTS: event.Check(GetManager().GetPane("RESULTS").IsShown()); break; case ID_VIEW_STATISTICS: event.Check(GetManager().GetPane("STATISTICS").IsShown()); break; default: wxFAIL; } } bool MyFrame::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { GetManager().GetPane("QUERY").Show(true); GetManager().Update(); // Take care that DialogFileOpen always results in opening in the query. // Otherwise if results are focused, the file is opened in the results. return m_Query->Open(filename, line_number, match, flags); } void MyFrame::RunQuery(const wxString& query, bool empty_results) { wxStopWatch sw; const wxString query_lower = query.Lower(); // Query functions supported by ODBC // $SQLTables, $SQLColumns, etc. // $SQLTables $1:'%' // allow you to get database schema. if (query_lower.StartsWith("select") || query_lower.StartsWith("describe") || query_lower.StartsWith("show") || query_lower.StartsWith("explain") || query_lower.StartsWith("$sql")) { long rpc; if (m_Results->IsShown()) { rpc = wxExOTLQueryToGrid(&m_db, query, m_Results, m_Stopped, empty_results); } else { rpc = wxExOTLQueryToSTC(&m_db, query, m_Shell, m_Stopped); } sw.Pause(); UpdateStatistics(sw, rpc); } else { const long rpc = otl_cursor::direct_exec(m_db, query.c_str()); sw.Pause(); UpdateStatistics(sw, rpc); } m_Shell->DocumentEnd(); } void MyFrame::RunQueries(const wxString& text) { if (m_Results->IsShown()) { m_Results->ClearGrid(); } // Skip sql comments. wxString output = text; wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, ""); // Queries are seperated by ; character. wxStringTokenizer tkz(output, ";"); int no_queries = 0; wxStopWatch sw; m_Running = true; // Run all queries. while (tkz.HasMoreTokens() && !m_Stopped) { wxString query = tkz.GetNextToken(); query.Trim(true); query.Trim(false); if (!query.empty()) { try { RunQuery(query, no_queries == 0); no_queries++; wxYield(); } catch (otl_exception& p) { m_Statistics.Inc(_("Number of query errors")); m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg) + _(" in: ") + Quoted(query)); } } } m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"), no_queries, (float)sw.Time() / (float)1000)); m_Running = false; } void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc) { m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"), rpc, (float)sw.Time() / (float)1000)); m_Statistics.Set(_("Rows processed"), rpc); m_Statistics.Set(_("Query runtime"), sw.Time()); m_Statistics.Inc(_("Total number of queries run")); m_Statistics.Inc(_("Total query runtime"), sw.Time()); m_Statistics.Inc(_("Total rows processed"), rpc); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "init.h" #include "networkstyle.h" #include "ui_interface.h" #include "util.h" #include "version.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> #include <QRadialGradient> SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) : QWidget(0, f), curAlignment(0) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; float devicePixelRatio = 1.0; #if QT_VERSION > 0x050100 devicePixelRatio = ((QGuiApplication*)QCoreApplication::instance())->devicePixelRatio(); #endif // define text to place QString titleText = tr("Bitcoin Core"); QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")); QString titleAddText = networkStyle->getTitleAddText(); QString font = "Arial"; // create a bitmap according to device pixelratio QSize splashSize(480*devicePixelRatio,320*devicePixelRatio); pixmap = QPixmap(splashSize); #if QT_VERSION > 0x050100 // change to HiDPI if it makes sense pixmap.setDevicePixelRatio(devicePixelRatio); #endif QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100,100,100)); // draw a slighly radial gradient QRadialGradient gradient(QPoint(0,0), splashSize.width()/devicePixelRatio); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, QColor(247,247,247)); QRect rGradient(QPoint(0,0), splashSize); pixPaint.fillRect(rGradient, gradient); // draw the bitcoin icon, expected size of PNG: 1024x1024 QRect rectIcon(QPoint(-150,-122), QSize(430,430)); const QSize requiredSize(1024,1024); QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize)); pixPaint.drawPixmap(rectIcon, icon); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); // draw additional text if special network if(!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleAddTextWidth-10,15,titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio)); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget *mainWin) { Q_UNUSED(mainWin); hide(); } static void InitMessage(SplashScreen *splash, const std::string &message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter), Q_ARG(QColor, QColor(55,55,55))); } static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen *splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET if(pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color) { curMessage = message; curAlignment = alignment; curColor = color; update(); } void SplashScreen::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawPixmap(0, 0, pixmap); QRect r = rect().adjusted(5, 5, -5, -5); painter.setPen(curColor); painter.drawText(r, curAlignment, curMessage); } void SplashScreen::closeEvent(QCloseEvent *event) { StartShutdown(); // allows an "emergency" shutdown during startup event->ignore(); } <commit_msg>qt: avoid hard-coding font names<commit_after>// Copyright (c) 2011-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "init.h" #include "networkstyle.h" #include "ui_interface.h" #include "util.h" #include "version.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> #include <QRadialGradient> SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) : QWidget(0, f), curAlignment(0) { // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; float devicePixelRatio = 1.0; #if QT_VERSION > 0x050100 devicePixelRatio = ((QGuiApplication*)QCoreApplication::instance())->devicePixelRatio(); #endif // define text to place QString titleText = tr("Bitcoin Core"); QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // create a bitmap according to device pixelratio QSize splashSize(480*devicePixelRatio,320*devicePixelRatio); pixmap = QPixmap(splashSize); #if QT_VERSION > 0x050100 // change to HiDPI if it makes sense pixmap.setDevicePixelRatio(devicePixelRatio); #endif QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100,100,100)); // draw a slighly radial gradient QRadialGradient gradient(QPoint(0,0), splashSize.width()/devicePixelRatio); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, QColor(247,247,247)); QRect rGradient(QPoint(0,0), splashSize); pixPaint.fillRect(rGradient, gradient); // draw the bitcoin icon, expected size of PNG: 1024x1024 QRect rectIcon(QPoint(-150,-122), QSize(430,430)); const QSize requiredSize(1024,1024); QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize)); pixPaint.drawPixmap(rectIcon, icon); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); // draw additional text if special network if(!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width()/devicePixelRatio-titleAddTextWidth-10,15,titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio)); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget *mainWin) { Q_UNUSED(mainWin); hide(); } static void InitMessage(SplashScreen *splash, const std::string &message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter), Q_ARG(QColor, QColor(55,55,55))); } static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen *splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET if(pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } void SplashScreen::showMessage(const QString &message, int alignment, const QColor &color) { curMessage = message; curAlignment = alignment; curColor = color; update(); } void SplashScreen::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.drawPixmap(0, 0, pixmap); QRect r = rect().adjusted(5, 5, -5, -5); painter.setPen(curColor); painter.drawText(r, curAlignment, curMessage); } void SplashScreen::closeEvent(QCloseEvent *event) { StartShutdown(); // allows an "emergency" shutdown during startup event->ignore(); } <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix.hpp> #include <nix/hdf5/BlockHDF5.hpp> using namespace std; namespace nix { /** * Go through the tree of sources originating from every source in this * block until a max. level of "max_depth" and check for each source * whether to return it depending on predicate function "filter". * Return resulting vector of sources, which may contain duplicates. * * @param object filter function of type std::function<bool(const Source &)> * @param int maximum depth to search tree * @return object vector of sources */ std::vector<Source> Block::findSources( util::AcceptAll<Source> filter, size_t max_depth) const { vector<Source> probes = sources(); vector<Source> matches; vector<Source> result; for (typename std::vector<Source>::iterator it = probes.begin(); it!=probes.end(); ++it) { matches = it->findSources(filter, max_depth); result.insert( result.end(), matches.begin(), matches.end() ); } return result; } } <commit_msg>Block: remove unnecessary typename for an iterator<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix.hpp> #include <nix/hdf5/BlockHDF5.hpp> using namespace std; namespace nix { /** * Go through the tree of sources originating from every source in this * block until a max. level of "max_depth" and check for each source * whether to return it depending on predicate function "filter". * Return resulting vector of sources, which may contain duplicates. * * @param object filter function of type std::function<bool(const Source &)> * @param int maximum depth to search tree * @return object vector of sources */ std::vector<Source> Block::findSources( util::AcceptAll<Source> filter, size_t max_depth) const { vector<Source> probes = sources(); vector<Source> matches; vector<Source> result; for (std::vector<Source>::iterator it = probes.begin(); it!=probes.end(); ++it) { matches = it->findSources(filter, max_depth); result.insert( result.end(), matches.begin(), matches.end() ); } return result; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkFEMLoadLandmark.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkFEMLoadLandmark.h" namespace itk { namespace fem { /** * Read a LoadLandmark object from the input stream */ void LoadLandmark::Read( std::istream& f, void* info ) { int n1, n2; vnl_vector<Float> pu; vnl_vector<Float> pd; bool isFound = false; // Convert the info pointer to a usable objects ReadInfoType::ElementArrayPointer elements=static_cast<ReadInfoType*>(info)->m_el; // first call the parent's read function Superclass::Read(f,info); // Read the landmark ID - obsolete // SkipWhiteSpace(f); f>>id; if(!f) goto out; // read the dimensions of the undeformed point and set the size of the point accordingly SkipWhiteSpace(f); f>>n1; if(!f) goto out; pu.resize(n1); this->m_pt.resize(n1); // read the undeformed point in global coordinates SkipWhiteSpace(f); f>>pu; if(!f) goto out; // Read the dimensions of the deformed point and set the size of the point accordingly SkipWhiteSpace(f); f>>n2; if(!f) goto out; pd.resize(n2); m_force.resize(n2); // read the deformed point in global coordinates SkipWhiteSpace(f); f>>pd; if(!f) goto out; m_source = pd; m_pt = pd; m_target = pu; m_force = pu-pd; // read the square root of the variance associated with this landmark SkipWhiteSpace(f); f>>eta; if(!f) goto out; // Verify that the undeformed and deformed points are of the same size. if (n1 != n2) { goto out; } this->el.resize(1); // Compute & store the local coordinates of the undeformed point and // the pointer to the element /* for (Element::ArrayType::const_iterator n = elements->begin(); n!=elements->end() && !isFound; n++) { if ( (*n)->GetLocalFromGlobalCoordinates(pd, this->m_pt) ) { isFound = true; this->el.push_back( ( &**n ) ); } }*/ out: if( !f ) { throw FEMExceptionIO(__FILE__,__LINE__,"LoadLandmark::Read()","Error reading landmark load!"); } } /** * Write the LoadLandmark object to the output stream */ void LoadLandmark::Write( std::ostream& f ) const { /** first call the parent's write function */ Superclass::Write(f); /** * Write the actual LoadLandmark data */ /** Information */ f<<"\t"<<"Each vector below is preceded by its size"<<"\n"; /** Write the point coordinates in the undeformed state */ f<<"\t"<<m_pt.size()<<" "<<m_pt<<"\t%Point (local) coordinates, undeformed state"<<"\n"; /** check for errors */ if (!f) { throw FEMExceptionIO(__FILE__,__LINE__,"LoadBCMFC::Write()","Error writing FEM load!"); } } FEM_CLASS_REGISTER(LoadLandmark) }} // end namespace itk::fem <commit_msg><commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkFEMLoadLandmark.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkFEMLoadLandmark.h" namespace itk { namespace fem { /** * Read a LoadLandmark object from the input stream */ void LoadLandmark::Read( std::istream& f, void* info ) { int n1, n2; vnl_vector<Float> pu; vnl_vector<Float> pd; // bool isFound = false; // Convert the info pointer to a usable objects // ReadInfoType::ElementArrayPointer elements=static_cast<ReadInfoType*>(info)->m_el; // first call the parent's read function Superclass::Read(f,info); // Read the landmark ID - obsolete // SkipWhiteSpace(f); f>>id; if(!f) goto out; // read the dimensions of the undeformed point and set the size of the point accordingly SkipWhiteSpace(f); f>>n1; if(!f) goto out; pu.resize(n1); this->m_pt.resize(n1); // read the undeformed point in global coordinates SkipWhiteSpace(f); f>>pu; if(!f) goto out; // Read the dimensions of the deformed point and set the size of the point accordingly SkipWhiteSpace(f); f>>n2; if(!f) goto out; pd.resize(n2); m_force.resize(n2); // read the deformed point in global coordinates SkipWhiteSpace(f); f>>pd; if(!f) goto out; m_source = pd; m_pt = pd; m_target = pu; m_force = pu-pd; // read the square root of the variance associated with this landmark SkipWhiteSpace(f); f>>eta; if(!f) goto out; // Verify that the undeformed and deformed points are of the same size. if (n1 != n2) { goto out; } this->el.resize(1); // Compute & store the local coordinates of the undeformed point and // the pointer to the element /* for (Element::ArrayType::const_iterator n = elements->begin(); n!=elements->end() && !isFound; n++) { if ( (*n)->GetLocalFromGlobalCoordinates(pd, this->m_pt) ) { isFound = true; this->el.push_back( ( &**n ) ); } }*/ out: if( !f ) { throw FEMExceptionIO(__FILE__,__LINE__,"LoadLandmark::Read()","Error reading landmark load!"); } } /** * Write the LoadLandmark object to the output stream */ void LoadLandmark::Write( std::ostream& f ) const { /** first call the parent's write function */ Superclass::Write(f); /** * Write the actual LoadLandmark data */ /** Information */ f<<"\t"<<"Each vector below is preceded by its size"<<"\n"; /** Write the point coordinates in the undeformed state */ f<<"\t"<<m_pt.size()<<" "<<m_pt<<"\t%Point (local) coordinates, undeformed state"<<"\n"; /** check for errors */ if (!f) { throw FEMExceptionIO(__FILE__,__LINE__,"LoadBCMFC::Write()","Error writing FEM load!"); } } FEM_CLASS_REGISTER(LoadLandmark) }} // end namespace itk::fem <|endoftext|>
<commit_before>/************************************ * file enc : ASCII * author : wuyanyi09@gmail.com ************************************/ #include "KeyWordExt.h" namespace CppJieba { KeyWordExt::KeyWordExt() { } KeyWordExt::~KeyWordExt() { } bool KeyWordExt::init() { return _segment.init(); } bool KeyWordExt::loadSegDict(const string& filePath) { return _segment.loadSegDict(filePath); } bool KeyWordExt::loadPriorSubWords(const string& filePath) { LogInfo(string_format("loadPriorSubWords(%s) start", filePath.c_str())); if(!checkFileExist(filePath.c_str())) { LogError(string_format("cann't find file[%s].",filePath.c_str())); return false; } if(!_priorSubWords.empty()) { LogError("_priorSubWords has been initted before"); return false; } ifstream infile(filePath.c_str()); string subword; while(getline(infile, subword)) { _priorSubWords.push_back(subword); } LogInfo(string_format("loadPriorSubWords(%s) end", filePath.c_str())); infile.close(); return true; } bool KeyWordExt::loadStopWords(const string& filePath) { LogInfo(string_format("loadStopWords(%s) start", filePath.c_str())); if(!_stopWords.empty()) { LogError("_stopWords has been loaded before! "); return false; } if(!checkFileExist(filePath.c_str())) { LogError(string_format("cann't find file[%s].",filePath.c_str())); return false; } ifstream ifile(filePath.c_str()); string line; while(getline(ifile, line)) { _stopWords.insert(line); } LogInfo(string_format("load stopwords[%d] finished.", _stopWords.size())); return true; } bool KeyWordExt::dispose() { _segment.dispose(); return true; } bool KeyWordExt::_wordInfoCompare(const WordInfo& a, const WordInfo& b) { return a.weight > b.weight; } bool KeyWordExt::_sortWLIDF(vector<WordInfo>& wordInfos) { //size_t wLenSum = 0; for(uint i = 0; i < wordInfos.size(); i++) { wordInfos[i].wLen = TransCode::getWordLength(wordInfos[i].word); if(0 == wordInfos[i].wLen) { LogFatal("wLen is 0"); return false; } //wLenSum += wordInfos[i].wLen; } /* if(0 == wLenSum) { LogFatal("wLenSum == 0."); return false; }*/ for(uint i = 0; i < wordInfos.size(); i++) { WordInfo& wInfo = wordInfos[i]; double logWordFreq = _segment.getWordWeight(wInfo.word); wInfo.idf = -logWordFreq; size_t wLen = TransCode::getWordLength(wInfo.word); if(0 == wLen) { LogFatal("getUtf8WordLen(%s) return 0"); } wInfo.weight = log(double(wLen + 1)) * wInfo.idf; } sort(wordInfos.begin(), wordInfos.end(), _wordInfoCompare); return true; } bool KeyWordExt::_extractTopN(const vector<string>& words, vector<string>& keywords, uint topN) { keywords.clear(); vector<WordInfo> wordInfos; for(uint i = 0; i < words.size(); i++) { WordInfo wInfo; wInfo.word = words[i]; wordInfos.push_back(wInfo); } _sortWLIDF(wordInfos); #ifdef DEBUG LogDebug(string_format("calc weight & sorted:%s",joinWordInfos(wordInfos).c_str())); #endif _prioritizeSubWords(wordInfos); #ifdef DEBUG LogDebug(string_format("_prioritizeSubWords res:%s", joinWordInfos(wordInfos).c_str())); #endif //extract TopN for(uint i = 0; i < topN && i < wordInfos.size(); i++) { keywords.push_back(wordInfos[i].word); } return true; } bool KeyWordExt::extract(const vector<string>& _words, vector<string>& keywords, uint topN) { if(_words.empty()) { return false; } vector<string> words(_words); #ifdef DEBUG LogDebug(string_format("words:[%s]", joinStr(words, ",").c_str())); #endif bool retFlag = _filter(words); if(!retFlag) { LogError("_filter failed."); return false; } #ifdef DEBUG LogDebug(string_format("_filter res:[%s]", joinStr(words, ",").c_str())); #endif retFlag = _extractTopN(words, keywords, topN); if(!retFlag) { LogError("_extractTopN failed."); return false; } //LogDebug("_extractTopN finished."); #ifdef DEBUG LogDebug(string_format("ext res:[%s]", joinStr(keywords, ",").c_str())); #endif } bool KeyWordExt::extract(const string& title, vector<string>& keywords, uint topN) { if(title.empty()) { return false; } #ifdef DEBUG LogDebug(string_format("title:[%s]",title.c_str())); #endif bool retFlag; vector<string> words; retFlag = _segment.cutDAG(title, words); if(!retFlag) { LogError(string_format("cutDAG(%s) failed.", title.c_str())); return false; } #ifdef DEBUG LogDebug(string_format("cutDAG result:[%s]", joinStr(words, ",").c_str())); #endif retFlag = _filter(words); if(!retFlag) { LogError("_filter failed."); return false; } #ifdef DEBUG LogDebug(string_format("_filter res:[%s]", joinStr(words, ",").c_str())); #endif retFlag = _extractTopN(words, keywords, topN); if(!retFlag) { LogError("_extractTopN failed."); return false; } //LogDebug("_extractTopN finished."); #ifdef DEBUG LogDebug(string_format("ext res:[%s]", joinStr(keywords, ",").c_str())); #endif return true; } bool KeyWordExt::_filter(vector<string>& strs) { bool retFlag; retFlag = _filterDuplicate(strs); if(!retFlag) { LogError("_filterDuplicate failed."); return false; } //LogDebug(string_format("_filterDuplicate res:[%s]", joinStr(strs, ",").c_str())); retFlag = _filterSingleWord(strs); if(!retFlag) { LogError("_filterSingleWord failed."); return false; } //LogDebug(string_format("_filterSingleWord res:[%s]", joinStr(strs, ",").c_str())); retFlag = _filterStopWords(strs); if(!retFlag) { LogError("_filterStopWords failed."); return false; } //LogDebug(string_format("_filterStopWords res:[%s]", joinStr(strs, ",").c_str())); retFlag = _filterSubstr(strs); if(!retFlag) { LogError("_filterSubstr failed."); return false; } //LogDebug(string_format("_filterSubstr res:[%s]", joinStr(strs, ",").c_str())); return true; } bool KeyWordExt::_filterStopWords(vector<string>& strs) { if(_stopWords.empty()) { return true; } for(VSI it = strs.begin(); it != strs.end();) { if(_stopWords.find(*it) != _stopWords.end()) { it = strs.erase(it); } else { it ++; } } return true; } bool KeyWordExt::_filterDuplicate(vector<string>& strs) { set<string> st; for(VSI it = strs.begin(); it != strs.end(); ) { if(st.find(*it) != st.end()) { it = strs.erase(it); } else { st.insert(*it); it++; } } return true; } bool KeyWordExt::_filterSingleWord(vector<string>& strs) { for(vector<string>::iterator it = strs.begin(); it != strs.end();) { // filter single word if(1 == TransCode::getWordLength(*it)) { it = strs.erase(it); } else { it++; } } return true; } bool KeyWordExt::_filterSubstr(vector<string>& strs) { vector<string> tmp = strs; set<string> subs; for(VSI it = strs.begin(); it != strs.end(); it ++) { for(uint j = 0; j < tmp.size(); j++) { if(*it != tmp[j] && string::npos != tmp[j].find(*it, 0)) { subs.insert(*it); } } } //erase subs from strs for(VSI it = strs.begin(); it != strs.end(); ) { if(subs.end() != subs.find(*it)) { it = strs.erase(it); } else { it ++; } } return true; } bool KeyWordExt::_isContainSubWords(const string& word) { for(uint i = 0; i < _priorSubWords.size(); i++) { if(string::npos != word.find(_priorSubWords[i])) { return true; } } return false; } bool KeyWordExt::_prioritizeSubWords(vector<WordInfo>& wordInfos) { if(2 > wordInfos.size()) { return true; } WordInfo prior; bool flag = false; for(vector<WordInfo>::iterator it = wordInfos.begin(); it != wordInfos.end(); ) { if(_isContainSubWords(it->word)) { prior = *it; it = wordInfos.erase(it); flag = true; break; } else { it ++; } } if(flag) { wordInfos.insert(wordInfos.begin(), prior); } return true; } } #ifdef KEYWORDEXT_UT using namespace CppJieba; int main() { KeyWordExt ext; ext.init(); if(!ext.loadSegDict("../dicts/segdict.gbk.v2.1")) { return 1; } ext.loadStopWords("../dicts/stopwords.gbk.v1.0"); if(!ext.loadPriorSubWords("../dicts/prior.gbk")) { cerr<<"err"<<endl; return 1; } ifstream ifile("testtitle.gbk"); vector<string> res; string line; while(getline(ifile, line)) { cout<<line<<endl; res.clear(); ext.extract(line, res, 20); PRINT_VECTOR(res); } ext.dispose(); return 0; } #endif <commit_msg>fix warn bug<commit_after>/************************************ * file enc : ASCII * author : wuyanyi09@gmail.com ************************************/ #include "KeyWordExt.h" namespace CppJieba { KeyWordExt::KeyWordExt() { } KeyWordExt::~KeyWordExt() { } bool KeyWordExt::init() { return _segment.init(); } bool KeyWordExt::loadSegDict(const string& filePath) { return _segment.loadSegDict(filePath); } bool KeyWordExt::loadPriorSubWords(const string& filePath) { LogInfo(string_format("loadPriorSubWords(%s) start", filePath.c_str())); if(!checkFileExist(filePath.c_str())) { LogError(string_format("cann't find file[%s].",filePath.c_str())); return false; } if(!_priorSubWords.empty()) { LogError("_priorSubWords has been initted before"); return false; } ifstream infile(filePath.c_str()); string subword; while(getline(infile, subword)) { _priorSubWords.push_back(subword); } LogInfo(string_format("loadPriorSubWords(%s) end", filePath.c_str())); infile.close(); return true; } bool KeyWordExt::loadStopWords(const string& filePath) { LogInfo(string_format("loadStopWords(%s) start", filePath.c_str())); if(!_stopWords.empty()) { LogError("_stopWords has been loaded before! "); return false; } if(!checkFileExist(filePath.c_str())) { LogError(string_format("cann't find file[%s].",filePath.c_str())); return false; } ifstream ifile(filePath.c_str()); string line; while(getline(ifile, line)) { _stopWords.insert(line); } LogInfo(string_format("load stopwords[%d] finished.", _stopWords.size())); return true; } bool KeyWordExt::dispose() { _segment.dispose(); return true; } bool KeyWordExt::_wordInfoCompare(const WordInfo& a, const WordInfo& b) { return a.weight > b.weight; } bool KeyWordExt::_sortWLIDF(vector<WordInfo>& wordInfos) { //size_t wLenSum = 0; for(uint i = 0; i < wordInfos.size(); i++) { wordInfos[i].wLen = TransCode::getWordLength(wordInfos[i].word); if(0 == wordInfos[i].wLen) { LogFatal("wLen is 0"); return false; } //wLenSum += wordInfos[i].wLen; } /* if(0 == wLenSum) { LogFatal("wLenSum == 0."); return false; }*/ for(uint i = 0; i < wordInfos.size(); i++) { WordInfo& wInfo = wordInfos[i]; double logWordFreq = _segment.getWordWeight(wInfo.word); wInfo.idf = -logWordFreq; size_t wLen = TransCode::getWordLength(wInfo.word); if(0 == wLen) { LogFatal("getUtf8WordLen(%s) return 0"); } wInfo.weight = log(double(wLen + 1)) * wInfo.idf; } sort(wordInfos.begin(), wordInfos.end(), _wordInfoCompare); return true; } bool KeyWordExt::_extractTopN(const vector<string>& words, vector<string>& keywords, uint topN) { keywords.clear(); vector<WordInfo> wordInfos; for(uint i = 0; i < words.size(); i++) { WordInfo wInfo; wInfo.word = words[i]; wordInfos.push_back(wInfo); } _sortWLIDF(wordInfos); #ifdef DEBUG LogDebug(string_format("calc weight & sorted:%s",joinWordInfos(wordInfos).c_str())); #endif _prioritizeSubWords(wordInfos); #ifdef DEBUG LogDebug(string_format("_prioritizeSubWords res:%s", joinWordInfos(wordInfos).c_str())); #endif //extract TopN for(uint i = 0; i < topN && i < wordInfos.size(); i++) { keywords.push_back(wordInfos[i].word); } return true; } bool KeyWordExt::extract(const vector<string>& _words, vector<string>& keywords, uint topN) { if(_words.empty()) { return false; } vector<string> words(_words); #ifdef DEBUG LogDebug(string_format("words:[%s]", joinStr(words, ",").c_str())); #endif bool retFlag = _filter(words); if(!retFlag) { LogError("_filter failed."); return false; } #ifdef DEBUG LogDebug(string_format("_filter res:[%s]", joinStr(words, ",").c_str())); #endif retFlag = _extractTopN(words, keywords, topN); if(!retFlag) { LogError("_extractTopN failed."); return false; } //LogDebug("_extractTopN finished."); #ifdef DEBUG LogDebug(string_format("ext res:[%s]", joinStr(keywords, ",").c_str())); #endif return true; } bool KeyWordExt::extract(const string& title, vector<string>& keywords, uint topN) { if(title.empty()) { return false; } #ifdef DEBUG LogDebug(string_format("title:[%s]",title.c_str())); #endif bool retFlag; vector<string> words; retFlag = _segment.cutDAG(title, words); if(!retFlag) { LogError(string_format("cutDAG(%s) failed.", title.c_str())); return false; } #ifdef DEBUG LogDebug(string_format("cutDAG result:[%s]", joinStr(words, ",").c_str())); #endif retFlag = _filter(words); if(!retFlag) { LogError("_filter failed."); return false; } #ifdef DEBUG LogDebug(string_format("_filter res:[%s]", joinStr(words, ",").c_str())); #endif retFlag = _extractTopN(words, keywords, topN); if(!retFlag) { LogError("_extractTopN failed."); return false; } //LogDebug("_extractTopN finished."); #ifdef DEBUG LogDebug(string_format("ext res:[%s]", joinStr(keywords, ",").c_str())); #endif return true; } bool KeyWordExt::_filter(vector<string>& strs) { bool retFlag; retFlag = _filterDuplicate(strs); if(!retFlag) { LogError("_filterDuplicate failed."); return false; } //LogDebug(string_format("_filterDuplicate res:[%s]", joinStr(strs, ",").c_str())); retFlag = _filterSingleWord(strs); if(!retFlag) { LogError("_filterSingleWord failed."); return false; } //LogDebug(string_format("_filterSingleWord res:[%s]", joinStr(strs, ",").c_str())); retFlag = _filterStopWords(strs); if(!retFlag) { LogError("_filterStopWords failed."); return false; } //LogDebug(string_format("_filterStopWords res:[%s]", joinStr(strs, ",").c_str())); retFlag = _filterSubstr(strs); if(!retFlag) { LogError("_filterSubstr failed."); return false; } //LogDebug(string_format("_filterSubstr res:[%s]", joinStr(strs, ",").c_str())); return true; } bool KeyWordExt::_filterStopWords(vector<string>& strs) { if(_stopWords.empty()) { return true; } for(VSI it = strs.begin(); it != strs.end();) { if(_stopWords.find(*it) != _stopWords.end()) { it = strs.erase(it); } else { it ++; } } return true; } bool KeyWordExt::_filterDuplicate(vector<string>& strs) { set<string> st; for(VSI it = strs.begin(); it != strs.end(); ) { if(st.find(*it) != st.end()) { it = strs.erase(it); } else { st.insert(*it); it++; } } return true; } bool KeyWordExt::_filterSingleWord(vector<string>& strs) { for(vector<string>::iterator it = strs.begin(); it != strs.end();) { // filter single word if(1 == TransCode::getWordLength(*it)) { it = strs.erase(it); } else { it++; } } return true; } bool KeyWordExt::_filterSubstr(vector<string>& strs) { vector<string> tmp = strs; set<string> subs; for(VSI it = strs.begin(); it != strs.end(); it ++) { for(uint j = 0; j < tmp.size(); j++) { if(*it != tmp[j] && string::npos != tmp[j].find(*it, 0)) { subs.insert(*it); } } } //erase subs from strs for(VSI it = strs.begin(); it != strs.end(); ) { if(subs.end() != subs.find(*it)) { it = strs.erase(it); } else { it ++; } } return true; } bool KeyWordExt::_isContainSubWords(const string& word) { for(uint i = 0; i < _priorSubWords.size(); i++) { if(string::npos != word.find(_priorSubWords[i])) { return true; } } return false; } bool KeyWordExt::_prioritizeSubWords(vector<WordInfo>& wordInfos) { if(2 > wordInfos.size()) { return true; } WordInfo prior; bool flag = false; for(vector<WordInfo>::iterator it = wordInfos.begin(); it != wordInfos.end(); ) { if(_isContainSubWords(it->word)) { prior = *it; it = wordInfos.erase(it); flag = true; break; } else { it ++; } } if(flag) { wordInfos.insert(wordInfos.begin(), prior); } return true; } } #ifdef KEYWORDEXT_UT using namespace CppJieba; int main() { KeyWordExt ext; ext.init(); if(!ext.loadSegDict("../dicts/segdict.gbk.v2.1")) { return 1; } ext.loadStopWords("../dicts/stopwords.gbk.v1.0"); if(!ext.loadPriorSubWords("../dicts/prior.gbk")) { cerr<<"err"<<endl; return 1; } ifstream ifile("testtitle.gbk"); vector<string> res; string line; while(getline(ifile, line)) { cout<<line<<endl; res.clear(); ext.extract(line, res, 20); PRINT_VECTOR(res); } ext.dispose(); return 0; } #endif <|endoftext|>
<commit_before>/* Sirikata * CSVObjectFactory.cpp * * Copyright (c) 2010, Ewen Cheslack-Postava * 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 Sirikata 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 "CSVObjectFactory.hpp" #include <list> #include <sirikata/oh/Platform.hpp> #include <sirikata/oh/HostedObject.hpp> #include <vector> namespace Sirikata { CSVObjectFactory::CSVObjectFactory(ObjectHostContext* ctx, ObjectHost* oh, const SpaceID& space, const String& filename, int32 max_objects, int32 connect_rate) : mContext(ctx), mOH(oh), mSpace(space), mFilename(filename), mMaxObjects(max_objects), mConnectRate(connect_rate) { } template<typename T> T safeLexicalCast(const String& orig, T default_val) { if (orig.empty()) return default_val; return boost::lexical_cast<T>(orig); } template<typename T> T safeLexicalCast(const String& orig) { return safeLexicalCast<T>(orig, (T)0); } void CSVObjectFactory::generate() { int count; typedef std::vector<String> StringList; std::ifstream fp(mFilename.c_str()); if (!fp) return; bool is_first = true; int objtype_idx = -1; int pos_idx = -1; int orient_idx = -1; int vel_idx = -1; int mesh_idx = -1; int quat_vel_idx = -1; int script_file_idx = -1; int scale_idx = -1; // For each line while(fp && (count < mMaxObjects)) { String line; std::getline(fp, line); // First char is # and not the first non whitespace char // then this is a comment if(line.length() > 0 && line.at(0) == '#') { continue; } // Split into parts StringList line_parts; int last_comma = -1; String::size_type next_comma = 0; while(next_comma != String::npos) { next_comma = line.find(',', last_comma+1); String next_val; if (next_comma == String::npos) next_val = line.substr(last_comma + 1); else next_val = line.substr(last_comma + 1, next_comma - (last_comma+1)); // Remove quotes from beginning and end if (next_val.size() > 2 && next_val[0] == '"' && next_val[next_val.size()-1] == '"') next_val = next_val.substr(1, next_val.size() - 2); line_parts.push_back(next_val); last_comma = next_comma; } if (is_first) { for(uint32 idx = 0; idx < line_parts.size(); idx++) { if (line_parts[idx] == "objtype") objtype_idx = idx; if (line_parts[idx] == "pos_x") pos_idx = idx; if (line_parts[idx] == "orient_x") orient_idx = idx; if (line_parts[idx] == "vel_x") vel_idx = idx; if (line_parts[idx] == "meshURI") mesh_idx = idx; if (line_parts[idx] == "rot_axis_x") quat_vel_idx = idx; if (line_parts[idx] == "script_file") script_file_idx = idx; if (line_parts[idx] == "scale") scale_idx = idx; } is_first = false; } else { //note: script_file is not required, so not checking it witht he assert assert(objtype_idx != -1 && pos_idx != -1 && orient_idx != -1 && vel_idx != -1 && mesh_idx != -1 && quat_vel_idx != -1); //assert(objtype_idx != -1 && pos_idx != -1 && mesh_idx != -1); if (line_parts[objtype_idx] == "mesh") { Vector3d pos( safeLexicalCast<double>(line_parts[pos_idx+0]), safeLexicalCast<double>(line_parts[pos_idx+1]), safeLexicalCast<double>(line_parts[pos_idx+2]) ); Quaternion orient = orient_idx == -1 ? Quaternion(0, 0, 0, 1) : Quaternion( safeLexicalCast<float>(line_parts[orient_idx+0]), safeLexicalCast<float>(line_parts[orient_idx+1]), safeLexicalCast<float>(line_parts[orient_idx+2]), safeLexicalCast<float>(line_parts[orient_idx+3]), Quaternion::XYZW() ); Vector3f vel = vel_idx == -1 ? Vector3f(0, 0, 0) : Vector3f( safeLexicalCast<float>(line_parts[vel_idx+0]), safeLexicalCast<float>(line_parts[vel_idx+1]), safeLexicalCast<float>(line_parts[vel_idx+2]) ); Vector3f rot_axis = quat_vel_idx == -1 ? Vector3f(0, 0, 0) : Vector3f( safeLexicalCast<float>(line_parts[quat_vel_idx+0]), safeLexicalCast<float>(line_parts[quat_vel_idx+1]), safeLexicalCast<float>(line_parts[quat_vel_idx+2]) ); float angular_speed = quat_vel_idx == -1 ? 0 : safeLexicalCast<float>(line_parts[quat_vel_idx+3]); String mesh( line_parts[mesh_idx] ); String scriptFile = ""; String scriptType = ""; if(script_file_idx != -1) { if(script_file_idx < (int)line_parts.size()) { scriptFile = line_parts[script_file_idx]; scriptType = line_parts[script_file_idx + 1]; } } float scale = scale_idx == -1 ? 1.f : safeLexicalCast<float>(line_parts[scale_idx], 1.f); HostedObjectPtr obj = HostedObject::construct<HostedObject>(mContext, mOH, UUID::random(), false); obj->init(); ObjectConnectInfo oci; oci.object = obj; oci.loc = Location( pos, orient, vel, rot_axis, angular_speed); oci.bounds = BoundingSphere3f(Vector3f::nil(), scale); oci.mesh = mesh; oci.scriptType = scriptType; oci.scriptFile = scriptFile; mIncompleteObjects.push(oci); count++; } } } fp.close(); connectObjects(); return; } void CSVObjectFactory::connectObjects() { if (mContext->stopped()) return; for(int32 i = 0; i < mConnectRate && !mIncompleteObjects.empty(); i++) { ObjectConnectInfo oci = mIncompleteObjects.front(); mIncompleteObjects.pop(); oci.object->connect( mSpace, oci.loc, oci.bounds, oci.mesh, UUID::null(), NULL, oci.scriptFile, oci.scriptType ); } if (!mIncompleteObjects.empty()) mContext->mainStrand->post( Duration::seconds(1.f), std::tr1::bind(&CSVObjectFactory::connectObjects, this) ); } } <commit_msg>Fix uninitialized count bug in CSVObjectFactory which caused it to sometimes not load all the objects.<commit_after>/* Sirikata * CSVObjectFactory.cpp * * Copyright (c) 2010, Ewen Cheslack-Postava * 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 Sirikata 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 "CSVObjectFactory.hpp" #include <list> #include <sirikata/oh/Platform.hpp> #include <sirikata/oh/HostedObject.hpp> #include <vector> namespace Sirikata { CSVObjectFactory::CSVObjectFactory(ObjectHostContext* ctx, ObjectHost* oh, const SpaceID& space, const String& filename, int32 max_objects, int32 connect_rate) : mContext(ctx), mOH(oh), mSpace(space), mFilename(filename), mMaxObjects(max_objects), mConnectRate(connect_rate) { } template<typename T> T safeLexicalCast(const String& orig, T default_val) { if (orig.empty()) return default_val; return boost::lexical_cast<T>(orig); } template<typename T> T safeLexicalCast(const String& orig) { return safeLexicalCast<T>(orig, (T)0); } void CSVObjectFactory::generate() { int count = 0; typedef std::vector<String> StringList; std::ifstream fp(mFilename.c_str()); if (!fp) return; bool is_first = true; int objtype_idx = -1; int pos_idx = -1; int orient_idx = -1; int vel_idx = -1; int mesh_idx = -1; int quat_vel_idx = -1; int script_file_idx = -1; int scale_idx = -1; // For each line while(fp && (count < mMaxObjects)) { String line; std::getline(fp, line); // First char is # and not the first non whitespace char // then this is a comment if(line.length() > 0 && line.at(0) == '#') { continue; } // Split into parts StringList line_parts; int last_comma = -1; String::size_type next_comma = 0; while(next_comma != String::npos) { next_comma = line.find(',', last_comma+1); String next_val; if (next_comma == String::npos) next_val = line.substr(last_comma + 1); else next_val = line.substr(last_comma + 1, next_comma - (last_comma+1)); // Remove quotes from beginning and end if (next_val.size() > 2 && next_val[0] == '"' && next_val[next_val.size()-1] == '"') next_val = next_val.substr(1, next_val.size() - 2); line_parts.push_back(next_val); last_comma = next_comma; } if (is_first) { for(uint32 idx = 0; idx < line_parts.size(); idx++) { if (line_parts[idx] == "objtype") objtype_idx = idx; if (line_parts[idx] == "pos_x") pos_idx = idx; if (line_parts[idx] == "orient_x") orient_idx = idx; if (line_parts[idx] == "vel_x") vel_idx = idx; if (line_parts[idx] == "meshURI") mesh_idx = idx; if (line_parts[idx] == "rot_axis_x") quat_vel_idx = idx; if (line_parts[idx] == "script_file") script_file_idx = idx; if (line_parts[idx] == "scale") scale_idx = idx; } is_first = false; } else { //note: script_file is not required, so not checking it witht he assert assert(objtype_idx != -1 && pos_idx != -1 && orient_idx != -1 && vel_idx != -1 && mesh_idx != -1 && quat_vel_idx != -1); //assert(objtype_idx != -1 && pos_idx != -1 && mesh_idx != -1); if (line_parts[objtype_idx] == "mesh") { Vector3d pos( safeLexicalCast<double>(line_parts[pos_idx+0]), safeLexicalCast<double>(line_parts[pos_idx+1]), safeLexicalCast<double>(line_parts[pos_idx+2]) ); Quaternion orient = orient_idx == -1 ? Quaternion(0, 0, 0, 1) : Quaternion( safeLexicalCast<float>(line_parts[orient_idx+0]), safeLexicalCast<float>(line_parts[orient_idx+1]), safeLexicalCast<float>(line_parts[orient_idx+2]), safeLexicalCast<float>(line_parts[orient_idx+3]), Quaternion::XYZW() ); Vector3f vel = vel_idx == -1 ? Vector3f(0, 0, 0) : Vector3f( safeLexicalCast<float>(line_parts[vel_idx+0]), safeLexicalCast<float>(line_parts[vel_idx+1]), safeLexicalCast<float>(line_parts[vel_idx+2]) ); Vector3f rot_axis = quat_vel_idx == -1 ? Vector3f(0, 0, 0) : Vector3f( safeLexicalCast<float>(line_parts[quat_vel_idx+0]), safeLexicalCast<float>(line_parts[quat_vel_idx+1]), safeLexicalCast<float>(line_parts[quat_vel_idx+2]) ); float angular_speed = quat_vel_idx == -1 ? 0 : safeLexicalCast<float>(line_parts[quat_vel_idx+3]); String mesh( line_parts[mesh_idx] ); String scriptFile = ""; String scriptType = ""; if(script_file_idx != -1) { if(script_file_idx < (int)line_parts.size()) { scriptFile = line_parts[script_file_idx]; scriptType = line_parts[script_file_idx + 1]; } } float scale = scale_idx == -1 ? 1.f : safeLexicalCast<float>(line_parts[scale_idx], 1.f); HostedObjectPtr obj = HostedObject::construct<HostedObject>(mContext, mOH, UUID::random(), false); obj->init(); ObjectConnectInfo oci; oci.object = obj; oci.loc = Location( pos, orient, vel, rot_axis, angular_speed); oci.bounds = BoundingSphere3f(Vector3f::nil(), scale); oci.mesh = mesh; oci.scriptType = scriptType; oci.scriptFile = scriptFile; mIncompleteObjects.push(oci); count++; } } } fp.close(); connectObjects(); return; } void CSVObjectFactory::connectObjects() { if (mContext->stopped()) return; for(int32 i = 0; i < mConnectRate && !mIncompleteObjects.empty(); i++) { ObjectConnectInfo oci = mIncompleteObjects.front(); mIncompleteObjects.pop(); oci.object->connect( mSpace, oci.loc, oci.bounds, oci.mesh, UUID::null(), NULL, oci.scriptFile, oci.scriptType ); } if (!mIncompleteObjects.empty()) mContext->mainStrand->post( Duration::seconds(1.f), std::tr1::bind(&CSVObjectFactory::connectObjects, this) ); } } <|endoftext|>
<commit_before> #include "Math/Cartesian3D.h" #include "Math/Types.h" #include "benchmark/benchmark.h" template class ROOT::Math::Cartesian3D<double>; static void BM_Cartesian3D_CreateEmpty(benchmark::State &state) { while (state.KeepRunning()) ROOT::Math::Cartesian3D<double> c; } BENCHMARK(BM_Cartesian3D_CreateEmpty); template <typename T> static void BM_Cartesian3D_Theta(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1, 2, 3); while (state.KeepRunning()) c.Theta(); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, double)->Range(8, 8 << 10); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Double_v)->Range(8, 8 << 10); // Define our main. BENCHMARK_MAIN(); <commit_msg>Adding more use cases for Google benchmark.<commit_after>#include "Math/Cartesian3D.h" #include "Math/Point3D.h" #include "Math/Vector3D.h" #include "Math/Vector4D.h" #include "Math/GenVector/Rotation3D.h" #include "Math/GenVector/EulerAngles.h" #include "Math/GenVector/AxisAngle.h" #include "Math/GenVector/Quaternion.h" #include "Math/GenVector/RotationX.h" #include "Math/GenVector/RotationY.h" #include "Math/GenVector/RotationZ.h" #include "Math/GenVector/RotationZYX.h" #include "Math/GenVector/LorentzRotation.h" #include "Math/GenVector/Boost.h" #include "Math/GenVector/BoostX.h" #include "Math/GenVector/BoostY.h" #include "Math/GenVector/BoostZ.h" #include "Math/GenVector/Transform3D.h" #include "Math/GenVector/Plane3D.h" #include "Math/GenVector/VectorUtil.h" #include "Math/Types.h" #include "benchmark/benchmark.h" static bool is_aligned(const void *__restrict__ ptr, size_t align) { return (uintptr_t)ptr % align == 0; } template <typename T> using Point = ROOT::Math::PositionVector3D<ROOT::Math::Cartesian3D<T>, ROOT::Math::DefaultCoordinateSystemTag>; template <typename T> using Vector = ROOT::Math::DisplacementVector3D<ROOT::Math::Cartesian3D<T>, ROOT::Math::DefaultCoordinateSystemTag>; template <typename T> using Plane = ROOT::Math::Impl::Plane3D<T>; static std::default_random_engine ggen; static std::uniform_real_distribution<double> p_x(1, 2), p_y(2, 3), p_z(3, 4); static std::uniform_real_distribution<double> d_x(1, 2), d_y(2, 3), d_z(3, 4); static std::uniform_real_distribution<double> c_x(1, 2), c_y(2, 3), c_z(3, 4); static std::uniform_real_distribution<double> p0(-0.002, 0.002), p1(-0.2, 0.2), p2(0.97, 0.99), p3(-1300, 1300); template class ROOT::Math::Cartesian3D<double>; static void BM_Cartesian3D_CreateEmpty(benchmark::State &state) { while (state.KeepRunning()) ROOT::Math::Cartesian3D<ROOT::Double_v> c; } BENCHMARK(BM_Cartesian3D_CreateEmpty); template <typename T> static void BM_Cartesian3D_Theta(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1., 2., 3.); // std::cout << is_aligned(&c, 16) << std::endl; while (state.KeepRunning()) c.Theta(); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, float)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Cartesian3D_Phi(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1., 2., 3.); // std::cout << is_aligned(&c, 16) << std::endl; while (state.KeepRunning()) c.Phi(); state.SetComplexityN(state.range(0)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, float)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Cartesian3D_Mag2(benchmark::State &state) { ROOT::Math::Cartesian3D<T> c(1., 2., 3.); // std::cout << is_aligned(&c, 16) << std::endl; while (state.KeepRunning()) c.Mag2(); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Point3D(benchmark::State &state) { while (state.KeepRunning()) Point<T> sp1, sp2, sp3, sp4, sp5, sp6; } BENCHMARK_TEMPLATE(BM_Point3D, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Point3D, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Point3D_Gen(benchmark::State &state) { while (state.KeepRunning()) { Point<T> sp1(p_x(ggen), p_y(ggen), p_z(ggen)); } } BENCHMARK_TEMPLATE(BM_Point3D_Gen, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Point3D_Gen, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Transform3D(benchmark::State &state) { Point<T> sp1(p_x(ggen), p_y(ggen), p_z(ggen)); Point<T> sp2(p_x(ggen), p_y(ggen), p_z(ggen)); Point<T> sp3(p_x(ggen), p_y(ggen), p_z(ggen)); Point<T> sp4(p_x(ggen), p_y(ggen), p_z(ggen)); Point<T> sp5(p_x(ggen), p_y(ggen), p_z(ggen)); Point<T> sp6(p_x(ggen), p_y(ggen), p_z(ggen)); while (state.KeepRunning()) { ROOT::Math::Impl::Transform3D<T> st(sp1, sp2, sp3, sp4, sp5, sp6); st.Translation(); } } // BENCHMARK_TEMPLATE(BM_Transform3D, double)->Range(8, 8<<10)->Complexity(benchmark::o1); // BENCHMARK_TEMPLATE(BM_Transform3D, float)->Range(8, 8<<10)->Complexity(benchmark::o1); // BENCHMARK_TEMPLATE(BM_Transform3D, ROOT::Double_v)->Range(8, 8<<10)->Complexity(benchmark::o1); // BENCHMARK_TEMPLATE(BM_Transform3D, ROOT::Float_v)->Range(8, 8<<10)->Complexity(benchmark::o1); template <typename T> static void BM_Plane3D(benchmark::State &state) { const double a(p0(ggen)), b(p1(ggen)), c(p2(ggen)), d(p3(ggen)); while (state.KeepRunning()) { Plane<T> sc_plane(a, b, c, d); } } BENCHMARK_TEMPLATE(BM_Plane3D, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Plane3D, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Plane3D, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Plane3D_Hessian(benchmark::State &state) { const double a(p0(ggen)), b(p1(ggen)), c(p2(ggen)), d(p3(ggen)); while (state.KeepRunning()) { Plane<T> sc_plane(a, b, c, d); sc_plane.HesseDistance(); } } BENCHMARK_TEMPLATE(BM_Plane3D_Hessian, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Plane3D_Hessian, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); template <typename T> static void BM_Plane3D_Normal(benchmark::State &state) { const double a(p0(ggen)), b(p1(ggen)), c(p2(ggen)), d(p3(ggen)); while (state.KeepRunning()) { Plane<T> sc_plane(a, b, c, d); sc_plane.Normal(); } } BENCHMARK_TEMPLATE(BM_Plane3D_Normal, double)->Range(8, 8 << 10)->Complexity(benchmark::o1); ; BENCHMARK_TEMPLATE(BM_Plane3D_Normal, ROOT::Double_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); BENCHMARK_TEMPLATE(BM_Plane3D_Normal, ROOT::Float_v)->Range(8, 8 << 10)->Complexity(benchmark::o1); // Define our main. BENCHMARK_MAIN(); <|endoftext|>
<commit_before>// This file is part of the dune-pymor project: // https://github.com/pyMor/dune-pymor // Copyright Holders: Felix Albrecht, Stephan Rave // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // HAVE_CMAKE_CONFIG #include <type_traits> #include <memory> #include <dune/stuff/test/test_common.hh> #include <dune/pymor/common/exceptions.hh> #include <dune/pymor/la/container/interfaces.hh> #include <dune/pymor/la/container/dunedynamic.hh> //#if HAVE_EIGEN // #include <dune/pymor/la/container/eigenvector.hh> //#endif using namespace Dune; using namespace Dune::Pymor; static const size_t dim = 4; typedef testing::Types< Dune::Pymor::LA::DuneDynamicVector< double > //#if HAVE_EIGEN // , Dune::Pymor::LA::EigenDenseVector //#endif > VectorTypes; template< class ContainerImp > struct ContainerTest : public ::testing::Test { void check() const { // static tests typedef typename ContainerImp::Traits Traits; // * of the traits typedef typename Traits::derived_type T_derived_type; static_assert(std::is_same< ContainerImp, T_derived_type >::value, "derived_type has to be the correct Type!"); typedef typename Traits::ScalarType T_ScalarType; // * of the container as itself (aka the derived type) typedef typename ContainerImp::ScalarType D_ScalarType; // * of the container as the interface typedef typename LA::ContainerInterface< Traits > InterfaceType; typedef typename InterfaceType::derived_type I_derived_type; typedef typename InterfaceType::ScalarType I_ScalarType; // dynamic tests // * of the container as itself (aka the derived type) ContainerImp DUNE_UNUSED(d_empty); ContainerImp d_by_size(dim); ContainerImp d_by_size_and_value(dim, D_ScalarType(0)); //ContainerImp d_copy_constructor(d_by_size); // <-- this is not allowed! //ContainerImp d_copy_assignment = d_by_size; // <-- this is not allowed! ContainerImp DUNE_UNUSED(d_deep_copy) = d_by_size.copy(); d_by_size.scal(D_ScalarType(1)); d_by_size.axpy(D_ScalarType(1), d_by_size_and_value); if (!d_by_size.has_equal_shape(d_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); // * of the container as the interface InterfaceType& i_by_size = static_cast< InterfaceType& >(d_by_size); InterfaceType& DUNE_UNUSED(i_by_size_and_value) = static_cast< InterfaceType& >(d_by_size_and_value); i_by_size.scal(I_ScalarType(1)); i_by_size.axpy(I_ScalarType(1), d_by_size_and_value); ContainerImp DUNE_UNUSED(i_deep_copy) = i_by_size.copy(); } }; // struct ContainerTest TYPED_TEST_CASE(ContainerTest, VectorTypes); TYPED_TEST(ContainerTest, LA_CONTAINER) { this->check(); } template< class VectorImp > struct VectorTest : public ::testing::Test { void check() const { // static tests typedef typename VectorImp::Traits Traits; // * of the traits typedef typename Traits::derived_type T_derived_type; static_assert(std::is_same< VectorImp, T_derived_type >::value, "derived_type has to be the correct Type!"); typedef typename Traits::ScalarType T_ScalarType; // * of the vector as itself (aka the derived type) typedef typename VectorImp::ScalarType D_ScalarType; // * of the vector as the interface typedef typename LA::VectorInterface< Traits > InterfaceType; typedef typename InterfaceType::derived_type I_derived_type; typedef typename InterfaceType::ScalarType I_ScalarType; // dynamic tests // * of the vector as itself (aka the derived type) VectorImp d_by_size(dim); VectorImp d_by_size_and_value(dim, D_ScalarType(1)); unsigned int DUNE_UNUSED(d_dim) = d_by_size.dim(); bool d_almost_equal = d_by_size.almost_equal(d_by_size); if (!d_almost_equal) DUNE_PYMOR_THROW(PymorException, ""); d_by_size_and_value.scal(D_ScalarType(0)); if (!d_by_size_and_value.almost_equal(d_by_size)) DUNE_PYMOR_THROW(PymorException, ""); D_ScalarType d_dot = d_by_size.dot(d_by_size_and_value); if (!Dune::FloatCmp::eq(d_dot, D_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, d_dot); D_ScalarType d_l1_norm = d_by_size.l1_norm(); if (!Dune::FloatCmp::eq(d_l1_norm, D_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, d_l1_norm); D_ScalarType d_l2_norm = d_by_size.l2_norm(); if (!Dune::FloatCmp::eq(d_l2_norm, D_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, d_l2_norm); D_ScalarType d_sup_norm = d_by_size.sup_norm(); if (!Dune::FloatCmp::eq(d_sup_norm ,D_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, d_sup_norm); VectorImp d_ones(dim, D_ScalarType(1)); std::vector< D_ScalarType > d_amax = d_ones.amax(); if (int(d_amax[0]) != 0 || !Dune::FloatCmp::eq(d_amax[1], D_ScalarType(1))) DUNE_PYMOR_THROW(PymorException, ""); d_ones.add(d_by_size, d_by_size_and_value); if (!d_by_size_and_value.almost_equal(d_ones)) DUNE_PYMOR_THROW(PymorException, ""); VectorImp d_added = d_ones.add(d_by_size); if (!d_added.almost_equal(d_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); d_added.iadd(d_by_size); if (!d_added.almost_equal(d_ones)) DUNE_PYMOR_THROW(PymorException, ""); d_ones.sub(d_by_size, d_by_size_and_value); if (!d_by_size_and_value.almost_equal(d_ones)) DUNE_PYMOR_THROW(PymorException, ""); VectorImp d_subtracted = d_ones.sub(d_by_size); if (!d_subtracted.almost_equal(d_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); d_subtracted.isub(d_by_size); if (!d_subtracted.almost_equal(d_ones)) DUNE_PYMOR_THROW(PymorException, ""); // * of the vector as the interface VectorImp tmp1(dim); VectorImp tmp2(dim, D_ScalarType(1)); InterfaceType& i_by_size = static_cast< InterfaceType& >(tmp1); InterfaceType& i_by_size_and_value = static_cast< InterfaceType& >(tmp2); unsigned int DUNE_UNUSED(i_dim) = i_by_size.dim(); bool i_almost_equal = i_by_size.almost_equal(i_by_size); if (!i_almost_equal) DUNE_PYMOR_THROW(PymorException, ""); i_by_size_and_value.scal(I_ScalarType(0)); if (!i_by_size_and_value.almost_equal(i_by_size)) DUNE_PYMOR_THROW(PymorException, ""); I_ScalarType i_dot = i_by_size.dot(i_by_size_and_value); if (!Dune::FloatCmp::eq(i_dot, I_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, i_dot); I_ScalarType i_l1_norm = i_by_size.l1_norm(); if (!Dune::FloatCmp::eq(i_l1_norm, I_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, i_l1_norm); I_ScalarType i_l2_norm = i_by_size.l2_norm(); if (!Dune::FloatCmp::eq(i_l2_norm, I_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, i_l2_norm); I_ScalarType i_sup_norm = i_by_size.sup_norm(); if (!Dune::FloatCmp::eq(i_sup_norm ,I_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, i_sup_norm); VectorImp i_ones(dim, I_ScalarType(1)); std::vector< I_ScalarType > i_amax = i_ones.amax(); if (int(i_amax[0]) != 0 || !Dune::FloatCmp::eq(i_amax[1], I_ScalarType(1))) DUNE_PYMOR_THROW(PymorException, ""); i_ones.add(i_by_size, i_by_size_and_value); if (!i_by_size_and_value.almost_equal(i_ones)) DUNE_PYMOR_THROW(PymorException, ""); VectorImp i_added = i_ones.add(i_by_size); if (!i_added.almost_equal(i_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); i_added.iadd(i_by_size); if (!i_added.almost_equal(i_ones)) DUNE_PYMOR_THROW(PymorException, ""); i_ones.sub(i_by_size, i_by_size_and_value); if (!i_by_size_and_value.almost_equal(i_ones)) DUNE_PYMOR_THROW(PymorException, ""); VectorImp i_subtracted = i_ones.sub(i_by_size); if (!i_subtracted.almost_equal(i_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); i_subtracted.isub(i_by_size); if (!i_subtracted.almost_equal(i_ones)) DUNE_PYMOR_THROW(PymorException, ""); } }; // struct VectorTest TYPED_TEST_CASE(VectorTest, VectorTypes); TYPED_TEST(VectorTest, LA_CONTAINER) { this->check(); } int main(int argc, char** argv) { // try { test_init(argc, argv); return RUN_ALL_TESTS(); // } catch (Dune::PymorException& e) { // std::cerr << Dune::Stuff::Common::colorStringRed("dune-pymor reported: ") << e << std::endl; // } catch (Dune::Exception& e) { // std::cerr << Dune::Stuff::Common::colorStringRed("Dune reported error: ") << e << std::endl; // } catch (...) { // std::cerr << Dune::Stuff::Common::colorStringRed("Unknown exception thrown!") << std::endl; // } } <commit_msg>[test.la_container] update<commit_after>// This file is part of the dune-pymor project: // https://github.com/pyMor/dune-pymor // Copyright Holders: Felix Albrecht, Stephan Rave // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // HAVE_CMAKE_CONFIG #include <type_traits> #include <memory> #include <dune/stuff/test/test_common.hh> #include <dune/pymor/common/exceptions.hh> #include <dune/pymor/la/container/interfaces.hh> #include <dune/pymor/la/container/dunedynamic.hh> using namespace Dune; using namespace Dune::Pymor; static const size_t dim = 4; typedef testing::Types< Dune::Pymor::LA::DuneDynamicVector< double > > VectorTypes; typedef testing::Types< Dune::Pymor::LA::DuneDynamicMatrix< double > > MatrixTypes; typedef testing::Types< Dune::Pymor::LA::DuneDynamicVector< double > , Dune::Pymor::LA::DuneDynamicMatrix< double > > ContainerTypes; template< class ContainerImp > struct ContainerTest : public ::testing::Test { void check() const { // static tests typedef typename ContainerImp::Traits Traits; // * of the traits typedef typename Traits::derived_type T_derived_type; static_assert(std::is_same< ContainerImp, T_derived_type >::value, "derived_type has to be the correct Type!"); typedef typename Traits::ScalarType T_ScalarType; // * of the container as itself (aka the derived type) typedef typename ContainerImp::ScalarType D_ScalarType; // * of the container as the interface typedef typename LA::ContainerInterface< Traits > InterfaceType; typedef typename InterfaceType::derived_type I_derived_type; typedef typename InterfaceType::ScalarType I_ScalarType; // dynamic tests // * of the container as itself (aka the derived type) ContainerImp DUNE_UNUSED(d_empty); ContainerImp d_by_size(dim); ContainerImp d_by_size_and_value(dim, D_ScalarType(0)); //ContainerImp d_copy_constructor(d_by_size); // <-- this is not allowed! //ContainerImp d_copy_assignment = d_by_size; // <-- this is not allowed! ContainerImp DUNE_UNUSED(d_deep_copy) = d_by_size.copy(); d_by_size.scal(D_ScalarType(1)); d_by_size.axpy(D_ScalarType(1), d_by_size_and_value); if (!d_by_size.has_equal_shape(d_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); // * of the container as the interface InterfaceType& i_by_size = static_cast< InterfaceType& >(d_by_size); InterfaceType& DUNE_UNUSED(i_by_size_and_value) = static_cast< InterfaceType& >(d_by_size_and_value); i_by_size.scal(I_ScalarType(1)); i_by_size.axpy(I_ScalarType(1), d_by_size_and_value); ContainerImp DUNE_UNUSED(i_deep_copy) = i_by_size.copy(); } }; // struct ContainerTest TYPED_TEST_CASE(ContainerTest, ContainerTypes); TYPED_TEST(ContainerTest, LA_CONTAINER) { this->check(); } template< class VectorImp > struct VectorTest : public ::testing::Test { void check() const { // static tests typedef typename VectorImp::Traits Traits; // * of the traits typedef typename Traits::derived_type T_derived_type; static_assert(std::is_same< VectorImp, T_derived_type >::value, "derived_type has to be the correct Type!"); typedef typename Traits::ScalarType T_ScalarType; // * of the vector as itself (aka the derived type) typedef typename VectorImp::ScalarType D_ScalarType; // * of the vector as the interface typedef typename LA::VectorInterface< Traits > InterfaceType; typedef typename InterfaceType::derived_type I_derived_type; typedef typename InterfaceType::ScalarType I_ScalarType; // dynamic tests // * of the vector as itself (aka the derived type) VectorImp d_by_size(dim); VectorImp d_by_size_and_value(dim, D_ScalarType(1)); unsigned int DUNE_UNUSED(d_dim) = d_by_size.dim(); bool d_almost_equal = d_by_size.almost_equal(d_by_size); if (!d_almost_equal) DUNE_PYMOR_THROW(PymorException, ""); d_by_size_and_value.scal(D_ScalarType(0)); if (!d_by_size_and_value.almost_equal(d_by_size)) DUNE_PYMOR_THROW(PymorException, ""); D_ScalarType d_dot = d_by_size.dot(d_by_size_and_value); if (!Dune::FloatCmp::eq(d_dot, D_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, d_dot); D_ScalarType d_l1_norm = d_by_size.l1_norm(); if (!Dune::FloatCmp::eq(d_l1_norm, D_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, d_l1_norm); D_ScalarType d_l2_norm = d_by_size.l2_norm(); if (!Dune::FloatCmp::eq(d_l2_norm, D_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, d_l2_norm); D_ScalarType d_sup_norm = d_by_size.sup_norm(); if (!Dune::FloatCmp::eq(d_sup_norm ,D_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, d_sup_norm); VectorImp d_ones(dim, D_ScalarType(1)); std::vector< D_ScalarType > d_amax = d_ones.amax(); if (int(d_amax[0]) != 0 || !Dune::FloatCmp::eq(d_amax[1], D_ScalarType(1))) DUNE_PYMOR_THROW(PymorException, ""); d_ones.add(d_by_size, d_by_size_and_value); if (!d_by_size_and_value.almost_equal(d_ones)) DUNE_PYMOR_THROW(PymorException, ""); VectorImp d_added = d_ones.add(d_by_size); if (!d_added.almost_equal(d_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); d_added.iadd(d_by_size); if (!d_added.almost_equal(d_ones)) DUNE_PYMOR_THROW(PymorException, ""); d_ones.sub(d_by_size, d_by_size_and_value); if (!d_by_size_and_value.almost_equal(d_ones)) DUNE_PYMOR_THROW(PymorException, ""); VectorImp d_subtracted = d_ones.sub(d_by_size); if (!d_subtracted.almost_equal(d_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); d_subtracted.isub(d_by_size); if (!d_subtracted.almost_equal(d_ones)) DUNE_PYMOR_THROW(PymorException, ""); // * of the vector as the interface VectorImp tmp1(dim); VectorImp tmp2(dim, D_ScalarType(1)); InterfaceType& i_by_size = static_cast< InterfaceType& >(tmp1); InterfaceType& i_by_size_and_value = static_cast< InterfaceType& >(tmp2); unsigned int DUNE_UNUSED(i_dim) = i_by_size.dim(); bool i_almost_equal = i_by_size.almost_equal(i_by_size); if (!i_almost_equal) DUNE_PYMOR_THROW(PymorException, ""); i_by_size_and_value.scal(I_ScalarType(0)); if (!i_by_size_and_value.almost_equal(i_by_size)) DUNE_PYMOR_THROW(PymorException, ""); I_ScalarType i_dot = i_by_size.dot(i_by_size_and_value); if (!Dune::FloatCmp::eq(i_dot, I_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, i_dot); I_ScalarType i_l1_norm = i_by_size.l1_norm(); if (!Dune::FloatCmp::eq(i_l1_norm, I_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, i_l1_norm); I_ScalarType i_l2_norm = i_by_size.l2_norm(); if (!Dune::FloatCmp::eq(i_l2_norm, I_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, i_l2_norm); I_ScalarType i_sup_norm = i_by_size.sup_norm(); if (!Dune::FloatCmp::eq(i_sup_norm ,I_ScalarType(0))) DUNE_PYMOR_THROW(PymorException, i_sup_norm); VectorImp i_ones(dim, I_ScalarType(1)); std::vector< I_ScalarType > i_amax = i_ones.amax(); if (int(i_amax[0]) != 0 || !Dune::FloatCmp::eq(i_amax[1], I_ScalarType(1))) DUNE_PYMOR_THROW(PymorException, ""); i_ones.add(i_by_size, i_by_size_and_value); if (!i_by_size_and_value.almost_equal(i_ones)) DUNE_PYMOR_THROW(PymorException, ""); VectorImp i_added = i_ones.add(i_by_size); if (!i_added.almost_equal(i_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); i_added.iadd(i_by_size); if (!i_added.almost_equal(i_ones)) DUNE_PYMOR_THROW(PymorException, ""); i_ones.sub(i_by_size, i_by_size_and_value); if (!i_by_size_and_value.almost_equal(i_ones)) DUNE_PYMOR_THROW(PymorException, ""); VectorImp i_subtracted = i_ones.sub(i_by_size); if (!i_subtracted.almost_equal(i_by_size_and_value)) DUNE_PYMOR_THROW(PymorException, ""); i_subtracted.isub(i_by_size); if (!i_subtracted.almost_equal(i_ones)) DUNE_PYMOR_THROW(PymorException, ""); } }; // struct VectorTest TYPED_TEST_CASE(VectorTest, VectorTypes); TYPED_TEST(VectorTest, LA_CONTAINER) { this->check(); } int main(int argc, char** argv) { // try { test_init(argc, argv); return RUN_ALL_TESTS(); // } catch (Dune::PymorException& e) { // std::cerr << Dune::Stuff::Common::colorStringRed("dune-pymor reported: ") << e << std::endl; // } catch (Dune::Exception& e) { // std::cerr << Dune::Stuff::Common::colorStringRed("Dune reported error: ") << e << std::endl; // } catch (...) { // std::cerr << Dune::Stuff::Common::colorStringRed("Unknown exception thrown!") << std::endl; // } } <|endoftext|>
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "init.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <QApplication> #include <QPainter> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) : QSplashScreen(pixmap, f) { setAutoFillBackground(true); // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; // define text to place QString titleText = tr("Bitcoin Core"); QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")); QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(isTestNet) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(100,100,100)); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); // draw testnet string if testnet is on if(isTestNet) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int testnetAddTextWidth = fm.width(testnetAddText); pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText); } pixPaint.end(); this->setPixmap(newPixmap); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget *mainWin) { finish(mainWin); } static void InitMessage(SplashScreen *splash, const std::string &message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter), Q_ARG(QColor, QColor(55,55,55))); } static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen *splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); #ifdef ENABLE_WALLET if(pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } <commit_msg>Update splashscreen.cpp<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "init.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <QApplication> #include <QPainter> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) : QSplashScreen(pixmap, f) { setAutoFillBackground(true); // set reference point, paddings int paddingRight = 50; int paddingTop = 50; int titleVersionVSpace = 17; int titleCopyrightVSpace = 40; float fontFactor = 1.0; // define text to place QString titleText = tr("Feathercoin Core"); QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText = QChar(0xA9)+QString(" 2013-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Feathercoin Core developers")); QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(isTestNet) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(100,100,100)); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 33*fontFactor)); fm = pixPaint.fontMetrics(); titleTextWidth = fm.width(titleText); pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText); pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size fm = pixPaint.fontMetrics(); int versionTextWidth = fm.width(versionText); if(versionTextWidth > titleTextWidth+paddingRight-10) { pixPaint.setFont(QFont(font, 10*fontFactor)); titleVersionVSpace -= 5; } pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10*fontFactor)); pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); // draw testnet string if testnet is on if(isTestNet) { QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int testnetAddTextWidth = fm.width(testnetAddText); pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText); } pixPaint.end(); this->setPixmap(newPixmap); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget *mainWin) { finish(mainWin); } static void InitMessage(SplashScreen *splash, const std::string &message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom|Qt::AlignHCenter), Q_ARG(QColor, QColor(55,55,55))); } static void ShowProgress(SplashScreen *splash, const std::string &title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen *splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); #ifdef ENABLE_WALLET if(pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } <|endoftext|>
<commit_before>//____________________________________________________________________ // // To make an event sample (of size 100) do // // shell> root // root [0] .L pythiaExample.C // root [1] makeEventSample(1000) // // To start the tree view on the generated tree, do // // shell> root // root [0] .L pythiaExample.C // root [1] showEventSample() // // // The following session: // shell> root // root [0] .x pythiaExample.C(500) // will execute makeEventSample(500) and showEventSample() // // Alternatively, you can compile this to a program // and then generate 1000 events with // // ./pythiaExample 1000 // // To use the program to start the viewer, do // // ./pythiaExample -1 // // NOTE 1: To run this example, you must have a version of ROOT // compiled with the Pythia6 version enabled and have Pythia6 installed. // The statement gSystem->Load("$HOME/pythia6/libPythia6"); (see below) // assumes that the directory containing the Pythia6 library // is in the pythia6 subdirectory of your $HOME. Locations // that can specify this, are: // // Root.DynamicPath resource in your ROOT configuration file // (/etc/root/system.rootrc or ~/.rootrc). // Runtime load paths set on the executable (Using GNU ld, // specified with flag `-rpath'). // Dynamic loader search path as specified in the loaders // configuration file (On GNU/Linux this file is // etc/ld.so.conf). // For Un*x: Any directory mentioned in LD_LIBRARY_PATH // For Windows: Any directory mentioned in PATH // // NOTE 2: The example can also be run with ACLIC: // root > gSystem->Load("libEG"); // root > gSystem->Load("$HOME/pythia6/libPythia6"); //change to your setup // root > gSystem->Load("libEGPythia6"); // root > .x pythiaExample.C+ // // //____________________________________________________________________ // // Author: Christian Holm Christensen <cholm@hilux15.nbi.dk> // Update: 2002-08-16 16:40:27+0200 // Copyright: 2002 (C) Christian Holm Christensen // Copyright (C) 2006, Rene Brun and Fons Rademakers. // For the licensing terms see $ROOTSYS/LICENSE. // #ifndef __CINT__ #include "TApplication.h" #include "TPythia6.h" #include "TFile.h" #include "TError.h" #include "TTree.h" #include "TClonesArray.h" #include "TH1.h" #include "TF1.h" #include "TStyle.h" #include "TLatex.h" #include "TCanvas.h" #include "Riostream.h" #include <cstdlib> using namespace std; #endif #define FILENAME "pythia.root" #define TREENAME "tree" #define BRANCHNAME "particles" #define HISTNAME "ptSpectra" #define PDGNUMBER 211 // This funtion just load the needed libraries if we're executing from // an interactive session. void loadLibraries() { #ifdef __CINT__ // Load the Event Generator abstraction library, Pythia 6 // library, and the Pythia 6 interface library. gSystem->Load("libEG"); gSystem->Load("$HOME/pythia6/libPythia6"); //change to your setup gSystem->Load("libEGPythia6"); #endif } // nEvents is how many events we want. int makeEventSample(Int_t nEvents) { // Load needed libraries loadLibraries(); // Create an instance of the Pythia event generator ... TPythia6* pythia = new TPythia6; // ... and initialise it to run p+p at sqrt(200) GeV in CMS pythia->Initialize("cms", "p", "p", 200); // Open an output file TFile* file = TFile::Open(FILENAME, "RECREATE"); if (!file || !file->IsOpen()) { Error("makeEventSample", "Couldn;t open file %s", FILENAME); return 1; } // Make a tree in that file ... TTree* tree = new TTree(TREENAME, "Pythia 6 tree"); // ... and register a the cache of pythia on a branch (It's a // TClonesArray of TMCParticle objects. ) TClonesArray* particles = (TClonesArray*)pythia->GetListOfParticles(); tree->Branch(BRANCHNAME, &particles); // Now we make some events for (Int_t i = 0; i < nEvents; i++) { // Show how far we got every 100'th event. if (i % 100 == 0) cout << "Event # " << i << endl; // Make one event. pythia->GenerateEvent(); // Maybe you want to have another branch with global event // information. In that case, you should process that here. // You can also filter out particles here if you want. // Now we're ready to fill the tree, and the event is over. tree->Fill(); } // Show tree structure tree->Print(); // After the run is over, we may want to do some summary plots: TH1D* hist = new TH1D(HISTNAME, "p_{#perp} spectrum for #pi^{+}", 100, 0, 3); hist->SetXTitle("p_{#perp}"); hist->SetYTitle("dN/dp_{#perp}"); char expression[64]; sprintf(expression,"sqrt(pow(%s.fPx,2)+pow(%s.fPy,2))>>%s", BRANCHNAME, BRANCHNAME, HISTNAME); char selection[64]; sprintf(selection,"%s.fKF==%d", BRANCHNAME, PDGNUMBER); tree->Draw(expression,selection); // Normalise to the number of events, and the bin sizes. hist->Sumw2(); hist->Scale(3 / 100. / hist->Integral()); hist->Fit("expo", "QO+", "", .25, 1.75); TF1* func = hist->GetFunction("expo"); func->SetParNames("A", "- 1 / T"); // and now we flush and close the file file->Write(); file->Close(); return 0; } // Show the Pt spectra, and start the tree viewer. int showEventSample() { // Load needed libraries loadLibraries(); // Open the file TFile* file = TFile::Open(FILENAME, "READ"); if (!file || !file->IsOpen()) { Error("showEventSample", "Couldn;t open file %s", FILENAME); return 1; } // Get the tree TTree* tree = (TTree*)file->Get(TREENAME); if (!tree) { Error("showEventSample", "couldn't get TTree %s", TREENAME); return 2; } // Start the viewer. tree->StartViewer(); // Get the histogram TH1D* hist = (TH1D*)file->Get(HISTNAME); if (!hist) { Error("showEventSample", "couldn't get TH1D %s", HISTNAME); return 4; } // Draw the histogram in a canvas gStyle->SetOptStat(1); TCanvas* canvas = new TCanvas("canvas", "canvas"); canvas->SetLogy(); hist->Draw("e1"); TF1* func = hist->GetFunction("expo"); char expression[64]; sprintf(expression,"T #approx %5.1f", -1000 / func->GetParameter(1)); TLatex* latex = new TLatex(1.5, 1e-4, expression); latex->SetTextSize(.1); latex->SetTextColor(4); latex->Draw(); return 0; } void pythiaExample(Int_t n=1000) { makeEventSample(n); showEventSample(); } #ifndef __CINT__ int main(int argc, char** argv) { TApplication app("app", &argc, argv); Int_t n = 100; if (argc > 1) n = strtol(argv[1], NULL, 0); int retVal = 0; if (n > 0) retVal = makeEventSample(n); else { retVal = showEventSample(); app.Run(); } return retVal; } #endif //____________________________________________________________________ // // EOF // <commit_msg>Minor change to automatically load the libPythia6 shared lib from the directory $ROOTSYS/../pythia6 (was $HOME/pythia6 before).<commit_after>//____________________________________________________________________ // // To make an event sample (of size 100) do // // shell> root // root [0] .L pythiaExample.C // root [1] makeEventSample(1000) // // To start the tree view on the generated tree, do // // shell> root // root [0] .L pythiaExample.C // root [1] showEventSample() // // // The following session: // shell> root // root [0] .x pythiaExample.C(500) // will execute makeEventSample(500) and showEventSample() // // Alternatively, you can compile this to a program // and then generate 1000 events with // // ./pythiaExample 1000 // // To use the program to start the viewer, do // // ./pythiaExample -1 // // NOTE 1: To run this example, you must have a version of ROOT // compiled with the Pythia6 version enabled and have Pythia6 installed. // The statement gSystem->Load("$HOME/pythia6/libPythia6"); (see below) // assumes that the directory containing the Pythia6 library // is in the pythia6 subdirectory of your $HOME. Locations // that can specify this, are: // // Root.DynamicPath resource in your ROOT configuration file // (/etc/root/system.rootrc or ~/.rootrc). // Runtime load paths set on the executable (Using GNU ld, // specified with flag `-rpath'). // Dynamic loader search path as specified in the loaders // configuration file (On GNU/Linux this file is // etc/ld.so.conf). // For Un*x: Any directory mentioned in LD_LIBRARY_PATH // For Windows: Any directory mentioned in PATH // // NOTE 2: The example can also be run with ACLIC: // root > gSystem->Load("libEG"); // root > gSystem->Load("$ROOTSYS/../pythia6/libPythia6"); //change to your setup // root > gSystem->Load("libEGPythia6"); // root > .x pythiaExample.C+ // // //____________________________________________________________________ // // Author: Christian Holm Christensen <cholm@hilux15.nbi.dk> // Update: 2002-08-16 16:40:27+0200 // Copyright: 2002 (C) Christian Holm Christensen // Copyright (C) 2006, Rene Brun and Fons Rademakers. // For the licensing terms see $ROOTSYS/LICENSE. // #ifndef __CINT__ #include "TApplication.h" #include "TPythia6.h" #include "TFile.h" #include "TError.h" #include "TTree.h" #include "TClonesArray.h" #include "TH1.h" #include "TF1.h" #include "TStyle.h" #include "TLatex.h" #include "TCanvas.h" #include "Riostream.h" #include <cstdlib> using namespace std; #endif #define FILENAME "pythia.root" #define TREENAME "tree" #define BRANCHNAME "particles" #define HISTNAME "ptSpectra" #define PDGNUMBER 211 // This funtion just load the needed libraries if we're executing from // an interactive session. void loadLibraries() { #ifdef __CINT__ // Load the Event Generator abstraction library, Pythia 6 // library, and the Pythia 6 interface library. gSystem->Load("libEG"); gSystem->Load("$ROOTSYS/../pythia6/libPythia6"); //change to your setup gSystem->Load("libEGPythia6"); #endif } // nEvents is how many events we want. int makeEventSample(Int_t nEvents) { // Load needed libraries loadLibraries(); // Create an instance of the Pythia event generator ... TPythia6* pythia = new TPythia6; // ... and initialise it to run p+p at sqrt(200) GeV in CMS pythia->Initialize("cms", "p", "p", 200); // Open an output file TFile* file = TFile::Open(FILENAME, "RECREATE"); if (!file || !file->IsOpen()) { Error("makeEventSample", "Couldn;t open file %s", FILENAME); return 1; } // Make a tree in that file ... TTree* tree = new TTree(TREENAME, "Pythia 6 tree"); // ... and register a the cache of pythia on a branch (It's a // TClonesArray of TMCParticle objects. ) TClonesArray* particles = (TClonesArray*)pythia->GetListOfParticles(); tree->Branch(BRANCHNAME, &particles); // Now we make some events for (Int_t i = 0; i < nEvents; i++) { // Show how far we got every 100'th event. if (i % 100 == 0) cout << "Event # " << i << endl; // Make one event. pythia->GenerateEvent(); // Maybe you want to have another branch with global event // information. In that case, you should process that here. // You can also filter out particles here if you want. // Now we're ready to fill the tree, and the event is over. tree->Fill(); } // Show tree structure tree->Print(); // After the run is over, we may want to do some summary plots: TH1D* hist = new TH1D(HISTNAME, "p_{#perp} spectrum for #pi^{+}", 100, 0, 3); hist->SetXTitle("p_{#perp}"); hist->SetYTitle("dN/dp_{#perp}"); char expression[64]; sprintf(expression,"sqrt(pow(%s.fPx,2)+pow(%s.fPy,2))>>%s", BRANCHNAME, BRANCHNAME, HISTNAME); char selection[64]; sprintf(selection,"%s.fKF==%d", BRANCHNAME, PDGNUMBER); tree->Draw(expression,selection); // Normalise to the number of events, and the bin sizes. hist->Sumw2(); hist->Scale(3 / 100. / hist->Integral()); hist->Fit("expo", "QO+", "", .25, 1.75); TF1* func = hist->GetFunction("expo"); func->SetParNames("A", "- 1 / T"); // and now we flush and close the file file->Write(); file->Close(); return 0; } // Show the Pt spectra, and start the tree viewer. int showEventSample() { // Load needed libraries loadLibraries(); // Open the file TFile* file = TFile::Open(FILENAME, "READ"); if (!file || !file->IsOpen()) { Error("showEventSample", "Couldn;t open file %s", FILENAME); return 1; } // Get the tree TTree* tree = (TTree*)file->Get(TREENAME); if (!tree) { Error("showEventSample", "couldn't get TTree %s", TREENAME); return 2; } // Start the viewer. tree->StartViewer(); // Get the histogram TH1D* hist = (TH1D*)file->Get(HISTNAME); if (!hist) { Error("showEventSample", "couldn't get TH1D %s", HISTNAME); return 4; } // Draw the histogram in a canvas gStyle->SetOptStat(1); TCanvas* canvas = new TCanvas("canvas", "canvas"); canvas->SetLogy(); hist->Draw("e1"); TF1* func = hist->GetFunction("expo"); char expression[64]; sprintf(expression,"T #approx %5.1f", -1000 / func->GetParameter(1)); TLatex* latex = new TLatex(1.5, 1e-4, expression); latex->SetTextSize(.1); latex->SetTextColor(4); latex->Draw(); return 0; } void pythiaExample(Int_t n=1000) { makeEventSample(n); showEventSample(); } #ifndef __CINT__ int main(int argc, char** argv) { TApplication app("app", &argc, argv); Int_t n = 100; if (argc > 1) n = strtol(argv[1], NULL, 0); int retVal = 0; if (n > 0) retVal = makeEventSample(n); else { retVal = showEventSample(); app.Run(); } return retVal; } #endif //____________________________________________________________________ // // EOF // <|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/ui/input_window_dialog.h" #include "base/compiler_specific.h" #include "base/message_loop.h" #include "base/task.h" #include "base/utf_string_conversions.h" #include "grit/generated_resources.h" #include "views/controls/label.h" #include "views/controls/textfield/textfield.h" #include "views/controls/textfield/textfield_controller.h" #include "views/layout/grid_layout.h" #include "views/layout/layout_constants.h" #include "views/widget/widget.h" #include "views/window/dialog_delegate.h" namespace { // Width of the text field, in pixels. const int kTextfieldWidth = 200; } // namespace namespace views { class Widget; } // The Windows implementation of the cross platform input dialog interface. class WinInputWindowDialog : public InputWindowDialog { public: WinInputWindowDialog(gfx::NativeWindow parent, const std::wstring& window_title, const std::wstring& label, const std::wstring& contents, Delegate* delegate); virtual ~WinInputWindowDialog(); virtual void Show(); virtual void Close(); const std::wstring& window_title() const { return window_title_; } const std::wstring& label() const { return label_; } const std::wstring& contents() const { return contents_; } InputWindowDialog::Delegate* delegate() { return delegate_.get(); } private: // Our chrome views window. views::Widget* window_; // Strings to feed to the on screen window. std::wstring window_title_; std::wstring label_; std::wstring contents_; // Our delegate. Consumes the window's output. scoped_ptr<InputWindowDialog::Delegate> delegate_; }; // ContentView, as the name implies, is the content view for the InputWindow. // It registers accelerators that accept/cancel the input. class ContentView : public views::DialogDelegateView, public views::TextfieldController { public: explicit ContentView(WinInputWindowDialog* delegate) : delegate_(delegate), ALLOW_THIS_IN_INITIALIZER_LIST(focus_grabber_factory_(this)) { DCHECK(delegate_); } // views::DialogDelegateView: virtual bool IsDialogButtonEnabled( MessageBoxFlags::DialogButton button) const; virtual bool Accept(); virtual bool Cancel(); virtual void DeleteDelegate(); virtual std::wstring GetWindowTitle() const; virtual bool IsModal() const { return true; } virtual views::View* GetContentsView(); // views::TextfieldController: virtual void ContentsChanged(views::Textfield* sender, const std::wstring& new_contents); virtual bool HandleKeyEvent(views::Textfield*, const views::KeyEvent&) { return false; } protected: // views::View: virtual void ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child); private: // Set up dialog controls and layout. void InitControlLayout(); // Sets focus to the first focusable element within the dialog. void FocusFirstFocusableControl(); // The Textfield that the user can type into. views::Textfield* text_field_; // The delegate that the ContentView uses to communicate changes to the // caller. WinInputWindowDialog* delegate_; // Helps us set focus to the first Textfield in the window. ScopedRunnableMethodFactory<ContentView> focus_grabber_factory_; DISALLOW_COPY_AND_ASSIGN(ContentView); }; /////////////////////////////////////////////////////////////////////////////// // ContentView, views::DialogDelegate implementation: bool ContentView::IsDialogButtonEnabled( MessageBoxFlags::DialogButton button) const { if (button == MessageBoxFlags::DIALOGBUTTON_OK && !delegate_->delegate()->IsValid(text_field_->text())) { return false; } return true; } bool ContentView::Accept() { delegate_->delegate()->InputAccepted(text_field_->text()); return true; } bool ContentView::Cancel() { delegate_->delegate()->InputCanceled(); return true; } void ContentView::DeleteDelegate() { delete delegate_; } std::wstring ContentView::GetWindowTitle() const { return delegate_->window_title(); } views::View* ContentView::GetContentsView() { return this; } /////////////////////////////////////////////////////////////////////////////// // ContentView, views::TextfieldController implementation: void ContentView::ContentsChanged(views::Textfield* sender, const std::wstring& new_contents) { GetDialogClientView()->UpdateDialogButtons(); } /////////////////////////////////////////////////////////////////////////////// // ContentView, protected: void ContentView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && child == this) InitControlLayout(); } /////////////////////////////////////////////////////////////////////////////// // ContentView, private: void ContentView::InitControlLayout() { text_field_ = new views::Textfield; text_field_->SetText(delegate_->contents()); text_field_->SetController(this); using views::ColumnSet; using views::GridLayout; // TODO(sky): Vertical alignment should be baseline. GridLayout* layout = GridLayout::CreatePanel(this); SetLayoutManager(layout); ColumnSet* c1 = layout->AddColumnSet(0); c1->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); c1->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); c1->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1, GridLayout::USE_PREF, kTextfieldWidth, kTextfieldWidth); layout->StartRow(0, 0); views::Label* label = new views::Label(delegate_->label()); layout->AddView(label); layout->AddView(text_field_); MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &ContentView::FocusFirstFocusableControl)); } void ContentView::FocusFirstFocusableControl() { text_field_->SelectAll(); text_field_->RequestFocus(); } WinInputWindowDialog::WinInputWindowDialog(gfx::NativeWindow parent, const std::wstring& window_title, const std::wstring& label, const std::wstring& contents, Delegate* delegate) : window_title_(window_title), label_(label), contents_(contents), delegate_(delegate) { window_ = views::Widget::CreateWindowWithParent(new ContentView(this), parent); window_->client_view()->AsDialogClientView()->UpdateDialogButtons(); } WinInputWindowDialog::~WinInputWindowDialog() { } void WinInputWindowDialog::Show() { window_->Show(); } void WinInputWindowDialog::Close() { window_->Close(); } // static InputWindowDialog* InputWindowDialog::Create(gfx::NativeWindow parent, const string16& window_title, const string16& label, const string16& contents, Delegate* delegate) { return new WinInputWindowDialog(parent, UTF16ToWide(window_title), UTF16ToWide(label), UTF16ToWide(contents), delegate); } <commit_msg>Change WinInputWindowDialog to use string16.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/input_window_dialog.h" #include "base/compiler_specific.h" #include "base/message_loop.h" #include "base/task.h" #include "base/utf_string_conversions.h" #include "grit/generated_resources.h" #include "views/controls/label.h" #include "views/controls/textfield/textfield.h" #include "views/controls/textfield/textfield_controller.h" #include "views/layout/grid_layout.h" #include "views/layout/layout_constants.h" #include "views/widget/widget.h" #include "views/window/dialog_delegate.h" namespace { // Width of the text field, in pixels. const int kTextfieldWidth = 200; } // namespace // The Windows implementation of the cross platform input dialog interface. class WinInputWindowDialog : public InputWindowDialog { public: WinInputWindowDialog(gfx::NativeWindow parent, const string16& window_title, const string16& label, const string16& contents, Delegate* delegate); virtual ~WinInputWindowDialog(); // Overridden from InputWindowDialog: virtual void Show() OVERRIDE; virtual void Close() OVERRIDE; const string16& window_title() const { return window_title_; } const string16& label() const { return label_; } const string16& contents() const { return contents_; } InputWindowDialog::Delegate* delegate() { return delegate_.get(); } private: // Our chrome views window. views::Widget* window_; // Strings to feed to the on screen window. string16 window_title_; string16 label_; string16 contents_; // Our delegate. Consumes the window's output. scoped_ptr<InputWindowDialog::Delegate> delegate_; }; // ContentView, as the name implies, is the content view for the InputWindow. // It registers accelerators that accept/cancel the input. class ContentView : public views::DialogDelegateView, public views::TextfieldController { public: explicit ContentView(WinInputWindowDialog* delegate); // views::DialogDelegateView: virtual bool IsDialogButtonEnabled( MessageBoxFlags::DialogButton button) const OVERRIDE; virtual bool Accept() OVERRIDE; virtual bool Cancel() OVERRIDE; virtual void DeleteDelegate() OVERRIDE; virtual std::wstring GetWindowTitle() const OVERRIDE; virtual bool IsModal() const OVERRIDE; virtual views::View* GetContentsView() OVERRIDE; // views::TextfieldController: virtual void ContentsChanged(views::Textfield* sender, const std::wstring& new_contents) OVERRIDE; virtual bool HandleKeyEvent(views::Textfield*, const views::KeyEvent&) OVERRIDE; protected: // views::View: virtual void ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) OVERRIDE; private: // Set up dialog controls and layout. void InitControlLayout(); // Sets focus to the first focusable element within the dialog. void FocusFirstFocusableControl(); // The Textfield that the user can type into. views::Textfield* text_field_; // The delegate that the ContentView uses to communicate changes to the // caller. WinInputWindowDialog* delegate_; // Helps us set focus to the first Textfield in the window. ScopedRunnableMethodFactory<ContentView> focus_grabber_factory_; DISALLOW_COPY_AND_ASSIGN(ContentView); }; /////////////////////////////////////////////////////////////////////////////// // ContentView ContentView::ContentView(WinInputWindowDialog* delegate) : delegate_(delegate), ALLOW_THIS_IN_INITIALIZER_LIST(focus_grabber_factory_(this)) { DCHECK(delegate_); } /////////////////////////////////////////////////////////////////////////////// // ContentView, views::DialogDelegate implementation: bool ContentView::IsDialogButtonEnabled( MessageBoxFlags::DialogButton button) const { if (button == MessageBoxFlags::DIALOGBUTTON_OK && !delegate_->delegate()->IsValid(text_field_->text())) { return false; } return true; } bool ContentView::Accept() { delegate_->delegate()->InputAccepted(text_field_->text()); return true; } bool ContentView::Cancel() { delegate_->delegate()->InputCanceled(); return true; } void ContentView::DeleteDelegate() { delete delegate_; } std::wstring ContentView::GetWindowTitle() const { return UTF16ToWideHack(delegate_->window_title()); } bool ContentView::IsModal() const { return true; } views::View* ContentView::GetContentsView() { return this; } /////////////////////////////////////////////////////////////////////////////// // ContentView, views::TextfieldController implementation: void ContentView::ContentsChanged(views::Textfield* sender, const std::wstring& new_contents) { GetDialogClientView()->UpdateDialogButtons(); } bool ContentView::HandleKeyEvent(views::Textfield*, const views::KeyEvent&) { return false; } /////////////////////////////////////////////////////////////////////////////// // ContentView, protected: void ContentView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && child == this) InitControlLayout(); } /////////////////////////////////////////////////////////////////////////////// // ContentView, private: void ContentView::InitControlLayout() { text_field_ = new views::Textfield; text_field_->SetText(UTF16ToWideHack(delegate_->contents())); text_field_->SetController(this); using views::GridLayout; // TODO(sky): Vertical alignment should be baseline. GridLayout* layout = GridLayout::CreatePanel(this); SetLayoutManager(layout); views::ColumnSet* c1 = layout->AddColumnSet(0); c1->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); c1->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); c1->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1, GridLayout::USE_PREF, kTextfieldWidth, kTextfieldWidth); layout->StartRow(0, 0); views::Label* label = new views::Label(UTF16ToWideHack(delegate_->label())); layout->AddView(label); layout->AddView(text_field_); MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &ContentView::FocusFirstFocusableControl)); } void ContentView::FocusFirstFocusableControl() { text_field_->SelectAll(); text_field_->RequestFocus(); } WinInputWindowDialog::WinInputWindowDialog(gfx::NativeWindow parent, const string16& window_title, const string16& label, const string16& contents, Delegate* delegate) : window_title_(window_title), label_(label), contents_(contents), delegate_(delegate) { window_ = views::Widget::CreateWindowWithParent(new ContentView(this), parent); window_->client_view()->AsDialogClientView()->UpdateDialogButtons(); } WinInputWindowDialog::~WinInputWindowDialog() { } void WinInputWindowDialog::Show() { window_->Show(); } void WinInputWindowDialog::Close() { window_->Close(); } // static InputWindowDialog* InputWindowDialog::Create(gfx::NativeWindow parent, const string16& window_title, const string16& label, const string16& contents, Delegate* delegate) { return new WinInputWindowDialog( parent, window_title, label, contents, delegate); } <|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-2014 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 "OgreTerrainMaterialGeneratorA.h" #include "OgreRoot.h" #include "OgreHardwarePixelBuffer.h" #include "OgreTextureManager.h" #include "OgreTexture.h" #include "OgreTerrain.h" #include "OgreManualObject.h" #include "OgreCamera.h" #include "OgreViewport.h" #include "OgreRenderSystem.h" #include "OgreRenderTarget.h" #include "OgreRenderTexture.h" #include "OgreSceneNode.h" #include "OgreRectangle2D.h" #if OGRE_COMPILER == OGRE_COMPILER_MSVC // we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing # pragma warning (disable : 4244) #endif namespace Ogre { //--------------------------------------------------------------------- TerrainMaterialGenerator::TerrainMaterialGenerator() : mActiveProfile(0) , mChangeCounter(0) , mDebugLevel(0) , mCompositeMapSM(0) , mCompositeMapCam(0) , mCompositeMapRTT(0) , mCompositeMapPlane(0) , mCompositeMapLight(0) { } //--------------------------------------------------------------------- TerrainMaterialGenerator::~TerrainMaterialGenerator() { for (ProfileList::iterator i = mProfiles.begin(); i != mProfiles.end(); ++i) OGRE_DELETE *i; if (mCompositeMapRTT && TextureManager::getSingletonPtr()) { TextureManager::getSingleton().remove(mCompositeMapRTT->getHandle()); mCompositeMapRTT = 0; } if (mCompositeMapSM && Root::getSingletonPtr()) { // will also delete cam and objects etc Root::getSingleton().destroySceneManager(mCompositeMapSM); mCompositeMapSM = 0; mCompositeMapCam = 0; mCompositeMapPlane = 0; mCompositeMapLight = 0; mLightNode = 0; } } //--------------------------------------------------------------------- void TerrainMaterialGenerator::_renderCompositeMap(size_t size, const Rect& rect, const MaterialPtr& mat, const TexturePtr& destCompositeMap) { if (!mCompositeMapSM) { // dedicated SceneManager mCompositeMapSM = Root::getSingleton().createSceneManager(DefaultSceneManagerFactory::FACTORY_TYPE_NAME); mCompositeMapCam = mCompositeMapSM->createCamera("cam"); mCompositeMapSM->getRootSceneNode()->attachObject(mCompositeMapCam); mCompositeMapCam->setProjectionType(PT_ORTHOGRAPHIC); mCompositeMapCam->setNearClipDistance(0.5); mCompositeMapCam->setFarClipDistance(1.5); mCompositeMapCam->setOrthoWindow(2, 2); // Just in case material relies on light auto params mCompositeMapLight = mCompositeMapSM->createLight(); mCompositeMapLight->setType(Light::LT_DIRECTIONAL); mLightNode = mCompositeMapSM->getRootSceneNode()->createChildSceneNode(); mLightNode->attachObject(mCompositeMapLight); RenderSystem* rSys = Root::getSingleton().getRenderSystem(); Real hOffset = rSys->getHorizontalTexelOffset() / (Real)size; Real vOffset = rSys->getVerticalTexelOffset() / (Real)size; // set up scene mCompositeMapPlane = new Rectangle2D(true); mCompositeMapPlane->setCorners(-1, 1, 1, -1); mCompositeMapPlane->setUVs({0 - hOffset, 0 - vOffset}, {0 - hOffset, 1 - vOffset}, {1 - hOffset, 0 - vOffset}, {1 - hOffset, 1 - vOffset}); mCompositeMapPlane->setBoundingBox(AxisAlignedBox::BOX_INFINITE); mCompositeMapSM->getRootSceneNode()->attachObject(mCompositeMapPlane); } // update mCompositeMapPlane->setMaterial(mat); TerrainGlobalOptions& globalopts = TerrainGlobalOptions::getSingleton(); mLightNode->setDirection(globalopts.getLightMapDirection(), Node::TS_WORLD); mCompositeMapLight->setDiffuseColour(globalopts.getCompositeMapDiffuse()); mCompositeMapSM->setAmbientLight(globalopts.getCompositeMapAmbient()); // check for size change (allow smaller to be reused) if (mCompositeMapRTT && size != mCompositeMapRTT->getWidth()) { TextureManager::getSingleton().remove(mCompositeMapRTT->getHandle()); mCompositeMapRTT = 0; } if (!mCompositeMapRTT) { mCompositeMapRTT = TextureManager::getSingleton().createManual( mCompositeMapSM->getName() + "/compRTT", mat->getGroup(), TEX_TYPE_2D, static_cast<uint>(size), static_cast<uint>(size), 0, PF_BYTE_RGBA, TU_RENDERTARGET).get(); RenderTarget* rtt = mCompositeMapRTT->getBuffer()->getRenderTarget(); // don't render all the time, only on demand rtt->setAutoUpdated(false); Viewport* vp = rtt->addViewport(mCompositeMapCam); // don't render overlays vp->setOverlaysEnabled(false); } // calculate the area we need to update Real vpleft = (Real)rect.left / (Real)size; Real vptop = (Real)rect.top / (Real)size; Real vpright = (Real)rect.right / (Real)size; Real vpbottom = (Real)rect.bottom / (Real)size; RenderTarget* rtt = mCompositeMapRTT->getBuffer()->getRenderTarget(); mCompositeMapCam->setWindow(vpleft, vptop, vpright, vpbottom); rtt->update(); // We have an RTT, we want to copy the results into a regular texture // That's because in non-update scenarios we don't want to keep an RTT // around. We use a single RTT to serve all terrain pages which is more // efficient. Box box(rect); destCompositeMap->getBuffer()->blit(mCompositeMapRTT->getBuffer(), box, box); } //--------------------------------------------------------------------- //--------------------------------------------------------------------- void TerrainMaterialGenerator::Profile::updateCompositeMap(const Terrain* terrain, const Rect& rect) { // convert point-space rect into image space int32 compSize = terrain->getCompositeMap()->getWidth(); Rect imgRect; Vector3 inVec, outVec; inVec.x = rect.left; inVec.y = rect.bottom - 1; // this is 'top' in image space, also make inclusive terrain->convertPosition(Terrain::POINT_SPACE, inVec, Terrain::TERRAIN_SPACE, outVec); imgRect.left = outVec.x * compSize; imgRect.top = (1.0f - outVec.y) * compSize; inVec.x = rect.right - 1; inVec.y = rect.top; // this is 'bottom' in image space terrain->convertPosition(Terrain::POINT_SPACE, inVec, Terrain::TERRAIN_SPACE, outVec); imgRect.right = outVec.x * (Real)compSize + 1; imgRect.bottom = (1.0 - outVec.y) * compSize + 1; imgRect = imgRect.intersect({0, 0, compSize, compSize}); mParent->_renderCompositeMap( compSize, imgRect, terrain->getCompositeMapMaterial(), terrain->getCompositeMap()); } } <commit_msg>Terrain: Delete plane when shutting down.<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-2014 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 "OgreTerrainMaterialGeneratorA.h" #include "OgreRoot.h" #include "OgreHardwarePixelBuffer.h" #include "OgreTextureManager.h" #include "OgreTexture.h" #include "OgreTerrain.h" #include "OgreManualObject.h" #include "OgreCamera.h" #include "OgreViewport.h" #include "OgreRenderSystem.h" #include "OgreRenderTarget.h" #include "OgreRenderTexture.h" #include "OgreSceneNode.h" #include "OgreRectangle2D.h" #if OGRE_COMPILER == OGRE_COMPILER_MSVC // we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing # pragma warning (disable : 4244) #endif namespace Ogre { //--------------------------------------------------------------------- TerrainMaterialGenerator::TerrainMaterialGenerator() : mActiveProfile(0) , mChangeCounter(0) , mDebugLevel(0) , mCompositeMapSM(0) , mCompositeMapCam(0) , mCompositeMapRTT(0) , mCompositeMapPlane(0) , mCompositeMapLight(0) { } //--------------------------------------------------------------------- TerrainMaterialGenerator::~TerrainMaterialGenerator() { for (ProfileList::iterator i = mProfiles.begin(); i != mProfiles.end(); ++i) OGRE_DELETE *i; if (mCompositeMapRTT && TextureManager::getSingletonPtr()) { TextureManager::getSingleton().remove(mCompositeMapRTT->getHandle()); mCompositeMapRTT = 0; } if (mCompositeMapSM && Root::getSingletonPtr()) { // will also delete cam and objects etc Root::getSingleton().destroySceneManager(mCompositeMapSM); mCompositeMapSM = 0; mCompositeMapCam = 0; mCompositeMapLight = 0; mLightNode = 0; } delete mCompositeMapPlane; } //--------------------------------------------------------------------- void TerrainMaterialGenerator::_renderCompositeMap(size_t size, const Rect& rect, const MaterialPtr& mat, const TexturePtr& destCompositeMap) { if (!mCompositeMapSM) { // dedicated SceneManager mCompositeMapSM = Root::getSingleton().createSceneManager(DefaultSceneManagerFactory::FACTORY_TYPE_NAME); mCompositeMapCam = mCompositeMapSM->createCamera("cam"); mCompositeMapSM->getRootSceneNode()->attachObject(mCompositeMapCam); mCompositeMapCam->setProjectionType(PT_ORTHOGRAPHIC); mCompositeMapCam->setNearClipDistance(0.5); mCompositeMapCam->setFarClipDistance(1.5); mCompositeMapCam->setOrthoWindow(2, 2); // Just in case material relies on light auto params mCompositeMapLight = mCompositeMapSM->createLight(); mCompositeMapLight->setType(Light::LT_DIRECTIONAL); mLightNode = mCompositeMapSM->getRootSceneNode()->createChildSceneNode(); mLightNode->attachObject(mCompositeMapLight); RenderSystem* rSys = Root::getSingleton().getRenderSystem(); Real hOffset = rSys->getHorizontalTexelOffset() / (Real)size; Real vOffset = rSys->getVerticalTexelOffset() / (Real)size; // set up scene mCompositeMapPlane = new Rectangle2D(true); mCompositeMapPlane->setCorners(-1, 1, 1, -1); mCompositeMapPlane->setUVs({0 - hOffset, 0 - vOffset}, {0 - hOffset, 1 - vOffset}, {1 - hOffset, 0 - vOffset}, {1 - hOffset, 1 - vOffset}); mCompositeMapPlane->setBoundingBox(AxisAlignedBox::BOX_INFINITE); mCompositeMapSM->getRootSceneNode()->attachObject(mCompositeMapPlane); } // update mCompositeMapPlane->setMaterial(mat); TerrainGlobalOptions& globalopts = TerrainGlobalOptions::getSingleton(); mLightNode->setDirection(globalopts.getLightMapDirection(), Node::TS_WORLD); mCompositeMapLight->setDiffuseColour(globalopts.getCompositeMapDiffuse()); mCompositeMapSM->setAmbientLight(globalopts.getCompositeMapAmbient()); // check for size change (allow smaller to be reused) if (mCompositeMapRTT && size != mCompositeMapRTT->getWidth()) { TextureManager::getSingleton().remove(mCompositeMapRTT->getHandle()); mCompositeMapRTT = 0; } if (!mCompositeMapRTT) { mCompositeMapRTT = TextureManager::getSingleton().createManual( mCompositeMapSM->getName() + "/compRTT", mat->getGroup(), TEX_TYPE_2D, static_cast<uint>(size), static_cast<uint>(size), 0, PF_BYTE_RGBA, TU_RENDERTARGET).get(); RenderTarget* rtt = mCompositeMapRTT->getBuffer()->getRenderTarget(); // don't render all the time, only on demand rtt->setAutoUpdated(false); Viewport* vp = rtt->addViewport(mCompositeMapCam); // don't render overlays vp->setOverlaysEnabled(false); } // calculate the area we need to update Real vpleft = (Real)rect.left / (Real)size; Real vptop = (Real)rect.top / (Real)size; Real vpright = (Real)rect.right / (Real)size; Real vpbottom = (Real)rect.bottom / (Real)size; RenderTarget* rtt = mCompositeMapRTT->getBuffer()->getRenderTarget(); mCompositeMapCam->setWindow(vpleft, vptop, vpright, vpbottom); rtt->update(); // We have an RTT, we want to copy the results into a regular texture // That's because in non-update scenarios we don't want to keep an RTT // around. We use a single RTT to serve all terrain pages which is more // efficient. Box box(rect); destCompositeMap->getBuffer()->blit(mCompositeMapRTT->getBuffer(), box, box); } //--------------------------------------------------------------------- //--------------------------------------------------------------------- void TerrainMaterialGenerator::Profile::updateCompositeMap(const Terrain* terrain, const Rect& rect) { // convert point-space rect into image space int32 compSize = terrain->getCompositeMap()->getWidth(); Rect imgRect; Vector3 inVec, outVec; inVec.x = rect.left; inVec.y = rect.bottom - 1; // this is 'top' in image space, also make inclusive terrain->convertPosition(Terrain::POINT_SPACE, inVec, Terrain::TERRAIN_SPACE, outVec); imgRect.left = outVec.x * compSize; imgRect.top = (1.0f - outVec.y) * compSize; inVec.x = rect.right - 1; inVec.y = rect.top; // this is 'bottom' in image space terrain->convertPosition(Terrain::POINT_SPACE, inVec, Terrain::TERRAIN_SPACE, outVec); imgRect.right = outVec.x * (Real)compSize + 1; imgRect.bottom = (1.0 - outVec.y) * compSize + 1; imgRect = imgRect.intersect({0, 0, compSize, compSize}); mParent->_renderCompositeMap( compSize, imgRect, terrain->getCompositeMapMaterial(), terrain->getCompositeMap()); } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/svg/output/svg_renderer.hpp> namespace mapnik { struct symbol_type_dispatch : public boost::static_visitor<bool> { template <typename Symbolizer> bool operator()(Symbolizer const& sym) const { return false; } bool operator()(line_symbolizer const& sym) const { return true; } bool operator()(polygon_symbolizer const& sym) const { return true; } }; bool is_path_based(symbolizer const& sym) { return boost::apply_visitor(symbol_type_dispatch(), sym); } template <typename OutputIterator> bool svg_renderer<OutputIterator>::process(rule::symbolizers const& syms, mapnik::feature_impl & feature, proj_transform const& prj_trans) { // svg renderer supports processing of multiple symbolizers. typedef coord_transform<CoordTransform, geometry_type> path_type; bool process_path = false; // process each symbolizer to collect its (path) information. // path information (attributes from line_ and polygon_ symbolizers) // is collected with the path_attributes_ data member. for (symbolizer const& sym : syms) { if (is_path_based(sym)) { process_path = true; } boost::apply_visitor(symbol_dispatch(*this, feature, prj_trans), sym); } if (process_path) { // generate path output for each geometry of the current feature. for(std::size_t i=0; i<feature.num_geometries(); ++i) { geometry_type & geom = feature.get_geometry(i); if(geom.size() > 0) { path_type path(t_, geom, prj_trans); generator_.generate_path(path, path_attributes_); } } // set the previously collected values back to their defaults // for the feature that will be processed next. path_attributes_.reset(); } return true; } template bool svg_renderer<std::ostream_iterator<char> >::process(rule::symbolizers const& syms, mapnik::feature_impl & feature, proj_transform const& prj_trans); } <commit_msg>c++11<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/svg/output/svg_renderer.hpp> namespace mapnik { struct symbol_type_dispatch : public boost::static_visitor<bool> { template <typename Symbolizer> bool operator()(Symbolizer const& sym) const { return false; } bool operator()(line_symbolizer const& sym) const { return true; } bool operator()(polygon_symbolizer const& sym) const { return true; } }; bool is_path_based(symbolizer const& sym) { return boost::apply_visitor(symbol_type_dispatch(), sym); } template <typename OutputIterator> bool svg_renderer<OutputIterator>::process(rule::symbolizers const& syms, mapnik::feature_impl & feature, proj_transform const& prj_trans) { // svg renderer supports processing of multiple symbolizers. typedef coord_transform<CoordTransform, geometry_type> path_type; bool process_path = false; // process each symbolizer to collect its (path) information. // path information (attributes from line_ and polygon_ symbolizers) // is collected with the path_attributes_ data member. for (auto const& sym : syms) { if (is_path_based(sym)) { process_path = true; } boost::apply_visitor(symbol_dispatch(*this, feature, prj_trans), sym); } if (process_path) { // generate path output for each geometry of the current feature. for (auto & geom : feature.paths()) { if(geom.size() > 0) { path_type path(t_, geom, prj_trans); generator_.generate_path(path, path_attributes_); } } // set the previously collected values back to their defaults // for the feature that will be processed next. path_attributes_.reset(); } return true; } template bool svg_renderer<std::ostream_iterator<char> >::process(rule::symbolizers const& syms, mapnik::feature_impl & feature, proj_transform const& prj_trans); } <|endoftext|>
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "subprocess.h" #include <stdio.h> #include <algorithm> #include "util.h" namespace { void Win32Fatal(const char* function) { DWORD err = GetLastError(); char* msg_buf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&msg_buf, 0, NULL); Fatal("%s: %s", function, msg_buf); LocalFree(msg_buf); } } // anonymous namespace Subprocess::Subprocess() : child_(NULL) , overlapped_() { } Subprocess::~Subprocess() { // Reap child if forgotten. if (child_) Finish(); } HANDLE Subprocess::SetupPipe(HANDLE ioport) { char pipe_name[100]; snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\pipe\\ninja_pid%u_sp%p", GetCurrentProcessId(), this); pipe_ = ::CreateNamedPipeA(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 0, 0, INFINITE, NULL); if (pipe_ == INVALID_HANDLE_VALUE) Win32Fatal("CreateNamedPipe"); if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0)) Win32Fatal("CreateIoCompletionPort"); memset(&overlapped_, 0, sizeof(overlapped_)); if (!ConnectNamedPipe(pipe_, &overlapped_) && GetLastError() != ERROR_IO_PENDING) { Win32Fatal("ConnectNamedPipe"); } // Get the write end of the pipe as a handle inheritable across processes. HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); HANDLE output_write_child; if (!DuplicateHandle(GetCurrentProcess(), output_write_handle, GetCurrentProcess(), &output_write_child, 0, TRUE, DUPLICATE_SAME_ACCESS)) { Win32Fatal("DuplicateHandle"); } CloseHandle(output_write_handle); return output_write_child; } bool Subprocess::Start(SubprocessSet* set, const string& command) { HANDLE child_pipe = SetupPipe(set->ioport_); STARTUPINFOA startup_info; startup_info.cb = sizeof(STARTUPINFO); startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdOutput = child_pipe; // TODO: what does this hook up stdin to? startup_info.hStdInput = NULL; // TODO: is it ok to reuse pipe like this? startup_info.hStdError = child_pipe; PROCESS_INFORMATION process_info; // Do not prepend 'cmd /c' on Windows, this breaks command // lines greater than 8,191 chars. if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL, /* inherit handles */ TRUE, 0, NULL, NULL, &startup_info, &process_info)) { Win32Fatal("CreateProcess"); } // Close pipe channel only used by the child. if (child_pipe) CloseHandle(child_pipe); CloseHandle(process_info.hThread); child_ = process_info.hProcess; return true; } void Subprocess::OnPipeReady() { DWORD bytes; if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } Win32Fatal("GetOverlappedResult"); } if (bytes) buf_.append(overlapped_buf_, bytes); memset(&overlapped_, 0, sizeof(overlapped_)); if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_), &bytes, &overlapped_)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } if (GetLastError() != ERROR_IO_PENDING) Win32Fatal("ReadFile"); } // Even if we read any bytes in the readfile call, we'll enter this // function again later and get them at that point. } bool Subprocess::Finish() { // TODO: add error handling for all of these. WaitForSingleObject(child_, INFINITE); DWORD exit_code = 0; GetExitCodeProcess(child_, &exit_code); CloseHandle(child_); child_ = NULL; return exit_code == 0; } bool Subprocess::Done() const { return pipe_ == NULL; } const string& Subprocess::GetOutput() const { return buf_; } SubprocessSet::SubprocessSet() { ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if (!ioport_) Win32Fatal("CreateIoCompletionPort"); } SubprocessSet::~SubprocessSet() { CloseHandle(ioport_); } void SubprocessSet::Add(Subprocess* subprocess) { running_.push_back(subprocess); } void SubprocessSet::DoWork() { DWORD bytes_read; Subprocess* subproc; OVERLAPPED* overlapped; if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc, &overlapped, INFINITE)) { if (GetLastError() != ERROR_BROKEN_PIPE) Win32Fatal("GetQueuedCompletionStatus"); } subproc->OnPipeReady(); if (subproc->Done()) { vector<Subprocess*>::iterator end = std::remove(running_.begin(), running_.end(), subproc); if (running_.end() != end) { finished_.push(subproc); running_.resize(end - running_.begin()); } } } Subprocess* SubprocessSet::NextFinished() { if (finished_.empty()) return NULL; Subprocess* subproc = finished_.front(); finished_.pop(); return subproc; } <commit_msg>windows: clear process launch structs before using them<commit_after>// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "subprocess.h" #include <stdio.h> #include <algorithm> #include "util.h" namespace { void Win32Fatal(const char* function) { DWORD err = GetLastError(); char* msg_buf; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&msg_buf, 0, NULL); Fatal("%s: %s", function, msg_buf); LocalFree(msg_buf); } } // anonymous namespace Subprocess::Subprocess() : child_(NULL) , overlapped_() { } Subprocess::~Subprocess() { // Reap child if forgotten. if (child_) Finish(); } HANDLE Subprocess::SetupPipe(HANDLE ioport) { char pipe_name[100]; snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\pipe\\ninja_pid%u_sp%p", GetCurrentProcessId(), this); pipe_ = ::CreateNamedPipeA(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 0, 0, INFINITE, NULL); if (pipe_ == INVALID_HANDLE_VALUE) Win32Fatal("CreateNamedPipe"); if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0)) Win32Fatal("CreateIoCompletionPort"); memset(&overlapped_, 0, sizeof(overlapped_)); if (!ConnectNamedPipe(pipe_, &overlapped_) && GetLastError() != ERROR_IO_PENDING) { Win32Fatal("ConnectNamedPipe"); } // Get the write end of the pipe as a handle inheritable across processes. HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); HANDLE output_write_child; if (!DuplicateHandle(GetCurrentProcess(), output_write_handle, GetCurrentProcess(), &output_write_child, 0, TRUE, DUPLICATE_SAME_ACCESS)) { Win32Fatal("DuplicateHandle"); } CloseHandle(output_write_handle); return output_write_child; } bool Subprocess::Start(SubprocessSet* set, const string& command) { HANDLE child_pipe = SetupPipe(set->ioport_); STARTUPINFOA startup_info; memset(&startup_info, 0, sizeof(startup_info)); startup_info.cb = sizeof(STARTUPINFO); startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdOutput = child_pipe; // TODO: what does this hook up stdin to? startup_info.hStdInput = NULL; // TODO: is it ok to reuse pipe like this? startup_info.hStdError = child_pipe; PROCESS_INFORMATION process_info; memset(&process_info, 0, sizeof(process_info)); // Do not prepend 'cmd /c' on Windows, this breaks command // lines greater than 8,191 chars. if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL, /* inherit handles */ TRUE, 0, NULL, NULL, &startup_info, &process_info)) { Win32Fatal("CreateProcess"); } // Close pipe channel only used by the child. if (child_pipe) CloseHandle(child_pipe); CloseHandle(process_info.hThread); child_ = process_info.hProcess; return true; } void Subprocess::OnPipeReady() { DWORD bytes; if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } Win32Fatal("GetOverlappedResult"); } if (bytes) buf_.append(overlapped_buf_, bytes); memset(&overlapped_, 0, sizeof(overlapped_)); if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_), &bytes, &overlapped_)) { if (GetLastError() == ERROR_BROKEN_PIPE) { CloseHandle(pipe_); pipe_ = NULL; return; } if (GetLastError() != ERROR_IO_PENDING) Win32Fatal("ReadFile"); } // Even if we read any bytes in the readfile call, we'll enter this // function again later and get them at that point. } bool Subprocess::Finish() { // TODO: add error handling for all of these. WaitForSingleObject(child_, INFINITE); DWORD exit_code = 0; GetExitCodeProcess(child_, &exit_code); CloseHandle(child_); child_ = NULL; return exit_code == 0; } bool Subprocess::Done() const { return pipe_ == NULL; } const string& Subprocess::GetOutput() const { return buf_; } SubprocessSet::SubprocessSet() { ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1); if (!ioport_) Win32Fatal("CreateIoCompletionPort"); } SubprocessSet::~SubprocessSet() { CloseHandle(ioport_); } void SubprocessSet::Add(Subprocess* subprocess) { running_.push_back(subprocess); } void SubprocessSet::DoWork() { DWORD bytes_read; Subprocess* subproc; OVERLAPPED* overlapped; if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc, &overlapped, INFINITE)) { if (GetLastError() != ERROR_BROKEN_PIPE) Win32Fatal("GetQueuedCompletionStatus"); } subproc->OnPipeReady(); if (subproc->Done()) { vector<Subprocess*>::iterator end = std::remove(running_.begin(), running_.end(), subproc); if (running_.end() != end) { finished_.push(subproc); running_.resize(end - running_.begin()); } } } Subprocess* SubprocessSet::NextFinished() { if (finished_.empty()) return NULL; Subprocess* subproc = finished_.front(); finished_.pop(); return subproc; } <|endoftext|>
<commit_before>#define WIN32_NO_STATUS #include <Windows.h> #undef WIN32_NO_STATUS #include <ntstatus.h> #define WIN32_NO_STATUS #include <winscard.h> #include <string> #include <vector> #include <stdio.h> #include <io.h> #include <fcntl.h> #include <wincred.h> #include <Ole2.h> #include "SmartCardHelper.hpp" #include "Lsa.hpp" #include "SecIdentity.hpp" using std::vector; #undef NTSTATUS_FROM_WIN32 extern "C" NTSTATUS NTSTATUS_FROM_WIN32(long x) { return x <= 0 ? (NTSTATUS)x : (NTSTATUS)(((x) & 0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR); } enum StandardIO { Input, Output, Error }; extern "C" void close_stdio(StandardIO type) { switch(type) { case StandardIO::Input: fclose(stdin); break; case StandardIO::Output: fclose(stdout); break; case StandardIO::Error: fclose(stderr); break; } } extern "C" void open_stdio(StandardIO type) { FILE * f = nullptr; switch(type) { case StandardIO::Input: _wfreopen_s(&f, L"CONIN$", L"r+,ccs=UTF-16LE", stdin); //SetStdHandle(STD_INPUT_HANDLE, reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stdin)))); fflush(stdin); break; case StandardIO::Output: _wfreopen_s(&f, L"CONOUT$", L"w+,ccs=UTF-16LE", stdout); //SetStdHandle(STD_OUTPUT_HANDLE, reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stdout)))); //{ // int fh = _fileno(stdout); // std::wstring check(L"CHECK\n標準出力チェック\n"); // for(auto i = check.begin(), e = check.end(); i < e; i++) // { // auto c = *i; // _write(fh, &c, sizeof(c)); // } //} fflush(stdout); break; case StandardIO::Error: _wfreopen_s(&f, L"CONOUT$", L"w+,ccs=UTF-16LE", stderr); //SetStdHandle(STD_ERROR_HANDLE, reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stderr)))); //{ // std::wstring check(L"ERR CHECK\n標準エラーチェック\n"); // for(auto i = check.begin(), e = check.end(); i < e; i++) // { // _fputwc_nolock(*i, stderr); // } //} fflush(stderr); break; } } extern "C" void CALLBACK TestA(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow) { MessageBoxW(hwnd, L"このメッセージはでないはずだよ。", nullptr, MB_ICONHAND); } extern "C" void show_credential_dialog() { WCHAR szUserName[256]; WCHAR szDomainName[256]; WCHAR szPassword[256]; DWORD dwUserNameSize = sizeof(szUserName) / sizeof(WCHAR); DWORD dwDomainSize = sizeof(szDomainName) / sizeof(WCHAR); DWORD dwPasswordSize = sizeof(szPassword) / sizeof(WCHAR); DWORD dwResult; DWORD dwOutBufferSize; PVOID pOutBuffer; ULONG uAuthPackage = 0; CREDUI_INFOW uiInfo; HANDLE hToken; uiInfo.cbSize = sizeof(CREDUI_INFO); uiInfo.hwndParent = NULL; uiInfo.pszMessageText = L"message"; uiInfo.pszCaptionText = L"caption"; uiInfo.hbmBanner = NULL; dwOutBufferSize = 1024; pOutBuffer = (PVOID)LocalAlloc(LPTR, dwOutBufferSize); dwResult = CredUIPromptForWindowsCredentialsW(&uiInfo, 0, &uAuthPackage, NULL, 0, &pOutBuffer, &dwOutBufferSize, NULL, 0); if(dwResult != ERROR_SUCCESS) { LocalFree(pOutBuffer); _getwch(); return; } CredUnPackAuthenticationBufferW(0, pOutBuffer, dwOutBufferSize, szUserName, &dwUserNameSize, szDomainName, &dwDomainSize, szPassword, &dwPasswordSize); szUserName[dwUserNameSize] = '\0'; szPassword[dwPasswordSize] = '\0'; wprintf_s(L"User=%s,Pass=%s\n", szUserName, szPassword); if(LogonUserW(szUserName, NULL, szPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &hToken)) CloseHandle(hToken); else wprintf_s(L"ログオンに失敗。(%u)\n", GetLastError()); RtlSecureZeroMemory(szPassword, sizeof(szPassword)); RtlSecureZeroMemory(pOutBuffer, dwOutBufferSize); LocalFree(pOutBuffer); _getwch(); } extern "C" void test_smartcard_class() { SmartCardHelper * h = new SmartCardHelper(); if(h->GetReadersCount() == 0) { wprintf_s(L"カードリーダーが接続されていないか認識されていません。\n"); delete h; return; } wprintf_s(L"%u台のカードリーダーが見つかりました。\n", h->GetReadersCount()); // カードがセットされたらIDを出力する処理を登録 h->RegisterConnectionHandler([](ConnectionInfo * ci) { auto id = ci->Card->GetID(); auto rname = ci->Reader->GetName(); wprintf_s(L"[%s]カードを認識しました。(ID:%s)\n", rname.c_str(), id.c_str()); }); // カードが外された時の処理 h->RegisterDisconnectionHandler([](ConnectionInfo * ci) { auto id = ci->Card->GetID(); auto rname = ci->Reader->GetName(); wprintf_s(L"[%s]カードが外されました。(ID:%s)\n", rname.c_str(), id.c_str()); }); // 監視を開始 wprintf_s(L"カードリーダーの監視を開始します。\n"); h->WatchAll(); wprintf_s(L"何かキーを押すと終了します。\n"); _getwch(); // 監視を終了 h->UnwatchAll(); delete h; } extern "C" void EnumAccounts() { NtAccounts ac; vector<SecurityIdentity *> users; ac.GetUserAccounts(users); wstring name; for(auto i = users.begin(), e = users.end(); i != e; i++) { (*i)->GetName(name); wprintf(L"%s\n", name.c_str()); } ac.GetAll(users); for(auto i = users.begin(), e = users.end(); i != e; i++) { if((*i)->IsGroup()) { (*i)->GetName(name); wprintf(L"▶%s\n", name.c_str()); } } } extern "C" void CALLBACK TestW(HWND hwnd, HINSTANCE hinst, LPWSTR lpszCmdLine, int nCmdShow) { AllocConsole(); AttachConsole(GetCurrentProcessId()); open_stdio(StandardIO::Input); open_stdio(StandardIO::Output); open_stdio(StandardIO::Error); EnumAccounts(); #if false AllocateLsaHeap = [](ULONG s) { return reinterpret_cast<void*>(new unsigned char[s]); }; FreeLsaHeap = [](void * b) { delete[] static_cast<unsigned char*>(b); }; { auto lsa_str = CreateLsaString(L"LSA String Test"); wprintf_s(L"LSA_STRING::Buffer=%hs\nLSA_STRING::Length=%u\nLSA_STRING::MaxLen=%u\n", lsa_str->Buffer, lsa_str->Length, lsa_str->MaximumLength); wstring w; LoadLsaString(lsa_str, w); wprintf_s(L"復元:%s\n", w.c_str()); (*FreeLsaHeap)(lsa_str); } { auto lsa_str = CreateLsaString(L"LSA 文字列テスト"); wprintf_s(L"LSA_STRING::Buffer=%hs\nLSA_STRING::Length=%u\nLSA_STRING::MaxLen=%u\n", lsa_str->Buffer, lsa_str->Length, lsa_str->MaximumLength); wstring w; LoadLsaString(lsa_str, w); wprintf_s(L"復元:%s\n", w.c_str()); (*FreeLsaHeap)(lsa_str); } { wstring w(L"UNICODE_STRINGテスト"); auto ustr = CreateUnicodeString(w); wprintf_s(L"UNICODE_STRING::Buffer=%s\nUNICODE_STRING::Length=%u\nUNICODE_STRING::MaxLen=%u\n", ustr->Buffer, ustr->Length, ustr->MaximumLength); (*FreeLsaHeap)(ustr); } _getwch(); #endif #if false if(GetAsyncKeyState(VK_CONTROL) & 0x8000) { CoInitializeEx(nullptr, COINIT_DISABLE_OLE1DDE | COINIT_APARTMENTTHREADED); show_credential_dialog(); CoUninitialize(); } #endif //test_smartcard_class(); _getwch(); close_stdio(StandardIO::Error); close_stdio(StandardIO::Output); close_stdio(StandardIO::Input); FreeConsole(); } <commit_msg>パッケージの列挙とパッケージIDの取得テスト<commit_after>#define WIN32_NO_STATUS #include <Windows.h> #undef WIN32_NO_STATUS #include <ntstatus.h> #define WIN32_NO_STATUS #include <winscard.h> #include <string> #include <vector> #include <stdio.h> #include <io.h> #include <fcntl.h> #include <wincred.h> #include <Ole2.h> #include "SmartCardHelper.hpp" #include "Lsa.hpp" #include "SecIdentity.hpp" using std::vector; extern wstring * module_path; #undef NTSTATUS_FROM_WIN32 extern "C" NTSTATUS NTSTATUS_FROM_WIN32(long x) { return x <= 0 ? (NTSTATUS)x : (NTSTATUS)(((x) & 0x0000FFFF) | (FACILITY_NTWIN32 << 16) | ERROR_SEVERITY_ERROR); } enum StandardIO { Input, Output, Error }; extern "C" void close_stdio(StandardIO type) { switch(type) { case StandardIO::Input: fclose(stdin); break; case StandardIO::Output: fclose(stdout); break; case StandardIO::Error: fclose(stderr); break; } } extern "C" void open_stdio(StandardIO type) { FILE * f = nullptr; switch(type) { case StandardIO::Input: _wfreopen_s(&f, L"CONIN$", L"r+,ccs=UTF-16LE", stdin); //SetStdHandle(STD_INPUT_HANDLE, reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stdin)))); fflush(stdin); break; case StandardIO::Output: _wfreopen_s(&f, L"CONOUT$", L"w+,ccs=UTF-16LE", stdout); //SetStdHandle(STD_OUTPUT_HANDLE, reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stdout)))); //{ // int fh = _fileno(stdout); // std::wstring check(L"CHECK\n標準出力チェック\n"); // for(auto i = check.begin(), e = check.end(); i < e; i++) // { // auto c = *i; // _write(fh, &c, sizeof(c)); // } //} fflush(stdout); break; case StandardIO::Error: _wfreopen_s(&f, L"CONOUT$", L"w+,ccs=UTF-16LE", stderr); //SetStdHandle(STD_ERROR_HANDLE, reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stderr)))); //{ // std::wstring check(L"ERR CHECK\n標準エラーチェック\n"); // for(auto i = check.begin(), e = check.end(); i < e; i++) // { // _fputwc_nolock(*i, stderr); // } //} fflush(stderr); break; } } extern "C" void CALLBACK TestA(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow) { MessageBoxW(hwnd, L"このメッセージはでないはずだよ。", nullptr, MB_ICONHAND); } extern "C" void show_credential_dialog() { WCHAR szUserName[256]; WCHAR szDomainName[256]; WCHAR szPassword[256]; DWORD dwUserNameSize = sizeof(szUserName) / sizeof(WCHAR); DWORD dwDomainSize = sizeof(szDomainName) / sizeof(WCHAR); DWORD dwPasswordSize = sizeof(szPassword) / sizeof(WCHAR); DWORD dwResult; DWORD dwOutBufferSize; PVOID pOutBuffer; ULONG uAuthPackage = 0; CREDUI_INFOW uiInfo; HANDLE hToken; uiInfo.cbSize = sizeof(CREDUI_INFO); uiInfo.hwndParent = NULL; uiInfo.pszMessageText = L"message"; uiInfo.pszCaptionText = L"caption"; uiInfo.hbmBanner = NULL; dwOutBufferSize = 1024; pOutBuffer = (PVOID)LocalAlloc(LPTR, dwOutBufferSize); dwResult = CredUIPromptForWindowsCredentialsW(&uiInfo, 0, &uAuthPackage, NULL, 0, &pOutBuffer, &dwOutBufferSize, NULL, 0); if(dwResult != ERROR_SUCCESS) { LocalFree(pOutBuffer); _getwch(); return; } CredUnPackAuthenticationBufferW(0, pOutBuffer, dwOutBufferSize, szUserName, &dwUserNameSize, szDomainName, &dwDomainSize, szPassword, &dwPasswordSize); szUserName[dwUserNameSize] = '\0'; szPassword[dwPasswordSize] = '\0'; wprintf_s(L"User=%s,Pass=%s\n", szUserName, szPassword); if(LogonUserW(szUserName, NULL, szPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &hToken)) CloseHandle(hToken); else wprintf_s(L"ログオンに失敗。(%u)\n", GetLastError()); RtlSecureZeroMemory(szPassword, sizeof(szPassword)); RtlSecureZeroMemory(pOutBuffer, dwOutBufferSize); LocalFree(pOutBuffer); _getwch(); } extern "C" void test_smartcard_class() { SmartCardHelper * h = new SmartCardHelper(); if(h->GetReadersCount() == 0) { wprintf_s(L"カードリーダーが接続されていないか認識されていません。\n"); delete h; return; } wprintf_s(L"%u台のカードリーダーが見つかりました。\n", h->GetReadersCount()); // カードがセットされたらIDを出力する処理を登録 h->RegisterConnectionHandler([](ConnectionInfo * ci) { auto id = ci->Card->GetID(); auto rname = ci->Reader->GetName(); wprintf_s(L"[%s]カードを認識しました。(ID:%s)\n", rname.c_str(), id.c_str()); }); // カードが外された時の処理 h->RegisterDisconnectionHandler([](ConnectionInfo * ci) { auto id = ci->Card->GetID(); auto rname = ci->Reader->GetName(); wprintf_s(L"[%s]カードが外されました。(ID:%s)\n", rname.c_str(), id.c_str()); }); // 監視を開始 wprintf_s(L"カードリーダーの監視を開始します。\n"); h->WatchAll(); wprintf_s(L"何かキーを押すと終了します。\n"); _getwch(); // 監視を終了 h->UnwatchAll(); delete h; } extern "C" void EnumAuthenticationPackages() { HKEY lsa; LRESULT reg_result; reg_result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, LR"(SYSTEM\CurrentControlSet\Control\Lsa)", 0, KEY_QUERY_VALUE, &lsa); if(reg_result != ERROR_SUCCESS) { wprintf(L"LSAのレジストリキーを開けません 0x%08X\n", static_cast<unsigned int>(reg_result)); return; } DWORD size = 0; DWORD type; RegQueryValueExW(lsa, L"Security Packages", nullptr, &type, nullptr, &size); if(!((type == REG_SZ) || (type == REG_EXPAND_SZ) || (type == REG_MULTI_SZ))) { wprintf(L"文字列型ではありません。"); RegCloseKey(lsa); return; } wprintf(L"Authentication Packagesのサイズ %u\n", size); auto reg_value = new wchar_t[size / sizeof(wchar_t)]; RegQueryValueExW(lsa, L"Security Packages", nullptr, nullptr, reinterpret_cast<BYTE*>(reg_value), &size); auto packages = new vector<wstring>; if(type == REG_SZ) { packages->push_back(wstring(reg_value)); } else if(type == REG_EXPAND_SZ) { auto expand_size = ExpandEnvironmentStringsW(reg_value, nullptr, 0); auto expand_value = new wchar_t[expand_size]; ExpandEnvironmentStringsW(reg_value, expand_value, expand_size); packages->push_back(wstring(expand_value)); delete[] expand_value; } else if(type == REG_MULTI_SZ) { for(auto p = reg_value; *p; p += (1 + wcslen(p))) { packages->push_back(wstring(p)); } } delete[] reg_value; RegCloseKey(lsa); wprintf_s(L"パッケージの数 %u\n", packages->size()); auto c = 0u; LSA_HANDLE lsa_h; LSA_OPERATIONAL_MODE om; bool trusted_lsa; auto process = CreateLsaString(*module_path); if(LsaRegisterLogonProcess(process, &lsa_h, &om) != STATUS_SUCCESS) { trusted_lsa = false; if(LsaConnectUntrusted(&lsa_h) != STATUS_SUCCESS) { lsa_h = nullptr; } } else { wprintf_s(L"Trusted LSA mode. %u\n", om); trusted_lsa = true; } (*Lsa::FreeLsaHeap)(process); for(auto i = packages->begin(), e = packages->end(); i != e; i++) { ULONG pkgid; NTSTATUS lsa_result; if(lsa_h) { auto pkgname = CreateLsaString(*i); lsa_result = LsaLookupAuthenticationPackage(lsa_h, pkgname, &pkgid); if(lsa_result != STATUS_SUCCESS) { pkgid = 0xFFFFFFFEul; } (*Lsa::FreeLsaHeap)(pkgname); } else { lsa_result = STATUS_NOT_SUPPORTED; pkgid = 0xFFFFFFFFul; } if(lsa_result < 0) { wprintf(L"%03u:%s(ERR:0x%08X)\n", c++, i->c_str(), lsa_result); } else { wprintf(L"%03u:%s(%i)\n", c++, i->c_str(), static_cast<int>(pkgid)); } } if(lsa_h) { if(trusted_lsa) { LsaDeregisterLogonProcess(lsa_h); } else { LsaClose(lsa_h); } } delete packages; } extern "C" void EnumAccounts() { NtAccounts ac; vector<SecurityIdentity *> users; ac.GetUserAccounts(users); wstring name; for(auto i = users.begin(), e = users.end(); i != e; i++) { (*i)->GetName(name); wprintf(L"%s\n", name.c_str()); } ac.GetAll(users); for(auto i = users.begin(), e = users.end(); i != e; i++) { if((*i)->IsGroup()) { (*i)->GetName(name); wprintf(L"▶%s\n", name.c_str()); } } } extern "C" void CALLBACK TestW(HWND hwnd, HINSTANCE hinst, LPWSTR lpszCmdLine, int nCmdShow) { AllocConsole(); AttachConsole(GetCurrentProcessId()); open_stdio(StandardIO::Input); open_stdio(StandardIO::Output); open_stdio(StandardIO::Error); Lsa::AllocateLsaHeap = [](ULONG s) { return reinterpret_cast<void*>(new unsigned char[s]); }; Lsa::FreeLsaHeap = [](void * b) { delete[] static_cast<unsigned char*>(b); }; EnumAuthenticationPackages(); EnumAccounts(); #if false { auto lsa_str = CreateLsaString(L"LSA String Test"); wprintf_s(L"LSA_STRING::Buffer=%hs\nLSA_STRING::Length=%u\nLSA_STRING::MaxLen=%u\n", lsa_str->Buffer, lsa_str->Length, lsa_str->MaximumLength); wstring w; LoadLsaString(lsa_str, w); wprintf_s(L"復元:%s\n", w.c_str()); (*FreeLsaHeap)(lsa_str); } { auto lsa_str = CreateLsaString(L"LSA 文字列テスト"); wprintf_s(L"LSA_STRING::Buffer=%hs\nLSA_STRING::Length=%u\nLSA_STRING::MaxLen=%u\n", lsa_str->Buffer, lsa_str->Length, lsa_str->MaximumLength); wstring w; LoadLsaString(lsa_str, w); wprintf_s(L"復元:%s\n", w.c_str()); (*FreeLsaHeap)(lsa_str); } { wstring w(L"UNICODE_STRINGテスト"); auto ustr = CreateUnicodeString(w); wprintf_s(L"UNICODE_STRING::Buffer=%s\nUNICODE_STRING::Length=%u\nUNICODE_STRING::MaxLen=%u\n", ustr->Buffer, ustr->Length, ustr->MaximumLength); (*FreeLsaHeap)(ustr); } _getwch(); #endif #if false if(GetAsyncKeyState(VK_CONTROL) & 0x8000) { CoInitializeEx(nullptr, COINIT_DISABLE_OLE1DDE | COINIT_APARTMENTTHREADED); show_credential_dialog(); CoUninitialize(); } #endif //test_smartcard_class(); _getwch(); close_stdio(StandardIO::Error); close_stdio(StandardIO::Output); close_stdio(StandardIO::Input); FreeConsole(); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/options/cookies_view.h" #include <algorithm> #include "app/gfx/canvas.h" #include "app/gfx/color_utils.h" #include "app/l10n_util.h" #include "base/i18n/time_formatting.h" #include "base/message_loop.h" #include "base/string_util.h" #include "chrome/browser/cookies_tree_model.h" #include "chrome/browser/profile.h" #include "chrome/browser/views/cookie_info_view.h" #include "chrome/browser/views/database_info_view.h" #include "chrome/browser/views/local_storage_info_view.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "net/base/cookie_monster.h" #include "views/border.h" #include "views/grid_layout.h" #include "views/controls/label.h" #include "views/controls/button/native_button.h" #include "views/controls/tree/tree_view.h" #include "views/controls/textfield/textfield.h" #include "views/standard_layout.h" // static views::Window* CookiesView::instance_ = NULL; static const int kSearchFilterDelayMs = 500; /////////////////////////////////////////////////////////////////////////////// // CookiesTreeView // Overridden to handle Delete key presses class CookiesTreeView : public views::TreeView { public: explicit CookiesTreeView(CookiesTreeModel* cookies_model); virtual ~CookiesTreeView() {} // Removes the items associated with the selected node in the TreeView void RemoveSelectedItems(); private: DISALLOW_COPY_AND_ASSIGN(CookiesTreeView); }; CookiesTreeView::CookiesTreeView(CookiesTreeModel* cookies_model) { SetModel(cookies_model); SetRootShown(false); SetEditable(false); } void CookiesTreeView::RemoveSelectedItems() { TreeModelNode* selected_node = GetSelectedNode(); if (selected_node) { static_cast<CookiesTreeModel*>(model())->DeleteCookieNode( static_cast<CookieTreeNode*>(GetSelectedNode())); } } /////////////////////////////////////////////////////////////////////////////// // CookiesView, public: // static void CookiesView::ShowCookiesWindow(Profile* profile) { if (!instance_) { CookiesView* cookies_view = new CookiesView(profile); instance_ = views::Window::CreateChromeWindow( NULL, gfx::Rect(), cookies_view); } if (!instance_->IsVisible()) { instance_->Show(); } else { instance_->Activate(); } } CookiesView::~CookiesView() { cookies_tree_->SetModel(NULL); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, TreeModelObserver overrides: void CookiesView::TreeNodesAdded(TreeModel* model, TreeModelNode* parent, int start, int count) { UpdateRemoveButtonsState(); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::Buttonlistener implementation: void CookiesView::ButtonPressed( views::Button* sender, const views::Event& event) { if (sender == remove_button_) { cookies_tree_->RemoveSelectedItems(); if (cookies_tree_model_->GetRoot()->GetChildCount() == 0) UpdateForEmptyState(); } else if (sender == remove_all_button_) { cookies_tree_model_->DeleteAllStoredObjects(); UpdateForEmptyState(); } else if (sender == clear_search_button_) { ResetSearchQuery(); } } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::Textfield::Controller implementation: void CookiesView::ContentsChanged(views::Textfield* sender, const std::wstring& new_contents) { clear_search_button_->SetEnabled(!search_field_->text().empty()); search_update_factory_.RevokeAll(); MessageLoop::current()->PostDelayedTask(FROM_HERE, search_update_factory_.NewRunnableMethod( &CookiesView::UpdateSearchResults), kSearchFilterDelayMs); } bool CookiesView::HandleKeystroke(views::Textfield* sender, const views::Textfield::Keystroke& key) { if (key.GetKeyboardCode() == base::VKEY_ESCAPE) { ResetSearchQuery(); } else if (key.GetKeyboardCode() == base::VKEY_RETURN) { search_update_factory_.RevokeAll(); UpdateSearchResults(); } return false; } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::DialogDelegate implementation: std::wstring CookiesView::GetWindowTitle() const { return l10n_util::GetString(IDS_COOKIES_WEBSITE_PERMISSIONS_WINDOW_TITLE); } void CookiesView::WindowClosing() { instance_ = NULL; } views::View* CookiesView::GetContentsView() { return this; } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::View overrides: void CookiesView::Layout() { // Lay out the Remove/Remove All buttons in the parent view. gfx::Size ps = remove_button_->GetPreferredSize(); gfx::Rect parent_bounds = GetParent()->GetLocalBounds(false); int y_buttons = parent_bounds.bottom() - ps.height() - kButtonVEdgeMargin; remove_button_->SetBounds(kPanelHorizMargin, y_buttons, ps.width(), ps.height()); ps = remove_all_button_->GetPreferredSize(); int remove_all_x = remove_button_->x() + remove_button_->width() + kRelatedControlHorizontalSpacing; remove_all_button_->SetBounds(remove_all_x, y_buttons, ps.width(), ps.height()); // Lay out this View View::Layout(); } gfx::Size CookiesView::GetPreferredSize() { return gfx::Size(views::Window::GetLocalizedContentsSize( IDS_COOKIES_DIALOG_WIDTH_CHARS, IDS_COOKIES_DIALOG_HEIGHT_LINES)); } void CookiesView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && child == this) Init(); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::TreeViewController overrides: void CookiesView::OnTreeViewSelectionChanged(views::TreeView* tree_view) { CookieTreeNode::DetailedInfo detailed_info = static_cast<CookieTreeNode*>(tree_view->GetSelectedNode())-> GetDetailedInfo(); if (detailed_info.node_type == CookieTreeNode::DetailedInfo::TYPE_COOKIE) { UpdateVisibleDetailedInfo(cookie_info_view_); cookie_info_view_->SetCookie(detailed_info.cookie->first, detailed_info.cookie->second); } else if (detailed_info.node_type == CookieTreeNode::DetailedInfo::TYPE_DATABASE) { UpdateVisibleDetailedInfo(database_info_view_); database_info_view_->SetDatabaseInfo(*detailed_info.database_info); } else if (detailed_info.node_type == CookieTreeNode::DetailedInfo::TYPE_LOCAL_STORAGE) { UpdateVisibleDetailedInfo(local_storage_info_view_); local_storage_info_view_->SetLocalStorageInfo( *detailed_info.local_storage_info); } else { UpdateVisibleDetailedInfo(cookie_info_view_); cookie_info_view_->ClearCookieDisplay(); } } void CookiesView::OnTreeViewKeyDown(base::KeyboardCode keycode) { if (keycode == base::VKEY_DELETE) cookies_tree_->RemoveSelectedItems(); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, public: void CookiesView::UpdateSearchResults() { cookies_tree_model_->UpdateSearchResults(search_field_->text()); remove_button_->SetEnabled(cookies_tree_model_->GetRoot()-> GetTotalNodeCount() > 1); remove_all_button_->SetEnabled(cookies_tree_model_->GetRoot()-> GetTotalNodeCount() > 1); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, private: CookiesView::CookiesView(Profile* profile) : search_label_(NULL), search_field_(NULL), clear_search_button_(NULL), description_label_(NULL), cookies_tree_(NULL), cookie_info_view_(NULL), database_info_view_(NULL), local_storage_info_view_(NULL), remove_button_(NULL), remove_all_button_(NULL), profile_(profile), ALLOW_THIS_IN_INITIALIZER_LIST(search_update_factory_(this)) { } void CookiesView::Init() { search_label_ = new views::Label( l10n_util::GetString(IDS_COOKIES_SEARCH_LABEL)); search_field_ = new views::Textfield; search_field_->SetController(this); clear_search_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_COOKIES_CLEAR_SEARCH_LABEL)); clear_search_button_->SetEnabled(false); description_label_ = new views::Label( l10n_util::GetString(IDS_COOKIES_INFO_LABEL)); description_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); cookies_tree_model_.reset(new CookiesTreeModel(profile_, new BrowsingDataDatabaseHelper(profile_), new BrowsingDataLocalStorageHelper(profile_))); cookies_tree_model_->AddObserver(this); cookie_info_view_ = new CookieInfoView(false); database_info_view_ = new DatabaseInfoView; local_storage_info_view_ = new LocalStorageInfoView; cookies_tree_ = new CookiesTreeView(cookies_tree_model_.get()); remove_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_COOKIES_REMOVE_LABEL)); remove_all_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_COOKIES_REMOVE_ALL_LABEL)); using views::GridLayout; using views::ColumnSet; GridLayout* layout = CreatePanelGridLayout(this); SetLayoutManager(layout); const int five_column_layout_id = 0; ColumnSet* column_set = layout->AddColumnSet(five_column_layout_id); column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0, GridLayout::USE_PREF, 0, 0); const int single_column_layout_id = 1; column_set = layout->AddColumnSet(single_column_layout_id); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, five_column_layout_id); layout->AddView(search_label_); layout->AddView(search_field_); layout->AddView(clear_search_button_); layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing); layout->StartRow(0, single_column_layout_id); layout->AddView(description_label_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(1, single_column_layout_id); cookies_tree_->set_lines_at_root(true); cookies_tree_->set_auto_expand_children(true); layout->AddView(cookies_tree_); cookies_tree_->SetController(this); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_layout_id); layout->AddView(cookie_info_view_, 1, 2); layout->StartRow(0, single_column_layout_id); layout->AddView(database_info_view_); layout->StartRow(0, single_column_layout_id); layout->AddView(local_storage_info_view_); // Add the Remove/Remove All buttons to the ClientView View* parent = GetParent(); parent->AddChildView(remove_button_); parent->AddChildView(remove_all_button_); if (!cookies_tree_model_.get()->GetRoot()->GetChildCount()) UpdateForEmptyState(); else UpdateVisibleDetailedInfo(cookie_info_view_); } void CookiesView::ResetSearchQuery() { search_field_->SetText(std::wstring()); clear_search_button_->SetEnabled(false); UpdateSearchResults(); } void CookiesView::UpdateForEmptyState() { cookie_info_view_->ClearCookieDisplay(); remove_button_->SetEnabled(false); remove_all_button_->SetEnabled(false); UpdateVisibleDetailedInfo(cookie_info_view_); } void CookiesView::UpdateRemoveButtonsState() { remove_button_->SetEnabled(cookies_tree_model_->GetRoot()-> GetTotalNodeCount() > 1); remove_all_button_->SetEnabled(cookies_tree_model_->GetRoot()-> GetTotalNodeCount() > 1); } void CookiesView::UpdateVisibleDetailedInfo(views::View* view) { cookie_info_view_->SetVisible(view == cookie_info_view_); database_info_view_->SetVisible(view == database_info_view_); local_storage_info_view_->SetVisible(view == local_storage_info_view_); } <commit_msg>Fixes a bug where the "remove" and "remove all" buttons are enabled in the "Cookies" page even when there is nothing selected in the tree view.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/options/cookies_view.h" #include <algorithm> #include "app/gfx/canvas.h" #include "app/gfx/color_utils.h" #include "app/l10n_util.h" #include "base/i18n/time_formatting.h" #include "base/message_loop.h" #include "base/string_util.h" #include "chrome/browser/cookies_tree_model.h" #include "chrome/browser/profile.h" #include "chrome/browser/views/cookie_info_view.h" #include "chrome/browser/views/database_info_view.h" #include "chrome/browser/views/local_storage_info_view.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "net/base/cookie_monster.h" #include "views/border.h" #include "views/grid_layout.h" #include "views/controls/label.h" #include "views/controls/button/native_button.h" #include "views/controls/tree/tree_view.h" #include "views/controls/textfield/textfield.h" #include "views/standard_layout.h" // static views::Window* CookiesView::instance_ = NULL; static const int kSearchFilterDelayMs = 500; /////////////////////////////////////////////////////////////////////////////// // CookiesTreeView // Overridden to handle Delete key presses class CookiesTreeView : public views::TreeView { public: explicit CookiesTreeView(CookiesTreeModel* cookies_model); virtual ~CookiesTreeView() {} // Removes the items associated with the selected node in the TreeView void RemoveSelectedItems(); private: DISALLOW_COPY_AND_ASSIGN(CookiesTreeView); }; CookiesTreeView::CookiesTreeView(CookiesTreeModel* cookies_model) { SetModel(cookies_model); SetRootShown(false); SetEditable(false); } void CookiesTreeView::RemoveSelectedItems() { TreeModelNode* selected_node = GetSelectedNode(); if (selected_node) { static_cast<CookiesTreeModel*>(model())->DeleteCookieNode( static_cast<CookieTreeNode*>(GetSelectedNode())); } } /////////////////////////////////////////////////////////////////////////////// // CookiesView, public: // static void CookiesView::ShowCookiesWindow(Profile* profile) { if (!instance_) { CookiesView* cookies_view = new CookiesView(profile); instance_ = views::Window::CreateChromeWindow( NULL, gfx::Rect(), cookies_view); } if (!instance_->IsVisible()) { instance_->Show(); } else { instance_->Activate(); } } CookiesView::~CookiesView() { cookies_tree_->SetModel(NULL); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, TreeModelObserver overrides: void CookiesView::TreeNodesAdded(TreeModel* model, TreeModelNode* parent, int start, int count) { UpdateRemoveButtonsState(); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::Buttonlistener implementation: void CookiesView::ButtonPressed( views::Button* sender, const views::Event& event) { if (sender == remove_button_) { cookies_tree_->RemoveSelectedItems(); if (cookies_tree_model_->GetRoot()->GetChildCount() == 0) UpdateForEmptyState(); } else if (sender == remove_all_button_) { cookies_tree_model_->DeleteAllStoredObjects(); UpdateForEmptyState(); } else if (sender == clear_search_button_) { ResetSearchQuery(); } } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::Textfield::Controller implementation: void CookiesView::ContentsChanged(views::Textfield* sender, const std::wstring& new_contents) { clear_search_button_->SetEnabled(!search_field_->text().empty()); search_update_factory_.RevokeAll(); MessageLoop::current()->PostDelayedTask(FROM_HERE, search_update_factory_.NewRunnableMethod( &CookiesView::UpdateSearchResults), kSearchFilterDelayMs); } bool CookiesView::HandleKeystroke(views::Textfield* sender, const views::Textfield::Keystroke& key) { if (key.GetKeyboardCode() == base::VKEY_ESCAPE) { ResetSearchQuery(); } else if (key.GetKeyboardCode() == base::VKEY_RETURN) { search_update_factory_.RevokeAll(); UpdateSearchResults(); } return false; } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::DialogDelegate implementation: std::wstring CookiesView::GetWindowTitle() const { return l10n_util::GetString(IDS_COOKIES_WEBSITE_PERMISSIONS_WINDOW_TITLE); } void CookiesView::WindowClosing() { instance_ = NULL; } views::View* CookiesView::GetContentsView() { return this; } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::View overrides: void CookiesView::Layout() { // Lay out the Remove/Remove All buttons in the parent view. gfx::Size ps = remove_button_->GetPreferredSize(); gfx::Rect parent_bounds = GetParent()->GetLocalBounds(false); int y_buttons = parent_bounds.bottom() - ps.height() - kButtonVEdgeMargin; remove_button_->SetBounds(kPanelHorizMargin, y_buttons, ps.width(), ps.height()); ps = remove_all_button_->GetPreferredSize(); int remove_all_x = remove_button_->x() + remove_button_->width() + kRelatedControlHorizontalSpacing; remove_all_button_->SetBounds(remove_all_x, y_buttons, ps.width(), ps.height()); // Lay out this View View::Layout(); } gfx::Size CookiesView::GetPreferredSize() { return gfx::Size(views::Window::GetLocalizedContentsSize( IDS_COOKIES_DIALOG_WIDTH_CHARS, IDS_COOKIES_DIALOG_HEIGHT_LINES)); } void CookiesView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (is_add && child == this) Init(); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, views::TreeViewController overrides: void CookiesView::OnTreeViewSelectionChanged(views::TreeView* tree_view) { UpdateRemoveButtonsState(); CookieTreeNode::DetailedInfo detailed_info = static_cast<CookieTreeNode*>(tree_view->GetSelectedNode())-> GetDetailedInfo(); if (detailed_info.node_type == CookieTreeNode::DetailedInfo::TYPE_COOKIE) { UpdateVisibleDetailedInfo(cookie_info_view_); cookie_info_view_->SetCookie(detailed_info.cookie->first, detailed_info.cookie->second); } else if (detailed_info.node_type == CookieTreeNode::DetailedInfo::TYPE_DATABASE) { UpdateVisibleDetailedInfo(database_info_view_); database_info_view_->SetDatabaseInfo(*detailed_info.database_info); } else if (detailed_info.node_type == CookieTreeNode::DetailedInfo::TYPE_LOCAL_STORAGE) { UpdateVisibleDetailedInfo(local_storage_info_view_); local_storage_info_view_->SetLocalStorageInfo( *detailed_info.local_storage_info); } else { UpdateVisibleDetailedInfo(cookie_info_view_); cookie_info_view_->ClearCookieDisplay(); } } void CookiesView::OnTreeViewKeyDown(base::KeyboardCode keycode) { if (keycode == base::VKEY_DELETE) cookies_tree_->RemoveSelectedItems(); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, public: void CookiesView::UpdateSearchResults() { cookies_tree_model_->UpdateSearchResults(search_field_->text()); remove_button_->SetEnabled(cookies_tree_model_->GetRoot()-> GetTotalNodeCount() > 1); remove_all_button_->SetEnabled(cookies_tree_model_->GetRoot()-> GetTotalNodeCount() > 1); } /////////////////////////////////////////////////////////////////////////////// // CookiesView, private: CookiesView::CookiesView(Profile* profile) : search_label_(NULL), search_field_(NULL), clear_search_button_(NULL), description_label_(NULL), cookies_tree_(NULL), cookie_info_view_(NULL), database_info_view_(NULL), local_storage_info_view_(NULL), remove_button_(NULL), remove_all_button_(NULL), profile_(profile), ALLOW_THIS_IN_INITIALIZER_LIST(search_update_factory_(this)) { } void CookiesView::Init() { search_label_ = new views::Label( l10n_util::GetString(IDS_COOKIES_SEARCH_LABEL)); search_field_ = new views::Textfield; search_field_->SetController(this); clear_search_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_COOKIES_CLEAR_SEARCH_LABEL)); clear_search_button_->SetEnabled(false); description_label_ = new views::Label( l10n_util::GetString(IDS_COOKIES_INFO_LABEL)); description_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); cookies_tree_model_.reset(new CookiesTreeModel(profile_, new BrowsingDataDatabaseHelper(profile_), new BrowsingDataLocalStorageHelper(profile_))); cookies_tree_model_->AddObserver(this); cookie_info_view_ = new CookieInfoView(false); database_info_view_ = new DatabaseInfoView; local_storage_info_view_ = new LocalStorageInfoView; cookies_tree_ = new CookiesTreeView(cookies_tree_model_.get()); remove_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_COOKIES_REMOVE_LABEL)); remove_all_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_COOKIES_REMOVE_ALL_LABEL)); using views::GridLayout; using views::ColumnSet; GridLayout* layout = CreatePanelGridLayout(this); SetLayoutManager(layout); const int five_column_layout_id = 0; ColumnSet* column_set = layout->AddColumnSet(five_column_layout_id); column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0, GridLayout::USE_PREF, 0, 0); const int single_column_layout_id = 1; column_set = layout->AddColumnSet(single_column_layout_id); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, five_column_layout_id); layout->AddView(search_label_); layout->AddView(search_field_); layout->AddView(clear_search_button_); layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing); layout->StartRow(0, single_column_layout_id); layout->AddView(description_label_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(1, single_column_layout_id); cookies_tree_->set_lines_at_root(true); cookies_tree_->set_auto_expand_children(true); layout->AddView(cookies_tree_); cookies_tree_->SetController(this); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_layout_id); layout->AddView(cookie_info_view_, 1, 2); layout->StartRow(0, single_column_layout_id); layout->AddView(database_info_view_); layout->StartRow(0, single_column_layout_id); layout->AddView(local_storage_info_view_); // Add the Remove/Remove All buttons to the ClientView View* parent = GetParent(); parent->AddChildView(remove_button_); parent->AddChildView(remove_all_button_); if (!cookies_tree_model_.get()->GetRoot()->GetChildCount()) UpdateForEmptyState(); else UpdateVisibleDetailedInfo(cookie_info_view_); } void CookiesView::ResetSearchQuery() { search_field_->SetText(std::wstring()); clear_search_button_->SetEnabled(false); UpdateSearchResults(); } void CookiesView::UpdateForEmptyState() { cookie_info_view_->ClearCookieDisplay(); remove_button_->SetEnabled(false); remove_all_button_->SetEnabled(false); UpdateVisibleDetailedInfo(cookie_info_view_); } void CookiesView::UpdateRemoveButtonsState() { remove_button_->SetEnabled(cookies_tree_model_->GetRoot()-> GetTotalNodeCount() > 1 && cookies_tree_->GetSelectedNode()); remove_all_button_->SetEnabled(cookies_tree_model_->GetRoot()-> GetTotalNodeCount() > 1 && cookies_tree_->GetSelectedNode()); } void CookiesView::UpdateVisibleDetailedInfo(views::View* view) { cookie_info_view_->SetVisible(view == cookie_info_view_); database_info_view_->SetVisible(view == database_info_view_); local_storage_info_view_->SetVisible(view == local_storage_info_view_); } <|endoftext|>
<commit_before>/* * Copyright (C) 2016-2017, Egor Pugin * * 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 "command.h" #include "filesystem.h" #include <boost/algorithm/string.hpp> #include <boost/process.hpp> #include <iostream> #include <mutex> #include <thread> #include <primitives/log.h> DECLARE_STATIC_LOGGER(logger, "process"); #ifndef _WIN32 #if defined(__APPLE__) && defined(__DYNAMIC__) extern "C" { extern char ***_NSGetEnviron(void); } # define environ (*_NSGetEnviron()) #else # include <unistd.h> #endif #endif bool has_executable_in_path(std::string &prog, bool silent) { bool ret = true; try { prog = boost::process::find_executable_in_path(prog); } catch (fs::filesystem_error &e) { if (!silent) LOG_WARN(logger, "'" << prog << "' is missing in your path environment variable. Error: " << e.what()); ret = false; } return ret; } namespace command { class stream_reader { public: stream_reader(boost::process::pistream &in, std::ostream &out, std::string &buffer, const Options::Stream &opts) : in(in), out(out), buffer(buffer), opts(opts) { t = std::move(std::thread([&t = *this] { t(); })); } ~stream_reader() { t.join(); in.close(); } private: std::thread t; boost::process::pistream &in; std::ostream &out; std::string &buffer; const Options::Stream &opts; void operator()() { std::string s; while (std::getline(in, s)) { boost::trim(s); // before newline if (opts.action) opts.action(s); s += "\n"; if (opts.capture) buffer += s; if (opts.inherit) out << s; } } }; Result execute(const Args &args, const Options &opts) { using namespace boost::process; auto args_fixed = args; #ifdef _WIN32 if (args_fixed[0].rfind(".exe") != args_fixed[0].size() - 4) args_fixed[0] += ".exe"; #endif if (args_fixed[0].find_first_of("\\/") == std::string::npos && !has_executable_in_path(args_fixed[0])) throw std::runtime_error("Program '" + args_fixed[0] + "' not found"); #ifdef _WIN32 boost::algorithm::replace_all(args_fixed[0], "/", "\\"); #endif #ifndef NDEBUG { std::string s; for (auto &a : args_fixed) s += a + " "; s.resize(s.size() - 1); LOG_DEBUG(logger, "executing command: " << s); } #endif context ctx; ctx.stdin_behavior = inherit_stream(); auto set_behavior = [](auto &stream_behavior, auto &opts) { if (opts.capture) stream_behavior = capture_stream(); else if (opts.inherit) stream_behavior = inherit_stream(); else stream_behavior = silence_stream(); }; set_behavior(ctx.stdout_behavior, opts.out); set_behavior(ctx.stderr_behavior, opts.err); // copy env #ifndef _WIN32 auto env = environ; while (*env) { std::string s = *env; auto p = s.find("="); if (p != s.npos) ctx.environment[s.substr(0, p)] = s.substr(p + 1); env++; } #endif Result r; try { child c = boost::process::launch(args_fixed[0], args_fixed, ctx); std::unique_ptr<stream_reader> rdout, rderr; // run only if captured // inherit will be automatically done by boost::process #define RUN_READER(x) \ if (opts.x.capture) \ rd ## x = std::make_unique<stream_reader>(c.get_std ## x(), std::c ## x, r.x, opts.x) RUN_READER(out); RUN_READER(err); r.rc = c.wait().exit_status(); if (r.rc) LOG_WARN(logger, "Command exited with non zero status: " << args_fixed[0] << ", rc = " << r.rc); } catch (...) { LOG_FATAL(logger, "Command failed: " << args_fixed[0]); throw; } return r; } Result execute_and_capture(const Args &args, const Options &options) { auto opts = options; opts.out.capture = true; opts.err.capture = true; return execute(args, opts); } Result execute_with_output(const Args &args, const Options &options) { auto opts = options; opts.out.inherit = true; opts.err.inherit = true; return execute(args, opts); } void Result::write(path p) const { auto fn = p.filename().string(); p = p.parent_path(); write_file(p / (fn + "_out.txt"), out); write_file(p / (fn + "_err.txt"), err); } } // namespace command <commit_msg>Slightly improve command logging. Remove env copying for macos.<commit_after>/* * Copyright (C) 2016-2017, Egor Pugin * * 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 "command.h" #include "filesystem.h" #include <boost/algorithm/string.hpp> #include <boost/process.hpp> #include <iostream> #include <mutex> #include <thread> #include <primitives/log.h> DECLARE_STATIC_LOGGER(logger, "process"); #ifndef _WIN32 #if defined(__APPLE__) && defined(__DYNAMIC__) extern "C" { extern char ***_NSGetEnviron(void); } # define environ (*_NSGetEnviron()) #else # include <unistd.h> #endif #endif bool has_executable_in_path(std::string &prog, bool silent) { bool ret = true; try { prog = boost::process::find_executable_in_path(prog); } catch (fs::filesystem_error &e) { if (!silent) LOG_WARN(logger, "'" << prog << "' is missing in your path environment variable. Error: " << e.what()); ret = false; } return ret; } namespace command { class stream_reader { public: stream_reader(boost::process::pistream &in, std::ostream &out, std::string &buffer, const Options::Stream &opts) : in(in), out(out), buffer(buffer), opts(opts) { t = std::move(std::thread([&t = *this] { t(); })); } ~stream_reader() { t.join(); in.close(); } private: std::thread t; boost::process::pistream &in; std::ostream &out; std::string &buffer; const Options::Stream &opts; void operator()() { std::string s; while (std::getline(in, s)) { boost::trim(s); // before newline if (opts.action) opts.action(s); s += "\n"; if (opts.capture) buffer += s; if (opts.inherit) out << s; } } }; Result execute(const Args &args, const Options &opts) { using namespace boost::process; auto args_fixed = args; #ifdef _WIN32 if (args_fixed[0].rfind(".exe") != args_fixed[0].size() - 4) args_fixed[0] += ".exe"; #endif if (args_fixed[0].find_first_of("\\/") == std::string::npos && !has_executable_in_path(args_fixed[0])) throw std::runtime_error("Program '" + args_fixed[0] + "' not found"); #ifdef _WIN32 boost::algorithm::replace_all(args_fixed[0], "/", "\\"); #endif // log { std::string s; for (auto &a : args_fixed) s += a + " "; s.resize(s.size() - 1); LOG_DEBUG(logger, "executing command: " << s); } context ctx; ctx.stdin_behavior = inherit_stream(); auto set_behavior = [](auto &stream_behavior, auto &opts) { if (opts.capture) stream_behavior = capture_stream(); else if (opts.inherit) stream_behavior = inherit_stream(); else stream_behavior = silence_stream(); }; set_behavior(ctx.stdout_behavior, opts.out); set_behavior(ctx.stderr_behavior, opts.err); // copy env #if !defined(_WIN32) && !defined(__APPLE__) auto env = environ; while (*env) { std::string s = *env; auto p = s.find("="); if (p != s.npos) ctx.environment[s.substr(0, p)] = s.substr(p + 1); env++; } #endif Result r; try { child c = boost::process::launch(args_fixed[0], args_fixed, ctx); std::unique_ptr<stream_reader> rdout, rderr; // run only if captured // inherit will be automatically done by boost::process #define RUN_READER(x) \ if (opts.x.capture) \ rd ## x = std::make_unique<stream_reader>(c.get_std ## x(), std::c ## x, r.x, opts.x) RUN_READER(out); RUN_READER(err); r.rc = c.wait().exit_status(); if (r.rc) LOG_WARN(logger, "Command exited with non zero status: " << args_fixed[0] << ", rc = " << r.rc); } catch (std::exception &e) { LOG_FATAL(logger, "Command failed: " << args_fixed[0] << ": " << e.what()); throw; } return r; } Result execute_and_capture(const Args &args, const Options &options) { auto opts = options; opts.out.capture = true; opts.err.capture = true; return execute(args, opts); } Result execute_with_output(const Args &args, const Options &options) { auto opts = options; opts.out.inherit = true; opts.err.inherit = true; return execute(args, opts); } void Result::write(path p) const { auto fn = p.filename().string(); p = p.parent_path(); write_file(p / (fn + "_out.txt"), out); write_file(p / (fn + "_err.txt"), err); } } // namespace command <|endoftext|>
<commit_before>/* * cgeUtilFunctions.cpp * * Created on: 2015-12-15 * Author: Wang Yang * Mail: admin@wysaid.org */ #ifdef _CGE_USE_FFMPEG_ #include "cgeVideoUtils.h" #include "cgeFFmpegHeaders.h" #include "cgeVideoPlayer.h" #include "cgeVideoEncoder.h" #include "cgeSharedGLContext.h" #include "cgeMultipleEffects.h" #include "cgeBlendFilter.h" #include "cgeTextureUtils.h" #define USE_GPU_I420_ENCODING 1 extern "C" { JNIEXPORT jboolean JNICALL Java_org_wysaid_nativePort_CGEFFmpegNativeLibrary_nativeGenerateVideoWithFilter(JNIEnv *env, jclass cls, jstring outputFilename, jstring inputFilename, jstring filterConfig, jfloat filterIntensity, jobject blendImage, jint blendMode, jfloat blendIntensity, jboolean mute) { CGE_LOG_INFO("##### nativeGenerateVideoWithFilter!!!"); if(outputFilename == nullptr || inputFilename == nullptr) return false; CGESharedGLContext* glContext = CGESharedGLContext::create(2048, 2048); //Max video resolution size of 2k. if(glContext == nullptr) { CGE_LOG_ERROR("Create GL Context Failed!"); return false; } glContext->makecurrent(); CGETextureResult texResult = {0}; jclass nativeLibraryClass = env->FindClass("org/wysaid/nativePort/CGENativeLibrary"); if(blendImage != nullptr) texResult = cgeLoadTexFromBitmap_JNI(env, nativeLibraryClass, blendImage); const char* outFilenameStr = env->GetStringUTFChars(outputFilename, 0); const char* inFilenameStr = env->GetStringUTFChars(inputFilename, 0); const char* configStr = filterConfig == nullptr ? nullptr : env->GetStringUTFChars(filterConfig, 0); CGETexLoadArg texLoadArg; texLoadArg.env = env; texLoadArg.cls = env->FindClass("org/wysaid/nativePort/CGENativeLibrary"); bool retStatus = CGE::cgeGenerateVideoWithFilter(outFilenameStr, inFilenameStr, configStr, filterIntensity, texResult.texID, (CGETextureBlendMode)blendMode, blendIntensity, mute, &texLoadArg); env->ReleaseStringUTFChars(outputFilename, outFilenameStr); env->ReleaseStringUTFChars(inputFilename, inFilenameStr); if(configStr != nullptr) env->ReleaseStringUTFChars(filterConfig, configStr); CGE_LOG_INFO("generate over!\n"); delete glContext; return retStatus; } } namespace CGE { //A wrapper that Disables All Error Checking. class FastFrameHandler : public CGEImageHandler { public: void processingFilters() { if(m_vecFilters.empty() || m_bufferTextures[0] == 0) { glFlush(); return; } glDisable(GL_BLEND); assert(m_vertexArrayBuffer != 0); glViewport(0, 0, m_dstImageSize.width, m_dstImageSize.height); for(auto& filter : m_vecFilters) { swapBufferFBO(); glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffer); filter->render2Texture(this, m_bufferTextures[1], m_vertexArrayBuffer); glFlush(); } glFinish(); } void swapBufferFBO() { useImageFBO(); std::swap(m_bufferTextures[0], m_bufferTextures[1]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_bufferTextures[0], 0); } }; // A simple-slow offscreen video rendering function. bool cgeGenerateVideoWithFilter(const char* outputFilename, const char* inputFilename, const char* filterConfig, float filterIntensity, GLuint texID, CGETextureBlendMode blendMode, float blendIntensity, bool mute, CGETexLoadArg* loadArg) { static const int ENCODE_FPS = 30; CGEVideoDecodeHandler* decodeHandler = new CGEVideoDecodeHandler(); if(!decodeHandler->open(inputFilename)) { CGE_LOG_ERROR("Open %s failed!\n", inputFilename); delete decodeHandler; return false; } // decodeHandler->setSamplingStyle(CGEVideoDecodeHandler::ssFastBilinear); //already default int videoWidth = decodeHandler->getWidth(); int videoHeight = decodeHandler->getHeight(); unsigned char* cacheBuffer = nullptr; int cacheBufferSize = 0; CGEVideoPlayerYUV420P videoPlayer; videoPlayer.initWithDecodeHandler(decodeHandler); CGEVideoEncoderMP4 mp4Encoder; int audioSampleRate = decodeHandler->getAudioSampleRate(); CGE_LOG_INFO("The input audio sample-rate: %d", audioSampleRate); #if USE_GPU_I420_ENCODING //The video height must be mutiple of 8 when using the gpu encoding. if(videoHeight % 8 != 0) { videoHeight = (videoHeight & ~0x7u) + 8; } TextureDrawerRGB2YUV420P* gpuEncoder = TextureDrawerRGB2YUV420P::create(); gpuEncoder->setOutputSize(videoWidth, videoHeight); cgeMakeBlockLimit([&](){ CGE_LOG_INFO("delete I420 gpu encoder"); delete gpuEncoder; }); mp4Encoder.setRecordDataFormat(CGEVideoEncoderMP4::FMT_YUV420P); #else mp4Encoder.setRecordDataFormat(CGEVideoEncoderMP4::FMT_RGBA8888); #endif if(!mp4Encoder.init(outputFilename, ENCODE_FPS, videoWidth, videoHeight, !mute, 1650000, audioSampleRate)) { CGE_LOG_ERROR("CGEVideoEncoderMP4 - start recording failed!"); return false; } CGE_LOG_INFO("encoder created!"); FastFrameHandler handler; CGEBlendFilter* blendFilter = nullptr; if(texID != 0 && blendIntensity != 0.0f) { blendFilter = new CGEBlendFilter(); if(blendFilter->initWithMode(blendMode)) { blendFilter->setSamplerID(texID); blendFilter->setIntensity(blendIntensity); } else { delete blendFilter; blendFilter = nullptr; } } bool hasFilter = blendFilter != nullptr || (filterConfig != nullptr && *filterConfig != '\0' && filterIntensity != 0.0f); CGE_LOG_INFO("Has filter: %d\n", (int)hasFilter); if(hasFilter) { handler.initWithRawBufferData(nullptr, videoWidth, videoHeight, CGE_FORMAT_RGBA_INT8, false); // handler.getResultDrawer()->setFlipScale(1.0f, -1.0f); if(filterConfig != nullptr && *filterConfig != '\0' && filterIntensity != 0.0f) { CGEMutipleEffectFilter* filter = new CGEMutipleEffectFilter; filter->setTextureLoadFunction(cgeGlobalTextureLoadFunc, loadArg); filter->initWithEffectString(filterConfig); filter->setIntensity(filterIntensity); handler.addImageFilter(filter); } if(blendFilter != nullptr) { handler.addImageFilter(blendFilter); } cacheBufferSize = videoWidth * videoHeight * 4; cacheBuffer = new unsigned char[cacheBufferSize]; } int videoPTS = -1; CGEVideoEncoderMP4::ImageData imageData = {0}; imageData.width = videoWidth; imageData.height = videoHeight; #if USE_GPU_I420_ENCODING imageData.linesize[0] = videoWidth * videoHeight; imageData.linesize[1] = videoWidth * videoHeight >> 2; imageData.linesize[2] = videoWidth * videoHeight >> 2; imageData.data[0] = cacheBuffer; imageData.data[1] = cacheBuffer + imageData.linesize[0]; imageData.data[2] = imageData.data[1] + imageData.linesize[1]; #else imageData.linesize[0] = videoWidth * 4; imageData.data[0] = cacheBuffer; #endif CGE_LOG_INFO("Enter loop...\n"); while(1) { CGEFrameTypeNext nextFrameType = videoPlayer.queryNextFrame(); if(nextFrameType == FrameType_VideoFrame) { if(!videoPlayer.updateVideoFrame()) continue; int newPTS = round(decodeHandler->getCurrentTimestamp() / 1000.0 * ENCODE_FPS); CGE_LOG_INFO("last pts: %d, new pts; %d\n", videoPTS, newPTS); if(videoPTS < 0) { videoPTS = 0; } else if(videoPTS < newPTS) { videoPTS = newPTS; } else { CGE_LOG_ERROR("drop frame...\n"); continue; } if(hasFilter) { handler.setAsTarget(); glViewport(0, 0, videoPlayer.getLinesize(), videoHeight); videoPlayer.render(); handler.processingFilters(); #if USE_GPU_I420_ENCODING glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, videoWidth, videoHeight * 3 / 8); gpuEncoder->drawTexture(handler.getTargetTextureID()); glFinish(); glReadPixels(0, 0, videoWidth, videoHeight * 3 / 8, GL_RGBA, GL_UNSIGNED_BYTE, cacheBuffer); #elif 1 //Maybe faster than calling 'handler.getOutputBufferData' glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, videoWidth, videoHeight); handler.drawResult(); glFinish(); glReadPixels(0, 0, videoWidth, videoHeight, GL_RGBA, GL_UNSIGNED_BYTE, cacheBuffer); #else handler.getOutputBufferData(cacheBuffer, CGE_FORMAT_RGBA_INT8); #endif imageData.pts = videoPTS; if(!mp4Encoder.record(imageData)) { CGE_LOG_ERROR("record frame failed!"); } } else { AVFrame* frame = decodeHandler->getCurrentVideoAVFrame(); frame->pts = videoPTS; if(frame->data[0] == nullptr) continue; //maybe wrong for some audio, replace with the code below. mp4Encoder.recordVideoFrame(frame); } } else if(nextFrameType == FrameType_AudioFrame) { if(!mute) { #if 1 //Set this to 0 if you need to convert more audio formats and this function can not give a right result. AVFrame* pAudioFrame = decodeHandler->getCurrentAudioAVFrame(); if(pAudioFrame == nullptr) continue; mp4Encoder.recordAudioFrame(pAudioFrame); #else auto* decodeData = decodeHandler->getCurrentAudioFrame(); CGEVideoEncoderMP4::AudioSampleData encodeData; encodeData.data[0] = (const unsigned short*)decodeData->data; encodeData.nbSamples[0] = decodeData->nbSamples; encodeData.channels = decodeData->channels; CGE_LOG_INFO("ts: %g, nbSamples: %d, bps: %d, channels: %d, linesize: %d, format: %d", decodeData->timestamp, decodeData->nbSamples, decodeData->bytesPerSample, decodeData->channels, decodeData->linesize, decodeData->format); mp4Encoder.record(encodeData); #endif } } else { break; } } mp4Encoder.save(); delete[] cacheBuffer; return true; } } #endif<commit_msg>Update cgeVideoUtils.cpp<commit_after>/* * cgeUtilFunctions.cpp * * Created on: 2015-12-15 * Author: Wang Yang * Mail: admin@wysaid.org */ #ifdef _CGE_USE_FFMPEG_ #include "cgeVideoUtils.h" #include "cgeFFmpegHeaders.h" #include "cgeVideoPlayer.h" #include "cgeVideoEncoder.h" #include "cgeSharedGLContext.h" #include "cgeMultipleEffects.h" #include "cgeBlendFilter.h" #include "cgeTextureUtils.h" #define USE_GPU_I420_ENCODING 1 extern "C" { JNIEXPORT jboolean JNICALL Java_org_wysaid_nativePort_CGEFFmpegNativeLibrary_nativeGenerateVideoWithFilter(JNIEnv *env, jclass cls, jstring outputFilename, jstring inputFilename, jstring filterConfig, jfloat filterIntensity, jobject blendImage, jint blendMode, jfloat blendIntensity, jboolean mute) { CGE_LOG_INFO("##### nativeGenerateVideoWithFilter!!!"); if(outputFilename == nullptr || inputFilename == nullptr) return false; CGESharedGLContext* glContext = CGESharedGLContext::create(2048, 2048); //Max video resolution size of 2k. if(glContext == nullptr) { CGE_LOG_ERROR("Create GL Context Failed!"); return false; } glContext->makecurrent(); CGETextureResult texResult = {0}; jclass nativeLibraryClass = env->FindClass("org/wysaid/nativePort/CGENativeLibrary"); if(blendImage != nullptr) texResult = cgeLoadTexFromBitmap_JNI(env, nativeLibraryClass, blendImage); const char* outFilenameStr = env->GetStringUTFChars(outputFilename, 0); const char* inFilenameStr = env->GetStringUTFChars(inputFilename, 0); const char* configStr = filterConfig == nullptr ? nullptr : env->GetStringUTFChars(filterConfig, 0); CGETexLoadArg texLoadArg; texLoadArg.env = env; texLoadArg.cls = env->FindClass("org/wysaid/nativePort/CGENativeLibrary"); bool retStatus = CGE::cgeGenerateVideoWithFilter(outFilenameStr, inFilenameStr, configStr, filterIntensity, texResult.texID, (CGETextureBlendMode)blendMode, blendIntensity, mute, &texLoadArg); env->ReleaseStringUTFChars(outputFilename, outFilenameStr); env->ReleaseStringUTFChars(inputFilename, inFilenameStr); if(configStr != nullptr) env->ReleaseStringUTFChars(filterConfig, configStr); CGE_LOG_INFO("generate over!\n"); delete glContext; return retStatus; } } namespace CGE { //A wrapper that Disables All Error Checking. class FastFrameHandler : public CGEImageHandler { public: void processingFilters() { if(m_vecFilters.empty() || m_bufferTextures[0] == 0) { glFlush(); return; } glDisable(GL_BLEND); assert(m_vertexArrayBuffer != 0); glViewport(0, 0, m_dstImageSize.width, m_dstImageSize.height); for(auto& filter : m_vecFilters) { swapBufferFBO(); glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffer); filter->render2Texture(this, m_bufferTextures[1], m_vertexArrayBuffer); glFlush(); } glFinish(); } void swapBufferFBO() { useImageFBO(); std::swap(m_bufferTextures[0], m_bufferTextures[1]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_bufferTextures[0], 0); } }; // A simple-slow offscreen video rendering function. bool cgeGenerateVideoWithFilter(const char* outputFilename, const char* inputFilename, const char* filterConfig, float filterIntensity, GLuint texID, CGETextureBlendMode blendMode, float blendIntensity, bool mute, CGETexLoadArg* loadArg) { static const int ENCODE_FPS = 30; CGEVideoDecodeHandler* decodeHandler = new CGEVideoDecodeHandler(); if(!decodeHandler->open(inputFilename)) { CGE_LOG_ERROR("Open %s failed!\n", inputFilename); delete decodeHandler; return false; } // decodeHandler->setSamplingStyle(CGEVideoDecodeHandler::ssFastBilinear); //already default int videoWidth = decodeHandler->getWidth(); int videoHeight = decodeHandler->getHeight(); unsigned char* cacheBuffer = nullptr; int cacheBufferSize = 0; CGEVideoPlayerYUV420P videoPlayer; videoPlayer.initWithDecodeHandler(decodeHandler); CGEVideoEncoderMP4 mp4Encoder; int audioSampleRate = decodeHandler->getAudioSampleRate(); CGE_LOG_INFO("The input audio sample-rate: %d", audioSampleRate); #if USE_GPU_I420_ENCODING //The video height must be mutiple of 8 when using the gpu encoding. if(videoHeight % 8 != 0) { videoHeight = (videoHeight & ~0x7u) + 8; } TextureDrawerRGB2YUV420P* gpuEncoder = TextureDrawerRGB2YUV420P::create(); gpuEncoder->setOutputSize(videoWidth, videoHeight); cgeMakeBlockLimit([&](){ CGE_LOG_INFO("delete I420 gpu encoder"); delete gpuEncoder; }); mp4Encoder.setRecordDataFormat(CGEVideoEncoderMP4::FMT_YUV420P); #else mp4Encoder.setRecordDataFormat(CGEVideoEncoderMP4::FMT_RGBA8888); #endif if(!mp4Encoder.init(outputFilename, ENCODE_FPS, videoWidth, videoHeight, !mute, 1650000, audioSampleRate)) { CGE_LOG_ERROR("CGEVideoEncoderMP4 - start recording failed!"); return false; } CGE_LOG_INFO("encoder created!"); FastFrameHandler handler; CGEBlendFilter* blendFilter = nullptr; if(texID != 0 && blendIntensity != 0.0f) { blendFilter = new CGEBlendFilter(); if(blendFilter->initWithMode(blendMode)) { blendFilter->setSamplerID(texID); blendFilter->setIntensity(blendIntensity); } else { delete blendFilter; blendFilter = nullptr; } } bool hasFilter = blendFilter != nullptr || (filterConfig != nullptr && *filterConfig != '\0' && filterIntensity != 0.0f); CGE_LOG_INFO("Has filter: %d\n", (int)hasFilter); if(hasFilter) { handler.initWithRawBufferData(nullptr, videoWidth, videoHeight, CGE_FORMAT_RGBA_INT8, false); // handler.getResultDrawer()->setFlipScale(1.0f, -1.0f); if(filterConfig != nullptr && *filterConfig != '\0' && filterIntensity != 0.0f) { CGEMutipleEffectFilter* filter = new CGEMutipleEffectFilter; filter->setTextureLoadFunction(cgeGlobalTextureLoadFunc, loadArg); filter->initWithEffectString(filterConfig); filter->setIntensity(filterIntensity); handler.addImageFilter(filter); } if(blendFilter != nullptr) { handler.addImageFilter(blendFilter); } cacheBufferSize = videoWidth * videoHeight * 4; cacheBuffer = new unsigned char[cacheBufferSize]; } int videoPTS = -1; CGEVideoEncoderMP4::ImageData imageData = {0}; imageData.width = videoWidth; imageData.height = videoHeight; #if USE_GPU_I420_ENCODING imageData.linesize[0] = videoWidth * videoHeight; imageData.linesize[1] = videoWidth * videoHeight >> 2; imageData.linesize[2] = videoWidth * videoHeight >> 2; imageData.data[0] = cacheBuffer; imageData.data[1] = cacheBuffer + imageData.linesize[0]; imageData.data[2] = imageData.data[1] + imageData.linesize[1]; #else imageData.linesize[0] = videoWidth * 4; imageData.data[0] = cacheBuffer; #endif CGE_LOG_INFO("Enter loop...\n"); while(1) { CGEFrameTypeNext nextFrameType = videoPlayer.queryNextFrame(); if(nextFrameType == FrameType_VideoFrame) { if(!videoPlayer.updateVideoFrame()) continue; int newPTS = round(decodeHandler->getCurrentTimestamp() / 1000.0 * ENCODE_FPS); CGE_LOG_INFO("last pts: %d, new pts; %d\n", videoPTS, newPTS); if(videoPTS < 0) { videoPTS = 0; } else if(videoPTS < newPTS) { videoPTS = newPTS; } else { CGE_LOG_ERROR("drop frame...\n"); continue; } if(hasFilter) { handler.setAsTarget(); glViewport(0, 0, videoPlayer.getLinesize(), videoHeight); videoPlayer.render(); handler.processingFilters(); #if USE_GPU_I420_ENCODING glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, videoWidth, videoHeight * 3 / 8); gpuEncoder->drawTexture(handler.getTargetTextureID()); glFinish(); glReadPixels(0, 0, videoWidth, videoHeight * 3 / 8, GL_RGBA, GL_UNSIGNED_BYTE, cacheBuffer); #elif 1 //Maybe faster than calling 'handler.getOutputBufferData' glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, videoWidth, videoHeight); handler.drawResult(); glFinish(); glReadPixels(0, 0, videoWidth, videoHeight, GL_RGBA, GL_UNSIGNED_BYTE, cacheBuffer); #else handler.getOutputBufferData(cacheBuffer, CGE_FORMAT_RGBA_INT8); #endif imageData.pts = videoPTS; if(!mp4Encoder.record(imageData)) { CGE_LOG_ERROR("record frame failed!"); } } else { AVFrame* frame = decodeHandler->getCurrentVideoAVFrame(); frame->pts = videoPTS; if(frame->data[0] == nullptr) continue; //maybe wrong for some audio, replace with the code below. mp4Encoder.recordVideoFrame(frame); } } else if(nextFrameType == FrameType_AudioFrame) { if(!mute) { #if 1 //Set this to 0 when you need to convert more audio formats and this function can not give a right result. AVFrame* pAudioFrame = decodeHandler->getCurrentAudioAVFrame(); if(pAudioFrame == nullptr) continue; mp4Encoder.recordAudioFrame(pAudioFrame); #else auto* decodeData = decodeHandler->getCurrentAudioFrame(); CGEVideoEncoderMP4::AudioSampleData encodeData; encodeData.data[0] = (const unsigned short*)decodeData->data; encodeData.nbSamples[0] = decodeData->nbSamples; encodeData.channels = decodeData->channels; CGE_LOG_INFO("ts: %g, nbSamples: %d, bps: %d, channels: %d, linesize: %d, format: %d", decodeData->timestamp, decodeData->nbSamples, decodeData->bytesPerSample, decodeData->channels, decodeData->linesize, decodeData->format); mp4Encoder.record(encodeData); #endif } } else { break; } } mp4Encoder.save(); delete[] cacheBuffer; return true; } } #endif <|endoftext|>
<commit_before>/** * Title: CoreMIDI4J * Description: Core MIDI Device Provider for Java on OS X * Copyright: Copyright (c) 2015-2016 * Company: x.factory Librarians * * @author Derek Cook * * CoreMIDI4J is an open source Service Provider Interface for supporting external MIDI devices on MAC OS X * * This file is part of the XCODE project that provides the native implementation of CoreMIDI4J * * CREDITS - This library uses principles established by OSXMIDI4J, but converted so it operates at the JNI level with no additional libraries required * */ #include "CoreMidiDeviceProvider.h" ///////////////////////////////////////////////////////// // Native functions for CoreMidiDeviceProvider ///////////////////////////////////////////////////////// /* * Gets the number of MIDI sources provided by the Core MIDI system * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getNumberOfSources * Signature: ()I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * * @return The number of MIDI sources provided by the Core MIDI system * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getNumberOfSources(JNIEnv *env, jobject obj) { return (jint) MIDIGetNumberOfSources(); } /* * Gets the number of MIDI destinations provided by the Core MIDI system * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getNumberOfDestinations * Signature: ()I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * * @return The number of MIDI destinations provided by the Core MIDI system * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getNumberOfDestinations(JNIEnv *env, jobject obj) { return (jint) MIDIGetNumberOfDestinations(); } /* * Gets the specified Core MIDI Source * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getSource * Signature: (I)I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * @param sourceIndex The index of the MIDI source to get * * @return The specified Core MIDI Source * * @throws CoreMidiEXception if the source index is not valid * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getSource(JNIEnv *env, jobject obj, jint sourceIndex) { if ( sourceIndex >= MIDIGetNumberOfSources() ) { ThrowException(env,CFSTR("MIDIGetSource"),sourceIndex); } return MIDIGetSource(sourceIndex); } /* * Gets the specified Core MIDI Destination * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getDestination * Signature: (I)I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * @param destinationIndex The index of the MIDI destination to get * * @return The specified Core MIDI Destination * * @throws CoreMidiEXception if the destination index is not valid * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getDestination(JNIEnv *env, jobject obj, jint destinationIndex) { if ( destinationIndex >= MIDIGetNumberOfDestinations() ) { ThrowException(env,CFSTR("MIDIGetDestination"), destinationIndex); } return MIDIGetDestination(destinationIndex); } /* * Gets the unique ID (UID) of the specified end point * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getUniqueID * Signature: (I)I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * @param endPointReference The end point reference * * @return The unique ID (UID) of the specified end point * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getUniqueID(JNIEnv *env, jobject obj, jint endPointReference) { SInt32 uid = 0; MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyUniqueID, &uid); return uid; } /* * Creates and gets a MidiDevice.Info object for the specified end point reference * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getMidiDeviceInfo * Signature: (I)Ljavax/sound/midi/MidiDevice/Info; * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * @param endPointReference The end point reference * * @return A MidiDevice.Info object for the specified end point reference * */ JNIEXPORT jobject JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getMidiDeviceInfo(JNIEnv *env, jobject obj, jint endPointReference) { CFStringRef name = NULL; CFStringRef deviceName = NULL; CFStringRef description = NULL; CFStringRef manufacturer = NULL; SInt32 version; SInt32 uid; // Find the Java CoreMIDIDeviceInfo class and its constructor jclass javaClass = env->FindClass("uk/co/xfactorylibrarians/coremidi4j/CoreMidiDeviceInfo"); jmethodID constructor = env->GetMethodID(javaClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;III)V"); // Get the device properties MIDIObjectGetStringProperty(endPointReference, kMIDIPropertyName, &name); MIDIObjectGetStringProperty(endPointReference, kMIDIPropertyName, &deviceName); // Get this again in case our string build fails MIDIObjectGetStringProperty(endPointReference, kMIDIPropertyModel, &description); MIDIObjectGetStringProperty(endPointReference, kMIDIPropertyManufacturer, &manufacturer); MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyDriverVersion, &version); MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyUniqueID, &uid); CFMutableStringRef buildName = CFStringCreateMutable(NULL, 0); // Add "CoreMIDI4J - " to the start of our device name if we can if (buildName) { CFStringAppend(buildName, CFSTR("CoreMIDI4J - ")); CFStringAppend(buildName, name); // Overwrite the deviceName with our updated one deviceName = CFStringCreateCopy(NULL, buildName); // And release the temporary string CFRelease(buildName); } const char *deviceInfoName = CFStringGetCStringPtr ( deviceName, CFStringGetSystemEncoding() ); const char *deviceInfoDescription = CFStringGetCStringPtr ( description, CFStringGetSystemEncoding() ); const char *deviceInfoManufacturer = CFStringGetCStringPtr ( manufacturer, CFStringGetSystemEncoding() ); // Create the Java Object jobject info = env->NewObject(javaClass, constructor, env->NewStringUTF(( deviceInfoName != NULL ) ? deviceInfoName : "** Internal Error getting Device Name!"), env->NewStringUTF(( deviceInfoManufacturer != NULL ) ? deviceInfoManufacturer : "** Internal Error getting Device Manufacturer!"), env->NewStringUTF(( deviceInfoDescription != NULL ) ? deviceInfoDescription : "** Internal Error getting Device Description!"), version, endPointReference, uid); return info; } <commit_msg>Seems to do what #15 wants<commit_after>/** * Title: CoreMIDI4J * Description: Core MIDI Device Provider for Java on OS X * Copyright: Copyright (c) 2015-2016 * Company: x.factory Librarians * * @author Derek Cook * * CoreMIDI4J is an open source Service Provider Interface for supporting external MIDI devices on MAC OS X * * This file is part of the XCODE project that provides the native implementation of CoreMIDI4J * * CREDITS - This library uses principles established by OSXMIDI4J, but converted so it operates at the JNI level with no additional libraries required * */ #include "CoreMidiDeviceProvider.h" ///////////////////////////////////////////////////////// // Native functions for CoreMidiDeviceProvider ///////////////////////////////////////////////////////// /* * Gets the number of MIDI sources provided by the Core MIDI system * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getNumberOfSources * Signature: ()I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * * @return The number of MIDI sources provided by the Core MIDI system * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getNumberOfSources(JNIEnv *env, jobject obj) { return (jint) MIDIGetNumberOfSources(); } /* * Gets the number of MIDI destinations provided by the Core MIDI system * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getNumberOfDestinations * Signature: ()I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * * @return The number of MIDI destinations provided by the Core MIDI system * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getNumberOfDestinations(JNIEnv *env, jobject obj) { return (jint) MIDIGetNumberOfDestinations(); } /* * Gets the specified Core MIDI Source * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getSource * Signature: (I)I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * @param sourceIndex The index of the MIDI source to get * * @return The specified Core MIDI Source * * @throws CoreMidiEXception if the source index is not valid * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getSource(JNIEnv *env, jobject obj, jint sourceIndex) { if ( sourceIndex >= MIDIGetNumberOfSources() ) { ThrowException(env,CFSTR("MIDIGetSource"),sourceIndex); } return MIDIGetSource(sourceIndex); } /* * Gets the specified Core MIDI Destination * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getDestination * Signature: (I)I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * @param destinationIndex The index of the MIDI destination to get * * @return The specified Core MIDI Destination * * @throws CoreMidiEXception if the destination index is not valid * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getDestination(JNIEnv *env, jobject obj, jint destinationIndex) { if ( destinationIndex >= MIDIGetNumberOfDestinations() ) { ThrowException(env,CFSTR("MIDIGetDestination"), destinationIndex); } return MIDIGetDestination(destinationIndex); } /* * Gets the unique ID (UID) of the specified end point * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getUniqueID * Signature: (I)I * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * @param endPointReference The end point reference * * @return The unique ID (UID) of the specified end point * */ JNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getUniqueID(JNIEnv *env, jobject obj, jint endPointReference) { SInt32 uid = 0; MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyUniqueID, &uid); return uid; } /* * Creates and gets a MidiDevice.Info object for the specified end point reference * * Class: com_coremidi4j_CoreMidiDeviceProvider * Method: getMidiDeviceInfo * Signature: (I)Ljavax/sound/midi/MidiDevice/Info; * * @param env The JNI environment * @param obj The reference to the java object instance that called this native method * @param endPointReference The end point reference * * @return A MidiDevice.Info object for the specified end point reference * */ JNIEXPORT jobject JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getMidiDeviceInfo(JNIEnv *env, jobject obj, jint endPointReference) { CFStringRef name = NULL; CFStringRef deviceName = NULL; CFStringRef description = NULL; CFStringRef manufacturer = NULL; SInt32 version; SInt32 uid; // Find the Java CoreMIDIDeviceInfo class and its constructor jclass javaClass = env->FindClass("uk/co/xfactorylibrarians/coremidi4j/CoreMidiDeviceInfo"); jmethodID constructor = env->GetMethodID(javaClass, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;III)V"); // Get the device properties MIDIObjectGetStringProperty(endPointReference, kMIDIPropertyName, &name); MIDIObjectGetStringProperty(endPointReference, kMIDIPropertyName, &deviceName); // Get this again in case our string build fails MIDIObjectGetStringProperty(endPointReference, kMIDIPropertyModel, &description); MIDIObjectGetStringProperty(endPointReference, kMIDIPropertyManufacturer, &manufacturer); MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyDriverVersion, &version); MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyUniqueID, &uid); CFMutableStringRef buildName = CFStringCreateMutable(NULL, 0); // Add "CoreMIDI4J - " to the start of our device name if we can if (buildName) { CFStringAppend(buildName, CFSTR("CoreMIDI4J - ")); CFStringAppend(buildName, name); // Overwrite the deviceName with our updated one deviceName = CFStringCreateCopy(NULL, buildName); // And release the temporary string CFRelease(buildName); } const char *rawName = CFStringGetCStringPtr ( name, CFStringGetSystemEncoding() ); const char *deviceInfoName = CFStringGetCStringPtr ( deviceName, CFStringGetSystemEncoding() ); const char *deviceInfoDescription = CFStringGetCStringPtr ( description, CFStringGetSystemEncoding() ); const char *deviceInfoManufacturer = CFStringGetCStringPtr ( manufacturer, CFStringGetSystemEncoding() ); // Create the Java Object jobject info = env->NewObject(javaClass, constructor, env->NewStringUTF(( deviceInfoName != NULL ) ? deviceInfoName : "** Internal Error getting Device Name!"), env->NewStringUTF(( deviceInfoManufacturer != NULL ) ? deviceInfoManufacturer : "Unknown Manufacturer"), env->NewStringUTF(( deviceInfoDescription != NULL ) ? deviceInfoDescription : rawName), version, endPointReference, uid); return info; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <vector> #include <iostream> #include <fstream> #include <algorithm> #include "rosplan_knowledge_msgs/Notification.h" #include "rosplan_knowledge_msgs/Filter.h" #include "rosplan_knowledge_msgs/KnowledgeItem.h" #include "rosplan_knowledge_base/KnowledgeBase.h" namespace KCL_rosplan { /** * returns true is the knowledge item contains the instance, as instance or attribute parameter. */ bool KnowledgeBase::containsInstance(const rosplan_knowledge_msgs::KnowledgeItem &a, std::string &name) { if(0==a.instance_name.compare(name)) return true; for(size_t i=0;i<a.values.size();i++) { if(0==a.values[i].value.compare(name)) return true; } return false; } /** * returns true iff a is the same knowledge as b. */ bool KnowledgeBase::sameKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) { if(a.knowledge_type != b.knowledge_type) return false; if(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { if(0!=a.instance_type.compare(b.instance_type)) return false; if(0!=a.instance_name.compare(b.instance_name)) return false; } else { if(0!=a.attribute_name.compare(b.attribute_name)) return false; if(a.values.size() != b.values.size()) return false; for(size_t i=0;i<a.values.size();i++) { if(0!=a.values[i].key.compare(b.values[i].key)) return false; if(0!=a.values[i].value.compare(b.values[i].value)) return false; } } return true; } /** * returns true iff a matches the knowledge in b. */ bool KnowledgeBase::containsKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) { if(a.knowledge_type != b.knowledge_type) return false; if(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { if(0!=a.instance_type.compare(b.instance_type)) return false; if(a.instance_name!="" && 0!=a.instance_name.compare(b.instance_name)) return false; } else { if(a.attribute_name!="" && 0!=a.attribute_name.compare(b.attribute_name)) return false; for(size_t i=0;i<a.values.size();i++) { bool match = false; for(size_t j=0;j<b.values.size();j++) { if(0==a.values[i].key.compare(b.values[i].key) && 0!=a.values[i].value.compare(b.values[i].value)) match = true; } if(!match) return false; } } return true; } /** * returns true iff b is in the filter of a. */ bool KnowledgeBase::isInFilter(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) { if(a.knowledge_type != b.knowledge_type) return false; if(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { if(0!=a.instance_type.compare(b.instance_type)) return false; if(0==a.instance_name.compare("")) return true; if(0!=a.instance_name.compare(b.instance_name)) return false; } else { if(0!=a.attribute_name.compare(b.attribute_name)) return false; if(a.values.size() != b.values.size()) return false; for(size_t i=0;i<a.values.size();i++) { if(0!=a.values[i].key.compare(b.values[i].key)) return false; if(0!=a.values[i].value.compare(b.values[i].value)) return false; } } return true; } /** * check filter */ void KnowledgeBase::checkFilters(const rosplan_knowledge_msgs::KnowledgeItem &a, bool added) { bool filterViolated = false; if(added) { for(size_t i=0;i<missionFilter.size();i++) { if(isInFilter(missionFilter[i], a)) { filterViolated = true; break; } } } if(!added) { for(size_t i=0;i<planningFilter.size();i++) { if(isInFilter(planningFilter[i], a)) { filterViolated = true; break; } } } if(filterViolated) { ROS_INFO("KCL: (KB) Filter violated, sending notification"); rosplan_knowledge_msgs::Notification msg; if(added) msg.function = rosplan_knowledge_msgs::Notification::ADDED; else msg.function = rosplan_knowledge_msgs::Notification::REMOVED; msg.knowledge_item = a; notificationPublisher.publish(msg); } } /** * Recieve filter from planning_system and store. */ void KnowledgeBase::planningFilterCallback(const rosplan_knowledge_msgs::Filter::ConstPtr& msg) { ROS_INFO("KCL: (KB) Filter updated (CLEAR=0;ADD=1;REMOVE=2) function %i", msg->function); if(msg->function == rosplan_knowledge_msgs::Filter::CLEAR) { planningFilter.clear(); } if(msg->function == rosplan_knowledge_msgs::Filter::ADD) { for(size_t i=0; i<msg->knowledge_items.size(); i++) planningFilter.push_back(msg->knowledge_items[i]); } if(msg->function == rosplan_knowledge_msgs::Filter::REMOVE) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator position = planningFilter.begin(); for(size_t i=0; i<msg->knowledge_items.size(); i++) { for(; position != planningFilter.end(); position++) { rosplan_knowledge_msgs::KnowledgeItem item = msg->knowledge_items[i]; if(sameKnowledge(item, *position)) planningFilter.erase(position); } } } } /** * Recieve mission filter. */ void KnowledgeBase::missionFilterCallback(const rosplan_knowledge_msgs::Filter::ConstPtr& msg) { ROS_INFO("KCL: (KB) Mission Filter updated (CLEAR=0;ADD=1;REMOVE=2) function %i", msg->function); if(msg->function == rosplan_knowledge_msgs::Filter::CLEAR) { missionFilter.clear(); } if(msg->function == rosplan_knowledge_msgs::Filter::ADD) { for(size_t i=0; i<msg->knowledge_items.size(); i++) missionFilter.push_back(msg->knowledge_items[i]); } if(msg->function == rosplan_knowledge_msgs::Filter::REMOVE) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator position = missionFilter.begin(); for(size_t i=0; i<msg->knowledge_items.size(); i++) { for(; position != missionFilter.end(); position++) { rosplan_knowledge_msgs::KnowledgeItem item = msg->knowledge_items[i]; if(sameKnowledge(item, *position)) missionFilter.erase(position); } } } } } // close namespace <commit_msg>Updated filter<commit_after>#include <ros/ros.h> #include <vector> #include <iostream> #include <fstream> #include <algorithm> #include "rosplan_knowledge_msgs/Notification.h" #include "rosplan_knowledge_msgs/Filter.h" #include "rosplan_knowledge_msgs/KnowledgeItem.h" #include "rosplan_knowledge_base/KnowledgeBase.h" namespace KCL_rosplan { /** * returns true is the knowledge item contains the instance, as instance or attribute parameter. */ bool KnowledgeBase::containsInstance(const rosplan_knowledge_msgs::KnowledgeItem &a, std::string &name) { if(0==a.instance_name.compare(name)) return true; for(size_t i=0;i<a.values.size();i++) { if(0==a.values[i].value.compare(name)) return true; } return false; } /** * returns true iff a is the same knowledge as b. */ bool KnowledgeBase::sameKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) { if(a.knowledge_type != b.knowledge_type) return false; if(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { if(0!=a.instance_type.compare(b.instance_type)) return false; if(0!=a.instance_name.compare(b.instance_name)) return false; } else { if(0!=a.attribute_name.compare(b.attribute_name)) return false; if(a.values.size() != b.values.size()) return false; for(size_t i=0;i<a.values.size();i++) { if(0!=a.values[i].key.compare(b.values[i].key)) return false; if(0!=a.values[i].value.compare(b.values[i].value)) return false; } } return true; } /** * returns true iff a matches the knowledge in b. */ bool KnowledgeBase::containsKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) { if(a.knowledge_type != b.knowledge_type) return false; if(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { if(0!=a.instance_type.compare(b.instance_type)) return false; if(a.instance_name!="" && 0!=a.instance_name.compare(b.instance_name)) return false; } else { if(a.attribute_name!="" && 0!=a.attribute_name.compare(b.attribute_name)) return false; for(size_t i=0;i<a.values.size();i++) { bool match = false; for(size_t j=0;j<b.values.size();j++) { if(a.values[i].key == b.values[j].key && a.values[i].value == b.values[j].value) match = true; } if(!match) return false; } } return true; } /** * returns true iff b is in the filter of a. */ bool KnowledgeBase::isInFilter(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) { if(a.knowledge_type != b.knowledge_type) return false; if(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) { if(0!=a.instance_type.compare(b.instance_type)) return false; if(0==a.instance_name.compare("")) return true; if(0!=a.instance_name.compare(b.instance_name)) return false; } else { if(0!=a.attribute_name.compare(b.attribute_name)) return false; if(a.values.size() != b.values.size()) return false; for(size_t i=0;i<a.values.size();i++) { if(0!=a.values[i].key.compare(b.values[i].key)) return false; if(0!=a.values[i].value.compare(b.values[i].value)) return false; } } return true; } /** * check filter */ void KnowledgeBase::checkFilters(const rosplan_knowledge_msgs::KnowledgeItem &a, bool added) { bool filterViolated = false; if(added) { for(size_t i=0;i<missionFilter.size();i++) { if(isInFilter(missionFilter[i], a)) { filterViolated = true; break; } } } if(!added) { for(size_t i=0;i<planningFilter.size();i++) { if(isInFilter(planningFilter[i], a)) { filterViolated = true; break; } } } if(filterViolated) { ROS_INFO("KCL: (KB) Filter violated, sending notification"); rosplan_knowledge_msgs::Notification msg; if(added) msg.function = rosplan_knowledge_msgs::Notification::ADDED; else msg.function = rosplan_knowledge_msgs::Notification::REMOVED; msg.knowledge_item = a; notificationPublisher.publish(msg); } } /** * Recieve filter from planning_system and store. */ void KnowledgeBase::planningFilterCallback(const rosplan_knowledge_msgs::Filter::ConstPtr& msg) { ROS_INFO("KCL: (KB) Filter updated (CLEAR=0;ADD=1;REMOVE=2) function %i", msg->function); if(msg->function == rosplan_knowledge_msgs::Filter::CLEAR) { planningFilter.clear(); } if(msg->function == rosplan_knowledge_msgs::Filter::ADD) { for(size_t i=0; i<msg->knowledge_items.size(); i++) planningFilter.push_back(msg->knowledge_items[i]); } if(msg->function == rosplan_knowledge_msgs::Filter::REMOVE) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator position = planningFilter.begin(); for(size_t i=0; i<msg->knowledge_items.size(); i++) { for(; position != planningFilter.end(); position++) { rosplan_knowledge_msgs::KnowledgeItem item = msg->knowledge_items[i]; if(sameKnowledge(item, *position)) planningFilter.erase(position); } } } } /** * Recieve mission filter. */ void KnowledgeBase::missionFilterCallback(const rosplan_knowledge_msgs::Filter::ConstPtr& msg) { ROS_INFO("KCL: (KB) Mission Filter updated (CLEAR=0;ADD=1;REMOVE=2) function %i", msg->function); if(msg->function == rosplan_knowledge_msgs::Filter::CLEAR) { missionFilter.clear(); } if(msg->function == rosplan_knowledge_msgs::Filter::ADD) { for(size_t i=0; i<msg->knowledge_items.size(); i++) missionFilter.push_back(msg->knowledge_items[i]); } if(msg->function == rosplan_knowledge_msgs::Filter::REMOVE) { std::vector<rosplan_knowledge_msgs::KnowledgeItem>::iterator position = missionFilter.begin(); for(size_t i=0; i<msg->knowledge_items.size(); i++) { for(; position != missionFilter.end(); position++) { rosplan_knowledge_msgs::KnowledgeItem item = msg->knowledge_items[i]; if(sameKnowledge(item, *position)) missionFilter.erase(position); } } } } } // close namespace <|endoftext|>
<commit_before>#include "DrawService.hpp" #include <SFML/Graphics/RenderWindow.hpp> DrawService::Layer::Layer(Layer&& rhs): group(std::move(rhs.group)), view(std::move(rhs.view)) { } DrawService::Layer& DrawService::Layer::operator= (Layer&& rhs) { group = std::move(rhs.group); view = std::move(rhs.view); return *this; } DrawService::DrawService(sf::RenderWindow& window, std::size_t layerCount): m_window(window), m_layers(layerCount) { } void DrawService::clear() { m_window.clear(m_backgroundColor); } void DrawService::draw() { for (Layer& layer : m_layers) { m_window.setView(layer.view); m_window.draw(layer.group); } } void DrawService::display() { m_window.display(); } sf::RenderTarget& DrawService::renderTarget() { return m_window; } void DrawService::resetLayerViews() { for (Layer& layer : m_layers) layer.view = m_window.getDefaultView(); } <commit_msg>DrawService: Call resetLayerViews() in ctor.<commit_after>#include "DrawService.hpp" #include <SFML/Graphics/RenderWindow.hpp> DrawService::Layer::Layer(Layer&& rhs): group(std::move(rhs.group)), view(std::move(rhs.view)) { } DrawService::Layer& DrawService::Layer::operator= (Layer&& rhs) { group = std::move(rhs.group); view = std::move(rhs.view); return *this; } DrawService::DrawService(sf::RenderWindow& window, std::size_t layerCount): m_window(window), m_layers(layerCount) { resetLayerViews(); } void DrawService::clear() { m_window.clear(m_backgroundColor); } void DrawService::draw() { for (Layer& layer : m_layers) { m_window.setView(layer.view); m_window.draw(layer.group); } } void DrawService::display() { m_window.display(); } sf::RenderTarget& DrawService::renderTarget() { return m_window; } void DrawService::resetLayerViews() { for (Layer& layer : m_layers) layer.view = m_window.getDefaultView(); } <|endoftext|>
<commit_before>#ifndef SRC_RANGE_ALGORITHM_HPP_ #define SRC_RANGE_ALGORITHM_HPP_ #include <boost/range.hpp> #include <boost/range/adaptors.hpp> #include <functional> namespace fc { template<class predicate> struct filter_view { template<class in_range> auto operator()(const in_range& input) { return boost::adaptors::filter(input, pred); } predicate pred; }; template<class predicate> auto filter(predicate pred) { return filter_view<predicate>{pred}; } template<class operation> struct map_view { template<class in_range> auto operator()(const in_range& input) { return boost::adaptors::transform(input, op); } operation op; }; template<class operation> auto map(operation op) { return map_view<operation>{op}; } template<class binop, class T> struct reduce_view { template<class in_range> auto operator()(const in_range& input) { return std::accumulate(begin(input), end(input), init_value, op); } binop op; T init_value; }; template<class binop, class T> auto reduce(binop op, T initial_value) { return reduce_view<binop, T>{op, initial_value}; } template<class T> auto sum(T initial_value = T()) { return reduce(std::plus<>(), initial_value); } } // namespace fc #endif /* SRC_RANGE_ALGORITHM_HPP_ */ <commit_msg>changed parameters of operator() in range connectables to universal reference<commit_after>#ifndef SRC_RANGE_ALGORITHM_HPP_ #define SRC_RANGE_ALGORITHM_HPP_ #include <boost/range.hpp> #include <boost/range/adaptors.hpp> #include <functional> namespace fc { template<class predicate> struct filter_view { template<class in_range> auto operator()(const in_range&& input) { return boost::adaptors::filter(input, pred); } predicate pred; }; template<class predicate> auto filter(predicate pred) { return filter_view<predicate>{pred}; } template<class operation> struct map_view { template<class in_range> auto operator()(const in_range&& input) { return boost::adaptors::transform(input, op); } operation op; }; template<class operation> auto map(operation op) { return map_view<operation>{op}; } template<class binop, class T> struct reduce_view { template<class in_range> auto operator()(const in_range&& input) { return std::accumulate(begin(input), end(input), init_value, op); } binop op; T init_value; }; template<class binop, class T> auto reduce(binop op, T initial_value) { return reduce_view<binop, T>{op, initial_value}; } template<class T> auto sum(T initial_value = T()) { return reduce(std::plus<>(), initial_value); } } // namespace fc #endif /* SRC_RANGE_ALGORITHM_HPP_ */ <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2016 Vasil Kalchev 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 "LiquidMenu.h" #include "symbols.h" const uint8_t DIVISION_LINE_LENGTH = 40; ///< Sets the length of the division line. LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, uint8_t startingScreen) : _p_liquidCrystal(&liquidCrystal), _screenCount(0), _currentScreen(startingScreen - 1) { _p_liquidCrystal->createChar(15, symbol::rightFocus); _p_liquidCrystal->createChar(14, symbol::leftFocus); _p_liquidCrystal->createChar(13, symbol::customFocus); } LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, LiquidScreen &liquidScreen, uint8_t startingScreen) : LiquidMenu(liquidCrystal, startingScreen) { add_screen(liquidScreen); } LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, startingScreen) { add_screen(liquidScreen2); } LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, liquidScreen2, startingScreen) { add_screen(liquidScreen3); } LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, LiquidScreen &liquidScreen4, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, liquidScreen2, liquidScreen3, startingScreen) { add_screen(liquidScreen4); } bool LiquidMenu::add_screen(LiquidScreen &liquidScreen) { print_me((uint16_t)this); if (_screenCount < MAX_SCREENS) { _p_liquidScreen[_screenCount] = &liquidScreen; DEBUG(F("Added a new screen (")); DEBUG(_screenCount); DEBUGLN(F(")")); _screenCount++; return true; } DEBUG(F("Adding screen ")); DEBUG(_screenCount); DEBUGLN(F(" failed, edit LiquidMenu_config.h to allow for more screens")); return false; } void LiquidMenu::next_screen() { _p_liquidCrystal->clear(); if (_currentScreen < _screenCount - 1) { _currentScreen++; } else { _currentScreen = 0; } update(); DEBUG(F("Switched to the next screen (")); DEBUG(_currentScreen); DEBUG(F(")")); } void LiquidMenu::operator++() { next_screen(); } void LiquidMenu::operator++(int) { next_screen(); } void LiquidMenu::previous_screen() { _p_liquidCrystal->clear(); if (_currentScreen > 0) { _currentScreen--; } else { _currentScreen = _screenCount - 1; } update(); DEBUG(F("Switched to the previous screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); } void LiquidMenu::operator--() { previous_screen(); } void LiquidMenu::operator--(int) { previous_screen(); } bool LiquidMenu::change_screen(uint8_t number) { _p_liquidCrystal->clear(); if (number <= _screenCount) { _currentScreen = number; update(); DEBUG(F("Switched to screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); return true; } else { DEBUG(F("Invalid request for screen change to ")); DEBUGLN(number); return false; } } bool LiquidMenu::change_screen(LiquidScreen &p_liquidScreen) { _p_liquidCrystal->clear(); // _p_liquidMenu[_currentMenu]->_p_liquidCrystal->clear(); for (uint8_t s = 0; s < _screenCount; s++) { if ((uint16_t)&p_liquidScreen == (uint16_t) & (*_p_liquidScreen[s])) { _currentScreen = s; update(); DEBUG(F("Switched to screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); update(); return true; } } DEBUG(F("Invalid request for screen change to ")); DEBUGLN((uint16_t)&p_liquidScreen); return false; } bool LiquidMenu::operator=(uint8_t number) { return change_screen(number); } bool LiquidMenu::operator=(LiquidScreen &p_liquidScreen) { return change_screen(p_liquidScreen); } void LiquidMenu::switch_focus(bool forward) { _p_liquidCrystal->clear(); _p_liquidScreen[_currentScreen]->switch_focus(forward); update(); } bool LiquidMenu::set_focusPosition(Position position) { print_me((uint16_t)this); if (position == Position::CUSTOM) { DEBUGLN(F("Can't set a custom focus position for the whole menu at once")); return false; } else { DEBUG(F("Focus position set to ")); DEBUGLN((uint8_t)position); for (uint8_t s = 0; s < _screenCount; s++) { _p_liquidScreen[s]->set_focusPosition(position); } return true; } } bool LiquidMenu::set_focusSymbol(Position position, uint8_t symbol[8]) { switch (position) { case Position::RIGHT: { _p_liquidCrystal->createChar(15, symbol); DEBUG(F("Right")); break; } //case RIGHT case Position::LEFT: { _p_liquidCrystal->createChar(14, symbol); DEBUG(F("Left")); break; } //case LEFT case Position::CUSTOM: { _p_liquidCrystal->createChar(13, symbol); DEBUG(F("Custom")); break; } //case CUSTOM default: { DEBUGLN(F("Invalid focus position, options are 'RIGHT', 'LEFT' and 'CUSTOM'")); return false; break; } //default } //switch (position) DEBUGLN(F("Focus symbol changed to:")); for (uint8_t i = 0; i < 8; i++) { DEBUGLN2(symbol[i], BIN); } return true; } bool LiquidMenu::call_function(uint8_t number) const { bool returnValue = _p_liquidScreen[_currentScreen]->call_function(number - 1); update(); return returnValue; } void LiquidMenu::update() const { // _p_liquidCrystal->clear(); DEBUGLN(F("Updating the LCD")); for (uint8_t b = 0; b < DIVISION_LINE_LENGTH; b++) { DEBUG(F("-")); } DEBUGLN(); DEBUG(F("|Screen ")); DEBUGLN(_currentScreen); _p_liquidScreen[_currentScreen]->print(_p_liquidCrystal); for (uint8_t b = 0; b < DIVISION_LINE_LENGTH; b++) { DEBUG(F("-")); } DEBUGLN("\n"); } <commit_msg>Decrementing the number of the function no longer happens in the `LiquidMenu` class.<commit_after>/* The MIT License (MIT) Copyright (c) 2016 Vasil Kalchev 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 "LiquidMenu.h" #include "symbols.h" const uint8_t DIVISION_LINE_LENGTH = 40; ///< Sets the length of the division line. LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, uint8_t startingScreen) : _p_liquidCrystal(&liquidCrystal), _screenCount(0), _currentScreen(startingScreen - 1) { _p_liquidCrystal->createChar(15, symbol::rightFocus); _p_liquidCrystal->createChar(14, symbol::leftFocus); _p_liquidCrystal->createChar(13, symbol::customFocus); } LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, LiquidScreen &liquidScreen, uint8_t startingScreen) : LiquidMenu(liquidCrystal, startingScreen) { add_screen(liquidScreen); } LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, startingScreen) { add_screen(liquidScreen2); } LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, liquidScreen2, startingScreen) { add_screen(liquidScreen3); } LiquidMenu::LiquidMenu(LiquidCrystal &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, LiquidScreen &liquidScreen4, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, liquidScreen2, liquidScreen3, startingScreen) { add_screen(liquidScreen4); } bool LiquidMenu::add_screen(LiquidScreen &liquidScreen) { print_me((uint16_t)this); if (_screenCount < MAX_SCREENS) { _p_liquidScreen[_screenCount] = &liquidScreen; DEBUG(F("Added a new screen (")); DEBUG(_screenCount); DEBUGLN(F(")")); _screenCount++; return true; } DEBUG(F("Adding screen ")); DEBUG(_screenCount); DEBUGLN(F(" failed, edit LiquidMenu_config.h to allow for more screens")); return false; } void LiquidMenu::next_screen() { _p_liquidCrystal->clear(); if (_currentScreen < _screenCount - 1) { _currentScreen++; } else { _currentScreen = 0; } update(); DEBUG(F("Switched to the next screen (")); DEBUG(_currentScreen); DEBUG(F(")")); } void LiquidMenu::operator++() { next_screen(); } void LiquidMenu::operator++(int) { next_screen(); } void LiquidMenu::previous_screen() { _p_liquidCrystal->clear(); if (_currentScreen > 0) { _currentScreen--; } else { _currentScreen = _screenCount - 1; } update(); DEBUG(F("Switched to the previous screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); } void LiquidMenu::operator--() { previous_screen(); } void LiquidMenu::operator--(int) { previous_screen(); } bool LiquidMenu::change_screen(uint8_t number) { _p_liquidCrystal->clear(); if (number <= _screenCount) { _currentScreen = number; update(); DEBUG(F("Switched to screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); return true; } else { DEBUG(F("Invalid request for screen change to ")); DEBUGLN(number); return false; } } bool LiquidMenu::change_screen(LiquidScreen &p_liquidScreen) { _p_liquidCrystal->clear(); // _p_liquidMenu[_currentMenu]->_p_liquidCrystal->clear(); for (uint8_t s = 0; s < _screenCount; s++) { if ((uint16_t)&p_liquidScreen == (uint16_t) & (*_p_liquidScreen[s])) { _currentScreen = s; update(); DEBUG(F("Switched to screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); update(); return true; } } DEBUG(F("Invalid request for screen change to ")); DEBUGLN((uint16_t)&p_liquidScreen); return false; } bool LiquidMenu::operator=(uint8_t number) { return change_screen(number); } bool LiquidMenu::operator=(LiquidScreen &p_liquidScreen) { return change_screen(p_liquidScreen); } void LiquidMenu::switch_focus(bool forward) { _p_liquidCrystal->clear(); _p_liquidScreen[_currentScreen]->switch_focus(forward); update(); } bool LiquidMenu::set_focusPosition(Position position) { print_me((uint16_t)this); if (position == Position::CUSTOM) { DEBUGLN(F("Can't set a custom focus position for the whole menu at once")); return false; } else { DEBUG(F("Focus position set to ")); DEBUGLN((uint8_t)position); for (uint8_t s = 0; s < _screenCount; s++) { _p_liquidScreen[s]->set_focusPosition(position); } return true; } } bool LiquidMenu::set_focusSymbol(Position position, uint8_t symbol[8]) { switch (position) { case Position::RIGHT: { _p_liquidCrystal->createChar(15, symbol); DEBUG(F("Right")); break; } //case RIGHT case Position::LEFT: { _p_liquidCrystal->createChar(14, symbol); DEBUG(F("Left")); break; } //case LEFT case Position::CUSTOM: { _p_liquidCrystal->createChar(13, symbol); DEBUG(F("Custom")); break; } //case CUSTOM default: { DEBUGLN(F("Invalid focus position, options are 'RIGHT', 'LEFT' and 'CUSTOM'")); return false; break; } //default } //switch (position) DEBUGLN(F("Focus symbol changed to:")); for (uint8_t i = 0; i < 8; i++) { DEBUGLN2(symbol[i], BIN); } return true; } bool LiquidMenu::call_function(uint8_t number) const { bool returnValue = _p_liquidScreen[_currentScreen]->call_function(number); update(); return returnValue; } void LiquidMenu::update() const { // _p_liquidCrystal->clear(); DEBUGLN(F("Updating the LCD")); for (uint8_t b = 0; b < DIVISION_LINE_LENGTH; b++) { DEBUG(F("-")); } DEBUGLN(); DEBUG(F("|Screen ")); DEBUGLN(_currentScreen); _p_liquidScreen[_currentScreen]->print(_p_liquidCrystal); for (uint8_t b = 0; b < DIVISION_LINE_LENGTH; b++) { DEBUG(F("-")); } DEBUGLN("\n"); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atlbase.h> #include <atlcom.h> #include "base/string_util.h" #include "chrome_frame/http_negotiate.h" #include "chrome_frame/html_utils.h" #include "gtest/gtest.h" #include "gmock/gmock.h" class HttpNegotiateTest : public testing::Test { protected: HttpNegotiateTest() { } }; class TestHttpNegotiate : public CComObjectRootEx<CComMultiThreadModel>, public IHttpNegotiate { public: TestHttpNegotiate() : beginning_transaction_ret_(S_OK), additional_headers_(NULL) { } BEGIN_COM_MAP(TestHttpNegotiate) COM_INTERFACE_ENTRY(IHttpNegotiate) END_COM_MAP() STDMETHOD(BeginningTransaction)(LPCWSTR url, LPCWSTR headers, // NOLINT DWORD reserved, // NOLINT LPWSTR* additional_headers) { // NOLINT if (additional_headers_) { int len = lstrlenW(additional_headers_); len++; *additional_headers = reinterpret_cast<wchar_t*>( ::CoTaskMemAlloc(len * sizeof(wchar_t))); lstrcpyW(*additional_headers, additional_headers_); } return beginning_transaction_ret_; } STDMETHOD(OnResponse)(DWORD response_code, LPCWSTR response_header, LPCWSTR request_header, LPWSTR* additional_request_headers) { return S_OK; } HRESULT beginning_transaction_ret_; const wchar_t* additional_headers_; }; TEST_F(HttpNegotiateTest, BeginningTransaction) { static const int kBeginningTransactionIndex = 3; CComObjectStackEx<TestHttpNegotiate> test_http; IHttpNegotiate_BeginningTransaction_Fn original = reinterpret_cast<IHttpNegotiate_BeginningTransaction_Fn>( (*reinterpret_cast<void***>( static_cast<IHttpNegotiate*>(&test_http)))[kBeginningTransactionIndex]); std::wstring cf_ua( ASCIIToWide(http_utils::GetDefaultUserAgentHeaderWithCFTag())); std::wstring cf_tag( ASCIIToWide(http_utils::GetChromeFrameUserAgent())); EXPECT_NE(std::wstring::npos, cf_ua.find(cf_tag)); // TODO(tommi): Fix the two test cases that are currently // commented out. struct TestCase { const std::wstring original_headers_; const std::wstring delegate_additional_; const std::wstring expected_additional_; HRESULT delegate_return_value_; } test_cases[] = { //{ L"Accept: */*\r\n\r\n", // L"", // cf_ua + L"\r\n\r\n", // S_OK }, { L"Accept: */*\r\n\r\n", L"", L"", E_OUTOFMEMORY }, //{ L"", // L"Accept: */*\r\n\r\n", // L"Accept: */*\r\n" + cf_ua + L"\r\n\r\n", // S_OK }, { L"User-Agent: Bingo/1.0\r\n\r\n", L"", L"User-Agent: Bingo/1.0 " + cf_tag + L"\r\n\r\n", S_OK }, { L"User-Agent: NotMe/1.0\r\n\r\n", L"User-Agent: MeMeMe/1.0\r\n\r\n", L"User-Agent: MeMeMe/1.0 " + cf_tag + L"\r\n\r\n", S_OK }, { L"", L"User-Agent: MeMeMe/1.0\r\n\r\n", L"User-Agent: MeMeMe/1.0 " + cf_tag + L"\r\n\r\n", S_OK }, }; for (int i = 0; i < arraysize(test_cases); ++i) { TestCase& test = test_cases[i]; wchar_t* additional = NULL; test_http.beginning_transaction_ret_ = test.delegate_return_value_; test_http.additional_headers_ = test.delegate_additional_.c_str(); HttpNegotiatePatch::BeginningTransaction(original, &test_http, L"http://www.google.com", test.original_headers_.c_str(), 0, &additional); EXPECT_TRUE(additional != NULL); if (additional) { // Check against the expected additional headers. EXPECT_EQ(test.expected_additional_, std::wstring(additional)) << " case: " << i; ::CoTaskMemFree(additional); } } } <commit_msg>Revert 44898 - Disable two test cases in the BeginningTransaction test until I fix them.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atlbase.h> #include <atlcom.h> #include "base/string_util.h" #include "chrome_frame/http_negotiate.h" #include "chrome_frame/html_utils.h" #include "gtest/gtest.h" #include "gmock/gmock.h" class HttpNegotiateTest : public testing::Test { protected: HttpNegotiateTest() { } }; class TestHttpNegotiate : public CComObjectRootEx<CComMultiThreadModel>, public IHttpNegotiate { public: TestHttpNegotiate() : beginning_transaction_ret_(S_OK), additional_headers_(NULL) { } BEGIN_COM_MAP(TestHttpNegotiate) COM_INTERFACE_ENTRY(IHttpNegotiate) END_COM_MAP() STDMETHOD(BeginningTransaction)(LPCWSTR url, LPCWSTR headers, // NOLINT DWORD reserved, // NOLINT LPWSTR* additional_headers) { // NOLINT if (additional_headers_) { int len = lstrlenW(additional_headers_); len++; *additional_headers = reinterpret_cast<wchar_t*>( ::CoTaskMemAlloc(len * sizeof(wchar_t))); lstrcpyW(*additional_headers, additional_headers_); } return beginning_transaction_ret_; } STDMETHOD(OnResponse)(DWORD response_code, LPCWSTR response_header, LPCWSTR request_header, LPWSTR* additional_request_headers) { return S_OK; } HRESULT beginning_transaction_ret_; const wchar_t* additional_headers_; }; TEST_F(HttpNegotiateTest, BeginningTransaction) { static const int kBeginningTransactionIndex = 3; CComObjectStackEx<TestHttpNegotiate> test_http; IHttpNegotiate_BeginningTransaction_Fn original = reinterpret_cast<IHttpNegotiate_BeginningTransaction_Fn>( (*reinterpret_cast<void***>( static_cast<IHttpNegotiate*>(&test_http)))[kBeginningTransactionIndex]); std::wstring cf_ua( ASCIIToWide(http_utils::GetDefaultUserAgentHeaderWithCFTag())); std::wstring cf_tag( ASCIIToWide(http_utils::GetChromeFrameUserAgent())); EXPECT_NE(std::wstring::npos, cf_ua.find(cf_tag)); struct TestCase { const std::wstring original_headers_; const std::wstring delegate_additional_; const std::wstring expected_additional_; HRESULT delegate_return_value_; } test_cases[] = { { L"Accept: */*\r\n\r\n", L"", cf_ua + L"\r\n\r\n", S_OK }, { L"Accept: */*\r\n\r\n", L"", L"", E_OUTOFMEMORY }, { L"", L"Accept: */*\r\n\r\n", L"Accept: */*\r\n" + cf_ua + L"\r\n\r\n", S_OK }, { L"User-Agent: Bingo/1.0\r\n\r\n", L"", L"User-Agent: Bingo/1.0 " + cf_tag + L"\r\n\r\n", S_OK }, { L"User-Agent: NotMe/1.0\r\n\r\n", L"User-Agent: MeMeMe/1.0\r\n\r\n", L"User-Agent: MeMeMe/1.0 " + cf_tag + L"\r\n\r\n", S_OK }, { L"", L"User-Agent: MeMeMe/1.0\r\n\r\n", L"User-Agent: MeMeMe/1.0 " + cf_tag + L"\r\n\r\n", S_OK }, }; for (int i = 0; i < arraysize(test_cases); ++i) { TestCase& test = test_cases[i]; wchar_t* additional = NULL; test_http.beginning_transaction_ret_ = test.delegate_return_value_; test_http.additional_headers_ = test.delegate_additional_.c_str(); HttpNegotiatePatch::BeginningTransaction(original, &test_http, L"http://www.google.com", test.original_headers_.c_str(), 0, &additional); EXPECT_TRUE(additional != NULL); if (additional) { // Check against the expected additional headers. EXPECT_EQ(test.expected_additional_, std::wstring(additional)); ::CoTaskMemFree(additional); } } } <|endoftext|>
<commit_before>/** @file Contains the LiquidMenu class definition. */ /* The MIT License (MIT) Copyright (c) 2016 Vasil Kalchev 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 "LiquidMenu.h" #include "glyphs.h" const uint8_t DIVISION_LINE_LENGTH = 40; ///< Sets the length of the division line. LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, uint8_t startingScreen) : _p_liquidCrystal(&liquidCrystal), _screenCount(0), _currentScreen(startingScreen - 1) { #ifndef I2C _p_liquidCrystal->createChar(15, glyph::rightFocus); _p_liquidCrystal->createChar(14, glyph::leftFocus); _p_liquidCrystal->createChar(13, glyph::customFocus); #endif } LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen, uint8_t startingScreen) : LiquidMenu(liquidCrystal, startingScreen) { add_screen(liquidScreen); } LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, startingScreen) { add_screen(liquidScreen2); } LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, liquidScreen2, startingScreen) { add_screen(liquidScreen3); } LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, LiquidScreen &liquidScreen4, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, liquidScreen2, liquidScreen3, startingScreen) { add_screen(liquidScreen4); } bool LiquidMenu::add_screen(LiquidScreen &liquidScreen) { print_me(reinterpret_cast<uintptr_t>(this)); if (_screenCount < MAX_SCREENS) { _p_liquidScreen[_screenCount] = &liquidScreen; DEBUG(F("Added a new screen (")); DEBUG(_screenCount); DEBUGLN(F(")")); _screenCount++; return true; } DEBUG(F("Adding screen ")); DEBUG(_screenCount); DEBUGLN(F(" failed, edit LiquidMenu_config.h to allow for more screens")); return false; } LiquidScreen* LiquidMenu::get_currentScreen() const { return _p_liquidScreen[_currentScreen]; } void LiquidMenu::next_screen() { _p_liquidCrystal->clear(); do { if (_currentScreen < _screenCount - 1) { _currentScreen++; } else { _currentScreen = 0; } } while (_p_liquidScreen[_currentScreen]->_hidden == true); update(); DEBUG(F("Switched to the next screen (")); DEBUG(_currentScreen); DEBUG(F(")")); } void LiquidMenu::operator++() { next_screen(); } void LiquidMenu::operator++(int) { next_screen(); } void LiquidMenu::previous_screen() { _p_liquidCrystal->clear(); do { if (_currentScreen > 0) { _currentScreen--; } else { _currentScreen = _screenCount - 1; } } while (_p_liquidScreen[_currentScreen]->_hidden == true); update(); DEBUG(F("Switched to the previous screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); } void LiquidMenu::operator--() { previous_screen(); } void LiquidMenu::operator--(int) { previous_screen(); } bool LiquidMenu::change_screen(uint8_t number) { uint8_t index = number - 1; if (index <= _screenCount) { _p_liquidCrystal->clear(); _currentScreen = index; update(); DEBUG(F("Switched to screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); return true; } else { DEBUG(F("Invalid request for screen change to ")); DEBUGLN(number); return false; } } bool LiquidMenu::change_screen(LiquidScreen &p_liquidScreen) { // _p_liquidMenu[_currentMenu]->_p_liquidCrystal->clear(); for (uint8_t s = 0; s < _screenCount; s++) { _p_liquidCrystal->clear(); if (reinterpret_cast<uintptr_t>(&p_liquidScreen) == reinterpret_cast<uintptr_t>(&(*_p_liquidScreen[s]))) { _currentScreen = s; update(); DEBUG(F("Switched to screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); update(); return true; } } DEBUG(F("Invalid request for screen change to 0x")); DEBUGLN(reinterpret_cast<uintptr_t>(&p_liquidScreen)); return false; } bool LiquidMenu::operator=(uint8_t number) { return change_screen(number); } bool LiquidMenu::operator=(LiquidScreen &p_liquidScreen) { return change_screen(p_liquidScreen); } void LiquidMenu::switch_focus(bool forward) { _p_liquidCrystal->clear(); _p_liquidScreen[_currentScreen]->switch_focus(forward); update(); } bool LiquidMenu::set_focusPosition(Position position) { print_me(reinterpret_cast<uintptr_t>(this)); if (position == Position::CUSTOM) { DEBUGLN(F("Can't set a custom focus position for the whole menu at once")); return false; } else { DEBUG(F("Focus position set to ")); DEBUGLN((uint8_t)position); for (uint8_t s = 0; s < _screenCount; s++) { _p_liquidScreen[s]->set_focusPosition(position); } return true; } } bool LiquidMenu::set_focusSymbol(Position position, uint8_t symbol[8]) { switch (position) { case Position::RIGHT: { _p_liquidCrystal->createChar(15, symbol); DEBUG(F("Right")); break; } //case RIGHT case Position::LEFT: { _p_liquidCrystal->createChar(14, symbol); DEBUG(F("Left")); break; } //case LEFT case Position::CUSTOM: { _p_liquidCrystal->createChar(13, symbol); DEBUG(F("Custom")); break; } //case CUSTOM default: { DEBUGLN(F("Invalid focus position, options are 'RIGHT', 'LEFT' and 'CUSTOM'")); return false; } //default } //switch (position) DEBUGLN(F("Focus symbol changed to:")); for (uint8_t i = 0; i < 8; i++) { DEBUGLN2(symbol[i], BIN); } return true; } bool LiquidMenu::call_function(uint8_t number) const { bool returnValue = _p_liquidScreen[_currentScreen]->call_function(number); update(); return returnValue; } void LiquidMenu::update() const { _p_liquidCrystal->clear(); softUpdate(); } void LiquidMenu::softUpdate() const { DEBUGLN(F("Updating the LCD")); for (uint8_t b = 0; b < DIVISION_LINE_LENGTH; b++) { DEBUG(F("-")); } DEBUGLN(); DEBUG(F("|Screen ")); DEBUGLN(_currentScreen); _p_liquidScreen[_currentScreen]->print(_p_liquidCrystal); for (uint8_t b = 0; b < DIVISION_LINE_LENGTH; b++) { DEBUG(F("-")); } DEBUGLN("\n"); } void LiquidMenu::init() const { _p_liquidCrystal->createChar(15, glyph::rightFocus); _p_liquidCrystal->createChar(14, glyph::leftFocus); _p_liquidCrystal->createChar(13, glyph::customFocus); } <commit_msg>Update LiquidMenu.cpp<commit_after>/* The MIT License (MIT) Copyright (c) 2016 Vasil Kalchev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** @file Contains the LiquidMenu class definition. */ #include "LiquidMenu.h" #include "glyphs.h" const uint8_t DIVISION_LINE_LENGTH = 40; ///< Sets the length of the division line. LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, uint8_t startingScreen) : _p_liquidCrystal(&liquidCrystal), _screenCount(0), _currentScreen(startingScreen - 1) { #ifndef I2C _p_liquidCrystal->createChar(15, glyph::rightFocus); _p_liquidCrystal->createChar(14, glyph::leftFocus); _p_liquidCrystal->createChar(13, glyph::customFocus); #endif } LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen, uint8_t startingScreen) : LiquidMenu(liquidCrystal, startingScreen) { add_screen(liquidScreen); } LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, startingScreen) { add_screen(liquidScreen2); } LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, liquidScreen2, startingScreen) { add_screen(liquidScreen3); } LiquidMenu::LiquidMenu(DisplayClass &liquidCrystal, LiquidScreen &liquidScreen1, LiquidScreen &liquidScreen2, LiquidScreen &liquidScreen3, LiquidScreen &liquidScreen4, uint8_t startingScreen) : LiquidMenu(liquidCrystal, liquidScreen1, liquidScreen2, liquidScreen3, startingScreen) { add_screen(liquidScreen4); } bool LiquidMenu::add_screen(LiquidScreen &liquidScreen) { print_me(reinterpret_cast<uintptr_t>(this)); if (_screenCount < MAX_SCREENS) { _p_liquidScreen[_screenCount] = &liquidScreen; DEBUG(F("Added a new screen (")); DEBUG(_screenCount); DEBUGLN(F(")")); _screenCount++; return true; } DEBUG(F("Adding screen ")); DEBUG(_screenCount); DEBUGLN(F(" failed, edit LiquidMenu_config.h to allow for more screens")); return false; } LiquidScreen* LiquidMenu::get_currentScreen() const { return _p_liquidScreen[_currentScreen]; } void LiquidMenu::next_screen() { _p_liquidCrystal->clear(); do { if (_currentScreen < _screenCount - 1) { _currentScreen++; } else { _currentScreen = 0; } } while (_p_liquidScreen[_currentScreen]->_hidden == true); update(); DEBUG(F("Switched to the next screen (")); DEBUG(_currentScreen); DEBUG(F(")")); } void LiquidMenu::operator++() { next_screen(); } void LiquidMenu::operator++(int) { next_screen(); } void LiquidMenu::previous_screen() { _p_liquidCrystal->clear(); do { if (_currentScreen > 0) { _currentScreen--; } else { _currentScreen = _screenCount - 1; } } while (_p_liquidScreen[_currentScreen]->_hidden == true); update(); DEBUG(F("Switched to the previous screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); } void LiquidMenu::operator--() { previous_screen(); } void LiquidMenu::operator--(int) { previous_screen(); } bool LiquidMenu::change_screen(uint8_t number) { uint8_t index = number - 1; if (index <= _screenCount) { _p_liquidCrystal->clear(); _currentScreen = index; update(); DEBUG(F("Switched to screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); return true; } else { DEBUG(F("Invalid request for screen change to ")); DEBUGLN(number); return false; } } bool LiquidMenu::change_screen(LiquidScreen &p_liquidScreen) { // _p_liquidMenu[_currentMenu]->_p_liquidCrystal->clear(); for (uint8_t s = 0; s < _screenCount; s++) { _p_liquidCrystal->clear(); if (reinterpret_cast<uintptr_t>(&p_liquidScreen) == reinterpret_cast<uintptr_t>(&(*_p_liquidScreen[s]))) { _currentScreen = s; update(); DEBUG(F("Switched to screen (")); DEBUG(_currentScreen); DEBUGLN(F(")")); update(); return true; } } DEBUG(F("Invalid request for screen change to 0x")); DEBUGLN(reinterpret_cast<uintptr_t>(&p_liquidScreen)); return false; } bool LiquidMenu::operator=(uint8_t number) { return change_screen(number); } bool LiquidMenu::operator=(LiquidScreen &p_liquidScreen) { return change_screen(p_liquidScreen); } void LiquidMenu::switch_focus(bool forward) { _p_liquidCrystal->clear(); _p_liquidScreen[_currentScreen]->switch_focus(forward); update(); } bool LiquidMenu::set_focusPosition(Position position) { print_me(reinterpret_cast<uintptr_t>(this)); if (position == Position::CUSTOM) { DEBUGLN(F("Can't set a custom focus position for the whole menu at once")); return false; } else { DEBUG(F("Focus position set to ")); DEBUGLN((uint8_t)position); for (uint8_t s = 0; s < _screenCount; s++) { _p_liquidScreen[s]->set_focusPosition(position); } return true; } } bool LiquidMenu::set_focusSymbol(Position position, uint8_t symbol[8]) { switch (position) { case Position::RIGHT: { _p_liquidCrystal->createChar(15, symbol); DEBUG(F("Right")); break; } //case RIGHT case Position::LEFT: { _p_liquidCrystal->createChar(14, symbol); DEBUG(F("Left")); break; } //case LEFT case Position::CUSTOM: { _p_liquidCrystal->createChar(13, symbol); DEBUG(F("Custom")); break; } //case CUSTOM default: { DEBUGLN(F("Invalid focus position, options are 'RIGHT', 'LEFT' and 'CUSTOM'")); return false; } //default } //switch (position) DEBUGLN(F("Focus symbol changed to:")); for (uint8_t i = 0; i < 8; i++) { DEBUGLN2(symbol[i], BIN); } return true; } bool LiquidMenu::call_function(uint8_t number) const { bool returnValue = _p_liquidScreen[_currentScreen]->call_function(number); update(); return returnValue; } void LiquidMenu::update() const { _p_liquidCrystal->clear(); softUpdate(); } void LiquidMenu::softUpdate() const { DEBUGLN(F("Updating the LCD")); for (uint8_t b = 0; b < DIVISION_LINE_LENGTH; b++) { DEBUG(F("-")); } DEBUGLN(); DEBUG(F("|Screen ")); DEBUGLN(_currentScreen); _p_liquidScreen[_currentScreen]->print(_p_liquidCrystal); for (uint8_t b = 0; b < DIVISION_LINE_LENGTH; b++) { DEBUG(F("-")); } DEBUGLN("\n"); } void LiquidMenu::init() const { _p_liquidCrystal->createChar(15, glyph::rightFocus); _p_liquidCrystal->createChar(14, glyph::leftFocus); _p_liquidCrystal->createChar(13, glyph::customFocus); } <|endoftext|>
<commit_before>// // LogManager.cpp // PDP-Experiment // // Created by 于京平 on 2017/6/19. // Copyright © 2017年 于京平. All rights reserved. // #include "LogManager.hpp" const std::string LogManager :: logPath = "Debug/PDPLOG.log"; std::ofstream LogManager :: logStream; LogManager LogManager :: singleton; double LogManager :: startTime; LogManager :: LogManager() { logStream.open(logPath, std::ios::app | std::ios::out); } void LogManager :: AppendToLog(std::string str) { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::time_t now_time = std::chrono::system_clock::to_time_t(now); logStream << std::ctime(&now_time) << str << std::endl; } void LogManager :: AppendToLog(const char *str) { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::time_t now_time = std::chrono::system_clock::to_time_t(now); logStream << std::ctime(&now_time) << str << std::endl; } void LogManager :: Alert(std::string str) { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::time_t now_time = std::chrono::system_clock::to_time_t(now); std::cout << str << std::endl; logStream << std::ctime(&now_time) << str << std::endl; } void LogManager :: Alert(const char *str) { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::time_t now_time = std::chrono::system_clock::to_time_t(now); std::cout << str << std::endl; logStream << std::ctime(&now_time) << str << std::endl; } void LogManager :: AlertWithExecutionTime(std::string str, bool restart) { Alert(str); logStream << "Execution Time: " << GetExecutionTime() << "ms." << std::endl; if(restart) StartTiming(); } void LogManager :: AlertWithExecutionTime(const char *str, bool restart) { Alert(str); logStream << "Execution Time: " << GetExecutionTime() << "ms. " << std::endl; if(restart) StartTiming(); } void LogManager :: StartTiming() { startTime = clock(); } double LogManager :: GetExecutionTime() { return (clock() - startTime)/(double)CLOCKS_PER_SEC * 1000; } std::string fromptf(const char *fmt, ...) { __gnuc_va_list args; va_start(args, fmt); char buf[32]; size_t n = std::vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); // Static buffer large enough? if (n < sizeof(buf)) { return {buf, n}; } // Static buffer too small std::string s(n + 1, 0); va_start(args, fmt); std::vsnprintf(const_cast<char*>(s.data()), s.size(), fmt, args); va_end(args); return s; } <commit_msg>PDP Log now locates on the root folder.<commit_after>// // LogManager.cpp // PDP-Experiment // // Created by 于京平 on 2017/6/19. // Copyright © 2017年 于京平. All rights reserved. // #include "LogManager.hpp" const std::string LogManager :: logPath = "PDPLOG.log"; std::ofstream LogManager :: logStream; LogManager LogManager :: singleton; double LogManager :: startTime; LogManager :: LogManager() { logStream.open(logPath, std::ios::app | std::ios::out); } void LogManager :: AppendToLog(std::string str) { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::time_t now_time = std::chrono::system_clock::to_time_t(now); logStream << std::ctime(&now_time) << str << std::endl; } void LogManager :: AppendToLog(const char *str) { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::time_t now_time = std::chrono::system_clock::to_time_t(now); logStream << std::ctime(&now_time) << str << std::endl; } void LogManager :: Alert(std::string str) { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::time_t now_time = std::chrono::system_clock::to_time_t(now); std::cout << str << std::endl; logStream << std::ctime(&now_time) << str << std::endl; } void LogManager :: Alert(const char *str) { std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now(); std::time_t now_time = std::chrono::system_clock::to_time_t(now); std::cout << str << std::endl; logStream << std::ctime(&now_time) << str << std::endl; } void LogManager :: AlertWithExecutionTime(std::string str, bool restart) { Alert(str); logStream << "Execution Time: " << GetExecutionTime() << "ms." << std::endl; if(restart) StartTiming(); } void LogManager :: AlertWithExecutionTime(const char *str, bool restart) { Alert(str); logStream << "Execution Time: " << GetExecutionTime() << "ms. " << std::endl; if(restart) StartTiming(); } void LogManager :: StartTiming() { startTime = clock(); } double LogManager :: GetExecutionTime() { return (clock() - startTime)/(double)CLOCKS_PER_SEC * 1000; } std::string fromptf(const char *fmt, ...) { __gnuc_va_list args; va_start(args, fmt); char buf[32]; size_t n = std::vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); // Static buffer large enough? if (n < sizeof(buf)) { return {buf, n}; } // Static buffer too small std::string s(n + 1, 0); va_start(args, fmt); std::vsnprintf(const_cast<char*>(s.data()), s.size(), fmt, args); va_end(args); return s; } <|endoftext|>
<commit_before>//===-- BrainF.cpp - BrainF compiler example ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===--------------------------------------------------------------------===// // // This class compiles the BrainF language into LLVM assembly. // // The BrainF language has 8 commands: // Command Equivalent C Action // ------- ------------ ------ // , *h=getchar(); Read a character from stdin, 255 on EOF // . putchar(*h); Write a character to stdout // - --*h; Decrement tape // + ++*h; Increment tape // < --h; Move head left // > ++h; Move head right // [ while(*h) { Start loop // ] } End loop // //===--------------------------------------------------------------------===// #include "BrainF.h" #include "llvm/ADT/STLExtras.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include <iostream> using namespace llvm; //Set the constants for naming const char *BrainF::tapereg = "tape"; const char *BrainF::headreg = "head"; const char *BrainF::label = "brainf"; const char *BrainF::testreg = "test"; Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf, LLVMContext& Context) { in = in1; memtotal = mem; comflag = cf; header(Context); readloop(0, 0, 0, Context); delete builder; return module; } void BrainF::header(LLVMContext& C) { module = new Module("BrainF", C); //Function prototypes //declare void @llvm.memset.p0i8.i32(i8 *, i8, i32, i32, i1) Type *Tys[] = { Type::getInt8PtrTy(C), Type::getInt32Ty(C) }; Function *memset_func = Intrinsic::getDeclaration(module, Intrinsic::memset, Tys); //declare i32 @getchar() getchar_func = cast<Function>(module-> getOrInsertFunction("getchar", IntegerType::getInt32Ty(C), NULL)); //declare i32 @putchar(i32) putchar_func = cast<Function>(module-> getOrInsertFunction("putchar", IntegerType::getInt32Ty(C), IntegerType::getInt32Ty(C), NULL)); //Function header //define void @brainf() brainf_func = cast<Function>(module-> getOrInsertFunction("brainf", Type::getVoidTy(C), NULL)); builder = new IRBuilder<>(BasicBlock::Create(C, label, brainf_func)); //%arr = malloc i8, i32 %d ConstantInt *val_mem = ConstantInt::get(C, APInt(32, memtotal)); BasicBlock* BB = builder->GetInsertBlock(); Type* IntPtrTy = IntegerType::getInt32Ty(C); Type* Int8Ty = IntegerType::getInt8Ty(C); Constant* allocsize = ConstantExpr::getSizeOf(Int8Ty); allocsize = ConstantExpr::getTruncOrBitCast(allocsize, IntPtrTy); ptr_arr = CallInst::CreateMalloc(BB, IntPtrTy, Int8Ty, allocsize, val_mem, NULL, "arr"); BB->getInstList().push_back(cast<Instruction>(ptr_arr)); //call void @llvm.memset.p0i8.i32(i8 *%arr, i8 0, i32 %d, i32 1, i1 0) { Value *memset_params[] = { ptr_arr, ConstantInt::get(C, APInt(8, 0)), val_mem, ConstantInt::get(C, APInt(32, 1)), ConstantInt::get(C, APInt(1, 0)) }; CallInst *memset_call = builder-> CreateCall(memset_func, memset_params); memset_call->setTailCall(false); } //%arrmax = getelementptr i8 *%arr, i32 %d if (comflag & flag_arraybounds) { ptr_arrmax = builder-> CreateGEP(ptr_arr, ConstantInt::get(C, APInt(32, memtotal)), "arrmax"); } //%head.%d = getelementptr i8 *%arr, i32 %d curhead = builder->CreateGEP(ptr_arr, ConstantInt::get(C, APInt(32, memtotal/2)), headreg); //Function footer //brainf.end: endbb = BasicBlock::Create(C, label, brainf_func); //call free(i8 *%arr) endbb->getInstList().push_back(CallInst::CreateFree(ptr_arr, endbb)); //ret void ReturnInst::Create(C, endbb); //Error block for array out of bounds if (comflag & flag_arraybounds) { //@aberrormsg = internal constant [%d x i8] c"\00" Constant *msg_0 = ConstantDataArray::getString(C, "Error: The head has left the tape.", true); GlobalVariable *aberrormsg = new GlobalVariable( *module, msg_0->getType(), true, GlobalValue::InternalLinkage, msg_0, "aberrormsg"); //declare i32 @puts(i8 *) Function *puts_func = cast<Function>(module-> getOrInsertFunction("puts", IntegerType::getInt32Ty(C), PointerType::getUnqual(IntegerType::getInt8Ty(C)), NULL)); //brainf.aberror: aberrorbb = BasicBlock::Create(C, label, brainf_func); //call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0)) { Constant *zero_32 = Constant::getNullValue(IntegerType::getInt32Ty(C)); Constant *gep_params[] = { zero_32, zero_32 }; Constant *msgptr = ConstantExpr:: getGetElementPtr(aberrormsg->getValueType(), aberrormsg, gep_params); Value *puts_params[] = { msgptr }; CallInst *puts_call = CallInst::Create(puts_func, puts_params, "", aberrorbb); puts_call->setTailCall(false); } //br label %brainf.end BranchInst::Create(endbb, aberrorbb); } } void BrainF::readloop(PHINode *phi, BasicBlock *oldbb, BasicBlock *testbb, LLVMContext &C) { Symbol cursym = SYM_NONE; int curvalue = 0; Symbol nextsym = SYM_NONE; int nextvalue = 0; char c; int loop; int direction; while(cursym != SYM_EOF && cursym != SYM_ENDLOOP) { // Write out commands switch(cursym) { case SYM_NONE: // Do nothing break; case SYM_READ: { //%tape.%d = call i32 @getchar() CallInst *getchar_call = builder->CreateCall(getchar_func, tapereg); getchar_call->setTailCall(false); Value *tape_0 = getchar_call; //%tape.%d = trunc i32 %tape.%d to i8 Value *tape_1 = builder-> CreateTrunc(tape_0, IntegerType::getInt8Ty(C), tapereg); //store i8 %tape.%d, i8 *%head.%d builder->CreateStore(tape_1, curhead); } break; case SYM_WRITE: { //%tape.%d = load i8 *%head.%d LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg); //%tape.%d = sext i8 %tape.%d to i32 Value *tape_1 = builder-> CreateSExt(tape_0, IntegerType::getInt32Ty(C), tapereg); //call i32 @putchar(i32 %tape.%d) Value *putchar_params[] = { tape_1 }; CallInst *putchar_call = builder-> CreateCall(putchar_func, putchar_params); putchar_call->setTailCall(false); } break; case SYM_MOVE: { //%head.%d = getelementptr i8 *%head.%d, i32 %d curhead = builder-> CreateGEP(curhead, ConstantInt::get(C, APInt(32, curvalue)), headreg); //Error block for array out of bounds if (comflag & flag_arraybounds) { //%test.%d = icmp uge i8 *%head.%d, %arrmax Value *test_0 = builder-> CreateICmpUGE(curhead, ptr_arrmax, testreg); //%test.%d = icmp ult i8 *%head.%d, %arr Value *test_1 = builder-> CreateICmpULT(curhead, ptr_arr, testreg); //%test.%d = or i1 %test.%d, %test.%d Value *test_2 = builder-> CreateOr(test_0, test_1, testreg); //br i1 %test.%d, label %main.%d, label %main.%d BasicBlock *nextbb = BasicBlock::Create(C, label, brainf_func); builder->CreateCondBr(test_2, aberrorbb, nextbb); //main.%d: builder->SetInsertPoint(nextbb); } } break; case SYM_CHANGE: { //%tape.%d = load i8 *%head.%d LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg); //%tape.%d = add i8 %tape.%d, %d Value *tape_1 = builder-> CreateAdd(tape_0, ConstantInt::get(C, APInt(8, curvalue)), tapereg); //store i8 %tape.%d, i8 *%head.%d\n" builder->CreateStore(tape_1, curhead); } break; case SYM_LOOP: { //br label %main.%d BasicBlock *testbb = BasicBlock::Create(C, label, brainf_func); builder->CreateBr(testbb); //main.%d: BasicBlock *bb_0 = builder->GetInsertBlock(); BasicBlock *bb_1 = BasicBlock::Create(C, label, brainf_func); builder->SetInsertPoint(bb_1); // Make part of PHI instruction now, wait until end of loop to finish PHINode *phi_0 = PHINode::Create(PointerType::getUnqual(IntegerType::getInt8Ty(C)), 2, headreg, testbb); phi_0->addIncoming(curhead, bb_0); curhead = phi_0; readloop(phi_0, bb_1, testbb, C); } break; default: std::cerr << "Error: Unknown symbol.\n"; abort(); break; } cursym = nextsym; curvalue = nextvalue; nextsym = SYM_NONE; // Reading stdin loop loop = (cursym == SYM_NONE) || (cursym == SYM_MOVE) || (cursym == SYM_CHANGE); while(loop) { *in>>c; if (in->eof()) { if (cursym == SYM_NONE) { cursym = SYM_EOF; } else { nextsym = SYM_EOF; } loop = 0; } else { direction = 1; switch(c) { case '-': direction = -1; // Fall through case '+': if (cursym == SYM_CHANGE) { curvalue += direction; // loop = 1 } else { if (cursym == SYM_NONE) { cursym = SYM_CHANGE; curvalue = direction; // loop = 1 } else { nextsym = SYM_CHANGE; nextvalue = direction; loop = 0; } } break; case '<': direction = -1; // Fall through case '>': if (cursym == SYM_MOVE) { curvalue += direction; // loop = 1 } else { if (cursym == SYM_NONE) { cursym = SYM_MOVE; curvalue = direction; // loop = 1 } else { nextsym = SYM_MOVE; nextvalue = direction; loop = 0; } } break; case ',': if (cursym == SYM_NONE) { cursym = SYM_READ; } else { nextsym = SYM_READ; } loop = 0; break; case '.': if (cursym == SYM_NONE) { cursym = SYM_WRITE; } else { nextsym = SYM_WRITE; } loop = 0; break; case '[': if (cursym == SYM_NONE) { cursym = SYM_LOOP; } else { nextsym = SYM_LOOP; } loop = 0; break; case ']': if (cursym == SYM_NONE) { cursym = SYM_ENDLOOP; } else { nextsym = SYM_ENDLOOP; } loop = 0; break; // Ignore other characters default: break; } } } } if (cursym == SYM_ENDLOOP) { if (!phi) { std::cerr << "Error: Extra ']'\n"; abort(); } // Write loop test { //br label %main.%d builder->CreateBr(testbb); //main.%d: //%head.%d = phi i8 *[%head.%d, %main.%d], [%head.%d, %main.%d] //Finish phi made at beginning of loop phi->addIncoming(curhead, builder->GetInsertBlock()); Value *head_0 = phi; //%tape.%d = load i8 *%head.%d LoadInst *tape_0 = new LoadInst(head_0, tapereg, testbb); //%test.%d = icmp eq i8 %tape.%d, 0 ICmpInst *test_0 = new ICmpInst(*testbb, ICmpInst::ICMP_EQ, tape_0, ConstantInt::get(C, APInt(8, 0)), testreg); //br i1 %test.%d, label %main.%d, label %main.%d BasicBlock *bb_0 = BasicBlock::Create(C, label, brainf_func); BranchInst::Create(bb_0, oldbb, test_0, testbb); //main.%d: builder->SetInsertPoint(bb_0); //%head.%d = phi i8 *[%head.%d, %main.%d] PHINode *phi_1 = builder-> CreatePHI(PointerType::getUnqual(IntegerType::getInt8Ty(C)), 1, headreg); phi_1->addIncoming(head_0, testbb); curhead = phi_1; } return; } //End of the program, so go to return block builder->CreateBr(endbb); if (phi) { std::cerr << "Error: Missing ']'\n"; abort(); } } <commit_msg>BrainF.cpp: Update CreateCall() according to r237624.<commit_after>//===-- BrainF.cpp - BrainF compiler example ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===--------------------------------------------------------------------===// // // This class compiles the BrainF language into LLVM assembly. // // The BrainF language has 8 commands: // Command Equivalent C Action // ------- ------------ ------ // , *h=getchar(); Read a character from stdin, 255 on EOF // . putchar(*h); Write a character to stdout // - --*h; Decrement tape // + ++*h; Increment tape // < --h; Move head left // > ++h; Move head right // [ while(*h) { Start loop // ] } End loop // //===--------------------------------------------------------------------===// #include "BrainF.h" #include "llvm/ADT/STLExtras.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include <iostream> using namespace llvm; //Set the constants for naming const char *BrainF::tapereg = "tape"; const char *BrainF::headreg = "head"; const char *BrainF::label = "brainf"; const char *BrainF::testreg = "test"; Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf, LLVMContext& Context) { in = in1; memtotal = mem; comflag = cf; header(Context); readloop(0, 0, 0, Context); delete builder; return module; } void BrainF::header(LLVMContext& C) { module = new Module("BrainF", C); //Function prototypes //declare void @llvm.memset.p0i8.i32(i8 *, i8, i32, i32, i1) Type *Tys[] = { Type::getInt8PtrTy(C), Type::getInt32Ty(C) }; Function *memset_func = Intrinsic::getDeclaration(module, Intrinsic::memset, Tys); //declare i32 @getchar() getchar_func = cast<Function>(module-> getOrInsertFunction("getchar", IntegerType::getInt32Ty(C), NULL)); //declare i32 @putchar(i32) putchar_func = cast<Function>(module-> getOrInsertFunction("putchar", IntegerType::getInt32Ty(C), IntegerType::getInt32Ty(C), NULL)); //Function header //define void @brainf() brainf_func = cast<Function>(module-> getOrInsertFunction("brainf", Type::getVoidTy(C), NULL)); builder = new IRBuilder<>(BasicBlock::Create(C, label, brainf_func)); //%arr = malloc i8, i32 %d ConstantInt *val_mem = ConstantInt::get(C, APInt(32, memtotal)); BasicBlock* BB = builder->GetInsertBlock(); Type* IntPtrTy = IntegerType::getInt32Ty(C); Type* Int8Ty = IntegerType::getInt8Ty(C); Constant* allocsize = ConstantExpr::getSizeOf(Int8Ty); allocsize = ConstantExpr::getTruncOrBitCast(allocsize, IntPtrTy); ptr_arr = CallInst::CreateMalloc(BB, IntPtrTy, Int8Ty, allocsize, val_mem, NULL, "arr"); BB->getInstList().push_back(cast<Instruction>(ptr_arr)); //call void @llvm.memset.p0i8.i32(i8 *%arr, i8 0, i32 %d, i32 1, i1 0) { Value *memset_params[] = { ptr_arr, ConstantInt::get(C, APInt(8, 0)), val_mem, ConstantInt::get(C, APInt(32, 1)), ConstantInt::get(C, APInt(1, 0)) }; CallInst *memset_call = builder-> CreateCall(memset_func, memset_params); memset_call->setTailCall(false); } //%arrmax = getelementptr i8 *%arr, i32 %d if (comflag & flag_arraybounds) { ptr_arrmax = builder-> CreateGEP(ptr_arr, ConstantInt::get(C, APInt(32, memtotal)), "arrmax"); } //%head.%d = getelementptr i8 *%arr, i32 %d curhead = builder->CreateGEP(ptr_arr, ConstantInt::get(C, APInt(32, memtotal/2)), headreg); //Function footer //brainf.end: endbb = BasicBlock::Create(C, label, brainf_func); //call free(i8 *%arr) endbb->getInstList().push_back(CallInst::CreateFree(ptr_arr, endbb)); //ret void ReturnInst::Create(C, endbb); //Error block for array out of bounds if (comflag & flag_arraybounds) { //@aberrormsg = internal constant [%d x i8] c"\00" Constant *msg_0 = ConstantDataArray::getString(C, "Error: The head has left the tape.", true); GlobalVariable *aberrormsg = new GlobalVariable( *module, msg_0->getType(), true, GlobalValue::InternalLinkage, msg_0, "aberrormsg"); //declare i32 @puts(i8 *) Function *puts_func = cast<Function>(module-> getOrInsertFunction("puts", IntegerType::getInt32Ty(C), PointerType::getUnqual(IntegerType::getInt8Ty(C)), NULL)); //brainf.aberror: aberrorbb = BasicBlock::Create(C, label, brainf_func); //call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0)) { Constant *zero_32 = Constant::getNullValue(IntegerType::getInt32Ty(C)); Constant *gep_params[] = { zero_32, zero_32 }; Constant *msgptr = ConstantExpr:: getGetElementPtr(aberrormsg->getValueType(), aberrormsg, gep_params); Value *puts_params[] = { msgptr }; CallInst *puts_call = CallInst::Create(puts_func, puts_params, "", aberrorbb); puts_call->setTailCall(false); } //br label %brainf.end BranchInst::Create(endbb, aberrorbb); } } void BrainF::readloop(PHINode *phi, BasicBlock *oldbb, BasicBlock *testbb, LLVMContext &C) { Symbol cursym = SYM_NONE; int curvalue = 0; Symbol nextsym = SYM_NONE; int nextvalue = 0; char c; int loop; int direction; while(cursym != SYM_EOF && cursym != SYM_ENDLOOP) { // Write out commands switch(cursym) { case SYM_NONE: // Do nothing break; case SYM_READ: { //%tape.%d = call i32 @getchar() CallInst *getchar_call = builder->CreateCall(getchar_func, {}, tapereg); getchar_call->setTailCall(false); Value *tape_0 = getchar_call; //%tape.%d = trunc i32 %tape.%d to i8 Value *tape_1 = builder-> CreateTrunc(tape_0, IntegerType::getInt8Ty(C), tapereg); //store i8 %tape.%d, i8 *%head.%d builder->CreateStore(tape_1, curhead); } break; case SYM_WRITE: { //%tape.%d = load i8 *%head.%d LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg); //%tape.%d = sext i8 %tape.%d to i32 Value *tape_1 = builder-> CreateSExt(tape_0, IntegerType::getInt32Ty(C), tapereg); //call i32 @putchar(i32 %tape.%d) Value *putchar_params[] = { tape_1 }; CallInst *putchar_call = builder-> CreateCall(putchar_func, putchar_params); putchar_call->setTailCall(false); } break; case SYM_MOVE: { //%head.%d = getelementptr i8 *%head.%d, i32 %d curhead = builder-> CreateGEP(curhead, ConstantInt::get(C, APInt(32, curvalue)), headreg); //Error block for array out of bounds if (comflag & flag_arraybounds) { //%test.%d = icmp uge i8 *%head.%d, %arrmax Value *test_0 = builder-> CreateICmpUGE(curhead, ptr_arrmax, testreg); //%test.%d = icmp ult i8 *%head.%d, %arr Value *test_1 = builder-> CreateICmpULT(curhead, ptr_arr, testreg); //%test.%d = or i1 %test.%d, %test.%d Value *test_2 = builder-> CreateOr(test_0, test_1, testreg); //br i1 %test.%d, label %main.%d, label %main.%d BasicBlock *nextbb = BasicBlock::Create(C, label, brainf_func); builder->CreateCondBr(test_2, aberrorbb, nextbb); //main.%d: builder->SetInsertPoint(nextbb); } } break; case SYM_CHANGE: { //%tape.%d = load i8 *%head.%d LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg); //%tape.%d = add i8 %tape.%d, %d Value *tape_1 = builder-> CreateAdd(tape_0, ConstantInt::get(C, APInt(8, curvalue)), tapereg); //store i8 %tape.%d, i8 *%head.%d\n" builder->CreateStore(tape_1, curhead); } break; case SYM_LOOP: { //br label %main.%d BasicBlock *testbb = BasicBlock::Create(C, label, brainf_func); builder->CreateBr(testbb); //main.%d: BasicBlock *bb_0 = builder->GetInsertBlock(); BasicBlock *bb_1 = BasicBlock::Create(C, label, brainf_func); builder->SetInsertPoint(bb_1); // Make part of PHI instruction now, wait until end of loop to finish PHINode *phi_0 = PHINode::Create(PointerType::getUnqual(IntegerType::getInt8Ty(C)), 2, headreg, testbb); phi_0->addIncoming(curhead, bb_0); curhead = phi_0; readloop(phi_0, bb_1, testbb, C); } break; default: std::cerr << "Error: Unknown symbol.\n"; abort(); break; } cursym = nextsym; curvalue = nextvalue; nextsym = SYM_NONE; // Reading stdin loop loop = (cursym == SYM_NONE) || (cursym == SYM_MOVE) || (cursym == SYM_CHANGE); while(loop) { *in>>c; if (in->eof()) { if (cursym == SYM_NONE) { cursym = SYM_EOF; } else { nextsym = SYM_EOF; } loop = 0; } else { direction = 1; switch(c) { case '-': direction = -1; // Fall through case '+': if (cursym == SYM_CHANGE) { curvalue += direction; // loop = 1 } else { if (cursym == SYM_NONE) { cursym = SYM_CHANGE; curvalue = direction; // loop = 1 } else { nextsym = SYM_CHANGE; nextvalue = direction; loop = 0; } } break; case '<': direction = -1; // Fall through case '>': if (cursym == SYM_MOVE) { curvalue += direction; // loop = 1 } else { if (cursym == SYM_NONE) { cursym = SYM_MOVE; curvalue = direction; // loop = 1 } else { nextsym = SYM_MOVE; nextvalue = direction; loop = 0; } } break; case ',': if (cursym == SYM_NONE) { cursym = SYM_READ; } else { nextsym = SYM_READ; } loop = 0; break; case '.': if (cursym == SYM_NONE) { cursym = SYM_WRITE; } else { nextsym = SYM_WRITE; } loop = 0; break; case '[': if (cursym == SYM_NONE) { cursym = SYM_LOOP; } else { nextsym = SYM_LOOP; } loop = 0; break; case ']': if (cursym == SYM_NONE) { cursym = SYM_ENDLOOP; } else { nextsym = SYM_ENDLOOP; } loop = 0; break; // Ignore other characters default: break; } } } } if (cursym == SYM_ENDLOOP) { if (!phi) { std::cerr << "Error: Extra ']'\n"; abort(); } // Write loop test { //br label %main.%d builder->CreateBr(testbb); //main.%d: //%head.%d = phi i8 *[%head.%d, %main.%d], [%head.%d, %main.%d] //Finish phi made at beginning of loop phi->addIncoming(curhead, builder->GetInsertBlock()); Value *head_0 = phi; //%tape.%d = load i8 *%head.%d LoadInst *tape_0 = new LoadInst(head_0, tapereg, testbb); //%test.%d = icmp eq i8 %tape.%d, 0 ICmpInst *test_0 = new ICmpInst(*testbb, ICmpInst::ICMP_EQ, tape_0, ConstantInt::get(C, APInt(8, 0)), testreg); //br i1 %test.%d, label %main.%d, label %main.%d BasicBlock *bb_0 = BasicBlock::Create(C, label, brainf_func); BranchInst::Create(bb_0, oldbb, test_0, testbb); //main.%d: builder->SetInsertPoint(bb_0); //%head.%d = phi i8 *[%head.%d, %main.%d] PHINode *phi_1 = builder-> CreatePHI(PointerType::getUnqual(IntegerType::getInt8Ty(C)), 1, headreg); phi_1->addIncoming(head_0, testbb); curhead = phi_1; } return; } //End of the program, so go to return block builder->CreateBr(endbb); if (phi) { std::cerr << "Error: Missing ']'\n"; abort(); } } <|endoftext|>
<commit_before>/** * Copyright (c) 2017 by Botorabi. All rights reserved. * https://github.com/botorabi/Meet4Eat * * License: MIT License (MIT), read the LICENSE text in * main directory for more details. */ #include "systemtray.h" #include "mainwindow.h" #include <core/log.h> #include <settings/appsettings.h> #include <common/guiutils.h> #include <QApplication> #include <QSystemTrayIcon> #include <QMenu> namespace m4e { namespace gui { static const QString M4E_SYSTRAY_ICON_NORMAL = ":/icon-tray.png"; static const QString M4E_SYSTRAY_ICON_NOTIFY = ":/icon-tray-notify.png"; enum MenuIDs { MenuOpen = 100, MenuQuit = 101, MenuEnableNotification = 102, MenuEnableAlarm = 103, MenuEnableAutoStart = 104 }; SystemTray::SystemTray( webapp::WebApp* p_webApp, MainWindow* p_parent ) : QObject( p_parent ), _p_webApp( p_webApp ), _p_mainWindow( p_parent ) { setupSystemTray(); connect( _p_webApp, SIGNAL( onUserSignedIn( bool, QString ) ), this, SLOT( onUserSignedIn( bool, QString ) ) ); connect( _p_webApp, SIGNAL( onUserSignedOff( bool ) ), this, SLOT( onUserSignedOff( bool ) ) ); connect( _p_webApp, SIGNAL( onServerConnectionClosed() ), this, SLOT( onServerConnectionClosed() ) ); connect( _p_webApp->getNotifications(), SIGNAL( onEventMessage( QString, QString, QString, m4e::notify::NotifyEventPtr ) ), this, SLOT( onEventMessage( QString, QString, QString, m4e::notify::NotifyEventPtr ) ) ); connect( _p_webApp->getNotifications(), SIGNAL( onEventLocationVote( QString, QString, QString, QString, bool ) ), this, SLOT( onEventLocationVote( QString, QString, QString, QString, bool ) ) ); connect( _p_webApp->getMailBox(), SIGNAL( onResponseCountUnreadMails( bool, int ) ), this, SLOT( onResponseCountUnreadMails( bool, int ) ) ); connect( _p_webApp->getEvents(), SIGNAL( onLocationVotingStart( m4e::event::ModelEventPtr ) ), this, SLOT( onLocationVotingStart( m4e::event::ModelEventPtr ) ) ); connect( _p_webApp->getEvents(), SIGNAL( onLocationVotingEnd( m4e::event::ModelEventPtr ) ), this, SLOT( onLocationVotingEnd( m4e::event::ModelEventPtr ) ) ); connect( _p_webApp->getChatSystem(), SIGNAL( onReceivedChatMessageEvent( m4e::chat::ChatMessagePtr ) ), this, SLOT( onReceivedChatMessageEvent( m4e::chat::ChatMessagePtr ) ) ); connect( _p_webApp->getChatSystem(), SIGNAL( onReceivedChatMessageUser( m4e::chat::ChatMessagePtr ) ), this, SLOT( onReceivedChatMessageUser( m4e::chat::ChatMessagePtr ) ) ); } SystemTray::~SystemTray() { } void SystemTray::onActivated( QSystemTrayIcon::ActivationReason reason ) { switch ( reason ) { case QSystemTrayIcon::Trigger: case QSystemTrayIcon::DoubleClick: common::GuiUtils::bringWidgetToFront( _p_mainWindow ); break; default: break; } } void SystemTray::onMenuTriggert( QAction* p_action ) { int id = p_action->data().toInt(); switch( id ) { case MenuOpen: common::GuiUtils::bringWidgetToFront( _p_mainWindow ); break; case MenuQuit: _p_mainWindow->terminate(); break; case MenuEnableNotification: _enableNotification = p_action->isChecked(); settings::AppSettings::get()->writeSettingsValue( M4E_SETTINGS_CAT_NOTIFY, M4E_SETTINGS_KEY_NOTIFY_EVENT, _enableNotification ? "yes" : "no" ); break; case MenuEnableAlarm: _enableAlarm = p_action->isChecked(); settings::AppSettings::get()->writeSettingsValue( M4E_SETTINGS_CAT_NOTIFY, M4E_SETTINGS_KEY_NOTIFY_ALARM, _enableAlarm ? "yes" : "no" ); break; case MenuEnableAutoStart: settings::AppSettings::get()->writeSettingsValue( M4E_SETTINGS_CAT_APP, M4E_SETTINGS_KEY_APP_AUTOSTART, p_action->isChecked() ? "yes" : "no" ); break; default: log_warning << TAG << "unsupported tray menu option: " << id << std::endl; } showIconNotify( false ); } void SystemTray::onMenuAboutToShow() { showIconNotify( false ); } void SystemTray::onMessageClicked() { common::GuiUtils::bringWidgetToFront( _p_mainWindow ); } void SystemTray::setupSystemTray() { QString enablealarm = settings::AppSettings::get()->readSettingsValue( M4E_SETTINGS_CAT_NOTIFY, M4E_SETTINGS_KEY_NOTIFY_ALARM, "yes" ); QString enableevent = settings::AppSettings::get()->readSettingsValue( M4E_SETTINGS_CAT_NOTIFY, M4E_SETTINGS_KEY_NOTIFY_EVENT, "yes" ); QString autostart = settings::AppSettings::get()->readSettingsValue( M4E_SETTINGS_CAT_APP, M4E_SETTINGS_KEY_APP_AUTOSTART, "yes" ); _enableNotification = ( enableevent == "yes" ); _enableAlarm = ( enablealarm == "yes" ); bool enableautostart = ( autostart == "yes" ); _p_systemTray = new QSystemTrayIcon( QIcon( M4E_SYSTRAY_ICON_NORMAL ), this ); _p_systemTray->setToolTip( QApplication::translate( "SystemTray", M4E_APP_NAME ) ); connect( _p_systemTray, SIGNAL( activated( QSystemTrayIcon::ActivationReason ) ), this, SLOT( onActivated( QSystemTrayIcon::ActivationReason ) ) ); connect( _p_systemTray, SIGNAL( messageClicked() ), this, SLOT( onMessageClicked() ) ); QMenu* p_menu = new QMenu(); connect( p_menu, SIGNAL( triggered( QAction* ) ), this, SLOT( onMenuTriggert( QAction* ) ) ); connect( p_menu, SIGNAL( aboutToShow() ), this, SLOT( onMenuAboutToShow() ) ); QAction* p_action; p_action = new QAction(); p_action->setSeparator( true ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Open Meet4Eat" ) ); p_action->setData( QVariant( MenuOpen ) ); p_menu->addAction( p_action ); p_action = new QAction(); p_action->setSeparator( true ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Enable Notification" ) ); p_action->setCheckable( true ); p_action->setChecked( _enableNotification ); p_action->setData( QVariant( MenuEnableNotification ) ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Enable Alarm" ) ); p_action->setCheckable( true ); p_action->setChecked( _enableAlarm ); p_action->setData( QVariant( MenuEnableAlarm ) ); p_menu->addAction( p_action ); //! NOTE currently there is no support for auto-start on MacOS #ifndef Q_OS_MACOS p_action = new QAction(); p_action->setSeparator( true ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Start on Logon" ) ); p_action->setData( QVariant( MenuEnableAutoStart ) ); p_action->setCheckable( true ); p_action->setChecked( enableautostart ); p_menu->addAction( p_action ); #endif p_action = new QAction(); p_action->setSeparator( true ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Quit" ) ); p_action->setData( QVariant( MenuQuit ) ); p_menu->addAction( p_action ); _p_systemTray->setContextMenu( p_menu ); _p_systemTray->show(); } void SystemTray::showMessage( const QString& title, const QString& message, bool warning, int duration ) { // are notifications enabled? if ( !_enableNotification ) return; _p_systemTray->showMessage( title, message, warning ? QSystemTrayIcon::Warning : QSystemTrayIcon::Information, duration ); showIconNotify( true ); } void SystemTray::showIconNotify( bool show, const QString& toolTip ) { // ignore the request if the main window is not minimized if ( !( _p_mainWindow->isMinimized() || _p_mainWindow->isHidden() ) ) return; _p_systemTray->setIcon( QIcon( show ? M4E_SYSTRAY_ICON_NOTIFY : M4E_SYSTRAY_ICON_NORMAL ) ); _p_systemTray->setToolTip( toolTip ); } bool SystemTray::isTrayAvailable() { return QSystemTrayIcon::isSystemTrayAvailable(); } void SystemTray::onUserSignedIn( bool success, QString /*userId*/ ) { QString title = QApplication::translate( "SystemTray", "Meet4Eat - User Sign In" ); QString text; bool warning = false; if ( !success ) { warning = true; text = QApplication::translate( "SystemTray", "User could not sign in!" ); } else { text = QApplication::translate( "SystemTray", "User was successfully signed in." ); } showMessage( title, text, warning ); showIconNotify( false ); } void SystemTray::onUserSignedOff( bool /*success*/ ) { } void SystemTray::onServerConnectionClosed() { } void SystemTray::onEventMessage( QString senderId, QString /*senderName*/, QString eventId, notify::NotifyEventPtr notify ) { QString eventname; QString userid; event::ModelEventPtr event = _p_webApp->getEvents()->getUserEvent( eventId ); user::ModelUserPtr user = _p_webApp->getUser()->getUserData(); if ( event.valid() ) eventname = event->getName(); if ( user.valid() ) userid = user->getId(); // suppress echo if ( userid == senderId ) return; QString title = QApplication::translate( "SystemTray", "Meet4Eat - Event Notification" ); QString text = notify->getSubject(); showMessage( title, text, false ); } void SystemTray::onResponseCountUnreadMails( bool success, int count ) { if ( success && ( count > 0 ) ) { QString title = QApplication::translate( "SystemTray", "Meet4Eat - New Mails" ); QString text = QApplication::translate( "SystemTray", "You have received new mails." ); showMessage( title, text, false ); showIconNotify( true, text ); } } void SystemTray::onEventLocationVote( QString senderId, QString senderName, QString eventId, QString locationId, bool /*vote*/ ) { // check if notifications are enabled if ( !_enableNotification ) return; // suppress echo QString userid = _p_webApp->getUser()->getUserData()->getId(); if ( senderId == userid ) return; QString locationname; event::ModelEventPtr event = _p_webApp->getEvents()->getUserEvent( eventId ); if ( event.valid() ) { event::ModelLocationPtr loc = event->getLocation( locationId ); if ( loc.valid() ) locationname = loc->getName(); } QString title = QApplication::translate( "SystemTray", "Meet4Eat - New Vote from " ) + senderName; QString text = QApplication::translate( "SystemTray", "Location: " ) + " " + locationname; showMessage( title, text, false ); } void SystemTray::onLocationVotingStart( event::ModelEventPtr event ) { QString title = QApplication::translate( "SystemTray", "Meet4Eat - Voting Time" ); QString text = QApplication::translate( "SystemTray", "Event" ) + " " + event->getName(); showMessage( title, text, false ); } void SystemTray::onLocationVotingEnd( m4e::event::ModelEventPtr event ) { QString title = QApplication::translate( "SystemTray", "Meet4Eat - End of Voting Time" ); QString text = QApplication::translate( "SystemTray", "Event" ) + " " + event->getName(); showMessage( title, text, false ); } void SystemTray::onReceivedChatMessageUser( chat::ChatMessagePtr /*msg*/ ) { showIconNotify( true, QApplication::translate( "SystemTray", "New message arrived" ) ); } void SystemTray::onReceivedChatMessageEvent( chat::ChatMessagePtr /*msg*/ ) { showIconNotify( true, QApplication::translate( "SystemTray", "New message arrived" ) ); } } // namespace gui } // namespace m4e <commit_msg>Fixed an issue for MS Windows and system try<commit_after>/** * Copyright (c) 2017 by Botorabi. All rights reserved. * https://github.com/botorabi/Meet4Eat * * License: MIT License (MIT), read the LICENSE text in * main directory for more details. */ #include "systemtray.h" #include "mainwindow.h" #include <core/log.h> #include <settings/appsettings.h> #include <common/guiutils.h> #include <QApplication> #include <QSystemTrayIcon> #include <QMenu> namespace m4e { namespace gui { static const QString M4E_SYSTRAY_ICON_NORMAL = ":/icon-tray.png"; static const QString M4E_SYSTRAY_ICON_NOTIFY = ":/icon-tray-notify.png"; enum MenuIDs { MenuOpen = 100, MenuQuit = 101, MenuEnableNotification = 102, MenuEnableAlarm = 103, MenuEnableAutoStart = 104 }; SystemTray::SystemTray( webapp::WebApp* p_webApp, MainWindow* p_parent ) : QObject( p_parent ), _p_webApp( p_webApp ), _p_mainWindow( p_parent ) { setupSystemTray(); connect( _p_webApp, SIGNAL( onUserSignedIn( bool, QString ) ), this, SLOT( onUserSignedIn( bool, QString ) ) ); connect( _p_webApp, SIGNAL( onUserSignedOff( bool ) ), this, SLOT( onUserSignedOff( bool ) ) ); connect( _p_webApp, SIGNAL( onServerConnectionClosed() ), this, SLOT( onServerConnectionClosed() ) ); connect( _p_webApp->getNotifications(), SIGNAL( onEventMessage( QString, QString, QString, m4e::notify::NotifyEventPtr ) ), this, SLOT( onEventMessage( QString, QString, QString, m4e::notify::NotifyEventPtr ) ) ); connect( _p_webApp->getNotifications(), SIGNAL( onEventLocationVote( QString, QString, QString, QString, bool ) ), this, SLOT( onEventLocationVote( QString, QString, QString, QString, bool ) ) ); connect( _p_webApp->getMailBox(), SIGNAL( onResponseCountUnreadMails( bool, int ) ), this, SLOT( onResponseCountUnreadMails( bool, int ) ) ); connect( _p_webApp->getEvents(), SIGNAL( onLocationVotingStart( m4e::event::ModelEventPtr ) ), this, SLOT( onLocationVotingStart( m4e::event::ModelEventPtr ) ) ); connect( _p_webApp->getEvents(), SIGNAL( onLocationVotingEnd( m4e::event::ModelEventPtr ) ), this, SLOT( onLocationVotingEnd( m4e::event::ModelEventPtr ) ) ); connect( _p_webApp->getChatSystem(), SIGNAL( onReceivedChatMessageEvent( m4e::chat::ChatMessagePtr ) ), this, SLOT( onReceivedChatMessageEvent( m4e::chat::ChatMessagePtr ) ) ); connect( _p_webApp->getChatSystem(), SIGNAL( onReceivedChatMessageUser( m4e::chat::ChatMessagePtr ) ), this, SLOT( onReceivedChatMessageUser( m4e::chat::ChatMessagePtr ) ) ); } SystemTray::~SystemTray() { } void SystemTray::onActivated( QSystemTrayIcon::ActivationReason reason ) { switch ( reason ) { case QSystemTrayIcon::Trigger: case QSystemTrayIcon::DoubleClick: showIconNotify( false ); common::GuiUtils::bringWidgetToFront( _p_mainWindow ); break; default: break; } } void SystemTray::onMenuTriggert( QAction* p_action ) { int id = p_action->data().toInt(); switch( id ) { case MenuOpen: common::GuiUtils::bringWidgetToFront( _p_mainWindow ); break; case MenuQuit: _p_mainWindow->terminate(); break; case MenuEnableNotification: _enableNotification = p_action->isChecked(); settings::AppSettings::get()->writeSettingsValue( M4E_SETTINGS_CAT_NOTIFY, M4E_SETTINGS_KEY_NOTIFY_EVENT, _enableNotification ? "yes" : "no" ); break; case MenuEnableAlarm: _enableAlarm = p_action->isChecked(); settings::AppSettings::get()->writeSettingsValue( M4E_SETTINGS_CAT_NOTIFY, M4E_SETTINGS_KEY_NOTIFY_ALARM, _enableAlarm ? "yes" : "no" ); break; case MenuEnableAutoStart: settings::AppSettings::get()->writeSettingsValue( M4E_SETTINGS_CAT_APP, M4E_SETTINGS_KEY_APP_AUTOSTART, p_action->isChecked() ? "yes" : "no" ); break; default: log_warning << TAG << "unsupported tray menu option: " << id << std::endl; } showIconNotify( false ); } void SystemTray::onMenuAboutToShow() { showIconNotify( false ); } void SystemTray::onMessageClicked() { common::GuiUtils::bringWidgetToFront( _p_mainWindow ); } void SystemTray::setupSystemTray() { QString enablealarm = settings::AppSettings::get()->readSettingsValue( M4E_SETTINGS_CAT_NOTIFY, M4E_SETTINGS_KEY_NOTIFY_ALARM, "yes" ); QString enableevent = settings::AppSettings::get()->readSettingsValue( M4E_SETTINGS_CAT_NOTIFY, M4E_SETTINGS_KEY_NOTIFY_EVENT, "yes" ); QString autostart = settings::AppSettings::get()->readSettingsValue( M4E_SETTINGS_CAT_APP, M4E_SETTINGS_KEY_APP_AUTOSTART, "yes" ); _enableNotification = ( enableevent == "yes" ); _enableAlarm = ( enablealarm == "yes" ); bool enableautostart = ( autostart == "yes" ); _p_systemTray = new QSystemTrayIcon( QIcon( M4E_SYSTRAY_ICON_NORMAL ), this ); _p_systemTray->setToolTip( QApplication::translate( "SystemTray", M4E_APP_NAME ) ); connect( _p_systemTray, SIGNAL( activated( QSystemTrayIcon::ActivationReason ) ), this, SLOT( onActivated( QSystemTrayIcon::ActivationReason ) ) ); connect( _p_systemTray, SIGNAL( messageClicked() ), this, SLOT( onMessageClicked() ) ); QMenu* p_menu = new QMenu(); connect( p_menu, SIGNAL( triggered( QAction* ) ), this, SLOT( onMenuTriggert( QAction* ) ) ); connect( p_menu, SIGNAL( aboutToShow() ), this, SLOT( onMenuAboutToShow() ) ); QAction* p_action; p_action = new QAction(); p_action->setSeparator( true ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Open Meet4Eat" ) ); p_action->setData( QVariant( MenuOpen ) ); p_menu->addAction( p_action ); p_action = new QAction(); p_action->setSeparator( true ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Enable Notification" ) ); p_action->setCheckable( true ); p_action->setChecked( _enableNotification ); p_action->setData( QVariant( MenuEnableNotification ) ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Enable Alarm" ) ); p_action->setCheckable( true ); p_action->setChecked( _enableAlarm ); p_action->setData( QVariant( MenuEnableAlarm ) ); p_menu->addAction( p_action ); //! NOTE currently there is no support for auto-start on MacOS #ifndef Q_OS_MACOS p_action = new QAction(); p_action->setSeparator( true ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Start on Logon" ) ); p_action->setData( QVariant( MenuEnableAutoStart ) ); p_action->setCheckable( true ); p_action->setChecked( enableautostart ); p_menu->addAction( p_action ); #endif p_action = new QAction(); p_action->setSeparator( true ); p_menu->addAction( p_action ); p_action = new QAction( QApplication::translate( "SystemTray", "Quit" ) ); p_action->setData( QVariant( MenuQuit ) ); p_menu->addAction( p_action ); _p_systemTray->setContextMenu( p_menu ); _p_systemTray->show(); } void SystemTray::showMessage( const QString& title, const QString& message, bool warning, int duration ) { // are notifications enabled? if ( !_enableNotification ) return; _p_systemTray->showMessage( title, message, warning ? QSystemTrayIcon::Warning : QSystemTrayIcon::Information, duration ); showIconNotify( true ); } void SystemTray::showIconNotify( bool show, const QString& toolTip ) { // ignore the request if the main window is not minimized if ( !( _p_mainWindow->isMinimized() || _p_mainWindow->isHidden() ) ) return; _p_systemTray->setIcon( QIcon( show ? M4E_SYSTRAY_ICON_NOTIFY : M4E_SYSTRAY_ICON_NORMAL ) ); _p_systemTray->setToolTip( toolTip ); } bool SystemTray::isTrayAvailable() { return QSystemTrayIcon::isSystemTrayAvailable(); } void SystemTray::onUserSignedIn( bool success, QString /*userId*/ ) { QString title = QApplication::translate( "SystemTray", "Meet4Eat - User Sign In" ); QString text; bool warning = false; if ( !success ) { warning = true; text = QApplication::translate( "SystemTray", "User could not sign in!" ); } else { text = QApplication::translate( "SystemTray", "User was successfully signed in." ); } showMessage( title, text, warning ); showIconNotify( false ); } void SystemTray::onUserSignedOff( bool /*success*/ ) { } void SystemTray::onServerConnectionClosed() { } void SystemTray::onEventMessage( QString senderId, QString /*senderName*/, QString eventId, notify::NotifyEventPtr notify ) { QString eventname; QString userid; event::ModelEventPtr event = _p_webApp->getEvents()->getUserEvent( eventId ); user::ModelUserPtr user = _p_webApp->getUser()->getUserData(); if ( event.valid() ) eventname = event->getName(); if ( user.valid() ) userid = user->getId(); // suppress echo if ( userid == senderId ) return; QString title = QApplication::translate( "SystemTray", "Meet4Eat - Event Notification" ); QString text = notify->getSubject(); showMessage( title, text, false ); } void SystemTray::onResponseCountUnreadMails( bool success, int count ) { if ( success && ( count > 0 ) ) { QString title = QApplication::translate( "SystemTray", "Meet4Eat - New Mails" ); QString text = QApplication::translate( "SystemTray", "You have received new mails." ); showMessage( title, text, false ); showIconNotify( true, text ); } } void SystemTray::onEventLocationVote( QString senderId, QString senderName, QString eventId, QString locationId, bool /*vote*/ ) { // check if notifications are enabled if ( !_enableNotification ) return; // suppress echo QString userid = _p_webApp->getUser()->getUserData()->getId(); if ( senderId == userid ) return; QString locationname; event::ModelEventPtr event = _p_webApp->getEvents()->getUserEvent( eventId ); if ( event.valid() ) { event::ModelLocationPtr loc = event->getLocation( locationId ); if ( loc.valid() ) locationname = loc->getName(); } QString title = QApplication::translate( "SystemTray", "Meet4Eat - New Vote from " ) + senderName; QString text = QApplication::translate( "SystemTray", "Location: " ) + " " + locationname; showMessage( title, text, false ); } void SystemTray::onLocationVotingStart( event::ModelEventPtr event ) { QString title = QApplication::translate( "SystemTray", "Meet4Eat - Voting Time" ); QString text = QApplication::translate( "SystemTray", "Event" ) + " " + event->getName(); showMessage( title, text, false ); } void SystemTray::onLocationVotingEnd( m4e::event::ModelEventPtr event ) { QString title = QApplication::translate( "SystemTray", "Meet4Eat - End of Voting Time" ); QString text = QApplication::translate( "SystemTray", "Event" ) + " " + event->getName(); showMessage( title, text, false ); } void SystemTray::onReceivedChatMessageUser( chat::ChatMessagePtr /*msg*/ ) { showIconNotify( true, QApplication::translate( "SystemTray", "New message arrived" ) ); } void SystemTray::onReceivedChatMessageEvent( chat::ChatMessagePtr /*msg*/ ) { showIconNotify( true, QApplication::translate( "SystemTray", "New message arrived" ) ); } } // namespace gui } // namespace m4e <|endoftext|>
<commit_before>/*********************************************************************** created: 12/2/2012 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) # include <unistd.h> #endif #include "CEGUISamplesConfig.h" #include "CEGuiGLFWSharedBase.h" #include "SamplesFrameworkBase.h" #include "CEGUI/CEGUI.h" #include <stdexcept> #include <sstream> //----------------------------------------------------------------------------// CEGuiGLFWSharedBase* CEGuiGLFWSharedBase::d_appInstance = 0; double CEGuiGLFWSharedBase::d_frameTime = 0; int CEGuiGLFWSharedBase::d_modifiers = 0; bool CEGuiGLFWSharedBase::d_windowSized = false; int CEGuiGLFWSharedBase::d_newWindowWidth = CEGuiGLFWSharedBase::s_defaultWindowWidth; int CEGuiGLFWSharedBase::d_newWindowHeight = CEGuiGLFWSharedBase::s_defaultWindowWidth; bool CEGuiGLFWSharedBase::d_mouseLeftWindow = false; bool CEGuiGLFWSharedBase::d_mouseDisableCalled = false; int CEGuiGLFWSharedBase::d_oldMousePosX = 0; int CEGuiGLFWSharedBase::d_oldMousePosY = 0; //----------------------------------------------------------------------------// CEGuiGLFWSharedBase::CEGuiGLFWSharedBase() { if (d_appInstance) throw CEGUI::InvalidRequestException( "CEGuiGLFWSharedBase instance already exists!"); d_appInstance = this; } //----------------------------------------------------------------------------// CEGuiGLFWSharedBase::~CEGuiGLFWSharedBase() { } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::run() { d_sampleApp->initialise(); // Input callbacks of glfw for CEGUI glfwSetKeyCallback(glfwKeyCallback); glfwSetCharCallback(glfwCharCallback); glfwSetMouseButtonCallback(glfwMouseButtonCallback); glfwSetMouseWheelCallback(glfwMouseWheelCallback); glfwSetMousePosCallback(glfwMousePosCallback); //Window callbacks glfwSetWindowCloseCallback(glfwWindowCloseCallback); glfwSetWindowSizeCallback(glfwWindowResizeCallback); d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // set starting time d_frameTime = glfwGetTime(); while (!d_sampleApp->isQuitting() && glfwGetWindowParam(GLFW_OPENED)) { if (d_windowSized) { d_windowSized = false; CEGUI::System::getSingleton(). notifyDisplaySizeChanged( CEGUI::Sizef(static_cast<float>(d_newWindowWidth), static_cast<float>(d_newWindowHeight))); } drawFrame(); } d_sampleApp->deinitialise(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::destroyWindow() { glfwTerminate(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::beginRendering(const float /*elapsed*/) { glClear(GL_COLOR_BUFFER_BIT); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::endRendering() { glfwSwapBuffers(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::drawFrame() { // calculate time elapsed since last frame double time_now = glfwGetTime(); const double elapsed = time_now - d_frameTime; d_frameTime = time_now; d_appInstance->renderSingleFrame(static_cast<float>(elapsed)); } //----------------------------------------------------------------------------// int CEGuiGLFWSharedBase::glfwWindowCloseCallback(void) { d_sampleApp->setQuitting(true); return GL_TRUE; } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::glfwWindowResizeCallback(int w, int h) { // We cache this in order to minimise calls to notifyDisplaySizeChanged, // which happens in the main loop whenever d_windowSized is set to true. d_windowSized = true; d_newWindowWidth = w; d_newWindowHeight = h; } //----------------------------------------------------------------------------// CEGUI::Key::Scan CEGuiGLFWSharedBase::GlfwToCeguiKey(int glfwKey) { switch(glfwKey) { case GLFW_KEY_ESC : return CEGUI::Key::Escape; case GLFW_KEY_F1 : return CEGUI::Key::F1; case GLFW_KEY_F2 : return CEGUI::Key::F2; case GLFW_KEY_F3 : return CEGUI::Key::F3; case GLFW_KEY_F4 : return CEGUI::Key::F4; case GLFW_KEY_F5 : return CEGUI::Key::F5; case GLFW_KEY_F6 : return CEGUI::Key::F6; case GLFW_KEY_F7 : return CEGUI::Key::F7; case GLFW_KEY_F8 : return CEGUI::Key::F8; case GLFW_KEY_F9 : return CEGUI::Key::F9; case GLFW_KEY_F10 : return CEGUI::Key::F10; case GLFW_KEY_F11 : return CEGUI::Key::F11; case GLFW_KEY_F12 : return CEGUI::Key::F12; case GLFW_KEY_F13 : return CEGUI::Key::F13; case GLFW_KEY_F14 : return CEGUI::Key::F14; case GLFW_KEY_F15 : return CEGUI::Key::F15; case GLFW_KEY_UP : return CEGUI::Key::ArrowUp; case GLFW_KEY_DOWN : return CEGUI::Key::ArrowDown; case GLFW_KEY_LEFT : return CEGUI::Key::ArrowLeft; case GLFW_KEY_RIGHT : return CEGUI::Key::ArrowRight; case GLFW_KEY_LSHIFT : return CEGUI::Key::LeftShift; case GLFW_KEY_RSHIFT : return CEGUI::Key::RightShift; case GLFW_KEY_LCTRL : return CEGUI::Key::LeftControl; case GLFW_KEY_RCTRL : return CEGUI::Key::RightControl; case GLFW_KEY_LALT : return CEGUI::Key::LeftAlt; case GLFW_KEY_RALT : return CEGUI::Key::RightAlt; case GLFW_KEY_TAB : return CEGUI::Key::Tab; case GLFW_KEY_ENTER : return CEGUI::Key::Return; case GLFW_KEY_BACKSPACE : return CEGUI::Key::Backspace; case GLFW_KEY_INSERT : return CEGUI::Key::Insert; case GLFW_KEY_DEL : return CEGUI::Key::Delete; case GLFW_KEY_PAGEUP : return CEGUI::Key::PageUp; case GLFW_KEY_PAGEDOWN : return CEGUI::Key::PageDown; case GLFW_KEY_HOME : return CEGUI::Key::Home; case GLFW_KEY_END : return CEGUI::Key::End; case GLFW_KEY_KP_ENTER : return CEGUI::Key::NumpadEnter; default : return CEGUI::Key::Unknown; } } //----------------------------------------------------------------------------// CEGUI::MouseButton CEGuiGLFWSharedBase::GlfwToCeguiMouseButton(int glfwButton) { switch(glfwButton) { case GLFW_MOUSE_BUTTON_LEFT : return CEGUI::LeftButton; case GLFW_MOUSE_BUTTON_RIGHT : return CEGUI::RightButton; case GLFW_MOUSE_BUTTON_MIDDLE : return CEGUI::MiddleButton; default : return CEGUI::NoButton; } } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwKeyCallback(int key, int action) { CEGUI::Key::Scan ceguiKey = GlfwToCeguiKey(key); if(action == GLFW_PRESS) d_sampleApp->injectKeyDown(ceguiKey); else if (action == GLFW_RELEASE) d_sampleApp->injectKeyUp(ceguiKey); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwCharCallback(int character, int action) { if(action == GLFW_PRESS) d_sampleApp->injectChar(character); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMouseButtonCallback(int key, int action) { CEGUI::MouseButton ceguiMouseButton = GlfwToCeguiMouseButton(key); if(action == GLFW_PRESS) d_sampleApp->injectMouseButtonDown(ceguiMouseButton); else if (action == GLFW_RELEASE) d_sampleApp->injectMouseButtonUp(ceguiMouseButton); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMouseWheelCallback(int position) { static int lastPosition = 0; d_sampleApp->injectMouseWheelChange(static_cast<float>(position - lastPosition)); lastPosition = position; } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMousePosCallback(int x, int y) { if (!d_mouseDisableCalled) { // if cursor didn't leave the window nothing changes d_sampleApp->injectMousePosition(static_cast<float>(x), static_cast<float>(y)); } else { // if the cursor left the window, we need to use the saved position // because glfw beams the cursor to the middle of the window if // the cursor is disabled d_sampleApp->injectMousePosition(static_cast<float>(d_oldMousePosX), static_cast<float>(d_oldMousePosY)); glfwSetMousePos(d_oldMousePosX, d_oldMousePosY); d_mouseDisableCalled = false; } #ifndef DEBUG if (x < 0 || y < 0 || x > d_newWindowWidth || y > d_newWindowHeight) { // show cursor glfwEnable(GLFW_MOUSE_CURSOR); // move the cursor to the position where it left the window glfwSetMousePos(x, y); // "note down" that the cursor left the window d_mouseLeftWindow = true; } else { if (d_mouseLeftWindow) { // get cursor position to restore afterwards glfwGetMousePos(&d_oldMousePosX, &d_oldMousePosY); // we need to inject the previous cursor position // because glfw moves the cursor to the centre of // the render window if it is disabled. therefore // notify the next call of the "mouse disabled" event. d_mouseDisableCalled = true; // disable cursor glfwDisable(GLFW_MOUSE_CURSOR); // "note down" that the cursor is back in the render window d_mouseLeftWindow = false; } } #endif } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::initGLFW() { if(!glfwInit()) CEGUI_THROW(CEGUI::RendererException("Failed to initialise GLFW.")); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::createGLFWWindow() { if (glfwOpenWindow(s_defaultWindowWidth, s_defaultWindowHeight, 0, 0, 0, 0, 24, 8, GLFW_WINDOW) != GL_TRUE) { CEGUI_THROW(CEGUI::RendererException("Failed to open GLFW window.")); glfwTerminate(); } } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::setGLFWAppConfiguration() { glfwSetWindowTitle("Crazy Eddie's GUI Mk-2 - Sample Application"); //Deactivate VSYNC glfwSwapInterval(0); // Disable the mouse position in Non_Debug mode #ifndef DEBUG glfwDisable(GLFW_MOUSE_CURSOR); #endif // Clear Errors by GLFW, even if Setup is correct. glGetError(); } //----------------------------------------------------------------------------// <commit_msg>MOD: docu was a bit unclear<commit_after>/*********************************************************************** created: 12/2/2012 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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. ***************************************************************************/ #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) # include <unistd.h> #endif #include "CEGUISamplesConfig.h" #include "CEGuiGLFWSharedBase.h" #include "SamplesFrameworkBase.h" #include "CEGUI/CEGUI.h" #include <stdexcept> #include <sstream> //----------------------------------------------------------------------------// CEGuiGLFWSharedBase* CEGuiGLFWSharedBase::d_appInstance = 0; double CEGuiGLFWSharedBase::d_frameTime = 0; int CEGuiGLFWSharedBase::d_modifiers = 0; bool CEGuiGLFWSharedBase::d_windowSized = false; int CEGuiGLFWSharedBase::d_newWindowWidth = CEGuiGLFWSharedBase::s_defaultWindowWidth; int CEGuiGLFWSharedBase::d_newWindowHeight = CEGuiGLFWSharedBase::s_defaultWindowWidth; bool CEGuiGLFWSharedBase::d_mouseLeftWindow = false; bool CEGuiGLFWSharedBase::d_mouseDisableCalled = false; int CEGuiGLFWSharedBase::d_oldMousePosX = 0; int CEGuiGLFWSharedBase::d_oldMousePosY = 0; //----------------------------------------------------------------------------// CEGuiGLFWSharedBase::CEGuiGLFWSharedBase() { if (d_appInstance) throw CEGUI::InvalidRequestException( "CEGuiGLFWSharedBase instance already exists!"); d_appInstance = this; } //----------------------------------------------------------------------------// CEGuiGLFWSharedBase::~CEGuiGLFWSharedBase() { } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::run() { d_sampleApp->initialise(); // Input callbacks of glfw for CEGUI glfwSetKeyCallback(glfwKeyCallback); glfwSetCharCallback(glfwCharCallback); glfwSetMouseButtonCallback(glfwMouseButtonCallback); glfwSetMouseWheelCallback(glfwMouseWheelCallback); glfwSetMousePosCallback(glfwMousePosCallback); //Window callbacks glfwSetWindowCloseCallback(glfwWindowCloseCallback); glfwSetWindowSizeCallback(glfwWindowResizeCallback); d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // set starting time d_frameTime = glfwGetTime(); while (!d_sampleApp->isQuitting() && glfwGetWindowParam(GLFW_OPENED)) { if (d_windowSized) { d_windowSized = false; CEGUI::System::getSingleton(). notifyDisplaySizeChanged( CEGUI::Sizef(static_cast<float>(d_newWindowWidth), static_cast<float>(d_newWindowHeight))); } drawFrame(); } d_sampleApp->deinitialise(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::destroyWindow() { glfwTerminate(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::beginRendering(const float /*elapsed*/) { glClear(GL_COLOR_BUFFER_BIT); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::endRendering() { glfwSwapBuffers(); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::drawFrame() { // calculate time elapsed since last frame double time_now = glfwGetTime(); const double elapsed = time_now - d_frameTime; d_frameTime = time_now; d_appInstance->renderSingleFrame(static_cast<float>(elapsed)); } //----------------------------------------------------------------------------// int CEGuiGLFWSharedBase::glfwWindowCloseCallback(void) { d_sampleApp->setQuitting(true); return GL_TRUE; } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::glfwWindowResizeCallback(int w, int h) { // We cache this in order to minimise calls to notifyDisplaySizeChanged, // which happens in the main loop whenever d_windowSized is set to true. d_windowSized = true; d_newWindowWidth = w; d_newWindowHeight = h; } //----------------------------------------------------------------------------// CEGUI::Key::Scan CEGuiGLFWSharedBase::GlfwToCeguiKey(int glfwKey) { switch(glfwKey) { case GLFW_KEY_ESC : return CEGUI::Key::Escape; case GLFW_KEY_F1 : return CEGUI::Key::F1; case GLFW_KEY_F2 : return CEGUI::Key::F2; case GLFW_KEY_F3 : return CEGUI::Key::F3; case GLFW_KEY_F4 : return CEGUI::Key::F4; case GLFW_KEY_F5 : return CEGUI::Key::F5; case GLFW_KEY_F6 : return CEGUI::Key::F6; case GLFW_KEY_F7 : return CEGUI::Key::F7; case GLFW_KEY_F8 : return CEGUI::Key::F8; case GLFW_KEY_F9 : return CEGUI::Key::F9; case GLFW_KEY_F10 : return CEGUI::Key::F10; case GLFW_KEY_F11 : return CEGUI::Key::F11; case GLFW_KEY_F12 : return CEGUI::Key::F12; case GLFW_KEY_F13 : return CEGUI::Key::F13; case GLFW_KEY_F14 : return CEGUI::Key::F14; case GLFW_KEY_F15 : return CEGUI::Key::F15; case GLFW_KEY_UP : return CEGUI::Key::ArrowUp; case GLFW_KEY_DOWN : return CEGUI::Key::ArrowDown; case GLFW_KEY_LEFT : return CEGUI::Key::ArrowLeft; case GLFW_KEY_RIGHT : return CEGUI::Key::ArrowRight; case GLFW_KEY_LSHIFT : return CEGUI::Key::LeftShift; case GLFW_KEY_RSHIFT : return CEGUI::Key::RightShift; case GLFW_KEY_LCTRL : return CEGUI::Key::LeftControl; case GLFW_KEY_RCTRL : return CEGUI::Key::RightControl; case GLFW_KEY_LALT : return CEGUI::Key::LeftAlt; case GLFW_KEY_RALT : return CEGUI::Key::RightAlt; case GLFW_KEY_TAB : return CEGUI::Key::Tab; case GLFW_KEY_ENTER : return CEGUI::Key::Return; case GLFW_KEY_BACKSPACE : return CEGUI::Key::Backspace; case GLFW_KEY_INSERT : return CEGUI::Key::Insert; case GLFW_KEY_DEL : return CEGUI::Key::Delete; case GLFW_KEY_PAGEUP : return CEGUI::Key::PageUp; case GLFW_KEY_PAGEDOWN : return CEGUI::Key::PageDown; case GLFW_KEY_HOME : return CEGUI::Key::Home; case GLFW_KEY_END : return CEGUI::Key::End; case GLFW_KEY_KP_ENTER : return CEGUI::Key::NumpadEnter; default : return CEGUI::Key::Unknown; } } //----------------------------------------------------------------------------// CEGUI::MouseButton CEGuiGLFWSharedBase::GlfwToCeguiMouseButton(int glfwButton) { switch(glfwButton) { case GLFW_MOUSE_BUTTON_LEFT : return CEGUI::LeftButton; case GLFW_MOUSE_BUTTON_RIGHT : return CEGUI::RightButton; case GLFW_MOUSE_BUTTON_MIDDLE : return CEGUI::MiddleButton; default : return CEGUI::NoButton; } } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwKeyCallback(int key, int action) { CEGUI::Key::Scan ceguiKey = GlfwToCeguiKey(key); if(action == GLFW_PRESS) d_sampleApp->injectKeyDown(ceguiKey); else if (action == GLFW_RELEASE) d_sampleApp->injectKeyUp(ceguiKey); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwCharCallback(int character, int action) { if(action == GLFW_PRESS) d_sampleApp->injectChar(character); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMouseButtonCallback(int key, int action) { CEGUI::MouseButton ceguiMouseButton = GlfwToCeguiMouseButton(key); if(action == GLFW_PRESS) d_sampleApp->injectMouseButtonDown(ceguiMouseButton); else if (action == GLFW_RELEASE) d_sampleApp->injectMouseButtonUp(ceguiMouseButton); } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMouseWheelCallback(int position) { static int lastPosition = 0; d_sampleApp->injectMouseWheelChange(static_cast<float>(position - lastPosition)); lastPosition = position; } //----------------------------------------------------------------------------// void GLFWCALL CEGuiGLFWSharedBase::glfwMousePosCallback(int x, int y) { if (!d_mouseDisableCalled) { // if cursor didn't leave the window nothing changes d_sampleApp->injectMousePosition(static_cast<float>(x), static_cast<float>(y)); } else { // if the cursor left the window, we need to use the saved position // because glfw beams the cursor to the middle of the window if // the cursor is disabled d_sampleApp->injectMousePosition(static_cast<float>(d_oldMousePosX), static_cast<float>(d_oldMousePosY)); glfwSetMousePos(d_oldMousePosX, d_oldMousePosY); d_mouseDisableCalled = false; } #ifndef DEBUG if (x < 0 || y < 0 || x > d_newWindowWidth || y > d_newWindowHeight) { // show cursor glfwEnable(GLFW_MOUSE_CURSOR); // move the cursor to the position where it left the window glfwSetMousePos(x, y); // "note down" that the cursor left the window d_mouseLeftWindow = true; } else { if (d_mouseLeftWindow) { // get cursor position to restore afterwards glfwGetMousePos(&d_oldMousePosX, &d_oldMousePosY); // we need to inject the previous cursor position because // glfw moves the cursor to the centre of the render // window if it gets disabled. therefore notify the // next MousePosCallback invocation of the "mouse disabled" event. d_mouseDisableCalled = true; // disable cursor glfwDisable(GLFW_MOUSE_CURSOR); // "note down" that the cursor is back in the render window d_mouseLeftWindow = false; } } #endif } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::initGLFW() { if(!glfwInit()) CEGUI_THROW(CEGUI::RendererException("Failed to initialise GLFW.")); } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::createGLFWWindow() { if (glfwOpenWindow(s_defaultWindowWidth, s_defaultWindowHeight, 0, 0, 0, 0, 24, 8, GLFW_WINDOW) != GL_TRUE) { CEGUI_THROW(CEGUI::RendererException("Failed to open GLFW window.")); glfwTerminate(); } } //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::setGLFWAppConfiguration() { glfwSetWindowTitle("Crazy Eddie's GUI Mk-2 - Sample Application"); //Deactivate VSYNC glfwSwapInterval(0); // Disable the mouse position in Non_Debug mode #ifndef DEBUG glfwDisable(GLFW_MOUSE_CURSOR); #endif // Clear Errors by GLFW, even if Setup is correct. glGetError(); } //----------------------------------------------------------------------------// <|endoftext|>
<commit_before>#include "MainWindow.h" MainWindow::MainWindow(void) : BWindow(BRect(100,100,900,700),"MasterPiece",B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS, B_CURRENT_WORKSPACE) { BRect r(Bounds()); r.bottom = 20; mpMenuBar = new MenuBar(r); AddChild(mpMenuBar); rgb_color myColor = {215, 215, 215, 255}; fullView = new NewMasterView(); AddChild(fullView); fullView->SetViewColor(myColor); fullView->Hide(); openView = new OpenMasterView(); AddChild(openView); openView->SetViewColor(myColor); openView->Hide(); BRect sumRect(Bounds()); sumRect.top = 20; sumView = new SummaryView(sumRect); AddChild(sumView); sumView->SetViewColor(myColor); sumView->Hide(); sqlErrMsg = 0; sqlValue = sqlite3_open("./MasterPiece.db", &mpdb); // open masterpiece.db if(sqlite3_errcode(mpdb) != 0) // if error is not ok, then display error in alert. { errorAlert = new ErrorAlert(sqlite3_errmsg(mpdb)); errorAlert->Launch(); } } void MainWindow::MessageReceived(BMessage *msg) { switch (msg->what) { case MENU_NEW_MSG: // 1. need to center the modal window on the parent... // 2. check to see if course is currently open if(!this->sumView->IsHidden()) this->sumView->Hide(); if(!this->openView->IsHidden()) this->openView->Hide(); if(this->fullView->IsHidden()) this->fullView->Show(); break; case MENU_OPN_MSG: if(!this->sumView->IsHidden()) this->sumView->Hide(); if(!this->fullView->IsHidden()) this->fullView->Hide(); this->openView->openListView->MakeEmpty(); /* homeDir->Rewind(); while(homeDir->GetNextEntry(&entry) == B_OK) { char name[B_FILE_NAME_LENGTH]; entry.GetName(name); if(entry.IsDirectory()) { this->openView->openListView->AddItem(new BStringItem(name)); } } */ if(this->openView->IsHidden()) this->openView->Show(); break; case ADD_NEW_COURSE: tmpString = "select masterpieceName from mptable where masterpieceName = '"; tmpString += this->fullView->titleText->Text(); tmpString += "';"; sqlValue = sqlite3_get_table(mpdb, tmpString, &selectResult, &nrow, &ncol, &sqlErrMsg); if(sqlValue == SQLITE_OK) // if sql was successful { if(nrow >= 1) // course already exists { fprintf(stdout, "count: %d, %s = %s\n", nrow, selectResult[0], selectResult[1]); sqlite3_free_table(selectResult); tmpString = "The MasterPiece: \""; tmpString += this->fullView->titleText->Text(); tmpString += "\" already exists. Do you want to Open the existing, Create a new one or cancel?"; userAlert = new BAlert("MasterPiece Exists", tmpString, "Open", "Create", "Cancel", B_WIDTH_AS_USUAL, B_INFO_ALERT); userAlert->MoveTo(350, 250); userAlert->SetShortcut(2, B_ESCAPE); int alertReturn = userAlert->Go(); if(alertReturn == 0) // Open { fprintf(stdout, "open course\n"); this->SetTitle(this->fullView->titleText->Text()); if(!this->fullView->IsHidden()) this->fullView->Hide(); if(!this->openView->IsHidden()) this->openView->Hide(); if(this->sumView->IsHidden()) this->sumView->Show(); this->mpMenuBar->contentMenu->SetEnabled(true); this->mpMenuBar->layoutMenu->SetEnabled(true); // 1. need to load summary view with the existing course information } else if(alertReturn == 1) // Create { fprintf(stdout, "create course\n"); tmpString = "insert into mptable (masterpieceName) values('"; tmpString += this->fullView->titleText->Text(); tmpString += "');"; sqlValue = sqlite3_exec(mpdb, tmpString, NULL, NULL, &sqlErrMsg); if(sqlValue == SQLITE_OK) // insert was successful { this->SetTitle(this->fullView->titleText->Text()); if(!this->fullView->IsHidden()) this->fullView->Hide(); if(!this->openView->IsHidden()) this->openView->Hide(); if(this->sumView->IsHidden()) this->sumView->Show(); this->mpMenuBar->contentMenu->SetEnabled(true); this->mpMenuBar->layoutMenu->SetEnabled(true); // load empty summary view information for this new course } else { errorAlert = new ErrorAlert("Error 1. Course was not created successfully. Please Try Again."); errorAlert->Launch(); } } else if(alertReturn == 2) // Cancel { fprintf(stdout, "cancel course\n"); } } } else // sql not succesful, display error { errorAlert = new ErrorAlert(sqlErrMsg); errorAlert->Launch(); } this->fullView->titleText->SetText(""); // reset new course title to blank when done break; case CANCEL_NEW_COURSE: if(!this->fullView->IsHidden()) this->fullView->Hide(); this->fullView->titleText->SetText(""); // do soemthing here... break; case MENU_THT_MSG: if(this->sumView->IsHidden()) this->sumView->Show(); // do something here... break; case MNG_LAYOUT_MSG: // do something here... break; case CANCEL_OPEN_COURSE: if(!this->openView->IsHidden())this->openView->Hide(); // do something here... break; case OPEN_EXISTING_COURSE: // do something here... int32 selected; selected = this->openView->openListView->CurrentSelection(); if(selected < 0) { // error here } BStringItem *item; item = dynamic_cast<BStringItem*>(this->openView->openListView->ItemAt(selected)); if(item) { this->SetTitle(item->Text()); if(!this->openView->IsHidden()) this->openView->Hide(); if(!this->fullView->IsHidden()) this->fullView->Hide(); if(this->sumView->IsHidden()) this->sumView->Show(); this->mpMenuBar->contentMenu->SetEnabled(true); this->mpMenuBar->layoutMenu->SetEnabled(true); } break; default: { BWindow::MessageReceived(msg); break; } } } bool MainWindow::QuitRequested(void) { sqlite3_free(sqlErrMsg); sqlite3_close(mpdb); be_app->PostMessage(B_QUIT_REQUESTED); return true; } <commit_msg>modified sqlite_open command to only do open and not create... will further expand on this as I hone the directory location for the app<commit_after>#include "MainWindow.h" MainWindow::MainWindow(void) : BWindow(BRect(100,100,900,700),"MasterPiece",B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS, B_CURRENT_WORKSPACE) { BRect r(Bounds()); r.bottom = 20; mpMenuBar = new MenuBar(r); AddChild(mpMenuBar); rgb_color myColor = {215, 215, 215, 255}; fullView = new NewMasterView(); AddChild(fullView); fullView->SetViewColor(myColor); fullView->Hide(); openView = new OpenMasterView(); AddChild(openView); openView->SetViewColor(myColor); openView->Hide(); BRect sumRect(Bounds()); sumRect.top = 20; sumView = new SummaryView(sumRect); AddChild(sumView); sumView->SetViewColor(myColor); sumView->Hide(); sqlErrMsg = 0; sqlValue = sqlite3_open_v2("./MasterPiece.db", &mpdb, SQLITE_OPEN_READWRITE, NULL); // open masterpiece.db if(sqlite3_errcode(mpdb) != 0) // if error is not ok, then display error in alert. { tmpString = "1.1 Sql Error: "; tmpString += sqlite3_errmsg(mpdb); errorAlert = new ErrorAlert(tmpString); errorAlert->Launch(); this->mpMenuBar->fileMenu->SetEnabled(false); } } void MainWindow::MessageReceived(BMessage *msg) { switch (msg->what) { case MENU_NEW_MSG: // 1. need to center the modal window on the parent... // 2. check to see if course is currently open if(!this->sumView->IsHidden()) this->sumView->Hide(); if(!this->openView->IsHidden()) this->openView->Hide(); if(this->fullView->IsHidden()) this->fullView->Show(); break; case MENU_OPN_MSG: if(!this->sumView->IsHidden()) this->sumView->Hide(); if(!this->fullView->IsHidden()) this->fullView->Hide(); this->openView->openListView->MakeEmpty(); /* homeDir->Rewind(); while(homeDir->GetNextEntry(&entry) == B_OK) { char name[B_FILE_NAME_LENGTH]; entry.GetName(name); if(entry.IsDirectory()) { this->openView->openListView->AddItem(new BStringItem(name)); } } */ if(this->openView->IsHidden()) this->openView->Show(); break; case ADD_NEW_COURSE: tmpString = "select masterpieceName from mptable where masterpieceName = '"; tmpString += this->fullView->titleText->Text(); tmpString += "';"; sqlValue = sqlite3_get_table(mpdb, tmpString, &selectResult, &nrow, &ncol, &sqlErrMsg); if(sqlValue == SQLITE_OK) // if sql was successful { if(nrow >= 1) // course already exists { fprintf(stdout, "count: %d, %s = %s\n", nrow, selectResult[0], selectResult[1]); sqlite3_free_table(selectResult); tmpString = "The MasterPiece: \""; tmpString += this->fullView->titleText->Text(); tmpString += "\" already exists. Do you want to Open the existing, Create a new one or cancel?"; userAlert = new BAlert("MasterPiece Exists", tmpString, "Open", "Create", "Cancel", B_WIDTH_AS_USUAL, B_INFO_ALERT); userAlert->MoveTo(350, 250); userAlert->SetShortcut(2, B_ESCAPE); int alertReturn = userAlert->Go(); if(alertReturn == 0) // Open { fprintf(stdout, "open course\n"); this->SetTitle(this->fullView->titleText->Text()); if(!this->fullView->IsHidden()) this->fullView->Hide(); if(!this->openView->IsHidden()) this->openView->Hide(); if(this->sumView->IsHidden()) this->sumView->Show(); this->mpMenuBar->contentMenu->SetEnabled(true); this->mpMenuBar->layoutMenu->SetEnabled(true); // 1. need to load summary view with the existing course information } else if(alertReturn == 1) // Create { fprintf(stdout, "create course\n"); tmpString = "insert into mptable (masterpieceName) values('"; tmpString += this->fullView->titleText->Text(); tmpString += "');"; sqlValue = sqlite3_exec(mpdb, tmpString, NULL, NULL, &sqlErrMsg); if(sqlValue == SQLITE_OK) // insert was successful { this->SetTitle(this->fullView->titleText->Text()); if(!this->fullView->IsHidden()) this->fullView->Hide(); if(!this->openView->IsHidden()) this->openView->Hide(); if(this->sumView->IsHidden()) this->sumView->Show(); this->mpMenuBar->contentMenu->SetEnabled(true); this->mpMenuBar->layoutMenu->SetEnabled(true); // load empty summary view information for this new course } else { errorAlert = new ErrorAlert("Error 1. Course was not created successfully. Please Try Again."); errorAlert->Launch(); } } else if(alertReturn == 2) // Cancel { fprintf(stdout, "cancel course\n"); } } } else // sql not succesful, display error { errorAlert = new ErrorAlert(sqlErrMsg); errorAlert->Launch(); } this->fullView->titleText->SetText(""); // reset new course title to blank when done break; case CANCEL_NEW_COURSE: if(!this->fullView->IsHidden()) this->fullView->Hide(); this->fullView->titleText->SetText(""); // do soemthing here... break; case MENU_THT_MSG: if(this->sumView->IsHidden()) this->sumView->Show(); // do something here... break; case MNG_LAYOUT_MSG: // do something here... break; case CANCEL_OPEN_COURSE: if(!this->openView->IsHidden())this->openView->Hide(); // do something here... break; case OPEN_EXISTING_COURSE: // do something here... int32 selected; selected = this->openView->openListView->CurrentSelection(); if(selected < 0) { // error here } BStringItem *item; item = dynamic_cast<BStringItem*>(this->openView->openListView->ItemAt(selected)); if(item) { this->SetTitle(item->Text()); if(!this->openView->IsHidden()) this->openView->Hide(); if(!this->fullView->IsHidden()) this->fullView->Hide(); if(this->sumView->IsHidden()) this->sumView->Show(); this->mpMenuBar->contentMenu->SetEnabled(true); this->mpMenuBar->layoutMenu->SetEnabled(true); } break; default: { BWindow::MessageReceived(msg); break; } } } bool MainWindow::QuitRequested(void) { sqlite3_free(sqlErrMsg); sqlite3_close(mpdb); be_app->PostMessage(B_QUIT_REQUESTED); 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 "chrome/browser/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CrossOriginXHRBackgroundPage) { host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("cross_origin_xhr/background_page")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CrossOriginXHRAllURLs) { host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("cross_origin_xhr/all_urls")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CrossOriginXHRContentScript) { host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("cross_origin_xhr/content_script")) << message_; } // Flaky on Mac 10.5, crbug.com/105179. #if defined(OS_MACOSX) #define MAYBE_CrossOriginXHRFileAccess FLAKY_CrossOriginXHRFileAccess #else #define MAYBE_CrossOriginXHRFileAccess CrossOriginXHRFileAccess #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CrossOriginXHRFileAccess) { ASSERT_TRUE(RunExtensionTest("cross_origin_xhr/file_access")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CrossOriginXHRNoFileAccess) { ASSERT_TRUE(RunExtensionTestNoFileAccess( "cross_origin_xhr/no_file_access")) << message_; } <commit_msg>Remove FLAKY modifier from CrossOriginXHRFileAccess, it hasn't failed in the past month.<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/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CrossOriginXHRBackgroundPage) { host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("cross_origin_xhr/background_page")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CrossOriginXHRAllURLs) { host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("cross_origin_xhr/all_urls")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CrossOriginXHRContentScript) { host_resolver()->AddRule("*.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("cross_origin_xhr/content_script")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CrossOriginXHRFileAccess) { ASSERT_TRUE(RunExtensionTest("cross_origin_xhr/file_access")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CrossOriginXHRNoFileAccess) { ASSERT_TRUE(RunExtensionTestNoFileAccess( "cross_origin_xhr/no_file_access")) << 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/net/ssl_config_service_manager.h" #include <algorithm> #include <string> #include <vector> #include "base/basictypes.h" #include "base/command_line.h" #include "chrome/browser/prefs/pref_change_registrar.h" #include "chrome/browser/prefs/pref_member.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "content/browser/browser_thread.h" #include "content/common/notification_details.h" #include "content/common/notification_source.h" #include "net/base/ssl_cipher_suite_names.h" #include "net/base/ssl_config_service.h" namespace { // Converts a ListValue of StringValues into a vector of strings. Any Values // which cannot be converted will be skipped. std::vector<std::string> ListValueToStringVector(const ListValue* value) { std::vector<std::string> results; results.reserve(value->GetSize()); std::string s; for (ListValue::const_iterator it = value->begin(); it != value->end(); ++it) { if (!(*it)->GetAsString(&s)) continue; results.push_back(s); } return results; } // Parses a vector of cipher suite strings, returning a sorted vector // containing the underlying SSL/TLS cipher suites. Unrecognized/invalid // cipher suites will be ignored. std::vector<uint16> ParseCipherSuites( const std::vector<std::string>& cipher_strings) { std::vector<uint16> cipher_suites; cipher_suites.reserve(cipher_strings.size()); for (std::vector<std::string>::const_iterator it = cipher_strings.begin(); it != cipher_strings.end(); ++it) { uint16 cipher_suite = 0; if (!net::ParseSSLCipherString(*it, &cipher_suite)) { LOG(ERROR) << "Ignoring unrecognized or unparsable cipher suite: " << *it; continue; } cipher_suites.push_back(cipher_suite); } std::sort(cipher_suites.begin(), cipher_suites.end()); return cipher_suites; } } // namespace //////////////////////////////////////////////////////////////////////////////// // SSLConfigServicePref // An SSLConfigService which stores a cached version of the current SSLConfig // prefs, which are updated by SSLConfigServiceManagerPref when the prefs // change. class SSLConfigServicePref : public net::SSLConfigService { public: SSLConfigServicePref() {} virtual ~SSLConfigServicePref() {} // Store SSL config settings in |config|. Must only be called from IO thread. virtual void GetSSLConfig(net::SSLConfig* config); private: // Allow the pref watcher to update our internal state. friend class SSLConfigServiceManagerPref; // This method is posted to the IO thread from the browser thread to carry the // new config information. void SetNewSSLConfig(const net::SSLConfig& new_config); // Cached value of prefs, should only be accessed from IO thread. net::SSLConfig cached_config_; DISALLOW_COPY_AND_ASSIGN(SSLConfigServicePref); }; void SSLConfigServicePref::GetSSLConfig(net::SSLConfig* config) { *config = cached_config_; } void SSLConfigServicePref::SetNewSSLConfig( const net::SSLConfig& new_config) { net::SSLConfig orig_config = cached_config_; cached_config_ = new_config; ProcessConfigUpdate(orig_config, new_config); } //////////////////////////////////////////////////////////////////////////////// // SSLConfigServiceManagerPref // The manager for holding and updating an SSLConfigServicePref instance. class SSLConfigServiceManagerPref : public SSLConfigServiceManager, public NotificationObserver { public: explicit SSLConfigServiceManagerPref(PrefService* local_state); virtual ~SSLConfigServiceManagerPref() {} // Register local_state SSL preferences. static void RegisterPrefs(PrefService* prefs); virtual net::SSLConfigService* Get(); private: // Callback for preference changes. This will post the changes to the IO // thread with SetNewSSLConfig. virtual void Observe(int type, const NotificationSource& source, const NotificationDetails& details); // Store SSL config settings in |config|, directly from the preferences. Must // only be called from UI thread. void GetSSLConfigFromPrefs(net::SSLConfig* config); // Processes changes to the disabled cipher suites preference, updating the // cached list of parsed SSL/TLS cipher suites that are disabled. void OnDisabledCipherSuitesChange(PrefService* prefs); PrefChangeRegistrar pref_change_registrar_; // The prefs (should only be accessed from UI thread) BooleanPrefMember rev_checking_enabled_; // The cached list of disabled SSL cipher suites. std::vector<uint16> disabled_cipher_suites_; scoped_refptr<SSLConfigServicePref> ssl_config_service_; DISALLOW_COPY_AND_ASSIGN(SSLConfigServiceManagerPref); }; SSLConfigServiceManagerPref::SSLConfigServiceManagerPref( PrefService* local_state) : ssl_config_service_(new SSLConfigServicePref()) { DCHECK(local_state); rev_checking_enabled_.Init(prefs::kCertRevocationCheckingEnabled, local_state, this); pref_change_registrar_.Init(local_state); pref_change_registrar_.Add(prefs::kCipherSuiteBlacklist, this); OnDisabledCipherSuitesChange(local_state); // Initialize from UI thread. This is okay as there shouldn't be anything on // the IO thread trying to access it yet. GetSSLConfigFromPrefs(&ssl_config_service_->cached_config_); } // static void SSLConfigServiceManagerPref::RegisterPrefs(PrefService* prefs) { net::SSLConfig default_config; prefs->RegisterBooleanPref(prefs::kCertRevocationCheckingEnabled, default_config.rev_checking_enabled); prefs->RegisterListPref(prefs::kCipherSuiteBlacklist); } net::SSLConfigService* SSLConfigServiceManagerPref::Get() { return ssl_config_service_; } void SSLConfigServiceManagerPref::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { if (type == chrome::NOTIFICATION_PREF_CHANGED) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); std::string* pref_name_in = Details<std::string>(details).ptr(); PrefService* prefs = Source<PrefService>(source).ptr(); DCHECK(pref_name_in && prefs); if (*pref_name_in == prefs::kCipherSuiteBlacklist) OnDisabledCipherSuitesChange(prefs); net::SSLConfig new_config; GetSSLConfigFromPrefs(&new_config); // Post a task to |io_loop| with the new configuration, so it can // update |cached_config_|. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod( ssl_config_service_.get(), &SSLConfigServicePref::SetNewSSLConfig, new_config)); } } void SSLConfigServiceManagerPref::GetSSLConfigFromPrefs( net::SSLConfig* config) { config->rev_checking_enabled = rev_checking_enabled_.GetValue(); config->ssl3_enabled = !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableSSL3); config->tls1_enabled = !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableTLS1); config->disabled_cipher_suites = disabled_cipher_suites_; SSLConfigServicePref::SetSSLConfigFlags(config); } void SSLConfigServiceManagerPref::OnDisabledCipherSuitesChange( PrefService* prefs) { const ListValue* value = prefs->GetList(prefs::kCipherSuiteBlacklist); disabled_cipher_suites_ = ParseCipherSuites(ListValueToStringVector(value)); } //////////////////////////////////////////////////////////////////////////////// // SSLConfigServiceManager // static SSLConfigServiceManager* SSLConfigServiceManager::CreateDefaultManager( PrefService* local_state) { return new SSLConfigServiceManagerPref(local_state); } // static void SSLConfigServiceManager::RegisterPrefs(PrefService* prefs) { SSLConfigServiceManagerPref::RegisterPrefs(prefs); } <commit_msg>Use new callbacks for SSL pref manager.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/net/ssl_config_service_manager.h" #include <algorithm> #include <string> #include <vector> #include "base/basictypes.h" #include "base/bind.h" #include "base/command_line.h" #include "chrome/browser/prefs/pref_change_registrar.h" #include "chrome/browser/prefs/pref_member.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "content/browser/browser_thread.h" #include "content/common/notification_details.h" #include "content/common/notification_source.h" #include "net/base/ssl_cipher_suite_names.h" #include "net/base/ssl_config_service.h" namespace { // Converts a ListValue of StringValues into a vector of strings. Any Values // which cannot be converted will be skipped. std::vector<std::string> ListValueToStringVector(const ListValue* value) { std::vector<std::string> results; results.reserve(value->GetSize()); std::string s; for (ListValue::const_iterator it = value->begin(); it != value->end(); ++it) { if (!(*it)->GetAsString(&s)) continue; results.push_back(s); } return results; } // Parses a vector of cipher suite strings, returning a sorted vector // containing the underlying SSL/TLS cipher suites. Unrecognized/invalid // cipher suites will be ignored. std::vector<uint16> ParseCipherSuites( const std::vector<std::string>& cipher_strings) { std::vector<uint16> cipher_suites; cipher_suites.reserve(cipher_strings.size()); for (std::vector<std::string>::const_iterator it = cipher_strings.begin(); it != cipher_strings.end(); ++it) { uint16 cipher_suite = 0; if (!net::ParseSSLCipherString(*it, &cipher_suite)) { LOG(ERROR) << "Ignoring unrecognized or unparsable cipher suite: " << *it; continue; } cipher_suites.push_back(cipher_suite); } std::sort(cipher_suites.begin(), cipher_suites.end()); return cipher_suites; } } // namespace //////////////////////////////////////////////////////////////////////////////// // SSLConfigServicePref // An SSLConfigService which stores a cached version of the current SSLConfig // prefs, which are updated by SSLConfigServiceManagerPref when the prefs // change. class SSLConfigServicePref : public net::SSLConfigService { public: SSLConfigServicePref() {} virtual ~SSLConfigServicePref() {} // Store SSL config settings in |config|. Must only be called from IO thread. virtual void GetSSLConfig(net::SSLConfig* config); private: // Allow the pref watcher to update our internal state. friend class SSLConfigServiceManagerPref; // This method is posted to the IO thread from the browser thread to carry the // new config information. void SetNewSSLConfig(const net::SSLConfig& new_config); // Cached value of prefs, should only be accessed from IO thread. net::SSLConfig cached_config_; DISALLOW_COPY_AND_ASSIGN(SSLConfigServicePref); }; void SSLConfigServicePref::GetSSLConfig(net::SSLConfig* config) { *config = cached_config_; } void SSLConfigServicePref::SetNewSSLConfig( const net::SSLConfig& new_config) { net::SSLConfig orig_config = cached_config_; cached_config_ = new_config; ProcessConfigUpdate(orig_config, new_config); } //////////////////////////////////////////////////////////////////////////////// // SSLConfigServiceManagerPref // The manager for holding and updating an SSLConfigServicePref instance. class SSLConfigServiceManagerPref : public SSLConfigServiceManager, public NotificationObserver { public: explicit SSLConfigServiceManagerPref(PrefService* local_state); virtual ~SSLConfigServiceManagerPref() {} // Register local_state SSL preferences. static void RegisterPrefs(PrefService* prefs); virtual net::SSLConfigService* Get(); private: // Callback for preference changes. This will post the changes to the IO // thread with SetNewSSLConfig. virtual void Observe(int type, const NotificationSource& source, const NotificationDetails& details); // Store SSL config settings in |config|, directly from the preferences. Must // only be called from UI thread. void GetSSLConfigFromPrefs(net::SSLConfig* config); // Processes changes to the disabled cipher suites preference, updating the // cached list of parsed SSL/TLS cipher suites that are disabled. void OnDisabledCipherSuitesChange(PrefService* prefs); PrefChangeRegistrar pref_change_registrar_; // The prefs (should only be accessed from UI thread) BooleanPrefMember rev_checking_enabled_; // The cached list of disabled SSL cipher suites. std::vector<uint16> disabled_cipher_suites_; scoped_refptr<SSLConfigServicePref> ssl_config_service_; DISALLOW_COPY_AND_ASSIGN(SSLConfigServiceManagerPref); }; SSLConfigServiceManagerPref::SSLConfigServiceManagerPref( PrefService* local_state) : ssl_config_service_(new SSLConfigServicePref()) { DCHECK(local_state); rev_checking_enabled_.Init(prefs::kCertRevocationCheckingEnabled, local_state, this); pref_change_registrar_.Init(local_state); pref_change_registrar_.Add(prefs::kCipherSuiteBlacklist, this); OnDisabledCipherSuitesChange(local_state); // Initialize from UI thread. This is okay as there shouldn't be anything on // the IO thread trying to access it yet. GetSSLConfigFromPrefs(&ssl_config_service_->cached_config_); } // static void SSLConfigServiceManagerPref::RegisterPrefs(PrefService* prefs) { net::SSLConfig default_config; prefs->RegisterBooleanPref(prefs::kCertRevocationCheckingEnabled, default_config.rev_checking_enabled); prefs->RegisterListPref(prefs::kCipherSuiteBlacklist); } net::SSLConfigService* SSLConfigServiceManagerPref::Get() { return ssl_config_service_; } void SSLConfigServiceManagerPref::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { if (type == chrome::NOTIFICATION_PREF_CHANGED) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); std::string* pref_name_in = Details<std::string>(details).ptr(); PrefService* prefs = Source<PrefService>(source).ptr(); DCHECK(pref_name_in && prefs); if (*pref_name_in == prefs::kCipherSuiteBlacklist) OnDisabledCipherSuitesChange(prefs); net::SSLConfig new_config; GetSSLConfigFromPrefs(&new_config); // Post a task to |io_loop| with the new configuration, so it can // update |cached_config_|. BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind( &SSLConfigServicePref::SetNewSSLConfig, ssl_config_service_.get(), new_config)); } } void SSLConfigServiceManagerPref::GetSSLConfigFromPrefs( net::SSLConfig* config) { config->rev_checking_enabled = rev_checking_enabled_.GetValue(); config->ssl3_enabled = !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableSSL3); config->tls1_enabled = !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableTLS1); config->disabled_cipher_suites = disabled_cipher_suites_; SSLConfigServicePref::SetSSLConfigFlags(config); } void SSLConfigServiceManagerPref::OnDisabledCipherSuitesChange( PrefService* prefs) { const ListValue* value = prefs->GetList(prefs::kCipherSuiteBlacklist); disabled_cipher_suites_ = ParseCipherSuites(ListValueToStringVector(value)); } //////////////////////////////////////////////////////////////////////////////// // SSLConfigServiceManager // static SSLConfigServiceManager* SSLConfigServiceManager::CreateDefaultManager( PrefService* local_state) { return new SSLConfigServiceManagerPref(local_state); } // static void SSLConfigServiceManager::RegisterPrefs(PrefService* prefs) { SSLConfigServiceManagerPref::RegisterPrefs(prefs); } <|endoftext|>
<commit_before>#include "EntityManager.hpp" #include <imgui/imgui.h> #include <Components/EntityRepresentation.hpp> #include <glm/gtc/type_ptr.hpp> #include <Components/ComponentRegistrationManager.hpp> #include <Components/MeshRenderer.hh> #include <AssetManagement/AssetManager.hh> #include <EditorConfiguration.hpp> #include <Components/CameraComponent.hpp> #include <Components/FreeFlyComponent.hh> #include <Entities/Archetype.hpp> #include <Managers/ArchetypesEditorManager.hpp> #include <EntityHelpers/EntityImgui.hpp> #include <Entities/EntityReadablePacker.hpp> #include <Entities/ReadableEntityPack.hpp> #include <Entities/EntityBinaryPacker.hpp> #include <Entities/BinaryEntityPack.hpp> #include <Core/Inputs/Input.hh> namespace AGE { namespace WE { EntityManager::EntityManager(AScene *scene) : System(std::move(scene)) , _filter(std::move(scene)) , _meshRenderers(std::move(scene)) , _selectedEntity(nullptr) , _selectedEntityIndex(0) , _graphNodeDisplay(false) , _selectParent(false) { // auto name = "\0"; strcpy_s(_sceneName, name); _meshRenderers.requireComponent<MeshRenderer>(); _displayWindow = true; generateBasicEntities(); } EntityManager::~EntityManager(){} void EntityManager::updateMenu() { if (ImGui::MenuItem("Show", nullptr, &_displayWindow)) {} if (ImGui::MenuItem("Graphnode display", nullptr, &_graphNodeDisplay, _displayWindow)) {} if (_cam != nullptr && ImGui::BeginMenu("Render options")) { static char const *pipelineNames[RenderType::TOTAL] = { "Debug deferred rendering" , "Deferred rendering" }; for (auto i = 0; i < RenderType::TOTAL; ++i) { auto enabled = _cam->getPipeline() != RenderType(i); if (ImGui::MenuItem(pipelineNames[i], nullptr, nullptr, enabled) && enabled) { _pipelineToSet = i; } } ImGui::EndMenu(); } ImGui::Separator(); bool saveSceneEnabled = _sceneName[0] != '\0'; if (ImGui::MenuItem("Save scene", "CTRL+S", nullptr, saveSceneEnabled)) { _saveScene = true; } if (ImGui::BeginMenu("Open scene")) { if (ImGui::ListBox("Scenes", &WE::EditorConfiguration::getSelectedSceneIndex(), WE::EditorConfiguration::getScenesName().data(), static_cast<int>(WE::EditorConfiguration::getScenesName().size()))) { _reloadScene = true; } ImGui::EndMenu(); } } void EntityManager::updateBegin(float time) {} void EntityManager::updateEnd(float time) {} void EntityManager::mainUpdate(float time) { if (_reloadScene) { _scene->clearAllEntities(); generateBasicEntities(); WESerialization::SetSerializeForEditor(true); auto sceneFileName = WE::EditorConfiguration::getSelectedScenePath() + ".raw_scene"; strcpy_s(_sceneName, WE::EditorConfiguration::getSelectedSceneName().c_str()); ReadableEntityPack pack; pack.scene = _scene; pack.loadFromFile(sceneFileName); _reloadScene = false; } if (_saveScene) { WESerialization::SetSerializeForEditor(true); ReadableEntityPack pack; { CreateReadableEntityPack(pack, _entities); pack.saveToFile(WE::EditorConfiguration::GetEditedSceneDirectory() + std::string(_sceneName) + ".raw_scene"); } { BinaryEntityPack binaryPack = pack.toBinary(); binaryPack.saveToFile(WE::EditorConfiguration::GetExportedSceneDirectory() + std::string(_sceneName) + ".scene"); } WESerialization::SetSerializeForEditor(false); _saveScene = false; } if (_cam && _pipelineToSet > -1) { _cam->setPipeline(RenderType(_pipelineToSet)); _pipelineToSet = -1; } if (_displayWindow == false) { return; } ImGui::Begin("Entity list", nullptr, ImGuiWindowFlags_MenuBar); if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Options")) { updateMenu(); ImGui::EndMenu(); } ImGui::EndMenuBar(); } ImGui::Checkbox("Graphnode display", &_graphNodeDisplay); EntityFilter::Lock lock(_filter); // Disgusting but fuck it ! :) _entityNames.clear(); _entities.clear(); { EntityFilter::Lock lock(_filter); for (auto e : _filter.getCollection()) { auto representation = e->getComponent<AGE::WE::EntityRepresentation>(); if (representation->editorOnly) { _filter.manuallyRemoveEntity(e); continue; } if (_graphNodeDisplay) { // if it's not attached to root if (e->getLink().hasParent()) { continue; } } _entityNames.push_back(representation->name); _entities.push_back(e); } } if (_selectedEntityIndex >= _entities.size()) { _selectedEntityIndex = 0; } if (_entities.size() > 0 && !_graphNodeDisplay) { ImGui::PushItemWidth(-1); //ImGui::ListBoxHeader("##empty"); if (ImGui::ListBox("##empty", &_selectedEntityIndex, &(_entityNames.front()), (int)(_entityNames.size()))) { if (_entities.size() > 0 && _selectedEntityIndex < _entities.size()) { _selectedEntity = _entities[_selectedEntityIndex].getPtr(); } else { _selectedEntity = nullptr; } } //ImGui::ListBoxFooter(); ImGui::PopItemWidth(); } else { for (auto &e : _entities) { recursiveDisplayList(e, _selectedEntity, _selectParent); } } ImGui::Separator(); ImGui::BeginChild("Edit entity"); if (_entities.size() > 0 && _selectedEntity != nullptr) { auto entity = *_selectedEntity; displayEntity(entity, _scene); ImGui::Separator(); auto representation = entity->getComponent<AGE::WE::EntityRepresentation>(); auto archetypeCpt = entity->getComponent<AGE::ArchetypeComponent>(); if (archetypeCpt == nullptr) { auto &types = ComponentRegistrationManager::getInstance().getExposedType(); auto &creationFn = ComponentRegistrationManager::getInstance().getCreationFunctions(); if (ImGui::Button("Add component...")) ImGui::OpenPopup("add_component"); if (ImGui::BeginPopup("add_component")) { for (auto &t : types) { if (!entity->haveComponent(t.second)) { if (ImGui::Selectable(ComponentRegistrationManager::getInstance().getComponentName(t.second).c_str())) { creationFn.at(t.first)(&entity); } } } ImGui::EndPopup(); } ImGui::Separator(); } auto isAnArchetype = archetypeCpt != nullptr; auto isAnArchetypeChild = isAnArchetype && archetypeCpt->parentIsAnArchetype; if (!isAnArchetypeChild && ImGui::SmallButton("Delete entity")) { auto destroyAllHierarchy = archetypeCpt != nullptr; _scene->destroy(entity, destroyAllHierarchy); _selectedEntity = nullptr; _selectedEntityIndex = 0; } if (isAnArchetypeChild == false && ImGui::SmallButton("Duplicate")) { Entity duplicate; _scene->copyEntity(entity, duplicate, true, false); } if (isAnArchetypeChild == false) { ImGui::InputText("Archetype name", _archetypeName, MAX_SCENE_NAME_LENGTH); if (ImGui::SmallButton("Convert to Archetype")) { auto manager = _scene->getInstance<AGE::WE::ArchetypeEditorManager>(); manager->addOne(_archetypeName, *_selectedEntity); } } } if (ImGui::Button("Create entity")) { _scene->createEntity(); } _entities.clear(); { EntityFilter::Lock lock(_filter); for (auto e : _filter.getCollection()) { // if it's not attached to root if (e->getLink().hasParent()) { continue; } _entities.push_back(e); } } ImGui::InputText("Scene name", _sceneName, MAX_SCENE_NAME_LENGTH, ImGuiInputTextFlags_CharsNoBlank); ImGui::SameLine(); if (_sceneName[0] && ImGui::Button("Save")) { _saveScene = true; } ImGui::EndChild(); ImGui::End(); auto input = _scene->getInstance<Input>(); auto ctrl = input->getPhysicalKeyPressed(AGE_LCTRL); ctrl |= input->getPhysicalKeyPressed(AGE_RCTRL); auto sKey = input->getPhysicalKeyPressed(AGE_s); if (ctrl && sKey && _sceneName[0]) { _saveScene = true; } } bool EntityManager::initialize() { return true; } void EntityManager::generateBasicEntities() { auto camera = _scene->createEntity(); _cam = camera->addComponent<CameraComponent>(); camera->getLink().setPosition(glm::vec3(0, 3, 5)); camera->getLink().setForward(glm::vec3(0, 0, 0)); camera->addComponent<FreeFlyComponent>(); camera->addComponent<AGE::WE::EntityRepresentation>()->editorOnly = true; } } }<commit_msg>Delete entity modal, duplicate entity modal<commit_after>#include "EntityManager.hpp" #include <imgui/imgui.h> #include <Components/EntityRepresentation.hpp> #include <glm/gtc/type_ptr.hpp> #include <Components/ComponentRegistrationManager.hpp> #include <Components/MeshRenderer.hh> #include <AssetManagement/AssetManager.hh> #include <EditorConfiguration.hpp> #include <Components/CameraComponent.hpp> #include <Components/FreeFlyComponent.hh> #include <Entities/Archetype.hpp> #include <Managers/ArchetypesEditorManager.hpp> #include <EntityHelpers/EntityImgui.hpp> #include <Entities/EntityReadablePacker.hpp> #include <Entities/ReadableEntityPack.hpp> #include <Entities/EntityBinaryPacker.hpp> #include <Entities/BinaryEntityPack.hpp> #include <Core/Inputs/Input.hh> namespace AGE { namespace WE { EntityManager::EntityManager(AScene *scene) : System(std::move(scene)) , _filter(std::move(scene)) , _meshRenderers(std::move(scene)) , _selectedEntity(nullptr) , _selectedEntityIndex(0) , _graphNodeDisplay(false) , _selectParent(false) { // auto name = "\0"; strcpy_s(_sceneName, name); _meshRenderers.requireComponent<MeshRenderer>(); _displayWindow = true; generateBasicEntities(); } EntityManager::~EntityManager(){} void EntityManager::updateMenu() { if (ImGui::MenuItem("Show", nullptr, &_displayWindow)) {} if (ImGui::MenuItem("Graphnode display", nullptr, &_graphNodeDisplay, _displayWindow)) {} if (_cam != nullptr && ImGui::BeginMenu("Render options")) { static char const *pipelineNames[RenderType::TOTAL] = { "Debug deferred rendering" , "Deferred rendering" }; for (auto i = 0; i < RenderType::TOTAL; ++i) { auto enabled = _cam->getPipeline() != RenderType(i); if (ImGui::MenuItem(pipelineNames[i], nullptr, nullptr, enabled) && enabled) { _pipelineToSet = i; } } ImGui::EndMenu(); } ImGui::Separator(); bool saveSceneEnabled = _sceneName[0] != '\0'; if (ImGui::MenuItem("Save scene", "CTRL+S", nullptr, saveSceneEnabled)) { _saveScene = true; } if (ImGui::BeginMenu("Open scene")) { if (ImGui::ListBox("Scenes", &WE::EditorConfiguration::getSelectedSceneIndex(), WE::EditorConfiguration::getScenesName().data(), static_cast<int>(WE::EditorConfiguration::getScenesName().size()))) { _reloadScene = true; } ImGui::EndMenu(); } } void EntityManager::updateBegin(float time) {} void EntityManager::updateEnd(float time) {} void EntityManager::mainUpdate(float time) { if (_reloadScene) { _scene->clearAllEntities(); generateBasicEntities(); WESerialization::SetSerializeForEditor(true); auto sceneFileName = WE::EditorConfiguration::getSelectedScenePath() + ".raw_scene"; strcpy_s(_sceneName, WE::EditorConfiguration::getSelectedSceneName().c_str()); ReadableEntityPack pack; pack.scene = _scene; pack.loadFromFile(sceneFileName); _reloadScene = false; } if (_saveScene) { WESerialization::SetSerializeForEditor(true); ReadableEntityPack pack; { CreateReadableEntityPack(pack, _entities); pack.saveToFile(WE::EditorConfiguration::GetEditedSceneDirectory() + std::string(_sceneName) + ".raw_scene"); } { BinaryEntityPack binaryPack = pack.toBinary(); binaryPack.saveToFile(WE::EditorConfiguration::GetExportedSceneDirectory() + std::string(_sceneName) + ".scene"); } WESerialization::SetSerializeForEditor(false); _saveScene = false; } if (_cam && _pipelineToSet > -1) { _cam->setPipeline(RenderType(_pipelineToSet)); _pipelineToSet = -1; } if (_displayWindow == false) { return; } ImGui::Begin("Entity list", nullptr, ImGuiWindowFlags_MenuBar); if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Options")) { updateMenu(); ImGui::EndMenu(); } ImGui::EndMenuBar(); } ImGui::Checkbox("Graphnode display", &_graphNodeDisplay); EntityFilter::Lock lock(_filter); // Disgusting but fuck it ! :) _entityNames.clear(); _entities.clear(); { EntityFilter::Lock lock(_filter); for (auto e : _filter.getCollection()) { auto representation = e->getComponent<AGE::WE::EntityRepresentation>(); if (representation->editorOnly) { _filter.manuallyRemoveEntity(e); continue; } if (_graphNodeDisplay) { // if it's not attached to root if (e->getLink().hasParent()) { continue; } } _entityNames.push_back(representation->name); _entities.push_back(e); } } if (_selectedEntityIndex >= _entities.size()) { _selectedEntityIndex = 0; } if (_entities.size() > 0 && !_graphNodeDisplay) { ImGui::PushItemWidth(-1); //ImGui::ListBoxHeader("##empty"); if (ImGui::ListBox("##empty", &_selectedEntityIndex, &(_entityNames.front()), (int)(_entityNames.size()))) { if (_entities.size() > 0 && _selectedEntityIndex < _entities.size()) { _selectedEntity = _entities[_selectedEntityIndex].getPtr(); } else { _selectedEntity = nullptr; } } //ImGui::ListBoxFooter(); ImGui::PopItemWidth(); } else { for (auto &e : _entities) { recursiveDisplayList(e, _selectedEntity, _selectParent); } } ImGui::Separator(); ImGui::BeginChild("Edit entity"); if (_entities.size() > 0 && _selectedEntity != nullptr) { auto entity = *_selectedEntity; displayEntity(entity, _scene); ImGui::Separator(); auto representation = entity->getComponent<AGE::WE::EntityRepresentation>(); auto archetypeCpt = entity->getComponent<AGE::ArchetypeComponent>(); if (archetypeCpt == nullptr) { auto &types = ComponentRegistrationManager::getInstance().getExposedType(); auto &creationFn = ComponentRegistrationManager::getInstance().getCreationFunctions(); if (ImGui::Button("Add component...")) ImGui::OpenPopup("add_component"); if (ImGui::BeginPopup("add_component")) { for (auto &t : types) { if (!entity->haveComponent(t.second)) { if (ImGui::Selectable(ComponentRegistrationManager::getInstance().getComponentName(t.second).c_str())) { creationFn.at(t.first)(&entity); } } } ImGui::EndPopup(); } } auto isAnArchetype = archetypeCpt != nullptr; auto isAnArchetypeChild = isAnArchetype && archetypeCpt->parentIsAnArchetype; ImGui::SameLine(); if (!isAnArchetypeChild && ImGui::Button("Delete entity")) { ImGui::OpenPopup("Delete entity ?"); } if (ImGui::BeginPopupModal("Delete entity ?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::Text("Are you sure to delete entity ?\nThis operation cannot be undone!\n\n"); ImGui::Separator(); static bool dont_ask_me_next_time = false; ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0)); ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time); ImGui::PopStyleVar(); if (ImGui::Button("Delete", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); auto destroyAllHierarchy = archetypeCpt != nullptr; _scene->destroy(entity, destroyAllHierarchy); _selectedEntity = nullptr; _selectedEntityIndex = 0; } ImGui::SameLine(); if (ImGui::Button("Cancel", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } if (isAnArchetypeChild == false && ImGui::Button("Duplicate")) { ImGui::OpenPopup("Duplicate entity ?"); } if (ImGui::BeginPopupModal("Duplicate entity ?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) { Entity duplicate; _scene->copyEntity(entity, duplicate, true, false); auto copyRepresentationCpt = duplicate->getComponent<AGE::WE::EntityRepresentation>(); ImGui::Text("Duplicate entity"); ImGui::Separator(); ImGui::InputText("Entity name", copyRepresentationCpt->name, ENTITY_NAME_LENGTH); if (ImGui::Button("Okay", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); } ImGui::SameLine(); if (ImGui::Button("Cancel", ImVec2(120, 0))) { _scene->destroy(duplicate, true); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } if (isAnArchetypeChild == false) { ImGui::InputText("Archetype name", _archetypeName, MAX_SCENE_NAME_LENGTH); if (ImGui::SmallButton("Convert to Archetype")) { auto manager = _scene->getInstance<AGE::WE::ArchetypeEditorManager>(); manager->addOne(_archetypeName, *_selectedEntity); } } } if (ImGui::Button("Create entity")) { _scene->createEntity(); } _entities.clear(); { EntityFilter::Lock lock(_filter); for (auto e : _filter.getCollection()) { // if it's not attached to root if (e->getLink().hasParent()) { continue; } _entities.push_back(e); } } ImGui::InputText("Scene name", _sceneName, MAX_SCENE_NAME_LENGTH, ImGuiInputTextFlags_CharsNoBlank); ImGui::SameLine(); if (_sceneName[0] && ImGui::Button("Save")) { _saveScene = true; } ImGui::EndChild(); ImGui::End(); auto input = _scene->getInstance<Input>(); auto ctrl = input->getPhysicalKeyPressed(AGE_LCTRL); ctrl |= input->getPhysicalKeyPressed(AGE_RCTRL); auto sKey = input->getPhysicalKeyPressed(AGE_s); if (ctrl && sKey && _sceneName[0]) { _saveScene = true; } } bool EntityManager::initialize() { return true; } void EntityManager::generateBasicEntities() { auto camera = _scene->createEntity(); _cam = camera->addComponent<CameraComponent>(); camera->getLink().setPosition(glm::vec3(0, 3, 5)); camera->getLink().setForward(glm::vec3(0, 0, 0)); camera->addComponent<FreeFlyComponent>(); camera->addComponent<AGE::WE::EntityRepresentation>()->editorOnly = true; } } }<|endoftext|>
<commit_before>// SqlBak.cpp : Defines the entry point for the console application. // #include "stdafx.h" // The following come from "SQL Server 2005 Virtual Backup Device Interface (VDI) Specification" // http://www.microsoft.com/downloads/en/details.aspx?familyid=416f8a51-65a3-4e8e-a4c8-adfe15e850fc #include "vdi/vdi.h" // interface declaration #include "vdi/vdierror.h" // error constants #include "vdi/vdiguid.h" // define the interface identifiers. #include <process.h> // _beginthread, _endthread // Globals TCHAR* _serverInstanceName; bool _optionQuiet = false; // printf to stdout (if -q quiet option isn't specified) void log(const TCHAR* format, ...) { if (_optionQuiet) return; // Basically do a fprintf to stderr. The va_* stuff is just to handle variable args va_list arglist; va_start(arglist, format); vfwprintf(stderr, format, arglist); } // printf to stdout (regardless of -q quiet option) void err(const TCHAR* format, ...) { va_list arglist; va_start(arglist, format); vfwprintf(stderr, format, arglist); } // Get human-readable message given a HRESULT _bstr_t errorMessage(DWORD messageId) { LPTSTR szMessage; if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, messageId, 0, (LPTSTR)&szMessage, 0, NULL)) { szMessage = (LPTSTR)LocalAlloc(LPTR, 255); _snwprintf(szMessage, 255, L"Unknown error 0x%x.\n", messageId); } _bstr_t retval(szMessage, true); LocalFree(szMessage); return retval; } // Execute the given SQL against _serverInstanceName unsigned __stdcall executeSql(void* pArguments) { TCHAR* sql = (TCHAR*)pArguments; //log(L"\nexecuteSql '%s'\n", sql); // Using '_Connection_Deprecated' interface for maximum MDAC compatibility Connection15Ptr conn; HRESULT hr = conn.CreateInstance(__uuidof(Connection)); if (FAILED(hr)) { err(L"ADODB.Connection CreateInstance failed: %s", (TCHAR*)errorMessage(hr)); return hr; } // "lpc:..." = shared memory connection _bstr_t serverName = "lpc:."; if (_serverInstanceName != NULL) serverName += "\\" + _bstr_t(_serverInstanceName); try { conn->ConnectionString = "Provider=SQLOLEDB; Data Source=" + serverName + "; Initial Catalog=master; Integrated Security=SSPI;"; //log(L"%s\n", (TCHAR*)conn->ConnectionString); conn->ConnectionTimeout = 25; conn->Open("", "", "", adConnectUnspecified); } catch(_com_error e) { err(L"\nFailed to open connection to '" + serverName + L"': "); err(L"%s [%s]\n", (TCHAR*)e.Description(), (TCHAR*)e.Source()); return e.Error(); } try { log(L"%s\n", (TCHAR*)sql); variant_t recordsAffected; conn->CommandTimeout = 0; log(L" Exec before\n"); _Recordset* recordset; hr = conn->raw_Execute(sql, &recordsAffected, adOptionUnspecified, &recordset); if (FAILED(hr)) { log(L"Execute failed 0x%x\n", hr); return hr; } log(L" Exec after\n"); conn->Close(); log(L" Query complete\n"); } catch(_com_error e) { log(L" ERROR!\n"); err(L"\nQuery failed: '%s'\n%s [%s]\n", sql, (TCHAR*)e.Description(), (TCHAR*)e.Source()); conn->Close(); return e.Error(); } return 0; } // Transfer data from virtualDevice to backupfile or vice-versa HRESULT performTransfer(IClientVirtualDevice* virtualDevice, FILE* backupfile) { VDC_Command * cmd; DWORD completionCode; DWORD bytesTransferred; HRESULT hr; DWORD totalBytes = 0; //DWORD increment = 0; while (SUCCEEDED (hr = virtualDevice->GetCommand(3 * 60 * 1000, &cmd))) { //log(L">command %d, size %d\n", cmd->commandCode, cmd->size); bytesTransferred = 0; switch (cmd->commandCode) { case VDC_Read: while(bytesTransferred < cmd->size) bytesTransferred += fread(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile); totalBytes += bytesTransferred; log(L"%d bytes read \r", totalBytes); cmd->size = bytesTransferred; completionCode = ERROR_SUCCESS; break; case VDC_Write: //log(L"VDC_Write - size: %d\r\n", cmd->size); while(bytesTransferred < cmd->size) bytesTransferred += fwrite(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile); totalBytes += bytesTransferred; log(L"%d bytes written \r", totalBytes); completionCode = ERROR_SUCCESS; break; case VDC_Flush: //log(L"\nVDC_Flush %d\n", cmd->size); fflush(backupfile); completionCode = ERROR_SUCCESS; break; case VDC_ClearError: //log(L"\nVDC_ClearError\n"); //Debug::WriteLine("VDC_ClearError"); completionCode = ERROR_SUCCESS; break; default: log(L"Unknown commandCode %d\n", cmd->commandCode); // If command is unknown... completionCode = ERROR_NOT_SUPPORTED; } hr = virtualDevice->CompleteCommand(cmd, completionCode, bytesTransferred, 0); if (FAILED(hr)) { err(L"\nvirtualDevice->CompleteCommand failed: %s\n", (TCHAR*)errorMessage(hr)); return hr; } } log(L"\n"); if (hr != VD_E_CLOSE) { err(L"virtualDevice->GetCommand failed: "); if (hr == VD_E_TIMEOUT) err(L" timeout awaiting data.\n"); else if (hr == VD_E_ABORT) err(L" transfer is being aborted due to an error.\n"); else err(L"%s\n", (TCHAR*)errorMessage(hr)); return hr; } return NOERROR; } // Entry point int _tmain(int argc, _TCHAR* argv[]) { if (argc < 3) { err(L"\n\ Action and database required.\n\ \n\ Usage: sqlbak backup|restore <database> [options]\n\ Options:\n\ -q Quiet, don't print messages to STDERR\n\ -i instancename\n"); return 1; } TCHAR* command = argv[1]; TCHAR* databaseName = argv[2]; // Parse options for (int i = 0; i < argc; i++) { TCHAR* arg = _wcslwr(_wcsdup(argv[i])); if (wcscmp(arg, L"-q") == 0) _optionQuiet = true; if (wcscmp(arg, L"-i") == 0) _serverInstanceName = argv[i+1]; free(arg); } HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (FAILED(hr)) { // Switching from apartment to multi-threaded is OK if(hr != RPC_E_CHANGED_MODE) { err(L"CoInitializeEx failed: ", hr); return 1; } } // Create Device Set IClientVirtualDeviceSet2 * virtualDeviceSet; hr = CoCreateInstance( CLSID_MSSQL_ClientVirtualDeviceSet, NULL, CLSCTX_INPROC_SERVER, IID_IClientVirtualDeviceSet2, (void**)&virtualDeviceSet); if (FAILED(hr)) { err(L"Could not create VDI component. Check registration of SQLVDI.DLL. %s\n", (TCHAR*)errorMessage(hr)); return 2; } // Generate virtualDeviceName TCHAR virtualDeviceName[39]; GUID guid; CoCreateGuid(&guid); StringFromGUID2(guid, virtualDeviceName, sizeof(virtualDeviceName)); // Create Device VDConfig vdConfig = {0}; vdConfig.deviceCount = 1; hr = virtualDeviceSet->CreateEx(_serverInstanceName, virtualDeviceName, &vdConfig); if (!SUCCEEDED (hr)) { err(L"IClientVirtualDeviceSet2.CreateEx failed\r\n"); switch(hr) { case VD_E_INSTANCE_NAME: err(L"Didn't recognize the SQL Server instance name '"+ _bstr_t(_serverInstanceName) + L"'.\r\n"); break; case E_ACCESSDENIED: err(L"Access Denied: You must be logged in as a Windows administrator to create virtual devices.\r\n"); break; default: err(L"%s\n", (TCHAR*)errorMessage(hr)); break; } return 3; } TCHAR* sql; FILE* backupFile; if (_wcsicmp(command, L"backup") == 0) { sql = "BACKUP DATABASE [" + _bstr_t(databaseName) + "] TO VIRTUAL_DEVICE = '" + virtualDeviceName + "'"; backupFile = stdout; } else if(_wcsicmp(command, L"restore") == 0) { hr = executeSql((void*)(TCHAR*)("CREATE DATABASE ["+ _bstr_t(databaseName) +"]")); if (FAILED(hr)) return hr; sql = "RESTORE DATABASE [" + _bstr_t(databaseName) + "] FROM VIRTUAL_DEVICE = '" + virtualDeviceName + "' WITH REPLACE"; backupFile = stdin; } else { err(L"Unsupported command '%s': only BACKUP or RESTORE are supported.\n", command); return 1; } // Invoke backup on separate thread because virtualDeviceSet->GetConfiguration will block until "BACKUP DATABASE..." unsigned threadId; //HANDLE executeSqlThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&executeSql, sql, 0, &threadId); HANDLE executeSqlThread = (HANDLE)_beginthreadex(NULL, 0, &executeSql, (void*)(sql), 0, &threadId); // Ready... hr = virtualDeviceSet->GetConfiguration(30000, &vdConfig); if (FAILED(hr)) { err(L"\n%s: virtualDeviceSet->GetConfiguration failed: ", command); if (hr == VD_E_TIMEOUT) err(L"Timed out waiting for backup to be initiated.\n"); else err(L"%s\n", (TCHAR*)errorMessage(hr)); return 3; } // Steady... IClientVirtualDevice *virtualDevice = NULL; hr = virtualDeviceSet->OpenDevice(virtualDeviceName, &virtualDevice); if (FAILED(hr)) { err(L"virtualDeviceSet->OpenDevice failed: 0x%x - "); if (hr == VD_E_TIMEOUT) err(L" timeout.\n"); else err(L" %s.\n", (TCHAR*)errorMessage(hr)); return 4; } // Go _setmode(_fileno(backupFile), _O_BINARY); hr = performTransfer(virtualDevice, backupFile); // Transferred, now wait for executeSql thread to complete if (SUCCEEDED(hr)) { log(L"\n%s: Waiting for backup thread to complete...\n", command); WaitForSingleObject(executeSqlThread, 10000); } else { log(L"Transfer failed\n"); } // Tidy up CloseHandle(executeSqlThread); virtualDeviceSet->Close(); virtualDevice->Release(); virtualDeviceSet->Release(); log(L"%s: Finished.\n", command); } <commit_msg>ctrl-Z to before randomm changes<commit_after>// SqlBak.cpp : Defines the entry point for the console application. // #include "stdafx.h" // The following come from "SQL Server 2005 Virtual Backup Device Interface (VDI) Specification" // http://www.microsoft.com/downloads/en/details.aspx?familyid=416f8a51-65a3-4e8e-a4c8-adfe15e850fc #include "vdi/vdi.h" // interface declaration #include "vdi/vdierror.h" // error constants #include "vdi/vdiguid.h" // define the interface identifiers. // Globals TCHAR* _serverInstanceName; bool _optionQuiet = false; // printf to stdout (if -q quiet option isn't specified) void log(const _bstr_t format, ...) { if (_optionQuiet) return; // Basically do a fprintf to stderr. The va_* stuff is just to handle variable args va_list arglist; va_start(arglist, format); vfwprintf(stderr, format, arglist); } // printf to stdout (regardless of -q quiet option) void err(const _bstr_t format, ...) { va_list arglist; va_start(arglist, format); vfwprintf(stderr, format, arglist); } // Get human-readable message given a HRESULT _bstr_t errorMessage(DWORD messageId) { LPTSTR szMessage; if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, messageId, 0, (LPTSTR)&szMessage, 0, NULL)) { szMessage = (LPTSTR)LocalAlloc(LPTR, 50); _snwprintf(szMessage, sizeof(szMessage), L"Unknown error 0x%x.\n", messageId); } _bstr_t retval = szMessage; LocalFree(szMessage); return retval; } // Execute the given SQL against _serverInstanceName DWORD executeSql(TCHAR* sql) { //log("\nexecuteSql '%s'\n", sql); HRESULT hr; // Use '_Connection_Deprecated' interface for maximum MDAC compatibility _Connection_DeprecatedPtr conn; hr = conn.CreateInstance(__uuidof(Connection)); if (FAILED(hr)) { err("ADODB.Connection CreateInstance failed: %s", (TCHAR*)errorMessage(hr)); return hr; } // "lpc:..." ensures shared memory... _bstr_t serverName = "lpc:."; if (_serverInstanceName != NULL) serverName += "\\" + _bstr_t(_serverInstanceName); try { conn->ConnectionString = "Provider=SQLOLEDB; Data Source=" + serverName + "; Initial Catalog=master; Integrated Security=SSPI;"; //log(conn->ConnectionString); conn->ConnectionTimeout = 25; conn->Open("", "", "", adConnectUnspecified); } catch(_com_error e) { err("\nFailed to open connection to '" + serverName + L"': "); err("%s [%s]\n", (TCHAR*)e.Description(), (TCHAR*)e.Source()); return e.Error(); } try { //log("%s\n", (TCHAR*)sql); variant_t recordsAffected; conn->CommandTimeout = 0; conn->Execute(sql, &recordsAffected, adOptionUnspecified); conn->Close(); } catch(_com_error e) { err("\nQuery failed: '%s'\n%s [%s]\n", sql, (TCHAR*)e.Description(), (TCHAR*)e.Source()); conn->Close(); return e.Error(); } return 0; } // Transfer data from virtualDevice to backupfile or vice-versa HRESULT performTransfer(IClientVirtualDevice* virtualDevice, FILE* backupfile) { VDC_Command * cmd; DWORD completionCode; DWORD bytesTransferred; HRESULT hr; DWORD totalBytes = 0; //DWORD increment = 0; while (SUCCEEDED (hr = virtualDevice->GetCommand(3 * 60 * 1000, &cmd))) { //log(">command %d, size %d\n", cmd->commandCode, cmd->size); bytesTransferred = 0; switch (cmd->commandCode) { case VDC_Read: while(bytesTransferred < cmd->size) bytesTransferred += fread(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile); totalBytes += bytesTransferred; log("%d bytes read \r", totalBytes); //if ((increment += bytesTransferred)> 1000000) //{ // log("."); // increment = 0; //} cmd->size = bytesTransferred; completionCode = ERROR_SUCCESS; break; case VDC_Write: //log("VDC_Write - size: %d\r\n", cmd->size); while(bytesTransferred < cmd->size) bytesTransferred += fwrite(cmd->buffer + bytesTransferred, 1, cmd->size - bytesTransferred, backupfile); totalBytes += bytesTransferred; log("%d bytes written\r", totalBytes); completionCode = ERROR_SUCCESS; break; case VDC_Flush: //log("\nVDC_Flush %d\n", cmd->size); completionCode = ERROR_SUCCESS; break; case VDC_ClearError: log("\nVDC_ClearError\n"); //Debug::WriteLine("VDC_ClearError"); completionCode = ERROR_SUCCESS; break; default: // If command is unknown... completionCode = ERROR_NOT_SUPPORTED; } hr = virtualDevice->CompleteCommand(cmd, completionCode, bytesTransferred, 0); if (FAILED(hr)) { err("\nvirtualDevice->CompleteCommand failed: %s\n", (TCHAR*)errorMessage(hr)); return hr; } } log("\n"); if (hr != VD_E_CLOSE) { err("virtualDevice->GetCommand failed: "); if (hr == VD_E_TIMEOUT) err(" timeout awaiting data.\n"); else err("$s\n", (TCHAR*)errorMessage(hr)); return hr; } return NOERROR; } // Entry point int _tmain(int argc, _TCHAR* argv[]) { if (argc < 3) { err("\n\ Action and database required.\n\ \n\ Usage: sqlbak backup|restore <database> [options]\n\ Options:\n\ -q Quiet, don't print messages to STDERR\n\ -i instancename\n"); return 1; } TCHAR* command = argv[1]; TCHAR* databaseName = argv[2]; // Parse options for (int i = 0; i < argc; i++) { TCHAR* arg = _wcslwr(_wcsdup(argv[i])); if (wcscmp(arg, L"-q") == 0) _optionQuiet = true; if (wcscmp(arg, L"-i") == 0) _serverInstanceName = argv[i+1]; free(arg); } HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); if (FAILED(hr)) { // Switching from apartment to multi-threaded is OK if(hr != RPC_E_CHANGED_MODE) { err("CoInitializeEx failed: ", hr); return 1; } } // Create Device Set IClientVirtualDeviceSet2 * virtualDeviceSet; hr = CoCreateInstance( CLSID_MSSQL_ClientVirtualDeviceSet, NULL, CLSCTX_INPROC_SERVER, IID_IClientVirtualDeviceSet2, (void**)&virtualDeviceSet); if (FAILED(hr)) { err("Could not create VDI component. Check registration of SQLVDI.DLL. %s\n", (TCHAR*)errorMessage(hr)); return 2; } // Generate virtualDeviceName TCHAR virtualDeviceName[39]; GUID guid; CoCreateGuid(&guid); StringFromGUID2(guid, virtualDeviceName, sizeof(virtualDeviceName)); // Create Device VDConfig vdConfig = {0}; vdConfig.deviceCount = 1; hr = virtualDeviceSet->CreateEx(_serverInstanceName, virtualDeviceName, &vdConfig); if (!SUCCEEDED (hr)) { err("IClientVirtualDeviceSet2.CreateEx failed\r\n"); switch(hr) { case VD_E_INSTANCE_NAME: err("Didn't recognize the SQL Server instance name '"+ _bstr_t(_serverInstanceName) + L"'.\r\n"); break; case E_ACCESSDENIED: err("Access Denied: You must be logged in as a Windows administrator to create virtual devices.\r\n"); break; default: err("%s\n", (TCHAR*)errorMessage(hr)); break; } return 3; } TCHAR* sql; FILE* backupFile; if (_wcsicmp(command, L"backup") == 0) { sql = "BACKUP DATABASE [" + _bstr_t(databaseName) + "] TO VIRTUAL_DEVICE = '" + virtualDeviceName + "'"; backupFile = stdout; } else if(_wcsicmp(command, L"restore") == 0) { hr = executeSql("CREATE DATABASE ["+ _bstr_t(databaseName) +"]"); if (FAILED(hr)) return hr; sql = "RESTORE DATABASE [" + _bstr_t(databaseName) + "] FROM VIRTUAL_DEVICE = '" + virtualDeviceName + "' WITH REPLACE"; backupFile = stdin; } else { err("Unsupported command '%s': only BACKUP or RESTORE are supported.\n", command); return 1; } // Invoke backup on separate thread because virtualDeviceSet->GetConfiguration will block until "BACKUP DATABASE..." DWORD threadId; HANDLE executeSqlThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&executeSql, sql, 0, &threadId); // Ready... hr = virtualDeviceSet->GetConfiguration(30000, &vdConfig); if (FAILED(hr)) { err("\n%s: virtualDeviceSet->GetConfiguration failed: ", command); if (hr == VD_E_TIMEOUT) err("Timed out waiting for backup to be initiated.\n"); else err("%s\n", (TCHAR*)errorMessage(hr)); return 3; } // Steady... IClientVirtualDevice *virtualDevice = NULL; hr = virtualDeviceSet->OpenDevice(virtualDeviceName, &virtualDevice); if (FAILED(hr)) { err("virtualDeviceSet->OpenDevice failed: 0x%x - "); if (hr == VD_E_TIMEOUT) err(" timeout.\n"); else err(" %s.\n", (TCHAR*)errorMessage(hr)); return 4; } // Go _setmode(_fileno(backupFile), _O_BINARY); hr = performTransfer(virtualDevice, backupFile); // Transferred, now wait for executeSql thread to complete if (SUCCEEDED(hr)) { log("\n%s: Waiting for backup thread to complete...\n", command); WaitForSingleObject(executeSqlThread, 10000); } // Tidy up CloseHandle(executeSqlThread); virtualDeviceSet->Close(); virtualDevice->Release(); virtualDeviceSet->Release(); log("%s: Finished.\n", command); } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <SurgSim/Framework/Runtime.h> #include <SurgSim/Framework/Component.h> #include <SurgSim/Physics/PhysicsManager.h> #include <SurgSim/Physics/FreeMotion.h> #include <SurgSim/Physics/Representation.h> #include <SurgSim/Physics/DcdCollision.h> #include <SurgSim/Framework/Log.h> #include <list> namespace SurgSim { namespace Physics { PhysicsManager::PhysicsManager() { } PhysicsManager::~PhysicsManager() { } bool PhysicsManager::doInitialize() { m_logger = getRuntime()->getLogger("PhysicsManager"); m_freeMotionStep.reset(new FreeMotion()); m_dcdCollision.reset(new DcdCollision()); return m_logger != nullptr && m_freeMotionStep != nullptr; } bool PhysicsManager::doStartUp() { return true; } bool PhysicsManager::addComponent(std::shared_ptr<SurgSim::Framework::Component> component) { return tryAddComponent(component,&m_representations) != nullptr; } bool PhysicsManager::removeComponent(std::shared_ptr<SurgSim::Framework::Component> component) { return tryRemoveComponent(component, &m_representations); } bool PhysicsManager::doUpdate(double dt) { std::list<std::shared_ptr<PhysicsManagerState>> stateList; std::shared_ptr<PhysicsManagerState> state = std::make_shared<PhysicsManagerState>(); stateList.push_back(state); state->setRepresentations(m_representations); stateList.push_back(m_freeMotionStep->update(dt, stateList.back())); stateList.push_back(m_dcdCollision->update(dt, stateList.back())); return true; } }; // Physics }; // SurgSim <commit_msg>Call beforeUpdate() and afterUpdate() on the physics representations in PhysicsManager::doUpdate() This is needed to update the final pose.<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <SurgSim/Framework/Runtime.h> #include <SurgSim/Framework/Component.h> #include <SurgSim/Physics/PhysicsManager.h> #include <SurgSim/Physics/FreeMotion.h> #include <SurgSim/Physics/Representation.h> #include <SurgSim/Physics/DcdCollision.h> #include <SurgSim/Framework/Log.h> #include <list> namespace SurgSim { namespace Physics { PhysicsManager::PhysicsManager() { } PhysicsManager::~PhysicsManager() { } bool PhysicsManager::doInitialize() { m_logger = getRuntime()->getLogger("PhysicsManager"); m_freeMotionStep.reset(new FreeMotion()); m_dcdCollision.reset(new DcdCollision()); return m_logger != nullptr && m_freeMotionStep != nullptr; } bool PhysicsManager::doStartUp() { return true; } bool PhysicsManager::addComponent(std::shared_ptr<SurgSim::Framework::Component> component) { return tryAddComponent(component,&m_representations) != nullptr; } bool PhysicsManager::removeComponent(std::shared_ptr<SurgSim::Framework::Component> component) { return tryRemoveComponent(component, &m_representations); } bool PhysicsManager::doUpdate(double dt) { for (auto it = m_representations.begin(); it != m_representations.end(); ++it) { (*it)->beforeUpdate(dt); } std::list<std::shared_ptr<PhysicsManagerState>> stateList; std::shared_ptr<PhysicsManagerState> state = std::make_shared<PhysicsManagerState>(); stateList.push_back(state); state->setRepresentations(m_representations); stateList.push_back(m_freeMotionStep->update(dt, stateList.back())); stateList.push_back(m_dcdCollision->update(dt, stateList.back())); for (auto it = m_representations.begin(); it != m_representations.end(); ++it) { (*it)->afterUpdate(dt); } return true; } }; // Physics }; // SurgSim <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AccessiblePageHeaderArea.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: sab $ $Date: 2002-05-24 15:11:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SC_ACCESSIBLEPAGEHEADERAREA_HXX #define _SC_ACCESSIBLEPAGEHEADERAREA_HXX #ifndef _SC_ACCESSIBLE_CONTEXT_BASE_HXX #include "AccessibleContextBase.hxx" #endif #ifndef _SVX_SVXENUM_HXX #include <svx/svxenum.hxx> #endif class EditTextObject; namespace accessibility { class AccessibleTextHelper; } class ScPreviewShell; class ScAccessiblePageHeaderArea : public ScAccessibleContextBase { public: //===== internal ======================================================== ScAccessiblePageHeaderArea( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible>& rxParent, ScPreviewShell* pViewShell, const EditTextObject* pEditObj, sal_Bool bHeader, SvxAdjust eAdjust); protected: virtual ~ScAccessiblePageHeaderArea (void); public: const EditTextObject* GetEditTextObject() const { return mpEditObj; } virtual void SAL_CALL disposing(); ///===== XAccessibleComponent ============================================ virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& rPoint ) throw (::com::sun::star::uno::RuntimeException); ///===== XAccessibleContext ============================================== /// Return the number of currently visible children. // is overloaded to calculate this on demand virtual sal_Int32 SAL_CALL getAccessibleChildCount(void) throw (::com::sun::star::uno::RuntimeException); /// Return the specified child or NULL if index is invalid. // is overloaded to calculate this on demand virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild(sal_Int32 nIndex) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IndexOutOfBoundsException); /// Return the set of current states. virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL getAccessibleStateSet(void) throw (::com::sun::star::uno::RuntimeException); ///===== XTypeProvider =================================================== /** Returns a implementation id. */ virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId(void) throw (::com::sun::star::uno::RuntimeException); private: EditTextObject* mpEditObj; accessibility::AccessibleTextHelper* mpTextHelper; ScPreviewShell* mpViewShell; sal_Bool mbHeader; SvxAdjust meAdjust; void CreateTextHelper(); }; #endif <commit_msg>#99771#; add createAccessibleName, createAccessibleDescription, getBoundingBox and getBoundingBoxOnScreen<commit_after>/************************************************************************* * * $RCSfile: AccessiblePageHeaderArea.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: sab $ $Date: 2002-07-04 08:17:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SC_ACCESSIBLEPAGEHEADERAREA_HXX #define _SC_ACCESSIBLEPAGEHEADERAREA_HXX #ifndef _SC_ACCESSIBLE_CONTEXT_BASE_HXX #include "AccessibleContextBase.hxx" #endif #ifndef _SVX_SVXENUM_HXX #include <svx/svxenum.hxx> #endif class EditTextObject; namespace accessibility { class AccessibleTextHelper; } class ScPreviewShell; class ScAccessiblePageHeaderArea : public ScAccessibleContextBase { public: //===== internal ======================================================== ScAccessiblePageHeaderArea( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible>& rxParent, ScPreviewShell* pViewShell, const EditTextObject* pEditObj, sal_Bool bHeader, SvxAdjust eAdjust); protected: virtual ~ScAccessiblePageHeaderArea (void); public: const EditTextObject* GetEditTextObject() const { return mpEditObj; } virtual void SAL_CALL disposing(); ///===== XAccessibleComponent ============================================ virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& rPoint ) throw (::com::sun::star::uno::RuntimeException); ///===== XAccessibleContext ============================================== /// Return the number of currently visible children. // is overloaded to calculate this on demand virtual sal_Int32 SAL_CALL getAccessibleChildCount(void) throw (::com::sun::star::uno::RuntimeException); /// Return the specified child or NULL if index is invalid. // is overloaded to calculate this on demand virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible> SAL_CALL getAccessibleChild(sal_Int32 nIndex) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IndexOutOfBoundsException); /// Return the set of current states. virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL getAccessibleStateSet(void) throw (::com::sun::star::uno::RuntimeException); ///===== XTypeProvider =================================================== /** Returns a implementation id. */ virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId(void) throw (::com::sun::star::uno::RuntimeException); protected: virtual ::rtl::OUString SAL_CALL createAccessibleDescription(void) throw(::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL createAccessibleName(void) throw (::com::sun::star::uno::RuntimeException); virtual Rectangle GetBoundingBoxOnScreen(void) const throw(::com::sun::star::uno::RuntimeException); virtual Rectangle GetBoundingBox(void) const throw (::com::sun::star::uno::RuntimeException); private: EditTextObject* mpEditObj; accessibility::AccessibleTextHelper* mpTextHelper; ScPreviewShell* mpViewShell; sal_Bool mbHeader; SvxAdjust meAdjust; void CreateTextHelper(); }; #endif <|endoftext|>
<commit_before>#include <QtNetwork/QTcpSocket> #include <QFileInfo> #include <QFile> #include <QStringList> #include <QDir> #include "httpthread.h" HTTPThread::HTTPThread(const int socketDescriptor, const QString &docRoot, QObject *parent) : QThread(parent), socketDescriptor(socketDescriptor), docRoot(docRoot), responseStatusLine("HTTP/1.0 %1\r\n") { } void HTTPThread::run() { QTcpSocket socket; if(!socket.setSocketDescriptor(socketDescriptor)){ qDebug() << "Setting the sd has failed: " << socket.errorString(); emit error(socket.error()); return; } QString request = readRequest(&socket); qDebug() << request; QByteArray response = processRequestData(parseHTTPRequest(request)); //TODO: construct the response in a nice data structure and put it toghether here //also be good and send a Content-Length field (bytes) socket.write(response, response.size()); if(!socket.waitForBytesWritten()){ qDebug() << "Could not write byts to socket: " << socket.errorString(); emit error(socket.error()); } socket.close(); } QString HTTPThread::readRequest(QTcpSocket *socket){ QString request; //TODO: what if is a POST? do{ if(!socket->waitForReadyRead()){ qDebug() << "Error while waiting for client data: " << socket->errorString(); emit error(socket->error()); return request; } request.append(QString(socket->readAll())); }while(-1 == request.lastIndexOf("\n\n") && -1 == request.lastIndexOf("\r\n\r\n")); return request; } RequestData HTTPThread::parseHTTPRequest(QString request) { RequestData requestData; requestData.valid = false; //TODO: what if I encounter \r\n in the URL or in the POST data? //TODO: be tolerant and replace "\r" with "" and then work with "\n" QStringList parts = request.split("\r\n\r\n", QString::SkipEmptyParts); if(parts.isEmpty()){ return requestData; } QStringList fields = parts[0].split("\r\n", QString::SkipEmptyParts); QStringList statusLine = fields[0].split(" "); if(3 != statusLine.size()){ return requestData; } QStringList protocol = statusLine[2].split("/"); bool ok; if(2 != protocol.size()){ return requestData; } double ver = protocol[1].toDouble(&ok); if("HTTP" != protocol[0] || !ok || ver < 0.9 || ver > 1.1){ return requestData; } requestData.method = statusLine[0]; requestData.url.setUrl(statusLine[1]); requestData.protocol = protocol[0]; requestData.protocolVersion = ver; fields.removeAt(0); int spacePos; foreach(QString line, fields){ spacePos = line.indexOf(" "); requestData.fields.insert(line.left(spacePos-1), QStringList(line.right(line.size()-spacePos-1))); } if(requestData.fields.contains("Host")){ requestData.fields["Host"] = requestData.fields["Host"][0].split(":"); } if("POST" == requestData.method && 2 == parts.size() && !parts[1].isEmpty()){ requestData.postData = parsePostBody(parts[1]); //TODO: if it's empty error out } qDebug() << "Request data:\n\tStatusLine:\n\t\tMethod: " << requestData.method << "\n\t\tUrl: " << requestData.url << "\n\t\tProtocol: " << requestData.protocol << "\n\t\tVer: " <<requestData.protocolVersion << "\n\tFields: " << requestData.fields << "\n\tpost: " << requestData.postData; requestData.valid = true; return requestData; } QHash<QString, QString> HTTPThread::parsePostBody(QString postBody) { // what if a radiobox is checked and sent? // what if: "option_set", with no "=" sign, is it possible? // what if the data contains "&"? QHash<QString, QString> retval; QStringList pairs = postBody.split("&", QString::SkipEmptyParts); //TODO: ??? foreach(QString pair, pairs){ QStringList keyVal = pair.split("="); //TODO: ??? retval.insert(keyVal[0], keyVal[1]); //TODO: ??? } return retval; } QByteArray HTTPThread::processRequestData(const RequestData &requestData) { //TODO: add support for different Host values //TODO: URL rewriting? QByteArray response = responseStatusLine.arg("200 OK").toUtf8(); if(!requestData.valid){ return responseStatusLine.arg("400 Bad request\r\n").toAscii(); } if("GET" == requestData.method || "POST" == requestData.method){ //serve static files QString fullPath = docRoot + requestData.url.path(); QFileInfo f(fullPath); qDebug() << requestData.method << " " << fullPath; if(f.exists() && f.isReadable()){ if(f.isDir()){ response = serveStaticDir(response, f.absoluteFilePath()); } else{ response = serveStaticFile(response, f.absoluteFilePath()); if(response.isEmpty()){ response = responseStatusLine.arg( "500 Internal Server Error\r\n").toAscii(); } } } /* TODO: load HTTPSCripts via HTTPScriptLoader (.so and .dll files) ? * -> evolve this into FastCGI? read more * * or at least create a mapping of path -> method * *What's below isn't good because I have to modify the daemon every *time I want new functionality and the "login", "check", etc. methods are not a semantic part of HTTPThread */ else if("/patrat" == requestData.url.path()){ response = square(response, requestData); } else if("/login" == requestData.url.path()){ response = login(response, requestData); } else if("/verifica" == requestData.url.path()){ response = check(response, requestData); } else if(!f.exists()){ response = responseStatusLine.arg("404 Not Found\r\n").toAscii(); } else if(!f.isReadable()){ qDebug() << "Not readable!"; response = responseStatusLine.arg("403 Forbidden\r\n").toAscii() + "Permission denied\n"; } } else{ response = responseStatusLine.arg("501 Not Implemented\r\n").toAscii(); qDebug() << "Unsupported HTTP method!"; } return response; return responseStatusLine.arg("200 OK\r\n").toAscii(); } QByteArray HTTPThread::serveStaticFile(const QByteArray &partialResponse, const QString &filePath) { //TODO: set the mime type QFile file(filePath); if(!file.open( QIODevice::ReadOnly)){ qDebug() << "Cannot open"; return ""; } return partialResponse + "\r\n" + file.readAll(); } QByteArray HTTPThread::serveStaticDir(const QByteArray &partialResponse, const QString &dirPath) { QDir dir(dirPath); QStringList dirList = dir.entryList(); if(dirList.isEmpty()){ return responseStatusLine.arg("404 Not Found\r\n").toAscii(); } //TODO: format as HTML return partialResponse + "Content-Type: text/plain\r\n\r\n" + dirList.join("\n").toUtf8(); } QByteArray HTTPThread::square(const QByteArray &partialResponse, const RequestData &requestData) { if("GET" != requestData.method || !requestData.url.hasQueryItem("a")){ return responseStatusLine.arg("400 Bad Request\r\n").toAscii(); } QString numToSquare = requestData.url.queryItemValue("a"); QString body; bool ok; double n = numToSquare.toDouble(&ok); if(!ok){ body = "a-ul trebuie sa fie numar!\n"; } else{ body = numToSquare + "^2 = " + QString::number(n*n) + "\n"; } return partialResponse + "\r\n" + body.toAscii(); } QByteArray HTTPThread::login(const QByteArray &partialResponse, const RequestData &requestData) { QString page = "\r\n<html><body>" "<form method=\"POST\">" "%1" "Username: <input type=\"text\" name=\"username\">" "Password: <input type=\"password\" name=\"pass\">" "<INPUT type=\"submit\" value=\"Auth\">" "</form></body></html>"; if("GET" == requestData.method){ return partialResponse + page.arg("").toAscii(); } if("POST" == requestData.method && !requestData.postData.isEmpty()){ if(requestData.postData.contains("username") && "Ion" == requestData.postData["username"] && requestData.postData.contains("pass") && "1234" == requestData.postData["pass"]){ return partialResponse + "Set-Cookie: loggedin=1\r\n\r\nYou're logged in!"; } return partialResponse + page.arg("Login failed, try again!<br>").toAscii(); } return responseStatusLine.arg("400 Bad request\r\n").toAscii(); } QByteArray HTTPThread::check(const QByteArray &partialResponse, const RequestData &requestData) { if("GET" != requestData.method){ return responseStatusLine.arg("400 Bad request\r\n").toAscii(); } if(requestData.fields.contains("Cookie") && "loggedin=1" == requestData.fields["Cookie"][0]){ return partialResponse + "\r\nYou're logged in!"; } return partialResponse + "\r\nYou're not logged in!";; } <commit_msg>TODO cleanup<commit_after>#include <QtNetwork/QTcpSocket> #include <QFileInfo> #include <QFile> #include <QStringList> #include <QDir> #include "httpthread.h" HTTPThread::HTTPThread(const int socketDescriptor, const QString &docRoot, QObject *parent) : QThread(parent), socketDescriptor(socketDescriptor), docRoot(docRoot), responseStatusLine("HTTP/1.0 %1\r\n") { } void HTTPThread::run() { QTcpSocket socket; if(!socket.setSocketDescriptor(socketDescriptor)){ qDebug() << "Setting the sd has failed: " << socket.errorString(); emit error(socket.error()); return; } QString request = readRequest(&socket); qDebug() << request; //TODO: create a ResponseData struct instead of running around with QStrings? QByteArray response = processRequestData(parseHTTPRequest(request)); socket.write(response, response.size()); if(!socket.waitForBytesWritten()){ qDebug() << "Could not write byts to socket: " << socket.errorString(); emit error(socket.error()); } socket.close(); } QString HTTPThread::readRequest(QTcpSocket *socket){ QString request; //TODO: what if is a POST? do{ if(!socket->waitForReadyRead()){ qDebug() << "Error while waiting for client data: " << socket->errorString(); emit error(socket->error()); return request; } request.append(QString(socket->readAll())); }while(-1 == request.lastIndexOf("\n\n") && -1 == request.lastIndexOf("\r\n\r\n")); return request; } RequestData HTTPThread::parseHTTPRequest(QString request) { RequestData requestData; requestData.valid = false; QStringList parts = request.replace("\r", "").split("\n\n", QString::SkipEmptyParts); if(parts.isEmpty()){ return requestData; } QStringList fields = parts[0].split("\n", QString::SkipEmptyParts); qDebug() << "Fields" << fields; QStringList statusLine = fields[0].split(" "); if(3 != statusLine.size()){ return requestData; } QStringList protocol = statusLine[2].split("/"); bool ok; if(2 != protocol.size()){ return requestData; } double ver = protocol[1].toDouble(&ok); if("HTTP" != protocol[0] || !ok || ver < 0.9 || ver > 1.1){ return requestData; } requestData.method = statusLine[0]; requestData.url.setUrl(statusLine[1]); requestData.protocol = protocol[0]; requestData.protocolVersion = ver; fields.removeAt(0); int spacePos; foreach(QString line, fields){ spacePos = line.indexOf(" "); requestData.fields.insert(line.left(spacePos-1), QStringList(line.right(line.size()-spacePos-1))); } if(requestData.fields.contains("Host")){ requestData.fields["Host"] = requestData.fields["Host"][0].split(":"); } if("POST" == requestData.method && 2 == parts.size() && !parts[1].isEmpty()){ requestData.postData = parsePostBody(parts[1]); if(requestData.postData.isEmpty()){ return requestData; } } qDebug() << "Request data:\n\tStatusLine:\n\t\tMethod: " << requestData.method << "\n\t\tUrl: " << requestData.url << "\n\t\tProtocol: " << requestData.protocol << "\n\t\tVer: " <<requestData.protocolVersion << "\n\tFields: " << requestData.fields << "\n\tpost: " << requestData.postData; requestData.valid = true; return requestData; } QHash<QString, QString> HTTPThread::parsePostBody(QString postBody) { QHash<QString, QString> retval; QStringList pairs = postBody.split("&", QString::SkipEmptyParts); foreach(QString pair, pairs){ QStringList keyVal = pair.split("="); //TODO: URL-decode these retval.insert(keyVal[0], keyVal[1]); } return retval; } QByteArray HTTPThread::processRequestData(const RequestData &requestData) { //TODO: add support for different Host values? //TODO: URL rewriting? QByteArray response = responseStatusLine.arg("200 OK").toUtf8(); if(!requestData.valid){ return responseStatusLine.arg("400 Bad request\r\n").toAscii(); } if("GET" == requestData.method || "POST" == requestData.method){ //serve static files QString fullPath = docRoot + requestData.url.path(); QFileInfo f(fullPath); qDebug() << requestData.method << " " << fullPath; if(f.exists() && f.isReadable()){ if(f.isDir()){ response = serveStaticDir(response, f.absoluteFilePath()); } else{ response = serveStaticFile(response, f.absoluteFilePath()); if(response.isEmpty()){ response = responseStatusLine.arg( "500 Internal Server Error\r\n").toAscii(); } } } /* TODO: load things via a common interface from .so and .dll files? * -> evolve this into FastCGI? read more * * or at least create a mapping of path -> method * * What's below isn't good because I have to modify the daemon every * time I want new functionality and the "login", "check", etc. * methods are not a semantic part of HTTPThread */ else if("/patrat" == requestData.url.path()){ response = square(response, requestData); } else if("/login" == requestData.url.path()){ response = login(response, requestData); } else if("/verifica" == requestData.url.path()){ response = check(response, requestData); } else if(!f.exists()){ response = responseStatusLine.arg("404 Not Found\r\n").toAscii(); } else if(!f.isReadable()){ qDebug() << "Not readable!"; response = responseStatusLine.arg("403 Forbidden\r\n").toAscii() + "Permission denied\n"; } } else{ response = responseStatusLine.arg("501 Not Implemented\r\n").toAscii(); qDebug() << "Unsupported HTTP method!"; } return response; return responseStatusLine.arg("200 OK\r\n").toAscii(); } QByteArray HTTPThread::serveStaticFile(const QByteArray &partialResponse, const QString &filePath) { //TODO: set the mime type QFile file(filePath); if(!file.open( QIODevice::ReadOnly)){ qDebug() << "Cannot open"; return ""; } return partialResponse + "\r\n" + file.readAll(); } QByteArray HTTPThread::serveStaticDir(const QByteArray &partialResponse, const QString &dirPath) { QDir dir(dirPath); QStringList dirList = dir.entryList(); if(dirList.isEmpty()){ return responseStatusLine.arg("404 Not Found\r\n").toAscii(); } //TODO: format as HTML return partialResponse + "Content-Type: text/plain\r\n\r\n" + dirList.join("\n").toUtf8(); } QByteArray HTTPThread::square(const QByteArray &partialResponse, const RequestData &requestData) { if("GET" != requestData.method || !requestData.url.hasQueryItem("a")){ return responseStatusLine.arg("400 Bad Request\r\n").toAscii(); } QString numToSquare = requestData.url.queryItemValue("a"); QString body; bool ok; double n = numToSquare.toDouble(&ok); if(!ok){ body = "a-ul trebuie sa fie numar!\n"; } else{ body = numToSquare + "^2 = " + QString::number(n*n) + "\n"; } return partialResponse + "\r\n" + body.toAscii(); } QByteArray HTTPThread::login(const QByteArray &partialResponse, const RequestData &requestData) { QString page = "\r\n<html><body>" "<form method=\"POST\">" "%1" "Username: <input type=\"text\" name=\"username\">" "Password: <input type=\"password\" name=\"pass\">" "<INPUT type=\"submit\" value=\"Auth\">" "</form></body></html>"; if("GET" == requestData.method){ return partialResponse + page.arg("").toAscii(); } if("POST" == requestData.method && !requestData.postData.isEmpty()){ if(requestData.postData.contains("username") && "Ion" == requestData.postData["username"] && requestData.postData.contains("pass") && "1234" == requestData.postData["pass"]){ return partialResponse + "Set-Cookie: loggedin=1\r\n\r\nYou're logged in!"; } return partialResponse + page.arg("Login failed, try again!<br>").toAscii(); } return responseStatusLine.arg("400 Bad request\r\n").toAscii(); } QByteArray HTTPThread::check(const QByteArray &partialResponse, const RequestData &requestData) { if("GET" != requestData.method){ return responseStatusLine.arg("400 Bad request\r\n").toAscii(); } if(requestData.fields.contains("Cookie") && "loggedin=1" == requestData.fields["Cookie"][0]){ return partialResponse + "\r\nYou're logged in!"; } return partialResponse + "\r\nYou're not logged in!";; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // system implementation headers #include <math.h> // common implementation headers #include "BZDBCache.h" #include "AnsiCodes.h" #include "TextUtils.h" #include "CommandsStandard.h" #include "StateDatabase.h" // local implementation headers #include "LocalCommand.h" #include "Player.h" #include "Roster.h" #include "playing.h" // externs for RoamPos command extern float roamPos[3]; extern float roamTheta; extern float roamPhi; extern float roamZoom; static float parseFloatExpr(const std::string& str, bool zeroNan) { // BZDB.eval() can't take expressions directly BZDB.set("tmp", str); BZDB.setPersistent("tmp", false); float value = BZDB.eval("tmp"); if (!zeroNan) { return value; } else { if (value == value) { return value; } else { return 0.0f; } } } class SilenceCommand : LocalCommand { public: SilenceCommand(); virtual bool operator() (const char *commandLine); }; class UnsilenceCommand : LocalCommand { public: UnsilenceCommand(); virtual bool operator() (const char *commandLine); }; class DumpCommand : LocalCommand { public: DumpCommand(); virtual bool operator() (const char *commandLine); }; class ClientQueryCommand : LocalCommand { public: ClientQueryCommand(); virtual bool operator() (const char *commandLine); }; class HighlightCommand : LocalCommand { public: HighlightCommand(); virtual bool operator() (const char *commandLine); }; class SetCommand : LocalCommand { public: SetCommand(); virtual bool operator() (const char *commandLine); }; class DiffCommand : LocalCommand { public: DiffCommand(); virtual bool operator() (const char *commandLine); }; class LocalSetCommand : LocalCommand { public: LocalSetCommand(); virtual bool operator() (const char *commandLine); }; class QuitCommand : LocalCommand { public: QuitCommand(); virtual bool operator() (const char *commandLine); }; class RoamPosCommand : LocalCommand { public: RoamPosCommand(); virtual bool operator() (const char *commandLine); }; static SilenceCommand silenceCommand; static UnsilenceCommand unsilenceCommand; static DumpCommand dumpCommand; static ClientQueryCommand clientQueryCommand; static HighlightCommand highlightCommand; static SetCommand setCommand; static DiffCommand diffCommand; static LocalSetCommand localSetCommand; static QuitCommand quitCommand; static RoamPosCommand roamPosCommand; SilenceCommand::SilenceCommand() : LocalCommand("SILENCE") { } bool SilenceCommand::operator() (const char *commandLine) { Player *loudmouth = getPlayerByName(commandLine + 8); if (loudmouth) { silencePlayers.push_back(commandLine + 8); std::string silenceMessage = "Silenced "; silenceMessage += (commandLine + 8); addMessage(NULL, silenceMessage); } return true; } UnsilenceCommand::UnsilenceCommand() : LocalCommand("UNSILENCE") { } bool UnsilenceCommand::operator() (const char *commandLine) { Player *loudmouth = getPlayerByName(commandLine + 10); if (loudmouth) { std::vector<std::string>::iterator it = silencePlayers.begin(); for (; it != silencePlayers.end(); it++) { if (*it == commandLine + 10) { silencePlayers.erase(it); std::string unsilenceMessage = "Unsilenced "; unsilenceMessage += (commandLine + 10); addMessage(NULL, unsilenceMessage); break; } } } return true; } void printout(const std::string& name, void*) { std::cout << name << " = " << BZDB.get(name) << std::endl; } DumpCommand::DumpCommand() : LocalCommand("DUMP") { } bool DumpCommand::operator() (const char *) { BZDB.iterate(printout, NULL); return true; } ClientQueryCommand::ClientQueryCommand() : LocalCommand("CLIENTQUERY") { } bool ClientQueryCommand::operator() (const char *commandLine) { if (strlen(commandLine) != 11) return false; char messageBuffer[MessageLen]; memset(messageBuffer, 0, MessageLen); strncpy(messageBuffer, "/clientquery", MessageLen); nboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen); serverLink->send(MsgMessage, sizeof(messageMessage), messageMessage); return true; } HighlightCommand::HighlightCommand() : LocalCommand("/highlight") { } bool HighlightCommand::operator() (const char *commandLine) { const char* c = commandLine + 10; while ((*c != '\0') && isspace(*c)) c++; // skip leading white BZDB.set("highlightPattern", std::string(c)); return true; } static bool foundVarDiff = false; static bool varIsEqual(const std::string& name) { // avoid "poll" if (name[0] != '_') { return true; } // get the parameters const std::string exp = BZDB.get(name); const std::string defexp = BZDB.getDefault(name); const float val = BZDB.eval(name); const float defval = parseFloatExpr(defexp, false); const bool valNaN = !(val == val); const bool defNaN = !(defval == defval); if (valNaN != defNaN) { return false; } if (valNaN) { return (exp == defexp); } else { return (val == defval); } } static void listSetVars(const std::string& name, void* boolPtr) { bool& diff = *((bool*)boolPtr); if (diff) { if (varIsEqual(name)) { return; } else { foundVarDiff = true; } } char message[MessageLen]; if (BZDB.getPermission(name) == StateDatabase::Locked) { if (BZDBCache::colorful) { sprintf(message, "/set %s%s %s%f %s%s", ColorStrings[RedColor].c_str(), name.c_str(), ColorStrings[GreenColor].c_str(), BZDB.eval(name), ColorStrings[BlueColor].c_str(), BZDB.get(name).c_str()); } else { sprintf(message, "/set %s <%f> %s", name.c_str(), BZDB.eval(name), BZDB.get(name).c_str()); } addMessage(LocalPlayer::getMyTank(), message, 2); } } SetCommand::SetCommand() : LocalCommand("/set") { } bool SetCommand::operator() (const char *commandLine) { if (strlen(commandLine) != 4) return false; bool diff = false; BZDB.iterate(listSetVars, &diff); return true; } DiffCommand::DiffCommand() : LocalCommand("/diff") { } bool DiffCommand::operator() (const char *commandLine) { if (strlen(commandLine) != 5) return false; bool diff = true; foundVarDiff = false; BZDB.iterate(listSetVars, &diff); if (!foundVarDiff) { addMessage(LocalPlayer::getMyTank(), "all variables are at defaults", 2); } return true; } LocalSetCommand::LocalSetCommand() : LocalCommand("/localset") { } bool LocalSetCommand::operator() (const char *commandLine) { std::string params = commandLine + 9; std::vector<std::string> tokens = TextUtils::tokenize(params, " ", 2); if (tokens.size() == 2) { if (!(BZDB.getPermission(tokens[0]) == StateDatabase::Server)) { BZDB.setPersistent(tokens[0], BZDB.isPersistent(tokens[0])); BZDB.set(tokens[0], tokens[1]); std::string msg = "/localset " + tokens[0] + " " + tokens[1]; addMessage(NULL, msg); } else { addMessage (NULL, "This is a server-defined variable. Use /set instead of /localset."); } } else { addMessage(NULL, "usage: /localset <variable> <value>"); } return true; } QuitCommand::QuitCommand() : LocalCommand("/quit") { } bool QuitCommand::operator() (const char *commandLine) { char messageBuffer[MessageLen]; // send message memset(messageBuffer, 0, MessageLen); strncpy(messageBuffer, commandLine, MessageLen); nboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen); serverLink->send(MsgMessage, sizeof(messageMessage), messageMessage); CommandsStandard::quit(); // kill client return true; } RoamPosCommand::RoamPosCommand() : LocalCommand("/roampos") { } bool RoamPosCommand::operator() (const char *commandLine) { // change the observer position and orientation const char infoStr[] = "/roampos [ \"reset\" | degrees | {x y z [theta [phi [zoom]]]} ]"; std::string params = commandLine + 8; std::vector<std::string> tokens = TextUtils::tokenize(params, " "); if (tokens.size() == 1) { if (TextUtils::tolower(tokens[0]) == "reset") { roamPos[0] = 0.0f; roamPos[1] = 0.0f; roamPos[2] = BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); roamTheta = 0.0f; roamPhi = -0.0f; roamZoom = 60.0f; } else { const float degrees = parseFloatExpr(tokens[0], true); const float ws = BZDB.eval(StateDatabase::BZDB_WORLDSIZE); const float radians = degrees * (M_PI/180.0f); roamPos[0] = cosf(radians)* 0.5f * ws * M_SQRT2; roamPos[1] = sinf(radians)* 0.5f * ws * M_SQRT2; roamPos[2] = +0.25 * ws; roamTheta = degrees + 180.0f; roamPhi = -30.0f; roamZoom = 60.0f; } } else if (tokens.size() >= 3) { roamPos[0] = parseFloatExpr(tokens[0], true); roamPos[1] = parseFloatExpr(tokens[1], true); roamPos[2] = parseFloatExpr(tokens[2], true); if (tokens.size() >= 4) { roamTheta = parseFloatExpr(tokens[3], true); } if (tokens.size() >= 5) { roamPhi = parseFloatExpr(tokens[4], true); } if (tokens.size() == 6) { roamZoom = parseFloatExpr(tokens[5], true); } } else { addMessage(NULL, infoStr); } return true; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>casts and constants and headers, oh my!<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // BZFlag common header #include "common.h" // system implementation headers #include <math.h> // common implementation headers #include "BZDBCache.h" #include "AnsiCodes.h" #include "TextUtils.h" #include "CommandsStandard.h" #include "StateDatabase.h" // local implementation headers #include "LocalCommand.h" #include "Player.h" #include "Roster.h" #include "playing.h" // externs for RoamPos command extern float roamPos[3]; extern float roamTheta; extern float roamPhi; extern float roamZoom; static float parseFloatExpr(const std::string& str, bool zeroNan) { // BZDB.eval() can't take expressions directly BZDB.set("tmp", str); BZDB.setPersistent("tmp", false); float value = BZDB.eval("tmp"); if (!zeroNan) { return value; } else { if (value == value) { return value; } else { return 0.0f; } } } class SilenceCommand : LocalCommand { public: SilenceCommand(); virtual bool operator() (const char *commandLine); }; class UnsilenceCommand : LocalCommand { public: UnsilenceCommand(); virtual bool operator() (const char *commandLine); }; class DumpCommand : LocalCommand { public: DumpCommand(); virtual bool operator() (const char *commandLine); }; class ClientQueryCommand : LocalCommand { public: ClientQueryCommand(); virtual bool operator() (const char *commandLine); }; class HighlightCommand : LocalCommand { public: HighlightCommand(); virtual bool operator() (const char *commandLine); }; class SetCommand : LocalCommand { public: SetCommand(); virtual bool operator() (const char *commandLine); }; class DiffCommand : LocalCommand { public: DiffCommand(); virtual bool operator() (const char *commandLine); }; class LocalSetCommand : LocalCommand { public: LocalSetCommand(); virtual bool operator() (const char *commandLine); }; class QuitCommand : LocalCommand { public: QuitCommand(); virtual bool operator() (const char *commandLine); }; class RoamPosCommand : LocalCommand { public: RoamPosCommand(); virtual bool operator() (const char *commandLine); }; static SilenceCommand silenceCommand; static UnsilenceCommand unsilenceCommand; static DumpCommand dumpCommand; static ClientQueryCommand clientQueryCommand; static HighlightCommand highlightCommand; static SetCommand setCommand; static DiffCommand diffCommand; static LocalSetCommand localSetCommand; static QuitCommand quitCommand; static RoamPosCommand roamPosCommand; SilenceCommand::SilenceCommand() : LocalCommand("SILENCE") { } bool SilenceCommand::operator() (const char *commandLine) { Player *loudmouth = getPlayerByName(commandLine + 8); if (loudmouth) { silencePlayers.push_back(commandLine + 8); std::string silenceMessage = "Silenced "; silenceMessage += (commandLine + 8); addMessage(NULL, silenceMessage); } return true; } UnsilenceCommand::UnsilenceCommand() : LocalCommand("UNSILENCE") { } bool UnsilenceCommand::operator() (const char *commandLine) { Player *loudmouth = getPlayerByName(commandLine + 10); if (loudmouth) { std::vector<std::string>::iterator it = silencePlayers.begin(); for (; it != silencePlayers.end(); it++) { if (*it == commandLine + 10) { silencePlayers.erase(it); std::string unsilenceMessage = "Unsilenced "; unsilenceMessage += (commandLine + 10); addMessage(NULL, unsilenceMessage); break; } } } return true; } void printout(const std::string& name, void*) { std::cout << name << " = " << BZDB.get(name) << std::endl; } DumpCommand::DumpCommand() : LocalCommand("DUMP") { } bool DumpCommand::operator() (const char *) { BZDB.iterate(printout, NULL); return true; } ClientQueryCommand::ClientQueryCommand() : LocalCommand("CLIENTQUERY") { } bool ClientQueryCommand::operator() (const char *commandLine) { if (strlen(commandLine) != 11) return false; char messageBuffer[MessageLen]; memset(messageBuffer, 0, MessageLen); strncpy(messageBuffer, "/clientquery", MessageLen); nboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen); serverLink->send(MsgMessage, sizeof(messageMessage), messageMessage); return true; } HighlightCommand::HighlightCommand() : LocalCommand("/highlight") { } bool HighlightCommand::operator() (const char *commandLine) { const char* c = commandLine + 10; while ((*c != '\0') && isspace(*c)) c++; // skip leading white BZDB.set("highlightPattern", std::string(c)); return true; } static bool foundVarDiff = false; static bool varIsEqual(const std::string& name) { // avoid "poll" if (name[0] != '_') { return true; } // get the parameters const std::string exp = BZDB.get(name); const std::string defexp = BZDB.getDefault(name); const float val = BZDB.eval(name); const float defval = parseFloatExpr(defexp, false); const bool valNaN = !(val == val); const bool defNaN = !(defval == defval); if (valNaN != defNaN) { return false; } if (valNaN) { return (exp == defexp); } else { return (val == defval); } } static void listSetVars(const std::string& name, void* boolPtr) { bool& diff = *((bool*)boolPtr); if (diff) { if (varIsEqual(name)) { return; } else { foundVarDiff = true; } } char message[MessageLen]; if (BZDB.getPermission(name) == StateDatabase::Locked) { if (BZDBCache::colorful) { sprintf(message, "/set %s%s %s%f %s%s", ColorStrings[RedColor].c_str(), name.c_str(), ColorStrings[GreenColor].c_str(), BZDB.eval(name), ColorStrings[BlueColor].c_str(), BZDB.get(name).c_str()); } else { sprintf(message, "/set %s <%f> %s", name.c_str(), BZDB.eval(name), BZDB.get(name).c_str()); } addMessage(LocalPlayer::getMyTank(), message, 2); } } SetCommand::SetCommand() : LocalCommand("/set") { } bool SetCommand::operator() (const char *commandLine) { if (strlen(commandLine) != 4) return false; bool diff = false; BZDB.iterate(listSetVars, &diff); return true; } DiffCommand::DiffCommand() : LocalCommand("/diff") { } bool DiffCommand::operator() (const char *commandLine) { if (strlen(commandLine) != 5) return false; bool diff = true; foundVarDiff = false; BZDB.iterate(listSetVars, &diff); if (!foundVarDiff) { addMessage(LocalPlayer::getMyTank(), "all variables are at defaults", 2); } return true; } LocalSetCommand::LocalSetCommand() : LocalCommand("/localset") { } bool LocalSetCommand::operator() (const char *commandLine) { std::string params = commandLine + 9; std::vector<std::string> tokens = TextUtils::tokenize(params, " ", 2); if (tokens.size() == 2) { if (!(BZDB.getPermission(tokens[0]) == StateDatabase::Server)) { BZDB.setPersistent(tokens[0], BZDB.isPersistent(tokens[0])); BZDB.set(tokens[0], tokens[1]); std::string msg = "/localset " + tokens[0] + " " + tokens[1]; addMessage(NULL, msg); } else { addMessage (NULL, "This is a server-defined variable. Use /set instead of /localset."); } } else { addMessage(NULL, "usage: /localset <variable> <value>"); } return true; } QuitCommand::QuitCommand() : LocalCommand("/quit") { } bool QuitCommand::operator() (const char *commandLine) { char messageBuffer[MessageLen]; // send message memset(messageBuffer, 0, MessageLen); strncpy(messageBuffer, commandLine, MessageLen); nboPackString(messageMessage + PlayerIdPLen, messageBuffer, MessageLen); serverLink->send(MsgMessage, sizeof(messageMessage), messageMessage); CommandsStandard::quit(); // kill client return true; } RoamPosCommand::RoamPosCommand() : LocalCommand("/roampos") { } bool RoamPosCommand::operator() (const char *commandLine) { // change the observer position and orientation const char infoStr[] = "/roampos [ \"reset\" | degrees | {x y z [theta [phi [zoom]]]} ]"; std::string params = commandLine + 8; std::vector<std::string> tokens = TextUtils::tokenize(params, " "); if (tokens.size() == 1) { if (TextUtils::tolower(tokens[0]) == "reset") { roamPos[0] = 0.0f; roamPos[1] = 0.0f; roamPos[2] = BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT); roamTheta = 0.0f; roamPhi = -0.0f; roamZoom = 60.0f; } else { const float degrees = parseFloatExpr(tokens[0], true); const float ws = BZDB.eval(StateDatabase::BZDB_WORLDSIZE); const float radians = degrees * ((float)M_PI/180.0f); roamPos[0] = cosf(radians)* 0.5f * ws * (float)M_SQRT2; roamPos[1] = sinf(radians)* 0.5f * ws * (float)M_SQRT2; roamPos[2] = +0.25f * ws; roamTheta = degrees + 180.0f; roamPhi = -30.0f; roamZoom = 60.0f; } } else if (tokens.size() >= 3) { roamPos[0] = parseFloatExpr(tokens[0], true); roamPos[1] = parseFloatExpr(tokens[1], true); roamPos[2] = parseFloatExpr(tokens[2], true); if (tokens.size() >= 4) { roamTheta = parseFloatExpr(tokens[3], true); } if (tokens.size() >= 5) { roamPhi = parseFloatExpr(tokens[4], true); } if (tokens.size() == 6) { roamZoom = parseFloatExpr(tokens[5], true); } } else { addMessage(NULL, infoStr); } return true; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // RawView plugin //============================================================================== #include "cliutils.h" #include "rawviewplugin.h" #include "rawviewwidget.h" //============================================================================== #include <QMainWindow> #include <QSettings> //============================================================================== namespace OpenCOR { namespace RawView { //============================================================================== PLUGININFO_FUNC RawViewPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin to edit files using a text editor.")); descriptions.insert("fr", QString::fromUtf8("une extension pour éditer des fichiers à l'aide d'un éditeur de texte.")); return new PluginInfo(PluginInfo::Editing, true, QStringList() << "CoreEditing", descriptions); } //============================================================================== RawViewPlugin::RawViewPlugin() : mViewWidgets(QMap<QString, RawViewWidget *>()), mEditorZoomLevel(0) { // Set our settings mGuiSettings->setView(GuiViewSettings::Editing, QStringList()); } //============================================================================== RawViewPlugin::~RawViewPlugin() { // Delete our view widgets foreach (QWidget *viewWidget, mViewWidgets) delete viewWidget; } //============================================================================== // Core interface //============================================================================== void RawViewPlugin::initialize() { // We don't handle this interface... } //============================================================================== void RawViewPlugin::finalize() { // We don't handle this interface... } //============================================================================== void RawViewPlugin::initialized(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== static const auto SettingsRawViewWidget = QStringLiteral("RawViewWidget"); static const auto SettingsRawViewWidgetEditorZoomLevel = QStringLiteral("EditorZoomLevel"); //============================================================================== void RawViewPlugin::loadSettings(QSettings *pSettings) { // Retrieve the zoom level of our editors pSettings->beginGroup(SettingsRawViewWidget); mEditorZoomLevel = pSettings->value(SettingsRawViewWidgetEditorZoomLevel, 0).toInt(); pSettings->endGroup(); } //============================================================================== void RawViewPlugin::saveSettings(QSettings *pSettings) const { // Keep track of the zoom level of our editors pSettings->beginGroup(SettingsRawViewWidget); pSettings->setValue(SettingsRawViewWidgetEditorZoomLevel, mEditorZoomLevel); pSettings->endGroup(); } //============================================================================== void RawViewPlugin::settingsLoaded(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void RawViewPlugin::handleArguments(const QStringList &pArguments) { Q_UNUSED(pArguments); // We don't handle this interface... } //============================================================================== void RawViewPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== // Editing interface //============================================================================== QScintillaSupport::QScintillaWidget * RawViewPlugin::editor(const QString &pFileName) const { // Return the requested editor return mViewWidgets.value(pFileName); } //============================================================================== // GUI interface //============================================================================== void RawViewPlugin::changeEvent(QEvent *pEvent) { Q_UNUSED(pEvent); // We don't handle this interface... } //============================================================================== void RawViewPlugin::updateGui(Plugin *pViewPlugin, const QString &pFileName) { Q_UNUSED(pViewPlugin); Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void RawViewPlugin::initializeView() { // We don't handle this interface... } //============================================================================== void RawViewPlugin::finalizeView() { // We don't handle this interface... } //============================================================================== bool RawViewPlugin::hasViewWidget(const QString &pFileName) { // Return whether we have a view widget associated with the given file return mViewWidgets.value(pFileName); } //============================================================================== QWidget * RawViewPlugin::viewWidget(const QString &pFileName, const bool &pCreate) { // Retrieve from our list the view widget associated with the file name RawViewWidget *res = mViewWidgets.value(pFileName); // Create a new view widget, if none could be retrieved if (!res && pCreate) { res = new RawViewWidget(pFileName, mMainWindow); // Keep track of changes to its zoom level connect(res, SIGNAL(SCN_ZOOM()), this, SLOT(editorZoomLevelChanged())); // Keep track of our new view widget mViewWidgets.insert(pFileName, res); } // Set/update the view widget's zoom level if (res) res->zoomTo(mEditorZoomLevel); // Return our view widget return res; } //============================================================================== void RawViewPlugin::removeViewWidget(const QString &pFileName) { // Remove the view widget from our list, should there be one for the given // file name RawViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) { // There is a view widget for the given file name, so delete it and // remove it from our list delete viewWidget; mViewWidgets.remove(pFileName); } } //============================================================================== QString RawViewPlugin::viewName() const { // Return our raw view's name return tr("Raw"); } //============================================================================== QIcon RawViewPlugin::fileTabIcon(const QString &pFileName) const { Q_UNUSED(pFileName); // We don't handle this interface... return QIcon(); } //============================================================================== bool RawViewPlugin::saveFile(const QString &pOldFileName, const QString &pNewFileName) { // Ask the given file's corresponding view widget to save its contents RawViewWidget *viewWidget = mViewWidgets.value(pOldFileName); bool res = Core::writeTextToFile(pNewFileName, viewWidget->contents()); if (res) viewWidget->resetUndoHistory(); return res; } //============================================================================== void RawViewPlugin::fileOpened(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void RawViewPlugin::filePermissionsChanged(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void RawViewPlugin::fileModified(const QString &pFileName, const bool &pModified) { Q_UNUSED(pFileName); Q_UNUSED(pModified); // We don't handle this interface... } //============================================================================== void RawViewPlugin::fileReloaded(const QString &pFileName) { // The given file has been reloaded, so let its corresponding view widget // know about it RawViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) viewWidget->fileReloaded(); } //============================================================================== void RawViewPlugin::fileRenamed(const QString &pOldFileName, const QString &pNewFileName) { // Update our view widgets mapping mViewWidgets.insert(pNewFileName, mViewWidgets.value(pOldFileName)); mViewWidgets.remove(pOldFileName); // Also ask the given file's corresponding view widget to update its name mViewWidgets.value(pNewFileName)->fileRenamed(pNewFileName); } //============================================================================== void RawViewPlugin::fileClosed(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== bool RawViewPlugin::canClose() { // We don't handle this interface... return true; } //============================================================================== // I18n interface //============================================================================== void RawViewPlugin::retranslateUi() { // We don't handle this interface... } //============================================================================== // Plugin specific //============================================================================== void RawViewPlugin::editorZoomLevelChanged() { // One of our view widgets had its zoom level changed, so keep track of the // new zoom level mEditorZoomLevel = qobject_cast<RawViewWidget *>(sender())->SendScintilla(QsciScintillaBase::SCI_GETZOOM); } //============================================================================== } // namespace RawView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // RawView plugin //============================================================================== #include "cliutils.h" #include "rawviewplugin.h" #include "rawviewwidget.h" //============================================================================== #include <QMainWindow> #include <QSettings> //============================================================================== namespace OpenCOR { namespace RawView { //============================================================================== PLUGININFO_FUNC RawViewPluginInfo() { Descriptions descriptions; descriptions.insert("en", QString::fromUtf8("a plugin to edit files using a text editor.")); descriptions.insert("fr", QString::fromUtf8("une extension pour éditer des fichiers à l'aide d'un éditeur de texte.")); return new PluginInfo(PluginInfo::Editing, true, QStringList() << "CoreEditing", descriptions); } //============================================================================== RawViewPlugin::RawViewPlugin() : mViewWidgets(QMap<QString, RawViewWidget *>()), mEditorZoomLevel(0) { // Set our settings mGuiSettings->setView(GuiViewSettings::Editing, QStringList()); } //============================================================================== RawViewPlugin::~RawViewPlugin() { // Delete our view widgets foreach (QWidget *viewWidget, mViewWidgets) delete viewWidget; } //============================================================================== // Core interface //============================================================================== void RawViewPlugin::initialize() { // We don't handle this interface... } //============================================================================== void RawViewPlugin::finalize() { // We don't handle this interface... } //============================================================================== void RawViewPlugin::initialized(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== static const auto SettingsRawViewWidget = QStringLiteral("RawViewWidget"); static const auto SettingsRawViewWidgetEditorZoomLevel = QStringLiteral("EditorZoomLevel"); //============================================================================== void RawViewPlugin::loadSettings(QSettings *pSettings) { // Retrieve the zoom level of our editors pSettings->beginGroup(SettingsRawViewWidget); mEditorZoomLevel = pSettings->value(SettingsRawViewWidgetEditorZoomLevel, 0).toInt(); pSettings->endGroup(); } //============================================================================== void RawViewPlugin::saveSettings(QSettings *pSettings) const { // Keep track of the zoom level of our editors pSettings->beginGroup(SettingsRawViewWidget); pSettings->setValue(SettingsRawViewWidgetEditorZoomLevel, mEditorZoomLevel); pSettings->endGroup(); } //============================================================================== void RawViewPlugin::settingsLoaded(const Plugins &pLoadedPlugins) { Q_UNUSED(pLoadedPlugins); // We don't handle this interface... } //============================================================================== void RawViewPlugin::handleArguments(const QStringList &pArguments) { Q_UNUSED(pArguments); // We don't handle this interface... } //============================================================================== void RawViewPlugin::handleAction(const QUrl &pUrl) { Q_UNUSED(pUrl); // We don't handle this interface... } //============================================================================== // Editing interface //============================================================================== QScintillaSupport::QScintillaWidget * RawViewPlugin::editor(const QString &pFileName) const { // Return the requested editor return mViewWidgets.value(pFileName); } //============================================================================== // GUI interface //============================================================================== void RawViewPlugin::changeEvent(QEvent *pEvent) { Q_UNUSED(pEvent); // We don't handle this interface... } //============================================================================== void RawViewPlugin::updateGui(Plugin *pViewPlugin, const QString &pFileName) { Q_UNUSED(pViewPlugin); Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void RawViewPlugin::initializeView() { // We don't handle this interface... } //============================================================================== void RawViewPlugin::finalizeView() { // We don't handle this interface... } //============================================================================== bool RawViewPlugin::hasViewWidget(const QString &pFileName) { // Return whether we have a view widget associated with the given file return mViewWidgets.value(pFileName); } //============================================================================== QWidget * RawViewPlugin::viewWidget(const QString &pFileName, const bool &pCreate) { // Retrieve from our list the view widget associated with the file name RawViewWidget *res = mViewWidgets.value(pFileName); // Create a new view widget, if none could be retrieved if (!res && pCreate) { res = new RawViewWidget(pFileName, mMainWindow); // Keep track of changes to its zoom level connect(res, SIGNAL(SCN_ZOOM()), this, SLOT(editorZoomLevelChanged())); // Keep track of our new view widget mViewWidgets.insert(pFileName, res); } // Set/update the view widget's zoom level if (res) res->zoomTo(mEditorZoomLevel); // Return our view widget return res; } //============================================================================== void RawViewPlugin::removeViewWidget(const QString &pFileName) { // Remove the view widget from our list, should there be one for the given // file name RawViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) { // There is a view widget for the given file name, so delete it and // remove it from our list delete viewWidget; mViewWidgets.remove(pFileName); } } //============================================================================== QString RawViewPlugin::viewName() const { // Return our raw view's name return tr("Raw"); } //============================================================================== QIcon RawViewPlugin::fileTabIcon(const QString &pFileName) const { Q_UNUSED(pFileName); // We don't handle this interface... return QIcon(); } //============================================================================== bool RawViewPlugin::saveFile(const QString &pOldFileName, const QString &pNewFileName) { // Ask the given file's corresponding view widget to save its contents RawViewWidget *viewWidget = mViewWidgets.value(pOldFileName); bool res = Core::writeTextToFile(pNewFileName, viewWidget->contents()); if (res) viewWidget->resetUndoHistory(); return res; } //============================================================================== void RawViewPlugin::fileOpened(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void RawViewPlugin::filePermissionsChanged(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== void RawViewPlugin::fileModified(const QString &pFileName, const bool &pModified) { Q_UNUSED(pFileName); Q_UNUSED(pModified); // We don't handle this interface... } //============================================================================== void RawViewPlugin::fileReloaded(const QString &pFileName) { // The given file has been reloaded, so let its corresponding view widget // know about it RawViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) viewWidget->fileReloaded(); } //============================================================================== void RawViewPlugin::fileRenamed(const QString &pOldFileName, const QString &pNewFileName) { // Update our view widgets mapping RawViewWidget *viewWidget = mViewWidgets.value(pOldFileName); mViewWidgets.insert(pNewFileName, viewWidget); mViewWidgets.remove(pOldFileName); // Also ask the given file's corresponding view widget to update its name viewWidget->fileRenamed(pNewFileName); } //============================================================================== void RawViewPlugin::fileClosed(const QString &pFileName) { Q_UNUSED(pFileName); // We don't handle this interface... } //============================================================================== bool RawViewPlugin::canClose() { // We don't handle this interface... return true; } //============================================================================== // I18n interface //============================================================================== void RawViewPlugin::retranslateUi() { // We don't handle this interface... } //============================================================================== // Plugin specific //============================================================================== void RawViewPlugin::editorZoomLevelChanged() { // One of our view widgets had its zoom level changed, so keep track of the // new zoom level mEditorZoomLevel = qobject_cast<RawViewWidget *>(sender())->SendScintilla(QsciScintillaBase::SCI_GETZOOM); } //============================================================================== } // namespace RawView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include "qt4maemodeployconfiguration.h" #include "debianmanager.h" #include "maddeuploadandinstallpackagesteps.h" #include "maemoconstants.h" #include "maemodeploybymountsteps.h" #include "maemodeployconfigurationwidget.h" #include "maemoglobal.h" #include "maemoinstalltosysrootstep.h" #include "maemopackagecreationstep.h" #include <coreplugin/icore.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/target.h> #include <projectexplorer/projectexplorer.h> #include <qt4projectmanager/qt4buildconfiguration.h> #include <qt4projectmanager/qt4project.h> #include <qtsupport/qtprofileinformation.h> #include <qtsupport/qtsupportconstants.h> #include <remotelinux/deployablefile.h> #include <remotelinux/deployablefilesperprofile.h> #include <remotelinux/deploymentinfo.h> #include <remotelinux/remotelinuxcheckforfreediskspacestep.h> #include <utils/qtcassert.h> #include <QFileInfo> #include <QString> #include <QMainWindow> #include <QMessageBox> using namespace ProjectExplorer; using namespace Qt4ProjectManager; using namespace RemoteLinux; const char OldDeployConfigId[] = "2.2MaemoDeployConfig"; const char DEPLOYMENT_ASSISTANT_SETTING[] = "RemoteLinux.DeploymentAssistant"; namespace Madde { namespace Internal { Qt4MaemoDeployConfiguration::Qt4MaemoDeployConfiguration(ProjectExplorer::Target *target, const Core::Id id, const QString &displayName) : RemoteLinuxDeployConfiguration(target, id, displayName) { init(); } Qt4MaemoDeployConfiguration::Qt4MaemoDeployConfiguration(ProjectExplorer::Target *target, Qt4MaemoDeployConfiguration *source) : RemoteLinuxDeployConfiguration(target, source) { init(); } QString Qt4MaemoDeployConfiguration::localDesktopFilePath(const DeployableFilesPerProFile *proFileInfo) const { QTC_ASSERT(proFileInfo->projectType() == ApplicationTemplate, return QString()); for (int i = 0; i < proFileInfo->rowCount(); ++i) { const DeployableFile &d = proFileInfo->deployableAt(i); if (QFileInfo(d.localFilePath).fileName().endsWith(QLatin1String(".desktop"))) return d.localFilePath; } return QString(); } DeployConfigurationWidget *Qt4MaemoDeployConfiguration::configurationWidget() const { return new MaemoDeployConfigurationWidget; } Qt4MaemoDeployConfiguration::~Qt4MaemoDeployConfiguration() {} Core::Id Qt4MaemoDeployConfiguration::fremantleWithPackagingId() { return Core::Id("DeployToFremantleWithPackaging"); } Core::Id Qt4MaemoDeployConfiguration::fremantleWithoutPackagingId() { return Core::Id("DeployToFremantleWithoutPackaging"); } Core::Id Qt4MaemoDeployConfiguration::harmattanId() { return Core::Id("DeployToHarmattan"); } DeploymentSettingsAssistant *Qt4MaemoDeployConfiguration::deploymentSettingsAssistant() { return static_cast<DeploymentSettingsAssistant *>(target()->project()->namedSettings(QLatin1String(DEPLOYMENT_ASSISTANT_SETTING)).value<QObject *>()); } QString Qt4MaemoDeployConfiguration::qmakeScope() const { Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(target()->profile()); if (deviceType == Maemo5OsType) return QLatin1String("maemo5"); if (deviceType == HarmattanOsType) return QLatin1String("contains(MEEGO_EDITION,harmattan)"); return QString("unix"); } QString Qt4MaemoDeployConfiguration::installPrefix() const { Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(target()->profile()); if (deviceType == Maemo5OsType) return QLatin1String("/opt"); if (deviceType == HarmattanOsType) return QLatin1String("/opt"); return QLatin1String("/usr/local"); } void Qt4MaemoDeployConfiguration::debianDirChanged(const Utils::FileName &dir) { if (dir == DebianManager::debianDirectory(target())) emit packagingChanged(); } void Qt4MaemoDeployConfiguration::setupPackaging() { if (target()->project()->activeTarget() != target()) return; disconnect(target()->project(), SIGNAL(fileListChanged()), this, SLOT(setupPackaging())); setupDebianPackaging(); } void Qt4MaemoDeployConfiguration::setupDebianPackaging() { Qt4BuildConfiguration *bc = qobject_cast<Qt4BuildConfiguration *>(target()->activeBuildConfiguration()); if (!bc || !target()->profile()) return; Utils::FileName debianDir = DebianManager::debianDirectory(target()); Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(target()->profile()); DebianManager *dm = DebianManager::instance(); QString projectName = target()->project()->displayName(); DebianManager::ActionStatus status = DebianManager::createTemplate(bc, debianDir); if (status == DebianManager::NoActionRequired || status == DebianManager::ActionFailed) return; if (!DebianManager::hasPackageManagerIcon(debianDir)) { // Such a file is created by the mobile wizards. Utils::FileName iconPath = Utils::FileName::fromString(target()->project()->projectDirectory()); iconPath.appendPath(projectName + QLatin1String("64.png")); if (iconPath.toFileInfo().exists()) dm->setPackageManagerIcon(debianDir, deviceType, iconPath); } dm->monitor(debianDir); connect(dm, SIGNAL(debianDirectoryChanged(Utils::FileName)), this, SLOT(debianDirChanged(Utils::FileName))); // Set up aegis manifest on harmattan: if (deviceType == HarmattanOsType) { Utils::FileName manifest = debianDir; const QString manifestName = QLatin1String("manifest.aegis"); manifest.appendPath(manifestName); const QFile aegisFile(manifest.toString()); if (!aegisFile.exists()) { Utils::FileReader reader; if (!reader.fetch(Core::ICore::resourcePath() + QLatin1String("/templates/shared/") + manifestName)) { qDebug("Reading manifest template failed."); return; } QString content = QString::fromUtf8(reader.data()); content.replace(QLatin1String("%%PROJECTNAME%%"), projectName); Utils::FileSaver writer(aegisFile.fileName(), QIODevice::WriteOnly); writer.write(content.toUtf8()); if (!writer.finalize()) { qDebug("Failure writing manifest file."); return; } } } emit packagingChanged(); // fix path: QStringList files = DebianManager::debianFiles(debianDir); Utils::FileName path = Utils::FileName::fromString(QDir(target()->project()->projectDirectory()) .relativeFilePath(debianDir.toString())); QStringList relativeFiles; foreach (const QString &f, files) { Utils::FileName fn = path; fn.appendPath(f); relativeFiles << fn.toString(); } addFilesToProject(relativeFiles); } void Qt4MaemoDeployConfiguration::addFilesToProject(const QStringList &files) { if (files.isEmpty()) return; const QString list = QLatin1String("<ul><li>") + files.join(QLatin1String("</li><li>")) + QLatin1String("</li></ul>"); QMessageBox::StandardButton button = QMessageBox::question(Core::ICore::mainWindow(), tr("Add Packaging Files to Project"), tr("<html>Qt Creator has set up the following files to enable " "packaging:\n %1\nDo you want to add them to the project?</html>") .arg(list), QMessageBox::Yes | QMessageBox::No); if (button == QMessageBox::Yes) ProjectExplorer::ProjectExplorerPlugin::instance() ->addExistingFiles(target()->project()->rootProjectNode(), files); } void Qt4MaemoDeployConfiguration::init() { // Make sure we have deploymentInfo, but create it only once: DeploymentSettingsAssistant *assistant = qobject_cast<DeploymentSettingsAssistant *>(target()->project()->namedSettings(QLatin1String(DEPLOYMENT_ASSISTANT_SETTING)).value<QObject *>()); if (!assistant) { assistant = new DeploymentSettingsAssistant(deploymentInfo(), static_cast<Qt4ProjectManager::Qt4Project *>(target()->project())); QVariant data = QVariant::fromValue(static_cast<QObject *>(assistant)); target()->project()->setNamedSettings(QLatin1String(DEPLOYMENT_ASSISTANT_SETTING), data); } connect(target()->project(), SIGNAL(fileListChanged()), this, SLOT(setupPackaging())); } Qt4MaemoDeployConfigurationFactory::Qt4MaemoDeployConfigurationFactory(QObject *parent) : DeployConfigurationFactory(parent) { setObjectName(QLatin1String("Qt4MaemoDeployConfigurationFactory")); } QList<Core::Id> Qt4MaemoDeployConfigurationFactory::availableCreationIds(Target *parent) const { QList<Core::Id> ids; if (!canHandle(parent)) return ids; Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(parent->profile()); if (deviceType == Maemo5OsType) ids << Qt4MaemoDeployConfiguration::fremantleWithPackagingId() << Qt4MaemoDeployConfiguration::fremantleWithoutPackagingId(); else if (deviceType == HarmattanOsType) ids << Qt4MaemoDeployConfiguration::harmattanId(); return ids; } QString Qt4MaemoDeployConfigurationFactory::displayNameForId(const Core::Id id) const { if (id == Qt4MaemoDeployConfiguration::fremantleWithoutPackagingId()) return tr("Copy Files to Maemo5 Device"); else if (id == Qt4MaemoDeployConfiguration::fremantleWithPackagingId()) return tr("Build Debian Package and Install to Maemo5 Device"); else if (id == Qt4MaemoDeployConfiguration::harmattanId()) return tr("Build Debian Package and Install to Harmattan Device"); return QString(); } bool Qt4MaemoDeployConfigurationFactory::canCreate(Target *parent, const Core::Id id) const { return availableCreationIds(parent).contains(id); } DeployConfiguration *Qt4MaemoDeployConfigurationFactory::create(Target *parent, const Core::Id id) { Q_ASSERT(canCreate(parent, id)); const QString displayName = displayNameForId(id); DeployConfiguration * const dc = new Qt4MaemoDeployConfiguration(parent, id, displayName); if (id == Qt4MaemoDeployConfiguration::fremantleWithoutPackagingId()) { dc->stepList()->insertStep(0, new MaemoMakeInstallToSysrootStep(dc->stepList())); dc->stepList()->insertStep(1, new RemoteLinuxCheckForFreeDiskSpaceStep(dc->stepList())); dc->stepList()->insertStep(2, new MaemoCopyFilesViaMountStep(dc->stepList())); } else if (id == Qt4MaemoDeployConfiguration::fremantleWithPackagingId()) { dc->stepList()->insertStep(0, new MaemoDebianPackageCreationStep(dc->stepList())); dc->stepList()->insertStep(1, new MaemoInstallDebianPackageToSysrootStep(dc->stepList())); dc->stepList()->insertStep(2, new RemoteLinuxCheckForFreeDiskSpaceStep(dc->stepList())); dc->stepList()->insertStep(3, new MaemoInstallPackageViaMountStep(dc->stepList())); } else if (id == Qt4MaemoDeployConfiguration::harmattanId()) { dc->stepList()->insertStep(0, new MaemoDebianPackageCreationStep(dc->stepList())); dc->stepList()->insertStep(1, new MaemoInstallDebianPackageToSysrootStep(dc->stepList())); dc->stepList()->insertStep(2, new RemoteLinuxCheckForFreeDiskSpaceStep(dc->stepList())); dc->stepList()->insertStep(3, new MaemoUploadAndInstallPackageStep(dc->stepList())); } return dc; } bool Qt4MaemoDeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const { Core::Id id = idFromMap(map); return canHandle(parent) && (availableCreationIds(parent).contains(id) || id == OldDeployConfigId) && MaemoGlobal::supportsMaemoDevice(parent->profile()); } DeployConfiguration *Qt4MaemoDeployConfigurationFactory::restore(Target *parent, const QVariantMap &map) { if (!canRestore(parent, map)) return 0; Core::Id id = idFromMap(map); Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(parent->profile()); if (id == OldDeployConfigId) { if (deviceType == Maemo5OsType) id = Qt4MaemoDeployConfiguration::fremantleWithPackagingId(); else if (deviceType == HarmattanOsType) id = Qt4MaemoDeployConfiguration::harmattanId(); } Qt4MaemoDeployConfiguration * const dc = qobject_cast<Qt4MaemoDeployConfiguration *>(create(parent, id)); if (!dc->fromMap(map)) { delete dc; return 0; } return dc; } DeployConfiguration *Qt4MaemoDeployConfigurationFactory::clone(Target *parent, DeployConfiguration *product) { if (!canClone(parent, product)) return 0; return new Qt4MaemoDeployConfiguration(parent, qobject_cast<Qt4MaemoDeployConfiguration *>(product)); } bool Qt4MaemoDeployConfigurationFactory::canHandle(Target *parent) const { if (!qobject_cast<Qt4ProjectManager::Qt4Project *>(parent->project())) return false; if (!parent->project()->supportsProfile(parent->profile())) return false; return MaemoGlobal::supportsMaemoDevice(parent->profile()); } } // namespace Internal } // namespace Madde <commit_msg>Madde: Only get values once they are needed<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include "qt4maemodeployconfiguration.h" #include "debianmanager.h" #include "maddeuploadandinstallpackagesteps.h" #include "maemoconstants.h" #include "maemodeploybymountsteps.h" #include "maemodeployconfigurationwidget.h" #include "maemoglobal.h" #include "maemoinstalltosysrootstep.h" #include "maemopackagecreationstep.h" #include <coreplugin/icore.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/target.h> #include <projectexplorer/projectexplorer.h> #include <qt4projectmanager/qt4buildconfiguration.h> #include <qt4projectmanager/qt4project.h> #include <qtsupport/qtprofileinformation.h> #include <qtsupport/qtsupportconstants.h> #include <remotelinux/deployablefile.h> #include <remotelinux/deployablefilesperprofile.h> #include <remotelinux/deploymentinfo.h> #include <remotelinux/remotelinuxcheckforfreediskspacestep.h> #include <utils/qtcassert.h> #include <QFileInfo> #include <QString> #include <QMainWindow> #include <QMessageBox> using namespace ProjectExplorer; using namespace Qt4ProjectManager; using namespace RemoteLinux; const char OldDeployConfigId[] = "2.2MaemoDeployConfig"; const char DEPLOYMENT_ASSISTANT_SETTING[] = "RemoteLinux.DeploymentAssistant"; namespace Madde { namespace Internal { Qt4MaemoDeployConfiguration::Qt4MaemoDeployConfiguration(ProjectExplorer::Target *target, const Core::Id id, const QString &displayName) : RemoteLinuxDeployConfiguration(target, id, displayName) { init(); } Qt4MaemoDeployConfiguration::Qt4MaemoDeployConfiguration(ProjectExplorer::Target *target, Qt4MaemoDeployConfiguration *source) : RemoteLinuxDeployConfiguration(target, source) { init(); } QString Qt4MaemoDeployConfiguration::localDesktopFilePath(const DeployableFilesPerProFile *proFileInfo) const { QTC_ASSERT(proFileInfo->projectType() == ApplicationTemplate, return QString()); for (int i = 0; i < proFileInfo->rowCount(); ++i) { const DeployableFile &d = proFileInfo->deployableAt(i); if (QFileInfo(d.localFilePath).fileName().endsWith(QLatin1String(".desktop"))) return d.localFilePath; } return QString(); } DeployConfigurationWidget *Qt4MaemoDeployConfiguration::configurationWidget() const { return new MaemoDeployConfigurationWidget; } Qt4MaemoDeployConfiguration::~Qt4MaemoDeployConfiguration() {} Core::Id Qt4MaemoDeployConfiguration::fremantleWithPackagingId() { return Core::Id("DeployToFremantleWithPackaging"); } Core::Id Qt4MaemoDeployConfiguration::fremantleWithoutPackagingId() { return Core::Id("DeployToFremantleWithoutPackaging"); } Core::Id Qt4MaemoDeployConfiguration::harmattanId() { return Core::Id("DeployToHarmattan"); } DeploymentSettingsAssistant *Qt4MaemoDeployConfiguration::deploymentSettingsAssistant() { return static_cast<DeploymentSettingsAssistant *>(target()->project()->namedSettings(QLatin1String(DEPLOYMENT_ASSISTANT_SETTING)).value<QObject *>()); } QString Qt4MaemoDeployConfiguration::qmakeScope() const { Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(target()->profile()); if (deviceType == Maemo5OsType) return QLatin1String("maemo5"); if (deviceType == HarmattanOsType) return QLatin1String("contains(MEEGO_EDITION,harmattan)"); return QString("unix"); } QString Qt4MaemoDeployConfiguration::installPrefix() const { Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(target()->profile()); if (deviceType == Maemo5OsType) return QLatin1String("/opt"); if (deviceType == HarmattanOsType) return QLatin1String("/opt"); return QLatin1String("/usr/local"); } void Qt4MaemoDeployConfiguration::debianDirChanged(const Utils::FileName &dir) { if (dir == DebianManager::debianDirectory(target())) emit packagingChanged(); } void Qt4MaemoDeployConfiguration::setupPackaging() { if (target()->project()->activeTarget() != target()) return; disconnect(target()->project(), SIGNAL(fileListChanged()), this, SLOT(setupPackaging())); setupDebianPackaging(); } void Qt4MaemoDeployConfiguration::setupDebianPackaging() { Qt4BuildConfiguration *bc = qobject_cast<Qt4BuildConfiguration *>(target()->activeBuildConfiguration()); if (!bc || !target()->profile()) return; Utils::FileName debianDir = DebianManager::debianDirectory(target()); DebianManager::ActionStatus status = DebianManager::createTemplate(bc, debianDir); if (status == DebianManager::NoActionRequired || status == DebianManager::ActionFailed) return; Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(target()->profile()); DebianManager *dm = DebianManager::instance(); QString projectName = target()->project()->displayName(); if (!DebianManager::hasPackageManagerIcon(debianDir)) { // Such a file is created by the mobile wizards. Utils::FileName iconPath = Utils::FileName::fromString(target()->project()->projectDirectory()); iconPath.appendPath(projectName + QLatin1String("64.png")); if (iconPath.toFileInfo().exists()) dm->setPackageManagerIcon(debianDir, deviceType, iconPath); } dm->monitor(debianDir); connect(dm, SIGNAL(debianDirectoryChanged(Utils::FileName)), this, SLOT(debianDirChanged(Utils::FileName))); // Set up aegis manifest on harmattan: if (deviceType == HarmattanOsType) { Utils::FileName manifest = debianDir; const QString manifestName = QLatin1String("manifest.aegis"); manifest.appendPath(manifestName); const QFile aegisFile(manifest.toString()); if (!aegisFile.exists()) { Utils::FileReader reader; if (!reader.fetch(Core::ICore::resourcePath() + QLatin1String("/templates/shared/") + manifestName)) { qDebug("Reading manifest template failed."); return; } QString content = QString::fromUtf8(reader.data()); content.replace(QLatin1String("%%PROJECTNAME%%"), projectName); Utils::FileSaver writer(aegisFile.fileName(), QIODevice::WriteOnly); writer.write(content.toUtf8()); if (!writer.finalize()) { qDebug("Failure writing manifest file."); return; } } } emit packagingChanged(); // fix path: QStringList files = DebianManager::debianFiles(debianDir); Utils::FileName path = Utils::FileName::fromString(QDir(target()->project()->projectDirectory()) .relativeFilePath(debianDir.toString())); QStringList relativeFiles; foreach (const QString &f, files) { Utils::FileName fn = path; fn.appendPath(f); relativeFiles << fn.toString(); } addFilesToProject(relativeFiles); } void Qt4MaemoDeployConfiguration::addFilesToProject(const QStringList &files) { if (files.isEmpty()) return; const QString list = QLatin1String("<ul><li>") + files.join(QLatin1String("</li><li>")) + QLatin1String("</li></ul>"); QMessageBox::StandardButton button = QMessageBox::question(Core::ICore::mainWindow(), tr("Add Packaging Files to Project"), tr("<html>Qt Creator has set up the following files to enable " "packaging:\n %1\nDo you want to add them to the project?</html>") .arg(list), QMessageBox::Yes | QMessageBox::No); if (button == QMessageBox::Yes) ProjectExplorer::ProjectExplorerPlugin::instance() ->addExistingFiles(target()->project()->rootProjectNode(), files); } void Qt4MaemoDeployConfiguration::init() { // Make sure we have deploymentInfo, but create it only once: DeploymentSettingsAssistant *assistant = qobject_cast<DeploymentSettingsAssistant *>(target()->project()->namedSettings(QLatin1String(DEPLOYMENT_ASSISTANT_SETTING)).value<QObject *>()); if (!assistant) { assistant = new DeploymentSettingsAssistant(deploymentInfo(), static_cast<Qt4ProjectManager::Qt4Project *>(target()->project())); QVariant data = QVariant::fromValue(static_cast<QObject *>(assistant)); target()->project()->setNamedSettings(QLatin1String(DEPLOYMENT_ASSISTANT_SETTING), data); } connect(target()->project(), SIGNAL(fileListChanged()), this, SLOT(setupPackaging())); } Qt4MaemoDeployConfigurationFactory::Qt4MaemoDeployConfigurationFactory(QObject *parent) : DeployConfigurationFactory(parent) { setObjectName(QLatin1String("Qt4MaemoDeployConfigurationFactory")); } QList<Core::Id> Qt4MaemoDeployConfigurationFactory::availableCreationIds(Target *parent) const { QList<Core::Id> ids; if (!canHandle(parent)) return ids; Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(parent->profile()); if (deviceType == Maemo5OsType) ids << Qt4MaemoDeployConfiguration::fremantleWithPackagingId() << Qt4MaemoDeployConfiguration::fremantleWithoutPackagingId(); else if (deviceType == HarmattanOsType) ids << Qt4MaemoDeployConfiguration::harmattanId(); return ids; } QString Qt4MaemoDeployConfigurationFactory::displayNameForId(const Core::Id id) const { if (id == Qt4MaemoDeployConfiguration::fremantleWithoutPackagingId()) return tr("Copy Files to Maemo5 Device"); else if (id == Qt4MaemoDeployConfiguration::fremantleWithPackagingId()) return tr("Build Debian Package and Install to Maemo5 Device"); else if (id == Qt4MaemoDeployConfiguration::harmattanId()) return tr("Build Debian Package and Install to Harmattan Device"); return QString(); } bool Qt4MaemoDeployConfigurationFactory::canCreate(Target *parent, const Core::Id id) const { return availableCreationIds(parent).contains(id); } DeployConfiguration *Qt4MaemoDeployConfigurationFactory::create(Target *parent, const Core::Id id) { Q_ASSERT(canCreate(parent, id)); const QString displayName = displayNameForId(id); DeployConfiguration * const dc = new Qt4MaemoDeployConfiguration(parent, id, displayName); if (id == Qt4MaemoDeployConfiguration::fremantleWithoutPackagingId()) { dc->stepList()->insertStep(0, new MaemoMakeInstallToSysrootStep(dc->stepList())); dc->stepList()->insertStep(1, new RemoteLinuxCheckForFreeDiskSpaceStep(dc->stepList())); dc->stepList()->insertStep(2, new MaemoCopyFilesViaMountStep(dc->stepList())); } else if (id == Qt4MaemoDeployConfiguration::fremantleWithPackagingId()) { dc->stepList()->insertStep(0, new MaemoDebianPackageCreationStep(dc->stepList())); dc->stepList()->insertStep(1, new MaemoInstallDebianPackageToSysrootStep(dc->stepList())); dc->stepList()->insertStep(2, new RemoteLinuxCheckForFreeDiskSpaceStep(dc->stepList())); dc->stepList()->insertStep(3, new MaemoInstallPackageViaMountStep(dc->stepList())); } else if (id == Qt4MaemoDeployConfiguration::harmattanId()) { dc->stepList()->insertStep(0, new MaemoDebianPackageCreationStep(dc->stepList())); dc->stepList()->insertStep(1, new MaemoInstallDebianPackageToSysrootStep(dc->stepList())); dc->stepList()->insertStep(2, new RemoteLinuxCheckForFreeDiskSpaceStep(dc->stepList())); dc->stepList()->insertStep(3, new MaemoUploadAndInstallPackageStep(dc->stepList())); } return dc; } bool Qt4MaemoDeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const { Core::Id id = idFromMap(map); return canHandle(parent) && (availableCreationIds(parent).contains(id) || id == OldDeployConfigId) && MaemoGlobal::supportsMaemoDevice(parent->profile()); } DeployConfiguration *Qt4MaemoDeployConfigurationFactory::restore(Target *parent, const QVariantMap &map) { if (!canRestore(parent, map)) return 0; Core::Id id = idFromMap(map); Core::Id deviceType = ProjectExplorer::DeviceTypeProfileInformation::deviceTypeId(parent->profile()); if (id == OldDeployConfigId) { if (deviceType == Maemo5OsType) id = Qt4MaemoDeployConfiguration::fremantleWithPackagingId(); else if (deviceType == HarmattanOsType) id = Qt4MaemoDeployConfiguration::harmattanId(); } Qt4MaemoDeployConfiguration * const dc = qobject_cast<Qt4MaemoDeployConfiguration *>(create(parent, id)); if (!dc->fromMap(map)) { delete dc; return 0; } return dc; } DeployConfiguration *Qt4MaemoDeployConfigurationFactory::clone(Target *parent, DeployConfiguration *product) { if (!canClone(parent, product)) return 0; return new Qt4MaemoDeployConfiguration(parent, qobject_cast<Qt4MaemoDeployConfiguration *>(product)); } bool Qt4MaemoDeployConfigurationFactory::canHandle(Target *parent) const { if (!qobject_cast<Qt4ProjectManager::Qt4Project *>(parent->project())) return false; if (!parent->project()->supportsProfile(parent->profile())) return false; return MaemoGlobal::supportsMaemoDevice(parent->profile()); } } // namespace Internal } // namespace Madde <|endoftext|>
<commit_before>#ifndef HTTP_SERVER3_REQUEST_HANDLER_HPP #define HTTP_SERVER3_REQUEST_HANDLER_HPP #include <string> #include <fstream> #include "request.hpp" #include "response.hpp" #include "status_code.hpp" namespace webserver { #define DEFAULT_WEB_PAGE "index.html" #define RESPONSE_CHUNK_SIZE 512 class RequestHandler { public: RequestHandler(std::string &location) : location_(location) { } void handle(Request request, Response response) { // TODO: Refactor std::string request_uri; try { request_uri = url_decode(request.uri); is_path_absolute(request_uri); } catch (const std::exception& e) { response = Response::response(status::HTTP_400_BAD_REQUEST); return; } // Append default web page if path is a directory if (request_uri[request_uri.size() - 1] == '/') { request_uri += DEFAULT_WEB_PAGE; } std::size_t last_dot_pos = request_uri.find_last_of("."); std::string extension = request_uri.substr(last_dot_pos + 1); // Open the file specified in path std::string full_path = location_ + request_uri; std::ifstream server_file(full_path.c_str(), std::ios::in | std::ios::binary); if (!server_file) { response = Response::response(status::HTTP_404_NOT_FOUND); return; } // Write data stream to response // TODO: Examine cases where files are very big response = Response::response(status::HTTP_200_OK, status::get_mime_type(extension)); char buffer[RESPONSE_CHUNK_SIZE]; while (server_file.read(buffer, sizeof(buffer)).gcount() > 0) response.content.append(buffer, server_file.gcount()); } private: std::string location_; static std::string url_decode(std::string str) { // TODO: implement return str; } bool is_path_absolute(std::string path) { // TODO: check if path is absolute return true; } }; } // namespace webserver #endif // HTTP_SERVER3_REQUEST_HANDLER_HPP <commit_msg>Refactor request handler<commit_after>#ifndef WEBSERVER_REQUEST_HANDLER_HPP #define WEBSERVER_REQUEST_HANDLER_HPP #include <string> #include <fstream> #include "request.hpp" #include "response.hpp" #include "status_code.hpp" namespace webserver { #define DEFAULT_WEB_PAGE "index.html" #define RESPONSE_CHUNK_SIZE 512 class RequestHandler { public: RequestHandler(std::string &location) : location_(location) { } void handle(Request request, Response response) { std::string request_uri = create_uri(&request, &response); if (request_uri == "") return; std::string extension = get_extension(request_uri); std::fstream server_file = open_file(location_ + request_uri); if (!server_file) { response = Response::response(status::HTTP_404_NOT_FOUND); return; } response = Response::response(status::HTTP_200_OK, status::get_mime_type(extension)); write_data_stream(response, server_file); } private: std::string location_; std::string create_uri(Request *request, Response *response) { std::string request_uri; try { request_uri = url_decode(request->uri); } catch (const std::exception& e) { *response = Response::response(status::HTTP_400_BAD_REQUEST); return ""; } request_uri = append_web_page(request_uri); return request_uri; } static std::string get_extension(std::string request_uri) { std::size_t last_dot_pos = request_uri.find_last_of("."); std::string extension = request_uri.substr(last_dot_pos + 1); return extension; } static void write_data_stream(Response &response, std::fstream file) { // TODO: Examine cases where files are very big char buffer[RESPONSE_CHUNK_SIZE]; while (file.read(buffer, sizeof(buffer)).gcount() > 0) response.content.append(buffer, file.gcount()); } static std::string append_web_page(std::string path) { /* Append default web page if path is a directory */ if (path[path.size() - 1] == '/') path += DEFAULT_WEB_PAGE; return path; } static std::string url_decode(std::string str) { // TODO: implement return str; } static std::fstream open_file(std::string path) { std::fstream file(path.c_str(), std::ios::in | std::ios::binary); return file; } }; } // namespace webserver #endif // WEBSERVER_REQUEST_HANDLER_HPP <|endoftext|>
<commit_before><?hh //strict /** * This file is part of hhpack\package. * * (c) Noritaka Horio <holy.shared.design@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace hhpack\package; final class NameMatcher implements Matcher<NamedObject> { private string $pattern; public function __construct( string $pattern ) { $this->pattern = '/' . $pattern . '/'; } public function matches(NamedObject $item) : bool { return preg_match($this->pattern, $item->getName()) === 1; } public static function startsWith(string $keyword) : this { $pattern = '^' . preg_quote($keyword, '/'); return new static($pattern); } public static function endsWith(string $keyword) : this { $pattern = preg_quote($keyword, '/') . '$'; return new static($pattern); } } <commit_msg><commit_after><?hh //strict /** * This file is part of hhpack\package. * * (c) Noritaka Horio <holy.shared.design@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace hhpack\package; final class NameMatcher<T as NamedObject> implements Matcher<T as NamedObject> { private string $pattern; public function __construct( string $pattern ) { $this->pattern = '/' . $pattern . '/'; } public function matches(T $item) : bool { return preg_match($this->pattern, $item->getName()) === 1; } public static function startsWith(string $keyword) : this { $pattern = '^' . preg_quote($keyword, '/'); return new static($pattern); } public static function endsWith(string $keyword) : this { $pattern = preg_quote($keyword, '/') . '$'; return new static($pattern); } } <|endoftext|>
<commit_before>/** * @file server.cpp * @author Shae Bolt, CS3800 Section A * @author Jordan Giacone, CS3800 Section B * @date Apr 25, 2016 * @brief Description: The server file to handle multiple * clients sending messages to one another * @details Details: */ #include <string.h> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <pthread.h> #include <signal.h> //server port #define SERVER_PORT 9993 //max number of clients #define MAX_CLIENT 10 //handles clients on a per client basis and is responsible for sending messages out to all clients //these threads are removed if a client disconnects or the server is shutdown void *client_messenger(void* arg); //handles signal processing for cntrlc which closes the entire server given a message void cntrlc_signal_handle(int signal); //mutex for stop variable pthread_mutex_t stop_lock; //mutex for file descriptor array pthread_mutex_t file_descriptor_lock; //stop variable to end the server bool stop = false; //stream_socket = socket, //temp_fd = temporaray file descriptor //k = temporary size variable for write and //reads for the amount written int stream_socket, temp_fd, k; //server address struct sockaddr_in server_addr; //client address struct sockaddr_in client_addr; //client length unsigned int client_len; //host pointer char *host; //file descriptor arrays for client connections int file_descriptor_array[MAX_CLIENT]; /* allocate as many file descriptors as the number of clients */ pthread_t client_handlers[100]; //counter for the number of current connections int counter; int main() { //signals cntrlc quit signal(SIGINT, cntrlc_signal_handle); server_addr = { AF_INET, htons( SERVER_PORT)}; client_addr = { AF_INET}; client_len = sizeof(client_addr); counter = 0; /* create a stream socket */ if ((stream_socket = socket( AF_INET, SOCK_STREAM, 0)) == -1) { perror("server: socket failed"); exit(1); } int enable = 1; /* setting socket to be resuable incase of previous runt */ if (setsockopt(stream_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { perror("setsockopt(SO_REUSEADDR) failed"); } /* bind the socket to an internet port */ if (bind(stream_socket, (struct sockaddr*) &server_addr, sizeof(server_addr)) == -1) { perror("server: bind failed"); exit(1); } //listening for the server if (listen(stream_socket, 10) == -1) { perror("server: listen failed"); exit(1); } //checking for client connections to accept printf("SERVER is listening for clients to establish a connection\n"); while (((temp_fd = accept(stream_socket, (struct sockaddr*) &client_addr, &client_len)) > 0) && !stop) { pthread_mutex_lock(&file_descriptor_lock); if (counter < MAX_CLIENT) { file_descriptor_array[counter] = temp_fd; pthread_create(&client_handlers[counter], NULL, client_messenger, (void*) &file_descriptor_array[counter]); pthread_mutex_unlock(&file_descriptor_lock); counter++; } else { std::cerr << "Error too many threads, a client tried to connect when the max number of clients " << MAX_CLIENT << " was met." << std::endl; } } close(stream_socket); unlink((const char*) &server_addr.sin_addr); return (0); } void cntrlc_signal_handle(int signal) { std::cout << "\nCNTRLC detected" << std::endl; char message_buffer[512] = "WARNING: The server will shut down in 10 seconds\n"; char quit_msg[32] = "/quit"; for (int i = 0; i < counter; i++) { write(file_descriptor_array[i], message_buffer, sizeof(message_buffer)); } for (int i = 0; i < counter; i++) { write(file_descriptor_array[i], quit_msg, sizeof(quit_msg)); } sleep(10); pthread_mutex_lock(&stop_lock); stop = true; pthread_mutex_unlock(&stop_lock); for (int i = 0; i < counter; i++) { pthread_cancel(client_handlers[i]); } close(stream_socket); unlink((const char*) &server_addr.sin_addr); } void *client_messenger(void* arg) /* what does 'bob' do ? */ { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); printf( "Child accept() successful.. a client has connected to child ! waiting for a message\n"); //buffer for read in messages char buf[512]; //this is FD, fd, or file descriptor int some_fd = *(int*) arg; char host_name[100]; gethostname(host_name, 100); char client_name[512]; char message_buffer[100 + 512]; char server_message[100]; while ((k = read(some_fd, buf, sizeof(buf))) != 0) { strcpy(message_buffer, "User "); strcpy(client_name, buf); strncat(message_buffer, client_name, 512); strncat(message_buffer, " has joined the channel\n", 512); //printf("GIVEN MESSAGE: %s\n", buf); pthread_mutex_lock(&file_descriptor_lock); for (int i = 0; i < counter; i++) { if (file_descriptor_array[i] != some_fd) { write(file_descriptor_array[i], message_buffer, sizeof(message_buffer)); } } pthread_mutex_unlock(&file_descriptor_lock); break; } while ((k = read(some_fd, buf, sizeof(buf))) != 0 && !stop) { bzero(message_buffer, 512 + 100); printf("SERVER RECEIVED: %s\n", buf); if (strcmp(buf, "/quit") == 0) { break; } strcpy(message_buffer, ">> "); strncat(message_buffer, client_name, sizeof(client_name)); strncat(message_buffer, ": ", 8); strncat(message_buffer, buf, 512); strncat(message_buffer, "\n", 3); pthread_mutex_lock(&file_descriptor_lock); for (int i = 0; i < counter; i++) { if (file_descriptor_array[i] != some_fd) { write(file_descriptor_array[i], message_buffer, sizeof(message_buffer)); } } pthread_mutex_unlock(&file_descriptor_lock); pthread_yield(); } pthread_mutex_lock(&file_descriptor_lock); bzero(message_buffer, 512 + 100); strcpy(message_buffer, "User "); strncat(message_buffer, client_name, sizeof(client_name)); strncat(message_buffer, " has disconnected.", 24); for (int i = 0; i < counter; i++) { if (file_descriptor_array[i] != some_fd) { write(file_descriptor_array[i], message_buffer, sizeof(message_buffer)); } } int i = 0; while ((file_descriptor_array[i] != some_fd)) { i++; } counter--; for (int j = i; j < counter; j++) { file_descriptor_array[j] = file_descriptor_array[j - 1]; } pthread_mutex_unlock(&file_descriptor_lock); close(some_fd); std::cout << "\n EXITING THREAD" << std::endl; pthread_exit(0); } <commit_msg>asdfads<commit_after>/** * @file server.cpp * @author Shae Bolt, CS3800 Section A * @author Jordan Giacone, CS3800 Section B * @date Apr 25, 2016 * @brief Description: The server file to handle multiple * clients sending messages to one another * @details Details: */ #include <string.h> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <pthread.h> #include <signal.h> //server port #define SERVER_PORT 9993 //max number of clients #define MAX_CLIENT 100 //handles clients on a per client basis and is responsible for sending messages out to all clients //these threads are removed if a client disconnects or the server is shutdown void *client_messenger(void* arg); //handles signal processing for cntrlc which closes the entire server given a message void cntrlc_signal_handle(int signal); //mutex for stop variable pthread_mutex_t stop_lock; //mutex for file descriptor array pthread_mutex_t file_descriptor_lock; //stop variable to end the server bool stop = false; //stream_socket = socket, //temp_fd = temporaray file descriptor //k = temporary size variable for write and //reads for the amount written int stream_socket, temp_fd, k; //server address struct sockaddr_in server_addr; //client address struct sockaddr_in client_addr; //client length unsigned int client_len; //host pointer char *host; //file descriptor arrays for client connections int file_descriptor_array[MAX_CLIENT]; /* allocate as many file descriptors as the number of clients */ pthread_t client_handlers[100]; //counter for the number of current connections int counter; int main() { //signals cntrlc quit signal(SIGINT, cntrlc_signal_handle); server_addr = { AF_INET, htons( SERVER_PORT)}; client_addr = { AF_INET}; client_len = sizeof(client_addr); counter = 0; /* create a stream socket */ if ((stream_socket = socket( AF_INET, SOCK_STREAM, 0)) == -1) { perror("server: socket failed"); exit(1); } int enable = 1; /* setting socket to be resuable incase of previous runt */ if (setsockopt(stream_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { perror("setsockopt(SO_REUSEADDR) failed"); } /* bind the socket to an internet port */ if (bind(stream_socket, (struct sockaddr*) &server_addr, sizeof(server_addr)) == -1) { perror("server: bind failed"); exit(1); } //listening for the server if (listen(stream_socket, 10) == -1) { perror("server: listen failed"); exit(1); } //checking for client connections to accept printf("SERVER is listening for clients to establish a connection\n"); while (((temp_fd = accept(stream_socket, (struct sockaddr*) &client_addr, &client_len)) > 0) && !stop) { pthread_mutex_lock(&file_descriptor_lock); if (counter < MAX_CLIENT) { file_descriptor_array[counter] = temp_fd; pthread_create(&client_handlers[counter], NULL, client_messenger, (void*) &file_descriptor_array[counter]); pthread_mutex_unlock(&file_descriptor_lock); counter++; } else { std::cerr << "Error too many threads, a client tried to connect when the max number of clients " << MAX_CLIENT << " was met." << std::endl; } } close(stream_socket); unlink((const char*) &server_addr.sin_addr); return (0); } void cntrlc_signal_handle(int signal) { std::cout << "\nCNTRLC detected" << std::endl; char message_buffer[512] = "WARNING: The server will shut down in 10 seconds\n"; char quit_msg[32] = "/quit"; for (int i = 0; i < counter; i++) { write(file_descriptor_array[i], message_buffer, sizeof(message_buffer)); } for (int i = 0; i < counter; i++) { write(file_descriptor_array[i], quit_msg, sizeof(quit_msg)); } sleep(10); pthread_mutex_lock(&stop_lock); stop = true; pthread_mutex_unlock(&stop_lock); pthread_mutex_lock(&file_descriptor_lock); for (int i = 0; i < counter; i++) { pthread_cancel(client_handlers[i]); } pthread_mutex_unlock(&file_descriptor_lock); close(stream_socket); unlink((const char*) &server_addr.sin_addr); } void *client_messenger(void* arg) /* what does 'bob' do ? */ { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); printf( "Child accept() successful.. a client has connected to child ! waiting for a message\n"); //buffer for read in messages char buf[512]; //this is FD, fd, or file descriptor int some_fd = *(int*) arg; char host_name[100]; gethostname(host_name, 100); char client_name[512]; char message_buffer[100 + 512]; char server_message[100]; while ((k = read(some_fd, buf, sizeof(buf))) != 0) { strcpy(message_buffer, "User "); strcpy(client_name, buf); strncat(message_buffer, client_name, 512); strncat(message_buffer, " has joined the channel\n", 512); //printf("GIVEN MESSAGE: %s\n", buf); pthread_mutex_lock(&file_descriptor_lock); for (int i = 0; i < counter; i++) { if (file_descriptor_array[i] != some_fd) { write(file_descriptor_array[i], message_buffer, sizeof(message_buffer)); } } pthread_mutex_unlock(&file_descriptor_lock); break; } while ((k = read(some_fd, buf, sizeof(buf))) != 0 && !stop) { bzero(message_buffer, 512 + 100); printf("SERVER RECEIVED: %s\n", buf); if (strcmp(buf, "/quit") == 0) { break; } strcpy(message_buffer, ">> "); strncat(message_buffer, client_name, sizeof(client_name)); strncat(message_buffer, ": ", 8); strncat(message_buffer, buf, 512); strncat(message_buffer, "\n", 3); pthread_mutex_lock(&file_descriptor_lock); for (int i = 0; i < counter; i++) { if (file_descriptor_array[i] != some_fd) { write(file_descriptor_array[i], message_buffer, sizeof(message_buffer)); } } pthread_mutex_unlock(&file_descriptor_lock); pthread_yield(); } pthread_mutex_lock(&file_descriptor_lock); bzero(message_buffer, 512 + 100); strcpy(message_buffer, "User "); strncat(message_buffer, client_name, sizeof(client_name)); strncat(message_buffer, " has disconnected.", 24); for (int i = 0; i < counter; i++) { if (file_descriptor_array[i] != some_fd) { write(file_descriptor_array[i], message_buffer, sizeof(message_buffer)); } } int i = 0; while ((file_descriptor_array[i] != some_fd)) { i++; } counter--; for (int j = i; j < counter; j++) { file_descriptor_array[j] = file_descriptor_array[j - 1]; } pthread_mutex_unlock(&file_descriptor_lock); close(some_fd); std::cout << "\n EXITING THREAD" << std::endl; pthread_exit(0); } <|endoftext|>
<commit_before>#include "halley_editor.h" #include "editor_root_stage.h" #include "halley/tools/project/project.h" #include "preferences.h" #include "halley/core/game/environment.h" #include "halley/tools/file/filesystem.h" #include "halley/tools/project/project_loader.h" using namespace Halley; void initOpenGLPlugin(IPluginRegistry &registry); void initSDLSystemPlugin(IPluginRegistry &registry, std::optional<String> cryptKey); void initSDLAudioPlugin(IPluginRegistry &registry); void initSDLInputPlugin(IPluginRegistry &registry); void initAsioPlugin(IPluginRegistry &registry); void initDX11Plugin(IPluginRegistry &registry); void initMetalPlugin(IPluginRegistry &registry); HalleyEditor::HalleyEditor() { } HalleyEditor::~HalleyEditor() { } int HalleyEditor::initPlugins(IPluginRegistry &registry) { initSDLSystemPlugin(registry, {}); initAsioPlugin(registry); initSDLAudioPlugin(registry); initSDLInputPlugin(registry); #ifdef _WIN32 initDX11Plugin(registry); #elif __APPLE__ initMetalPlugin(registry); #else initOpenGLPlugin(registry); #endif return HalleyAPIFlags::Video | HalleyAPIFlags::Audio | HalleyAPIFlags::Input | HalleyAPIFlags::Network; } void HalleyEditor::initResourceLocator(const Path& gamePath, const Path& assetsPath, const Path& unpackedAssetsPath, ResourceLocator& locator) { locator.addFileSystem(unpackedAssetsPath); } String HalleyEditor::getName() const { return "Halley Editor"; } String HalleyEditor::getDataPath() const { return "halley/editor"; } bool HalleyEditor::isDevMode() const { return true; } bool HalleyEditor::shouldCreateSeparateConsole() const { #ifdef _DEBUG return isDevMode(); #else return false; #endif } Preferences& HalleyEditor::getPreferences() { return *preferences; } void HalleyEditor::init(const Environment& environment, const Vector<String>& args) { rootPath = environment.getProgramPath().parentPath(); parseArguments(args); } void HalleyEditor::parseArguments(const std::vector<String>& args) { gotProjectPath = false; for (auto& arg : args) { if (arg.startsWith("--")) { std::cout << "Unknown argument \"" << arg << "\".\n"; } else { if (!gotProjectPath) { projectPath = arg.cppStr(); gotProjectPath = true; } else { std::cout << "Unknown argument \"" << arg << "\".\n"; } } } } std::unique_ptr<Stage> HalleyEditor::startGame() { auto& api = getAPI(); preferences = std::make_unique<Preferences>(*api.system, "2020-07-29"); projectLoader = std::make_unique<ProjectLoader>(api.core->getStatics(), rootPath); std::unique_ptr<Project> project; if (gotProjectPath) { project = loadProject(Path(projectPath)); } api.video->setWindow(preferences->getWindowDefinition()); api.video->setVsync(true); return std::make_unique<EditorRootStage>(*this, std::move(project)); } std::unique_ptr<Project> HalleyEditor::loadProject(Path path) { auto project = projectLoader->loadProject(path); if (!project) { throw Exception("Unable to load project at " + path.string(), HalleyExceptions::Tools); } project->loadGameResources(getAPI()); preferences->addRecent(path.string()); preferences->saveToFile(); return project; } std::unique_ptr<Project> HalleyEditor::createProject(Path path) { std::unique_ptr<Project> project; // TODO if (!project) { throw Exception("Unable to create project at " + path.string(), HalleyExceptions::Tools); } preferences->addRecent(path.string()); preferences->saveToFile(); return project; } HalleyGame(HalleyEditor); <commit_msg>Bump editor version<commit_after>#include "halley_editor.h" #include "editor_root_stage.h" #include "halley/tools/project/project.h" #include "preferences.h" #include "halley/core/game/environment.h" #include "halley/tools/file/filesystem.h" #include "halley/tools/project/project_loader.h" using namespace Halley; void initOpenGLPlugin(IPluginRegistry &registry); void initSDLSystemPlugin(IPluginRegistry &registry, std::optional<String> cryptKey); void initSDLAudioPlugin(IPluginRegistry &registry); void initSDLInputPlugin(IPluginRegistry &registry); void initAsioPlugin(IPluginRegistry &registry); void initDX11Plugin(IPluginRegistry &registry); void initMetalPlugin(IPluginRegistry &registry); HalleyEditor::HalleyEditor() { } HalleyEditor::~HalleyEditor() { } int HalleyEditor::initPlugins(IPluginRegistry &registry) { initSDLSystemPlugin(registry, {}); initAsioPlugin(registry); initSDLAudioPlugin(registry); initSDLInputPlugin(registry); #ifdef _WIN32 initDX11Plugin(registry); #elif __APPLE__ initMetalPlugin(registry); #else initOpenGLPlugin(registry); #endif return HalleyAPIFlags::Video | HalleyAPIFlags::Audio | HalleyAPIFlags::Input | HalleyAPIFlags::Network; } void HalleyEditor::initResourceLocator(const Path& gamePath, const Path& assetsPath, const Path& unpackedAssetsPath, ResourceLocator& locator) { locator.addFileSystem(unpackedAssetsPath); } String HalleyEditor::getName() const { return "Halley Editor"; } String HalleyEditor::getDataPath() const { return "halley/editor"; } bool HalleyEditor::isDevMode() const { return true; } bool HalleyEditor::shouldCreateSeparateConsole() const { #ifdef _DEBUG return isDevMode(); #else return false; #endif } Preferences& HalleyEditor::getPreferences() { return *preferences; } void HalleyEditor::init(const Environment& environment, const Vector<String>& args) { rootPath = environment.getProgramPath().parentPath(); parseArguments(args); } void HalleyEditor::parseArguments(const std::vector<String>& args) { gotProjectPath = false; for (auto& arg : args) { if (arg.startsWith("--")) { std::cout << "Unknown argument \"" << arg << "\".\n"; } else { if (!gotProjectPath) { projectPath = arg.cppStr(); gotProjectPath = true; } else { std::cout << "Unknown argument \"" << arg << "\".\n"; } } } } std::unique_ptr<Stage> HalleyEditor::startGame() { auto& api = getAPI(); preferences = std::make_unique<Preferences>(*api.system, "2020-08-03"); projectLoader = std::make_unique<ProjectLoader>(api.core->getStatics(), rootPath); std::unique_ptr<Project> project; if (gotProjectPath) { project = loadProject(Path(projectPath)); } api.video->setWindow(preferences->getWindowDefinition()); api.video->setVsync(true); return std::make_unique<EditorRootStage>(*this, std::move(project)); } std::unique_ptr<Project> HalleyEditor::loadProject(Path path) { auto project = projectLoader->loadProject(path); if (!project) { throw Exception("Unable to load project at " + path.string(), HalleyExceptions::Tools); } project->loadGameResources(getAPI()); preferences->addRecent(path.string()); preferences->saveToFile(); return project; } std::unique_ptr<Project> HalleyEditor::createProject(Path path) { std::unique_ptr<Project> project; // TODO if (!project) { throw Exception("Unable to create project at " + path.string(), HalleyExceptions::Tools); } preferences->addRecent(path.string()); preferences->saveToFile(); return project; } HalleyGame(HalleyEditor); <|endoftext|>
<commit_before>#include <stingray/toolkit/SystemException.h> #include <errno.h> #include <string.h> #include <stingray/toolkit/StringUtils.h> namespace stingray { SystemException::SystemException(const std::string &message) throw(): std::runtime_error(message + ": errno = " + GetErrorMessage(errno)), _error(errno) {} SystemException::SystemException(const std::string &message, int err) throw(): std::runtime_error(message + ": errno = " + GetErrorMessage(err)), _error(err) {} std::string SystemException::GetErrorMessage(int err) throw() { std::string result = ErrnoToStr(err); char buf[256]; char *msg = strerror_r(err, buf, sizeof(buf)); result += " ("; result += msg ? msg: "Unknown error"; result += ")"; return result; } std::string SystemException::GetErrorMessage() throw() { return GetErrorMessage(errno); } #define ERRNO_STR(val) case val: return #val std::string SystemException::ErrnoToStr(int e) { switch (e) { ERRNO_STR(EACCES); ERRNO_STR(EBUSY); ERRNO_STR(EFAULT); ERRNO_STR(EINVAL); ERRNO_STR(ELOOP); ERRNO_STR(EMFILE); ERRNO_STR(ENAMETOOLONG); ERRNO_STR(ENODEV); ERRNO_STR(ENOENT); ERRNO_STR(ENOMEM); ERRNO_STR(ENOTDIR); ERRNO_STR(ENXIO); ERRNO_STR(EPERM); ERRNO_STR(EBADF); ERRNO_STR(EINTR); default: return ToString(e); }; } #undef ERRNO_STR } <commit_msg>added ECHILD to SystemException<commit_after>#include <stingray/toolkit/SystemException.h> #include <errno.h> #include <string.h> #include <stingray/toolkit/StringUtils.h> namespace stingray { SystemException::SystemException(const std::string &message) throw(): std::runtime_error(message + ": errno = " + GetErrorMessage(errno)), _error(errno) {} SystemException::SystemException(const std::string &message, int err) throw(): std::runtime_error(message + ": errno = " + GetErrorMessage(err)), _error(err) {} std::string SystemException::GetErrorMessage(int err) throw() { std::string result = ErrnoToStr(err); char buf[256]; char *msg = strerror_r(err, buf, sizeof(buf)); result += " ("; result += msg ? msg: "Unknown error"; result += ")"; return result; } std::string SystemException::GetErrorMessage() throw() { return GetErrorMessage(errno); } #define ERRNO_STR(val) case val: return #val std::string SystemException::ErrnoToStr(int e) { switch (e) { ERRNO_STR(EACCES); ERRNO_STR(EBUSY); ERRNO_STR(EFAULT); ERRNO_STR(EINVAL); ERRNO_STR(ELOOP); ERRNO_STR(EMFILE); ERRNO_STR(ENAMETOOLONG); ERRNO_STR(ENODEV); ERRNO_STR(ENOENT); ERRNO_STR(ENOMEM); ERRNO_STR(ENOTDIR); ERRNO_STR(ENXIO); ERRNO_STR(EPERM); ERRNO_STR(EBADF); ERRNO_STR(EINTR); ERRNO_STR(ECHILD); default: return ToString(e); }; } #undef ERRNO_STR } <|endoftext|>
<commit_before>#include "unit_tests/suite/lumix_unit_tests.h" #include "engine/log.h" #ifdef _WIN32 #include "engine/win/simple_win.h" #endif #include <cstdio> namespace Lumix { namespace UnitTest { void outputToVS(const char* system, const char* message) { char tmp[2048]; copyString(tmp, system); catString(tmp, ": "); catString(tmp, message); catString(tmp, "\r"); #ifdef _WIN32 OutputDebugString(tmp); #endif } void outputToConsole(const char* system, const char* message) { printf("%s: %s\n", system, message); } void App::init() { g_log_info.getCallback().bind<outputToVS>(); g_log_warning.getCallback().bind<outputToVS>(); g_log_error.getCallback().bind<outputToVS>(); g_log_info.getCallback().bind<outputToConsole>(); g_log_warning.getCallback().bind<outputToConsole>(); g_log_error.getCallback().bind<outputToConsole>(); } void App::run(int argc, const char *argv[]) { Manager::instance().dumpTests(); Manager::instance().runTests("unit_tests/engine/simd/*"); Manager::instance().dumpResults(); } void App::exit() { Manager::release(); } } //~UnitTest } //~UnitTest<commit_msg>fixed unit tests<commit_after>#include "unit_tests/suite/lumix_unit_tests.h" #include "engine/log.h" #ifdef _WIN32 #include "engine/win/simple_win.h" #endif #include <cstdio> namespace Lumix { namespace UnitTest { void outputToVS(const char* system, const char* message) { char tmp[2048]; copyString(tmp, system); catString(tmp, ": "); catString(tmp, message); catString(tmp, "\r"); #ifdef _WIN32 OutputDebugString(tmp); #endif } void outputToConsole(const char* system, const char* message) { printf("%s: %s\n", system, message); } void App::init() { g_log_info.getCallback().bind<outputToVS>(); g_log_warning.getCallback().bind<outputToVS>(); g_log_error.getCallback().bind<outputToVS>(); g_log_info.getCallback().bind<outputToConsole>(); g_log_warning.getCallback().bind<outputToConsole>(); g_log_error.getCallback().bind<outputToConsole>(); } void App::run(int argc, const char *argv[]) { Manager::instance().dumpTests(); Manager::instance().runTests("*"); Manager::instance().dumpResults(); } void App::exit() { Manager::release(); } } //~UnitTest } //~UnitTest<|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep07/call_mss_freq.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file call_mss_freq.C * Contains the wrapper for istep 7.3 */ /******************************************************************************/ // Includes /******************************************************************************/ #include <stdint.h> #include <trace/interface.H> #include <initservice/taskargs.H> #include <errl/errlentry.H> #include <isteps/hwpisteperror.H> #include <errl/errludtarget.H> #include <initservice/isteps_trace.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/utilFilter.H> #include <config.h> #include <fapi2.H> #include <fapi2/plat_hwp_invoker.H> // SBE #include <sbeif.H> // HWP #include <p9_mss_freq.H> #include <p9_mss_freq_system.H> namespace ISTEP_07 { using namespace ISTEP; using namespace ISTEP_ERROR; using namespace ERRORLOG; using namespace TARGETING; // // Wrapper function to call mss_freq // void* call_mss_freq( void *io_pArgs ) { IStepError l_StepError; errlHndl_t l_err = NULL; TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_freq entry" ); TARGETING::TargetHandleList l_membufTargetList; getAllChiplets(l_membufTargetList, TYPE_MCS); for (const auto & l_membuf_target : l_membufTargetList) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "p9_mss_freq HWP target HUID %.8x", TARGETING::get_huid(l_membuf_target)); // call the HWP with each target ( if parallel, spin off a task ) fapi2::Target <fapi2::TARGET_TYPE_MCS> l_fapi_membuf_target (l_membuf_target); FAPI_INVOKE_HWP(l_err, p9_mss_freq, l_fapi_membuf_target); // process return code. if ( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "ERROR 0x%.8X: p9_mss_freq HWP on target HUID %.8x", l_err->reasonCode(), TARGETING::get_huid(l_membuf_target) ); // capture the target data in the elog ErrlUserDetailsTarget(l_membuf_target).addToLog( l_err ); // Create IStep error log and cross reference to error that occurred l_StepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : mss_freq HWP"); } } // End memBuf loop // Set PB frequency to ASYNC_FREQ_MHZ TARGETING::Target * l_sys = nullptr; TARGETING::targetService().getTopLevelTarget( l_sys ); uint32_t l_originalNest = l_sys->getAttr<TARGETING::ATTR_FREQ_PB_MHZ>(); uint32_t l_asyncFreq = l_sys->getAttr<TARGETING::ATTR_ASYNC_NEST_FREQ_MHZ>(); l_sys->setAttr<TARGETING::ATTR_FREQ_PB_MHZ>(l_asyncFreq); // Read MC_SYNC_MODE from SBE itself and set the attribute uint8_t l_bootSyncMode = 0; l_err = SBE::getBootMcSyncMode( l_bootSyncMode ); if( l_err ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Failed getting the boot mc sync mode from the SBE"); // Create IStep error log and cross reference to error that occurred l_StepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } TARGETING::Target * l_masterProc = nullptr; TARGETING::targetService() .masterProcChipTargetHandle( l_masterProc ); l_masterProc->setAttr<TARGETING::ATTR_MC_SYNC_MODE>(l_bootSyncMode); if(l_StepError.getErrorHandle() == NULL) { TARGETING::TargetHandleList l_mcbistTargetList; getAllChiplets(l_mcbistTargetList, TYPE_MCBIST); std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCBIST> > l_fapi2_mcbistTargetList; for (const auto & l_mcbist_target : l_mcbistTargetList) { // call the HWP with each target ( if parallel, spin off a task ) fapi2::Target <fapi2::TARGET_TYPE_MCBIST> l_fapi_mcbist_target(l_mcbist_target); l_fapi2_mcbistTargetList.push_back(l_fapi_mcbist_target); } FAPI_INVOKE_HWP(l_err, p9_mss_freq_system, l_fapi2_mcbistTargetList); // process return code. if ( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "ERROR 0x%.8X: p9_mss_freq_system HWP while running on mcbist targets"); // Create IStep error log and cross reference to error that occurred l_StepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : mss_freq_system HWP"); } } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "WARNING skipping p9_mss_freq_system HWP due to error detected in p9_mss_freq HWP. An error should have been committed."); } // Check MC_SYNC_MODE uint8_t l_mcSyncMode = l_masterProc->getAttr<TARGETING::ATTR_MC_SYNC_MODE>(); uint32_t l_newNest = 0; // TODO RTC: 161197 Remove logic to set nest based off sync mode // Set the nest frequency based off mc_sync_mode if( l_mcSyncMode == 0 ) { l_newNest = l_sys->getAttr<TARGETING::ATTR_ASYNC_NEST_FREQ_MHZ>(); } else { TARGETING::TargetHandleList l_mcbists; TARGETING::getAllChiplets(l_mcbists, TARGETING::TYPE_MCBIST); l_newNest = l_mcbists.at(0)->getAttr<TARGETING::ATTR_MSS_FREQ>(); } l_sys->setAttr<TARGETING::ATTR_FREQ_PB_MHZ>( l_newNest ); // TODO RTC: 161596 - Set ATTR_NEST_FREQ_MHZ as well until we know it is not being used anymore l_sys->setAttr<TARGETING::ATTR_NEST_FREQ_MHZ>( l_newNest ); if(l_StepError.getErrorHandle() == NULL) { //Trigger sbe update if the nest frequency changed. if( (l_newNest != l_originalNest) || (l_mcSyncMode != l_bootSyncMode) ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "The nest frequency or sync mode changed!" " Original Nest: %d New Nest: %d" " Original syncMode: %d New syncMode: %d", l_originalNest, l_newNest, l_bootSyncMode, l_mcSyncMode ); l_err = SBE::updateProcessorSbeSeeproms(); if( l_err ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_freq.C - Error calling updateProcessorSbeSeeproms"); // Create IStep error log and cross reference to error // that occurred l_StepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } } } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "WARNING skipping SBE update checks due to previous errors" ); } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_freq exit" ); return l_StepError.getErrorHandle(); } }; // end namespace <commit_msg>Remove logic in HB to set Nest frequency based off sync mode<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep07/call_mss_freq.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file call_mss_freq.C * Contains the wrapper for istep 7.3 */ /******************************************************************************/ // Includes /******************************************************************************/ #include <stdint.h> #include <trace/interface.H> #include <initservice/taskargs.H> #include <errl/errlentry.H> #include <isteps/hwpisteperror.H> #include <errl/errludtarget.H> #include <initservice/isteps_trace.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/utilFilter.H> #include <config.h> #include <fapi2.H> #include <fapi2/plat_hwp_invoker.H> // SBE #include <sbeif.H> // HWP #include <p9_mss_freq.H> #include <p9_mss_freq_system.H> namespace ISTEP_07 { using namespace ISTEP; using namespace ISTEP_ERROR; using namespace ERRORLOG; using namespace TARGETING; // // Wrapper function to call mss_freq // void* call_mss_freq( void *io_pArgs ) { IStepError l_StepError; errlHndl_t l_err = NULL; TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_freq entry" ); TARGETING::TargetHandleList l_membufTargetList; getAllChiplets(l_membufTargetList, TYPE_MCS); for (const auto & l_membuf_target : l_membufTargetList) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "p9_mss_freq HWP target HUID %.8x", TARGETING::get_huid(l_membuf_target)); // call the HWP with each target ( if parallel, spin off a task ) fapi2::Target <fapi2::TARGET_TYPE_MCS> l_fapi_membuf_target (l_membuf_target); FAPI_INVOKE_HWP(l_err, p9_mss_freq, l_fapi_membuf_target); // process return code. if ( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "ERROR 0x%.8X: p9_mss_freq HWP on target HUID %.8x", l_err->reasonCode(), TARGETING::get_huid(l_membuf_target) ); // capture the target data in the elog ErrlUserDetailsTarget(l_membuf_target).addToLog( l_err ); // Create IStep error log and cross reference to error that occurred l_StepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : mss_freq HWP"); } } // End memBuf loop // Set PB frequency to ASYNC_FREQ_MHZ TARGETING::Target * l_sys = nullptr; TARGETING::targetService().getTopLevelTarget( l_sys ); uint32_t l_originalNest = l_sys->getAttr<TARGETING::ATTR_FREQ_PB_MHZ>(); uint32_t l_asyncFreq = l_sys->getAttr<TARGETING::ATTR_ASYNC_NEST_FREQ_MHZ>(); l_sys->setAttr<TARGETING::ATTR_FREQ_PB_MHZ>(l_asyncFreq); // Read MC_SYNC_MODE from SBE itself and set the attribute uint8_t l_bootSyncMode = 0; l_err = SBE::getBootMcSyncMode( l_bootSyncMode ); if( l_err ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Failed getting the boot mc sync mode from the SBE"); // Create IStep error log and cross reference to error that occurred l_StepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } TARGETING::Target * l_masterProc = nullptr; TARGETING::targetService() .masterProcChipTargetHandle( l_masterProc ); l_masterProc->setAttr<TARGETING::ATTR_MC_SYNC_MODE>(l_bootSyncMode); if(l_StepError.getErrorHandle() == NULL) { TARGETING::TargetHandleList l_mcbistTargetList; getAllChiplets(l_mcbistTargetList, TYPE_MCBIST); std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCBIST> > l_fapi2_mcbistTargetList; for (const auto & l_mcbist_target : l_mcbistTargetList) { // call the HWP with each target ( if parallel, spin off a task ) fapi2::Target <fapi2::TARGET_TYPE_MCBIST> l_fapi_mcbist_target(l_mcbist_target); l_fapi2_mcbistTargetList.push_back(l_fapi_mcbist_target); } FAPI_INVOKE_HWP(l_err, p9_mss_freq_system, l_fapi2_mcbistTargetList); // process return code. if ( l_err ) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "ERROR 0x%.8X: p9_mss_freq_system HWP while running on mcbist targets"); // Create IStep error log and cross reference to error that occurred l_StepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : mss_freq_system HWP"); } } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "WARNING skipping p9_mss_freq_system HWP due to error detected in p9_mss_freq HWP. An error should have been committed."); } // Get latest MC_SYNC_MODE and FREQ_PB_MHZ uint8_t l_mcSyncMode = l_masterProc->getAttr<TARGETING::ATTR_MC_SYNC_MODE>(); uint32_t l_newNest = l_sys->getAttr<TARGETING::ATTR_FREQ_PB_MHZ>(); // TODO RTC: 161596 - Set ATTR_NEST_FREQ_MHZ as well until we know it is not being used anymore l_sys->setAttr<TARGETING::ATTR_NEST_FREQ_MHZ>( l_newNest ); if(l_StepError.getErrorHandle() == NULL) { //Trigger sbe update if the nest frequency changed. if( (l_newNest != l_originalNest) || (l_mcSyncMode != l_bootSyncMode) ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "The nest frequency or sync mode changed!" " Original Nest: %d New Nest: %d" " Original syncMode: %d New syncMode: %d", l_originalNest, l_newNest, l_bootSyncMode, l_mcSyncMode ); l_err = SBE::updateProcessorSbeSeeproms(); if( l_err ) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_freq.C - Error calling updateProcessorSbeSeeproms"); // Create IStep error log and cross reference to error // that occurred l_StepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, ISTEP_COMP_ID ); } } } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "WARNING skipping SBE update checks due to previous errors" ); } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_freq exit" ); return l_StepError.getErrorHandle(); } }; // end namespace <|endoftext|>
<commit_before>#include "csv-reader.h" #include <fstream> #include <sstream> CSVReader::CSVReader(std::string file_loc) { file_loc_ = file_loc; } CSVReader::~CSVReader() { } bool CSVReader::LoadFile() { if (file_loc_ == "") { return false; } else { std::ifstream mainFile; mainFile.open(file_loc_.c_str()); std::stringstream strStream; strStream << mainFile.rdbuf(); //read the file std::string data = strStream.str(); //str holds the content of the file GenerateCols(data); mainFile.close(); num_rows_ = rows.size(); } return true; } int CSVReader::get_num_rows() { return this->num_rows_; } int CSVReader::get_num_cols() { return this->num_cols_; } /* * This function locates the index of the *first* matching value container. * Searches rows between: start_row and end_row and * Columns between: start_col and end_col. * * Negatives values for the indices indicate no value. i.e. start_row == -1 implies start_row = 0 and * end_row == -1 implies end_row = LAST_ROW_INDEX */ LocationIndex CSVReader::FindString(std::string value, int start_row, int end_row, int start_col, int end_col) { if (start_row < 0) { start_row = 0; } if (end_row < 0) { end_row = this->get_num_rows() - 1; } if (start_col < 0) { start_col = 0; } if (end_col < 0) { end_col = this->get_num_cols() - 1; } // Search LocationIndex index; index.valid = false; for (int i = start_row; i <= end_row; i++) { for (int j = start_col; j <= end_col; j++) { if (this->rows[i][j] == value) { index.row = i; index.col = j; index.valid = true; } } } return index; } LocationIndex CSVReader::FindString(std::string value) { return FindString(value, -1, -1, -1, -1); } bool CSVReader::GenerateCols(std::string data) { char DOUBLE_QUOTE_CHAR = 34; char COMMA_CHAR = 44; char END_LINE = '\n'; std::vector< std::string > col; std::string currentCollected = ""; bool escaping = false; for (unsigned int i = 0; i < data.length(); i++) { char currentChar = data.at(i); if ((currentChar != END_LINE && currentChar != DOUBLE_QUOTE_CHAR && currentChar != COMMA_CHAR) || (currentChar == COMMA_CHAR && escaping) || (currentChar == END_LINE && escaping)) { currentCollected += currentChar; } else if ((currentChar == END_LINE && !escaping)) { // End of row. // If we didn't write out data already, write out the remainder. col.push_back(currentCollected); num_cols_ = col.size(); rows.push_back(col); col.clear(); currentCollected = ""; } else if (currentChar == COMMA_CHAR && !escaping) { // End of cell. col.push_back(currentCollected); currentCollected = ""; } else if (currentChar == DOUBLE_QUOTE_CHAR && !escaping) { // We need to start escaping. escaping = true; } else if (currentChar == DOUBLE_QUOTE_CHAR && escaping) { // If the next char is also a DOUBLE_QUOTE_CHAR, then we want to push a DOUBLE_QUOTE_CHAR. if (i < data.length() - 1 && data.at(i+1) == DOUBLE_QUOTE_CHAR) { currentCollected += currentChar; i++; // Skip next quote char. } else { // If not, then this is the end of the escaping period. escaping = false; } } } if (col.size() != 0) { col.push_back(currentCollected); rows.push_back(col); } return true; } <commit_msg>Remove wrong line endings<commit_after>#include "csv-reader.h" #include <fstream> #include <sstream> CSVReader::CSVReader(std::string file_loc) { file_loc_ = file_loc; } CSVReader::~CSVReader() { } bool CSVReader::LoadFile() { if (file_loc_ == "") { return false; } else { std::ifstream mainFile; mainFile.open(file_loc_.c_str()); std::stringstream strStream; strStream << mainFile.rdbuf(); //read the file std::string data = strStream.str(); //str holds the content of the file GenerateCols(data); mainFile.close(); num_rows_ = rows.size(); } return true; } int CSVReader::get_num_rows() { return this->num_rows_; } int CSVReader::get_num_cols() { return this->num_cols_; } /* * This function locates the index of the *first* matching value container. * Searches rows between: start_row and end_row and * Columns between: start_col and end_col. * * Negatives values for the indices indicate no value. i.e. start_row == -1 implies start_row = 0 and * end_row == -1 implies end_row = LAST_ROW_INDEX */ LocationIndex CSVReader::FindString(std::string value, int start_row, int end_row, int start_col, int end_col) { if (start_row < 0) { start_row = 0; } if (end_row < 0) { end_row = this->get_num_rows() - 1; } if (start_col < 0) { start_col = 0; } if (end_col < 0) { end_col = this->get_num_cols() - 1; } // Search LocationIndex index; index.valid = false; for (int i = start_row; i <= end_row; i++) { for (int j = start_col; j <= end_col; j++) { if (this->rows[i][j] == value) { index.row = i; index.col = j; index.valid = true; } } } return index; } LocationIndex CSVReader::FindString(std::string value) { return FindString(value, -1, -1, -1, -1); } bool CSVReader::GenerateCols(std::string data) { char DOUBLE_QUOTE_CHAR = 34; char COMMA_CHAR = 44; char END_LINE = '\n'; std::vector< std::string > col; std::string currentCollected = ""; bool escaping = false; for (unsigned int i = 0; i < data.length(); i++) { char currentChar = data.at(i); if ((currentChar != END_LINE && currentChar != DOUBLE_QUOTE_CHAR && currentChar != COMMA_CHAR) || (currentChar == COMMA_CHAR && escaping) || (currentChar == END_LINE && escaping)) { currentCollected += currentChar; } else if ((currentChar == END_LINE && !escaping)) { // End of row. // If we didn't write out data already, write out the remainder. col.push_back(currentCollected); num_cols_ = col.size(); rows.push_back(col); col.clear(); currentCollected = ""; } else if (currentChar == COMMA_CHAR && !escaping) { // End of cell. col.push_back(currentCollected); currentCollected = ""; } else if (currentChar == DOUBLE_QUOTE_CHAR && !escaping) { // We need to start escaping. escaping = true; currentCollected += currentChar; } else if (currentChar == DOUBLE_QUOTE_CHAR && escaping) { // If the next char is also a DOUBLE_QUOTE_CHAR, then we want to push a DOUBLE_QUOTE_CHAR. if (i < data.length() - 1 && data.at(i+1) == DOUBLE_QUOTE_CHAR) { currentCollected += currentChar; i++; // Skip next quote char. } else { // If not, then this is the end of the escaping period. escaping = false; currentCollected += currentChar; } } } if (col.size() != 0) { col.push_back(currentCollected); rows.push_back(col); } return true; } <|endoftext|>
<commit_before>#include "PrimeTower.h" #include <limits> #include "ExtruderTrain.h" #include "sliceDataStorage.h" #include "gcodeExport.h" #include "gcodePlanner.h" #include "infill.h" #include "PrintFeature.h" namespace cura { PrimeTower::PrimeTower() : is_hollow(false) , current_pre_wipe_location_idx(0) { for (int extruder_nr = 0; extruder_nr < MAX_EXTRUDERS; extruder_nr++) { last_prime_tower_poly_printed[extruder_nr] = -1; } } void PrimeTower::initConfigs(const MeshGroup* meshgroup) { extruder_count = meshgroup->getExtruderCount(); for (int extr = 0; extr < extruder_count; extr++) { config_per_extruder.emplace_back(PrintFeatureType::Support);// so that visualization in the old Cura still works (TODO) } for (int extr = 0; extr < extruder_count; extr++) { const ExtruderTrain* train = meshgroup->getExtruderTrain(extr); config_per_extruder[extr].init(train->getSettingInMillimetersPerSecond("speed_prime_tower"), train->getSettingInMillimetersPerSecond("acceleration_prime_tower"), train->getSettingInMillimetersPerSecond("jerk_prime_tower"), train->getSettingInMicrons("prime_tower_line_width"), train->getSettingInPercentage("prime_tower_flow")); } } void PrimeTower::setConfigs(const MeshGroup* meshgroup, const int layer_thickness) { extruder_count = meshgroup->getExtruderCount(); for (int extr = 0; extr < extruder_count; extr++) { GCodePathConfig& conf = config_per_extruder[extr]; conf.setLayerHeight(layer_thickness); } } void PrimeTower::generateGroundpoly(const SliceDataStorage& storage) { int64_t prime_tower_wall_thickness = storage.getSettingInMicrons("prime_tower_wall_thickness"); int64_t tower_size = storage.getSettingInMicrons("prime_tower_size"); if (prime_tower_wall_thickness * 2 < tower_size) { is_hollow = true; } PolygonRef p = ground_poly.newPoly(); int tower_distance = 0; int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y p.add(Point(x + tower_distance, y + tower_distance)); p.add(Point(x + tower_distance, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance)); middle = Point(x - tower_size / 2, y + tower_size / 2); if (is_hollow) { ground_poly = ground_poly.difference(ground_poly.offset(-prime_tower_wall_thickness)); } post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2); } void PrimeTower::generatePaths(const SliceDataStorage& storage, unsigned int total_layers) { extruder_count = storage.meshgroup->getExtruderCount(); if (storage.max_print_height_second_to_last_extruder >= 0 && storage.getSettingBoolean("prime_tower_enable")) { generatePaths_denseInfill(storage); generateWipeLocations(storage); } } void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage) { int n_patterns = 2; // alternating patterns between layers int infill_overlap = 60; // so that it can't be zero; EDIT: wtf? int extra_infill_shift = 0; generateGroundpoly(storage); int64_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position for (int extruder = 0; extruder < extruder_count; extruder++) { int line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width"); patterns_per_extruder.emplace_back(n_patterns); std::vector<ExtrusionMoves>& patterns = patterns_per_extruder.back(); patterns.resize(n_patterns); for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++) { patterns[pattern_idx].polygons = ground_poly.offset(-line_width / 2); Polygons& result_lines = patterns[pattern_idx].lines; int outline_offset = -line_width; int line_distance = line_width; double fill_angle = 45 + pattern_idx * 90; Polygons result_polygons; // should remain empty, since we generate lines pattern! Infill infill_comp(EFillMethod::LINES, ground_poly, outline_offset, line_width, line_distance, infill_overlap, fill_angle, z, extra_infill_shift); infill_comp.generate(result_polygons, result_lines); } } } void PrimeTower::addToGcode(const SliceDataStorage& storage, GCodePlanner& gcodeLayer, const GCodeExport& gcode, const int layer_nr, const int prev_extruder, const int new_extruder) { if (!( storage.max_print_height_second_to_last_extruder >= 0 && storage.getSettingInMicrons("prime_tower_size") > 0) ) { return; } bool prime_tower_added = false; for (int extruder = 0; extruder < storage.meshgroup->getExtruderCount() && !prime_tower_added; extruder++) { prime_tower_added = last_prime_tower_poly_printed[extruder] == int(layer_nr); } if (prime_tower_added) { // don't print the prime tower if it has been printed already return; } if (layer_nr > storage.max_print_height_second_to_last_extruder + 1) { return; } bool pre_wipe = storage.meshgroup->getExtruderTrain(new_extruder)->getSettingBoolean("dual_pre_wipe"); bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled"); if (prev_extruder == new_extruder) { pre_wipe = false; post_wipe = false; } // pre-wipe: if (pre_wipe) { preWipe(storage, gcodeLayer, new_extruder); } addToGcode_denseInfill(storage, gcodeLayer, gcode, layer_nr, prev_extruder, new_extruder); // post-wipe: if (post_wipe) { //Make sure we wipe the old extruder on the prime tower. gcodeLayer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder)); } } void PrimeTower::addToGcode_denseInfill(const SliceDataStorage& storage, GCodePlanner& gcodeLayer, const GCodeExport& gcode, const int layer_nr, const int prev_extruder, const int new_extruder) { ExtrusionMoves& pattern = patterns_per_extruder[new_extruder][layer_nr % 2]; GCodePathConfig& config = config_per_extruder[new_extruder]; gcodeLayer.addPolygonsByOptimizer(pattern.polygons, &config); gcodeLayer.addLinesByOptimizer(pattern.lines, &config, SpaceFillType::Lines); last_prime_tower_poly_printed[new_extruder] = layer_nr; CommandSocket::sendPolygons(PrintFeatureType::Support, pattern.polygons, config.getLineWidth()); CommandSocket::sendPolygons(PrintFeatureType::Support, pattern.lines, config.getLineWidth()); } Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) { Point ret(0, 0); int absolute_starting_points = 0; for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++) { ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0); if (train.getSettingBoolean("machine_extruder_start_pos_abs")) { ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y")); absolute_starting_points++; } } if (absolute_starting_points > 0) { // take the average over all absolute starting positions ret /= absolute_starting_points; } else { // use the middle of the bed if (!storage.getSettingBoolean("machine_center_is_zero")) { ret = Point(storage.getSettingInMicrons("machine_width"), storage.getSettingInMicrons("machine_depth")) / 2; } // otherwise keep (0, 0) } return ret; } void PrimeTower::generateWipeLocations(const SliceDataStorage& storage) { Point from = getLocationBeforePrimeTower(storage); // take the closer corner of the wipe tower and generate wipe locations on that side only: // // | // | // +----- // . // ^ nozzle switch location PolygonsPointIndex segment_start; // from where to start the sequence of wipe points PolygonsPointIndex segment_end; // where to end the sequence of wipe points if (is_hollow) { // take the same start as end point so that the whole poly os covered. // find the inner polygon. segment_start = segment_end = PolygonUtils::findNearestVert(middle, ground_poly); } else { // find the single line segment closest to [from] pointing most toward [from] PolygonsPointIndex closest_vert = PolygonUtils::findNearestVert(from, ground_poly); PolygonsPointIndex prev = closest_vert.prev(); PolygonsPointIndex next = closest_vert.next(); int64_t prev_dot_score = dot(from - closest_vert.p(), turn90CCW(prev.p() - closest_vert.p())); int64_t next_dot_score = dot(from - closest_vert.p(), turn90CCW(closest_vert.p() - next.p())); if (prev_dot_score > next_dot_score) { segment_start = prev; segment_end = closest_vert; } else { segment_start = closest_vert; segment_end = next; } } // TODO: come up with alternatives for better segments once the prime tower can be different shapes PolygonUtils::spreadDots(segment_start, segment_end, number_of_pre_wipe_locations, pre_wipe_locations); } void PrimeTower::preWipe(const SliceDataStorage& storage, GCodePlanner& gcode_layer, const int extruder_nr) { const ClosestPolygonPoint wipe_location = pre_wipe_locations[current_pre_wipe_location_idx]; current_pre_wipe_location_idx = (current_pre_wipe_location_idx + pre_wipe_location_skip) % number_of_pre_wipe_locations; ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr); const int inward_dist = train.getSettingInMicrons("machine_nozzle_size") * 3 / 2 ; const int start_dist = train.getSettingInMicrons("machine_nozzle_size") * 2; const Point end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist); const Point outward_dir = wipe_location.location - end; const Point start = wipe_location.location + normal(outward_dir, start_dist); if (is_hollow) { // for hollow wipe tower: // start from above // go to wipe start // go to the Z height of the previous/current layer // wipe // go to normal layer height (automatically on the next extrusion move... GCodePath& toward_middle = gcode_layer.addTravel(middle); toward_middle.perform_z_hop = true; gcode_layer.forceNewPathStart(); GCodePath& toward_wipe_start = gcode_layer.addTravel_simple(start); toward_wipe_start.perform_z_hop = false; // TODO problem: travel moves ignore actual requested height untill destination is reached :( } else { gcode_layer.addTravel(start); } float flow = 0.0001; // force this path being interpreted as an extrusion path, so that no Z hop will occur (TODO: really separately handle travel and extrusion moves) gcode_layer.addExtrusionMove(end, &config_per_extruder[extruder_nr], SpaceFillType::None, flow); } }//namespace cura <commit_msg>doc update prime tower (CURA-2325)<commit_after>#include "PrimeTower.h" #include <limits> #include "ExtruderTrain.h" #include "sliceDataStorage.h" #include "gcodeExport.h" #include "gcodePlanner.h" #include "infill.h" #include "PrintFeature.h" namespace cura { PrimeTower::PrimeTower() : is_hollow(false) , current_pre_wipe_location_idx(0) { for (int extruder_nr = 0; extruder_nr < MAX_EXTRUDERS; extruder_nr++) { last_prime_tower_poly_printed[extruder_nr] = -1; } } void PrimeTower::initConfigs(const MeshGroup* meshgroup) { extruder_count = meshgroup->getExtruderCount(); for (int extr = 0; extr < extruder_count; extr++) { config_per_extruder.emplace_back(PrintFeatureType::Support);// so that visualization in the old Cura still works (TODO) } for (int extr = 0; extr < extruder_count; extr++) { const ExtruderTrain* train = meshgroup->getExtruderTrain(extr); config_per_extruder[extr].init(train->getSettingInMillimetersPerSecond("speed_prime_tower"), train->getSettingInMillimetersPerSecond("acceleration_prime_tower"), train->getSettingInMillimetersPerSecond("jerk_prime_tower"), train->getSettingInMicrons("prime_tower_line_width"), train->getSettingInPercentage("prime_tower_flow")); } } void PrimeTower::setConfigs(const MeshGroup* meshgroup, const int layer_thickness) { extruder_count = meshgroup->getExtruderCount(); for (int extr = 0; extr < extruder_count; extr++) { GCodePathConfig& conf = config_per_extruder[extr]; conf.setLayerHeight(layer_thickness); } } void PrimeTower::generateGroundpoly(const SliceDataStorage& storage) { int64_t prime_tower_wall_thickness = storage.getSettingInMicrons("prime_tower_wall_thickness"); int64_t tower_size = storage.getSettingInMicrons("prime_tower_size"); if (prime_tower_wall_thickness * 2 < tower_size) { is_hollow = true; } PolygonRef p = ground_poly.newPoly(); int tower_distance = 0; int x = storage.getSettingInMicrons("prime_tower_position_x"); // storage.model_max.x int y = storage.getSettingInMicrons("prime_tower_position_y"); // storage.model_max.y p.add(Point(x + tower_distance, y + tower_distance)); p.add(Point(x + tower_distance, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance + tower_size)); p.add(Point(x + tower_distance - tower_size, y + tower_distance)); middle = Point(x - tower_size / 2, y + tower_size / 2); if (is_hollow) { ground_poly = ground_poly.difference(ground_poly.offset(-prime_tower_wall_thickness)); } post_wipe_point = Point(x + tower_distance - tower_size / 2, y + tower_distance + tower_size / 2); } void PrimeTower::generatePaths(const SliceDataStorage& storage, unsigned int total_layers) { extruder_count = storage.meshgroup->getExtruderCount(); if (storage.max_print_height_second_to_last_extruder >= 0 && storage.getSettingBoolean("prime_tower_enable")) { generatePaths_denseInfill(storage); generateWipeLocations(storage); } } void PrimeTower::generatePaths_denseInfill(const SliceDataStorage& storage) { int n_patterns = 2; // alternating patterns between layers int infill_overlap = 60; // so that it can't be zero; EDIT: wtf? int extra_infill_shift = 0; generateGroundpoly(storage); int64_t z = 0; // (TODO) because the prime tower stores the paths for each extruder for once instead of generating each layer, we don't know the z position for (int extruder = 0; extruder < extruder_count; extruder++) { int line_width = storage.meshgroup->getExtruderTrain(extruder)->getSettingInMicrons("prime_tower_line_width"); patterns_per_extruder.emplace_back(n_patterns); std::vector<ExtrusionMoves>& patterns = patterns_per_extruder.back(); patterns.resize(n_patterns); for (int pattern_idx = 0; pattern_idx < n_patterns; pattern_idx++) { patterns[pattern_idx].polygons = ground_poly.offset(-line_width / 2); Polygons& result_lines = patterns[pattern_idx].lines; int outline_offset = -line_width; int line_distance = line_width; double fill_angle = 45 + pattern_idx * 90; Polygons result_polygons; // should remain empty, since we generate lines pattern! Infill infill_comp(EFillMethod::LINES, ground_poly, outline_offset, line_width, line_distance, infill_overlap, fill_angle, z, extra_infill_shift); infill_comp.generate(result_polygons, result_lines); } } } void PrimeTower::addToGcode(const SliceDataStorage& storage, GCodePlanner& gcodeLayer, const GCodeExport& gcode, const int layer_nr, const int prev_extruder, const int new_extruder) { if (!( storage.max_print_height_second_to_last_extruder >= 0 && storage.getSettingInMicrons("prime_tower_size") > 0) ) { return; } bool prime_tower_added = false; for (int extruder = 0; extruder < storage.meshgroup->getExtruderCount() && !prime_tower_added; extruder++) { prime_tower_added = last_prime_tower_poly_printed[extruder] == int(layer_nr); } if (prime_tower_added) { // don't print the prime tower if it has been printed already return; } if (layer_nr > storage.max_print_height_second_to_last_extruder + 1) { return; } bool pre_wipe = storage.meshgroup->getExtruderTrain(new_extruder)->getSettingBoolean("dual_pre_wipe"); bool post_wipe = storage.meshgroup->getExtruderTrain(prev_extruder)->getSettingBoolean("prime_tower_wipe_enabled"); if (prev_extruder == new_extruder) { pre_wipe = false; post_wipe = false; } // pre-wipe: if (pre_wipe) { preWipe(storage, gcodeLayer, new_extruder); } addToGcode_denseInfill(storage, gcodeLayer, gcode, layer_nr, prev_extruder, new_extruder); // post-wipe: if (post_wipe) { //Make sure we wipe the old extruder on the prime tower. gcodeLayer.addTravel(post_wipe_point - gcode.getExtruderOffset(prev_extruder) + gcode.getExtruderOffset(new_extruder)); } } void PrimeTower::addToGcode_denseInfill(const SliceDataStorage& storage, GCodePlanner& gcodeLayer, const GCodeExport& gcode, const int layer_nr, const int prev_extruder, const int new_extruder) { ExtrusionMoves& pattern = patterns_per_extruder[new_extruder][layer_nr % 2]; GCodePathConfig& config = config_per_extruder[new_extruder]; gcodeLayer.addPolygonsByOptimizer(pattern.polygons, &config); gcodeLayer.addLinesByOptimizer(pattern.lines, &config, SpaceFillType::Lines); last_prime_tower_poly_printed[new_extruder] = layer_nr; CommandSocket::sendPolygons(PrintFeatureType::Support, pattern.polygons, config.getLineWidth()); CommandSocket::sendPolygons(PrintFeatureType::Support, pattern.lines, config.getLineWidth()); } Point PrimeTower::getLocationBeforePrimeTower(const SliceDataStorage& storage) { Point ret(0, 0); int absolute_starting_points = 0; for (int extruder_nr = 0; extruder_nr < storage.meshgroup->getExtruderCount(); extruder_nr++) { ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(0); if (train.getSettingBoolean("machine_extruder_start_pos_abs")) { ret += Point(train.getSettingInMicrons("machine_extruder_start_pos_x"), train.getSettingInMicrons("machine_extruder_start_pos_y")); absolute_starting_points++; } } if (absolute_starting_points > 0) { // take the average over all absolute starting positions ret /= absolute_starting_points; } else { // use the middle of the bed if (!storage.getSettingBoolean("machine_center_is_zero")) { ret = Point(storage.getSettingInMicrons("machine_width"), storage.getSettingInMicrons("machine_depth")) / 2; } // otherwise keep (0, 0) } return ret; } void PrimeTower::generateWipeLocations(const SliceDataStorage& storage) { Point from = getLocationBeforePrimeTower(storage); PolygonsPointIndex segment_start; // from where to start the sequence of wipe points PolygonsPointIndex segment_end; // where to end the sequence of wipe points if (is_hollow) { // take the same start as end point so that the whole poly os covered. // find the inner polygon. segment_start = segment_end = PolygonUtils::findNearestVert(middle, ground_poly); } else { // take the closer corner of the wipe tower and generate wipe locations on that side only: // // | // | // +----- // . // ^ nozzle switch location // find the single line segment closest to [from] pointing most toward [from] PolygonsPointIndex closest_vert = PolygonUtils::findNearestVert(from, ground_poly); PolygonsPointIndex prev = closest_vert.prev(); PolygonsPointIndex next = closest_vert.next(); int64_t prev_dot_score = dot(from - closest_vert.p(), turn90CCW(prev.p() - closest_vert.p())); int64_t next_dot_score = dot(from - closest_vert.p(), turn90CCW(closest_vert.p() - next.p())); if (prev_dot_score > next_dot_score) { segment_start = prev; segment_end = closest_vert; } else { segment_start = closest_vert; segment_end = next; } } PolygonUtils::spreadDots(segment_start, segment_end, number_of_pre_wipe_locations, pre_wipe_locations); } void PrimeTower::preWipe(const SliceDataStorage& storage, GCodePlanner& gcode_layer, const int extruder_nr) { const ClosestPolygonPoint wipe_location = pre_wipe_locations[current_pre_wipe_location_idx]; current_pre_wipe_location_idx = (current_pre_wipe_location_idx + pre_wipe_location_skip) % number_of_pre_wipe_locations; ExtruderTrain& train = *storage.meshgroup->getExtruderTrain(extruder_nr); const int inward_dist = train.getSettingInMicrons("machine_nozzle_size") * 3 / 2 ; const int start_dist = train.getSettingInMicrons("machine_nozzle_size") * 2; const Point end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist); const Point outward_dir = wipe_location.location - end; const Point start = wipe_location.location + normal(outward_dir, start_dist); if (is_hollow) { // for hollow wipe tower: // start from above // go to wipe start // go to the Z height of the previous/current layer // wipe // go to normal layer height (automatically on the next extrusion move... GCodePath& toward_middle = gcode_layer.addTravel(middle); toward_middle.perform_z_hop = true; gcode_layer.forceNewPathStart(); GCodePath& toward_wipe_start = gcode_layer.addTravel_simple(start); toward_wipe_start.perform_z_hop = false; // TODO problem: travel moves ignore actual requested height untill destination is reached :( } else { gcode_layer.addTravel(start); } float flow = 0.0001; // force this path being interpreted as an extrusion path, so that no Z hop will occur (TODO: really separately handle travel and extrusion moves) gcode_layer.addExtrusionMove(end, &config_per_extruder[extruder_nr], SpaceFillType::None, flow); } }//namespace cura <|endoftext|>
<commit_before><commit_msg>Coverity: Remove the check for index < 0 because index is a size_t and can never be < 0.<commit_after><|endoftext|>
<commit_before>/* * Ubitrack - Library for Ubiquitous Tracking * Copyright 2006, Technische Universitaet Muenchen, and individual * contributors as indicated by the @authors tag. See the * copyright.txt in the distribution for a full listing of individual * contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * @ingroup vision_components * @file * Finding the edges of a chessboard in an image * * @author Daniel Muhra <muhra@in.tum.de> */ #include <utDataflow/Component.h> #include <utDataflow/PushConsumer.h> #include <utDataflow/PushSupplier.h> #include <utDataflow/ComponentFactory.h> #include <utMeasurement/Measurement.h> #include <utMath/Vector.h> #include <utCalibration/Homography.h> #include <utCalibration/Munkres.h> #include <fstream> #include <sstream> #include <boost/scoped_array.hpp> #include <utVision/Image.h> #include <opencv/cv.h> namespace ublas = boost::numeric::ublas; namespace Ubitrack { namespace Vision { /** * @ingroup vision_components * ReorderGrid component. * This class contains a interprets a number of 2D Points as Grid and reorders them in an arranged, constant form. * * @par Input Ports * PushConsumer< Measurement::PositionList2 > of name "Input" * * @par Output Ports * PushSupplier<Measurement::PositionList2> with name "Output". * * @par Configuration * \c gridHeight: number of edges the grid has (height). * \c gridWidth: number of edges the grid has (width). * * @par Operation * The component returns a vector of 2D coordinates which represents the edges of an given grid * * @par Example Configuration * \verbatim <Pattern name="ReorderGrid" id="ReorderGrid1"> <Input> <Node name="Camera" id="Camera"/> <Node name="Grid" id="Grid"> <Attribute name="gridHeight" value="4"/> <Attribute name="gridWidth" value="4"/> </Node> <Node name="ImagePlane" id="ImagePlane"/> <Edge name="Input" source="Camera" destination="ImagePlane" pattern-ref="..." edge-ref="..."/> </Input> <Output> <Edge name="Output" source="Camera" destination="ImagePlane"/> </Output> <DataflowConfiguration> <UbitrackLib class="ReorderGrid"/> </DataflowConfiguration> </Pattern> \endverbatim */ class ReorderGridComponent : public Dataflow::Component { public: /** * Standard component constructor. * * @param sName Unique name of the component. * @param cfg ComponentConfiguration containing all configuration. */ ReorderGridComponent( const std::string& sName, boost::shared_ptr< Graph::UTQLSubgraph > pCfg ) : Dataflow::Component( sName ) , m_height( -1 ) , m_width( -1 ) , m_inPort( "Input", *this, boost::bind( &ReorderGridComponent::pushPoints, this, _1 ) ) , m_outPort( "Output", *this ) { // get height and width attributes from ChessBoard node Graph::UTQLSubgraph::NodePtr pCbNode = pCfg->getNode( "Grid" ); pCbNode->getAttributeData( "gridHeight", m_height ); pCbNode->getAttributeData( "gridWidth", m_width ); m_edges = m_height * m_width; for(int i=0; i < m_edges ;i++) { objPoints.push_back( Math::Vector< 2 >( double( i % m_height), double( i / m_height) ) ); } if ( m_height < 0 || m_width < 0 ) UBITRACK_THROW( "Grid nodes has no gridHeight or gridWidth attribute" ); } /** computes the angle */ double theta( const Math::Vector< 2 > & p1, const Math::Vector< 2 > & p2 ) { Math::Vector< 2 > dist = p2 - p1; double ax = abs( dist( 0 ) ); double ay = abs( dist( 1 ) ); double t = 0.0; if( ax + ay == 0.0 ) return 0.0; else t = dist( 1 ) / ( ax + ay ); if( dist( 0 ) < 0.0 ) t = 2 - t; else if( dist( 1 ) < 0.0 ) t = 4 + t; return t * 90.0; } /** computes the convex hull*/ unsigned int wrap( std::vector< Math::Vector< 2 > > & pts ) { Math::Vector< 2 > temp; unsigned int min = 0; unsigned int m = 0; unsigned int n = pts.size(); double minangle = 0.0; double v; for( unsigned int i = 1; i < pts.size(); i++ ) { if( pts.at( i )( 1 ) < pts.at( min )( 1 ) ) min = i; } pts.push_back( pts.at( min ) ); while( min != n ) { m++; temp = pts.at( m - 1 ); pts.at( m - 1 ) = pts.at( min ); pts.at( min ) = temp; min = n; v = minangle; minangle = 360.0; for( unsigned int i = m; i < n+1; i++ ) { double w = theta( pts.at( m - 1 ), pts.at( i ) ); if( w > v && w < minangle ) { min = i; minangle = w; } } } pts.pop_back(); return m; } /** computes the angle described by three points*/ double radiant( const Math::Vector< 2 > & x, const Math::Vector< 2 > & y, const Math::Vector< 2 > & z ) { double val = ublas::norm_2( z - y ); double val2 = ublas::norm_2( x - y ); if( val != 0 && val2 != 0) { val = ublas::inner_prod( ( z - y ) / val, ( x - y ) / val2 ); if( val < 0 ) return -val; else return val; } return 1; } /** computes the projected points*/ std::vector< Math::Vector< 2 > > getProjectedPoints( const std::vector< Math::Vector< 2 > > & pts, const unsigned int m ) { Math::Matrix< 3, 3 > H; std::vector< Math::Vector< 2 > > from; std::vector< Math::Vector< 2 > > to; std::vector< Math::Vector< 2 > > projected; Math::Vector< 2 > temp; temp( 0 ) = 0.0; temp( 1 ) = 0.0; to.push_back( temp ); temp( 0 ) = double( m_width - 1 ); temp( 1 ) = 0.0; to.push_back( temp ); temp( 0 ) = double( m_width - 1 ); temp( 1 ) = double( m_height - 1 ); to.push_back( temp ); temp( 0 ) = 0.0; temp( 1 ) = double( m_height - 1 ); to.push_back( temp ); if( m < 4 ) { return projected; } else if( m == 4 ) { from.push_back( pts.at( 0 ) ); from.push_back( pts.at( 1 ) ); from.push_back( pts.at( 2 ) ); from.push_back( pts.at( 3 ) ); } else //find 4 points with angle about 90 degrees { bool* picked = new bool[ m ]; //for initialization for( unsigned int i=0; i< m; i++ ) { picked[i] = false; } for( unsigned int i=0; i < 4; i++ ) { //set to any (not picked) val int index = 0; while( picked[index] ) { index++; } double min = 1.0; //look for smallest angle for( unsigned int j=m; j< 2*m; j++ ) { if( !picked[ j % m ] ) { double rad = radiant( pts.at( ( j - 1 ) % m ), pts.at( j % m ), pts.at( ( j + 1 ) % m ) ); if( rad < min ) { min = rad; index = j % m; } } } picked[ index ] = true; } //pick those 4 edge points in their oder for( unsigned int i=0; i< m; i++ ) { if( picked[i] ) from.push_back( pts.at( i ) ); } } H = Calibration::homographyDLT( from, to ); for( unsigned int i=0; i < pts.size(); i++ ) { Math::Vector< 3 > p( pts.at( i )( 0 ), pts.at( i )( 1 ), 1.0 ); p = ublas::prod( H, p ); projected.push_back( Math::Vector< 2 >( p( 0 ) / p ( 2 ), p( 1 ) / p( 2 ) ) ); } return projected; } /** computes the correspondences*/ std::vector< unsigned int > getCorrespondences( std::vector< Math::Vector< 2 > > & from, std::vector< Math::Vector< 2 > > & to ) { unsigned int fSize = from.size(); unsigned int tSize = to.size(); ublas::matrix< double > matrix( fSize, tSize ); for( unsigned int row=0; row<fSize; row++ ) { for( unsigned int col=0; col<tSize; col++ ) { matrix( row, col ) = ublas::norm_2( Math::Vector< 2 >( from.at(row) ) - to.at(col) ); } } Calibration::Munkres< double > m( matrix ); m.solve(); //match for constructed chessboard return m.getColMatchList(); } /** Method that computes the result. */ void pushPoints( const Measurement::PositionList2 pm ) { if( ( *pm ).size() == (unsigned int)m_edges ) { std::vector< Math::Vector< 2 > > pts = *pm; std::vector< Math::Vector< 2 > > lol; //sort in a way, that the hull points are at the beginning unsigned int m = wrap( pts ); //get the projected points std::vector< Math::Vector< 2 > > projected = getProjectedPoints( pts, m ); //to find out, how to sort the new points std::vector< unsigned int > corr = getCorrespondences( projected, objPoints ); std::vector< Math::Vector< 2 > > pts2; for(int i=0; i < m_edges ;i++) { pts2.push_back( pts.at( corr.at( i ) ) ); } //m_outPort.send(Measurement::PositionList2( pm.time(), projected ) ); m_outPort.send(Measurement::PositionList2( pm.time(), pts2 ) ); } } protected: /** defines the chessboard to be tracked */ int m_height; int m_width; int m_edges; std::vector< Math::Vector< 2 > > objPoints; /** Input port of the component. */ Dataflow::PushConsumer< Measurement::PositionList2 > m_inPort; /** Output ports of the component. */ Dataflow::PushSupplier< Measurement::PositionList2 > m_outPort; }; UBITRACK_REGISTER_COMPONENT( Dataflow::ComponentFactory* const cf ) { cf->registerComponent< ReorderGridComponent > ( "ReorderGrid" ); } } } // namespace Ubitrack::Components <commit_msg>ok, last change for today, so everything is fine again<commit_after>/* * Ubitrack - Library for Ubiquitous Tracking * Copyright 2006, Technische Universitaet Muenchen, and individual * contributors as indicated by the @authors tag. See the * copyright.txt in the distribution for a full listing of individual * contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * @ingroup vision_components * @file * Finding the edges of a chessboard in an image * * @author Daniel Muhra <muhra@in.tum.de> */ #include <utDataflow/Component.h> #include <utDataflow/PushConsumer.h> #include <utDataflow/PushSupplier.h> #include <utDataflow/ComponentFactory.h> #include <utMeasurement/Measurement.h> #include <utMath/Vector.h> #include <utCalibration/Homography.h> #include <utCalibration/Munkres.h> #include <fstream> #include <sstream> #include <boost/scoped_array.hpp> #include <utVision/Image.h> #include <opencv/cv.h> namespace ublas = boost::numeric::ublas; namespace Ubitrack { namespace Vision { /** * @ingroup vision_components * ReorderGrid component. * This class contains a interprets a number of 2D Points as Grid and reorders them in an arranged, constant form. * * @par Input Ports * PushConsumer< Measurement::PositionList2 > of name "Input" * * @par Output Ports * PushSupplier<Measurement::PositionList2> with name "Output". * * @par Configuration * \c gridHeight: number of edges the grid has (height). * \c gridWidth: number of edges the grid has (width). * * @par Operation * The component returns a vector of 2D coordinates which represents the edges of an given grid * * @par Example Configuration * \verbatim <Pattern name="ReorderGrid" id="ReorderGrid1"> <Input> <Node name="Camera" id="Camera"/> <Node name="Grid" id="Grid"> <Attribute name="gridHeight" value="4"/> <Attribute name="gridWidth" value="4"/> </Node> <Node name="ImagePlane" id="ImagePlane"/> <Edge name="Input" source="Camera" destination="ImagePlane" pattern-ref="..." edge-ref="..."/> </Input> <Output> <Edge name="Output" source="Camera" destination="ImagePlane"/> </Output> <DataflowConfiguration> <UbitrackLib class="ReorderGrid"/> </DataflowConfiguration> </Pattern> \endverbatim */ class ReorderGridComponent : public Dataflow::Component { public: /** * Standard component constructor. * * @param sName Unique name of the component. * @param cfg ComponentConfiguration containing all configuration. */ ReorderGridComponent( const std::string& sName, boost::shared_ptr< Graph::UTQLSubgraph > pCfg ) : Dataflow::Component( sName ) , m_height( -1 ) , m_width( -1 ) , m_inPort( "Input", *this, boost::bind( &ReorderGridComponent::pushPoints, this, _1 ) ) , m_outPort( "Output", *this ) { // get height and width attributes from ChessBoard node Graph::UTQLSubgraph::NodePtr pCbNode = pCfg->getNode( "Grid" ); pCbNode->getAttributeData( "gridHeight", m_height ); pCbNode->getAttributeData( "gridWidth", m_width ); m_edges = m_height * m_width; for(int i=0; i < m_edges ;i++) { objPoints.push_back( Math::Vector< 2 >( double( i % m_height), double( i / m_height) ) ); } if ( m_height < 0 || m_width < 0 ) UBITRACK_THROW( "Grid nodes has no gridHeight or gridWidth attribute" ); } /** computes the angle */ double theta( const Math::Vector< 2 > & p1, const Math::Vector< 2 > & p2 ) { Math::Vector< 2 > dist = p2 - p1; double ax = abs( dist( 0 ) ); double ay = abs( dist( 1 ) ); double t = 0.0; if( ax + ay == 0.0 ) return 0.0; else t = dist( 1 ) / ( ax + ay ); if( dist( 0 ) < 0.0 ) t = 2 - t; else if( dist( 1 ) < 0.0 ) t = 4 + t; return t * 90.0; } /** computes the convex hull*/ unsigned int wrap( std::vector< Math::Vector< 2 > > & pts ) { Math::Vector< 2 > temp; unsigned int min = 0; unsigned int m = 0; unsigned int n = pts.size(); double minangle = 0.0; double v; for( unsigned int i = 1; i < pts.size(); i++ ) { if( pts.at( i )( 1 ) < pts.at( min )( 1 ) ) min = i; } pts.push_back( pts.at( min ) ); while( min != n ) { m++; temp = pts.at( m - 1 ); pts.at( m - 1 ) = pts.at( min ); pts.at( min ) = temp; min = n; v = minangle; minangle = 360.0; for( unsigned int i = m; i < n+1; i++ ) { double w = theta( pts.at( m - 1 ), pts.at( i ) ); if( w > v && w < minangle ) { min = i; minangle = w; } } } pts.pop_back(); return m; } /** computes the angle described by three points*/ double radiant( const Math::Vector< 2 > & x, const Math::Vector< 2 > & y, const Math::Vector< 2 > & z ) { double val = ublas::norm_2( z - y ); double val2 = ublas::norm_2( x - y ); if( val != 0 && val2 != 0) { val = ublas::inner_prod( ( z - y ) / val, ( x - y ) / val2 ); if( val < 0 ) return -val; else return val; } return 1; } /** computes the projected points*/ std::vector< Math::Vector< 2 > > getProjectedPoints( const std::vector< Math::Vector< 2 > > & pts, const unsigned int m ) { Math::Matrix< 3, 3 > H; std::vector< Math::Vector< 2 > > from; std::vector< Math::Vector< 2 > > to; std::vector< Math::Vector< 2 > > projected; Math::Vector< 2 > temp; temp( 0 ) = 0.0; temp( 1 ) = 0.0; to.push_back( temp ); temp( 0 ) = double( m_width - 1 ); temp( 1 ) = 0.0; to.push_back( temp ); temp( 0 ) = double( m_width - 1 ); temp( 1 ) = double( m_height - 1 ); to.push_back( temp ); temp( 0 ) = 0.0; temp( 1 ) = double( m_height - 1 ); to.push_back( temp ); if( m < 4 ) { return projected; } else if( m == 4 ) { from.push_back( pts.at( 0 ) ); from.push_back( pts.at( 1 ) ); from.push_back( pts.at( 2 ) ); from.push_back( pts.at( 3 ) ); } else //find 4 points with angle about 90 degrees { bool* picked = new bool[ m ]; //for initialization for( unsigned int i=0; i< m; i++ ) { picked[i] = false; } for( unsigned int i=0; i < 4; i++ ) { //set to any (not picked) val int index = 0; while( picked[index] ) { index++; } double min = 1.0; //look for smallest angle for( unsigned int j=m; j< 2*m; j++ ) { if( !picked[ j % m ] ) { double rad = radiant( pts.at( ( j - 1 ) % m ), pts.at( j % m ), pts.at( ( j + 1 ) % m ) ); if( rad < min ) { min = rad; index = j % m; } } } picked[ index ] = true; } //pick those 4 edge points in their oder for( unsigned int i=0; i< m; i++ ) { if( picked[i] ) from.push_back( pts.at( i ) ); } } H = Calibration::homographyDLT( from, to ); for( unsigned int i=0; i < pts.size(); i++ ) { Math::Vector< 3 > p( pts.at( i )( 0 ), pts.at( i )( 1 ), 1.0 ); p = ublas::prod( H, p ); projected.push_back( Math::Vector< 2 >( p( 0 ) / p ( 2 ), p( 1 ) / p( 2 ) ) ); } return projected; } /** computes the correspondences*/ std::vector< std::size_t > getCorrespondences( std::vector< Math::Vector< 2 > > & from, std::vector< Math::Vector< 2 > > & to ) { std::size_t fSize = from.size(); std::size_t tSize = to.size(); ublas::matrix< double > matrix( fSize, tSize ); for( std::size_t row=0; row<fSize; row++ ) { for( std::size_t col=0; col<tSize; col++ ) { matrix( row, col ) = ublas::norm_2( Math::Vector< 2 >( from.at(row) ) - to.at(col) ); } } Calibration::Munkres< double > m( matrix ); m.solve(); //match for constructed chessboard return m.getColMatchList(); } /** Method that computes the result. */ void pushPoints( const Measurement::PositionList2 pm ) { if( ( *pm ).size() == (unsigned int)m_edges ) { std::vector< Math::Vector< 2 > > pts = *pm; std::vector< Math::Vector< 2 > > lol; //sort in a way, that the hull points are at the beginning unsigned int m = wrap( pts ); //get the projected points std::vector< Math::Vector< 2 > > projected = getProjectedPoints( pts, m ); //to find out, how to sort the new points std::vector< std::size_t > corr = getCorrespondences( projected, objPoints ); std::vector< Math::Vector< 2 > > pts2; for( std::size_t i( 0 ); i < m_edges; ++i ) { pts2.push_back( pts.at( corr.at( i ) ) ); } //m_outPort.send(Measurement::PositionList2( pm.time(), projected ) ); m_outPort.send(Measurement::PositionList2( pm.time(), pts2 ) ); } } protected: /** defines the chessboard to be tracked */ int m_height; int m_width; int m_edges; std::vector< Math::Vector< 2 > > objPoints; /** Input port of the component. */ Dataflow::PushConsumer< Measurement::PositionList2 > m_inPort; /** Output ports of the component. */ Dataflow::PushSupplier< Measurement::PositionList2 > m_outPort; }; UBITRACK_REGISTER_COMPONENT( Dataflow::ComponentFactory* const cf ) { cf->registerComponent< ReorderGridComponent > ( "ReorderGrid" ); } } } // namespace Ubitrack::Components <|endoftext|>
<commit_before> #include "Fluid.h" #include "HalfEdge.h" #include "Quaternion.h" #include "Vector.h" #include <Math.h> /* pi */ #define EPSILON 1e-6 namespace DDG { Fluid :: Fluid( Mesh*& surface_ptr, const ProjectionComponent& projectType ) :fluid_ptr( surface_ptr ) { // Initiate anything else? buildOperators( ); // Project pressure to guarantee initially divergence free field: if( projectType == CURL ){ projectCurl( ); } else if( projectType == DIV ){ projectDivergence( ); } else if ( projectType == HARMONIC ){ projectHarmonic( ); } else{ std::cerr << "Projection Component not implemented, exiting" << std::endl; return; } } Fluid :: ~Fluid( void ) {} void Fluid :: buildOperators( ) { HodgeStar0Form<Real>::build(*fluid_ptr, star0); HodgeStar1Form<Real>::build(*fluid_ptr, star1); HodgeStar2Form<Real>::build(*fluid_ptr, star2); ExteriorDerivative0Form<Real>::build(*fluid_ptr, d0); ExteriorDerivative1Form<Real>::build(*fluid_ptr, d1); } /* void Fluid :: flow( const float& dt, const AdvectionScheme& advectType, const ProjectionComponent& projectType, const Interpolation& interpType ) { assert( dt > 0. ); //TODO: check for interaction/input/Forces //advect velocity field if( advectType == SEMI_LAGRANGIAN ) { advectSemiLagrangian( dt ); } else{ std::cerr << "Advection Scheme not implemeted, exiting" << std::endl; return; } updateEdgeWeights( ); //project pressure under some criteria: if( projectType == CURL ){ projectCurl( ); } else if( projectType == DIV ){ projectDivergence( ); } else if ( projectType == HARMONIC ){ projectHarmonic( ); } else{ std::cerr << "Projection Component not implemented, exiting" << std::endl; return; } updateEdgeWeights( ); //advectMarker along the flow... update visualization (here? or in view?) advectMarkers( dt ); } */ void Fluid :: advectSemiLagrangian( const float& dt ) { for( EdgeIter e = fluid_ptr->edges.begin(); e != fluid_ptr->edges.end(); ++e ) { // Get center of edge Vector edge_vec = e->he->flip->vertex->position - e->he->vertex->position; Vector edge_crossing_coord = e->he->vertex->position + ( edge_vec / 2 ); // Integrate the velocity along the edge (get velocity at edge midpoint) // by interpolating one of the two bordering triangle faces Vector original_velocity = whitneyInterpolate( edge_crossing_coord, e ); // Determine which halfEdge to use (face associated with velocity direction) HalfEdgeIter current_he = dot( cross( edge_vec, original_velocity ), e->he->face->normal() ) > 0.0 ? e->he : e->he->flip; // TODO: Clean this up // Walk along this direction for distance [ h = v*dt ] Quaternion accumulated_angle; Vector final_coordinate; // Keep track of how much distance is left and the direction you are going (which must be tangent to the surface) // This assumes for small timesteps velocity is constant and so we step straight in one direction double h_remains = original_velocity.norm() * dt; Vector direction = original_velocity; direction.normalize(); while( h_remains > 0 ) ////what happens at mesh boundaries??? { // determine which of two other edges would be intersected first double counter = rayLineIntersectDistance( edge_crossing_coord, direction, current_he->next ); double clockwise = rayLineIntersectDistance( edge_crossing_coord, direction, current_he->next->next ); HalfEdgeIter crossing_he = counter < clockwise ? current_he->next : current_he->next->next; double distance = counter < clockwise ? counter : clockwise; if( h_remains > distance ) // Flip to the next face, continue to travel remaider of h { edge_crossing_coord += distance * direction; double theta = acos( dot( crossing_he->flip->face->normal(), current_he->face->normal() ) ); Quaternion angleChange = Quaternion( cos(theta/2), sin(theta/2)*direction); accumulated_angle = accumulated_angle * angleChange; direction = ( angleChange * Quaternion( direction ) * angleChange.conj() ).im(); //TODO: At every crossing should I also change direction to follow new field direction at crossing (?) // If we do this then we are curving along the field path as we travel a distance h, removing the small timestep assumption (!) // Although this is more advanced/accurate, if dt is small enough this will introduce unnecessary computation // This can be done simply by recomputing the velocity (WhitneyInterp) at edge crossings everytime instead of turning/curving the direction vec current_he = crossing_he->flip; } else{ final_coordinate = edge_crossing_coord + h_remains * direction; } h_remains -= distance; } // Compute interpolated velocity at this point Vector acquired_velocity = whitneyInterpolate( final_coordinate, current_he ); // current_he is now inside triangle face we care about // Parallel transport the velocity back to the original face // (rotate direction vector back by accumulated angle) acquired_velocity = ( accumulated_angle.conj() * Quaternion( acquired_velocity ) * accumulated_angle ).im(); assert( std::abs( dot( acquired_velocity, e->he->face->normal() ) ) <= EPSILON ); // acquired_velocity lives on plane of original face // Update the velocity at initial edge to be the dot product of aquired velocity with original velocity double advectedWeight = dot( acquired_velocity, edge_vec ); e->setCoef( advectedWeight ); } } void Fluid :: projectCurl( void ) { std::cerr << "Projection of Curl is not yet implemented, exiting" << std::endl; return; } void Fluid :: projectDivergence( void ) // first solve [ d * dp = d * u ] then solve [ u_new = u - dp ] { unsigned V = fluid_ptr->vertices.size(); unsigned E = fluid_ptr->edges.size(); // retrive vector of edge weights ( u ) DenseMatrix<Real> u = DenseMatrix<Real>(E, 1); for( EdgeIter e = fluid_ptr->edges.begin(); e != fluid_ptr->edges.end(); ++e ){ assert( 0 <= e->index && e->index < E ); u( e->getID() ) = fluid_ptr->edges[ e->getID() ].getCoef(); } SparseMatrix<Real> A( V, V ); A = ( d0.transpose() ) * star1 * d0; A.shift( 1e-15 ); SparseFactor<Real> L; L.build( A ); DenseMatrix<Real> divU( V, 1 ); divU = ( d0.transpose() ) * star1 * u; DenseMatrix<Real> p( V, 1 ); backsolvePositiveDefinite( L, x, y ); // ???, where to p and divU get used? DenseMatrix<Real> gradP( E, 1 ); gradP = d0 * p; for( EdgeIter e = fluid_ptr->edges.begin(); e != fluid_ptr->edges.end(); ++e ){ double u_new = e->getCoef() - gradP( e->getID() ); e->setCoef( u_new ); } } void Fluid :: projectHarmonic( void ) { std::cerr << "Projection of Harmonic is not yet implemented, exiting" << std::endl; return; } double Fluid :: rayLineIntersectDistance( const Vector& coordinate, const Vector& direction, const HalfEdgeIter& half_edge ) // ray should never negatively intersect with halfEdge // since rays are emitted internally to a triangle from the border { // Should assert not to be negative, else it will always be the smallest on error return 1e10; // Error should return large, not small distance, if anything } void Fluid :: updateEdgeWeights( ) { for( EdgeIter e = fluid_ptr->edges.begin(); e != fluid_ptr->edges.end(); ++e ) { e->updateRefCoef(); } } Vector Fluid :: whitneyInterpolate( const Vector& coordinate, const EdgeIter& edge ) { assert( coordinate lies on plane created by the edges neighboring triangle faces ); // Calls whitneyInterpolate( coordinate, HALF_EDGE ) twice for neighboring triangles of edge Vector left = whitneyInterpolate( coordinate, edge->he ); Vector right = whitneyInterpolate( coordinate, edge->he->flip ); // check if edge_wise components of vectors are the same assert( dot( left, ( e->he->flip->vertex->position - e->he->vertex->position ) ) == dot( right, ( e->he->flip->vertex->position - e->he->vertex->position ) ) ); // averages the flux/normal components to the edge and keeps the same edgewise component? // need to take the averaged component and project it down onto the face that dominates (otherwise the edge_normal component is off the surface) // TODO: if we find we get a lot of viscosity/damping on our flow, we might find taking the MAX or Min side here is better (?) // ...For now we just take the largest. return left.norm() > right.norm() ? left : right; } void Fluid :: BarycentricWeights( const Vector coordinate, const Vector v_i, const Vector v_j, const Vector v_k, float &a_i, float &a_j, float &a_k) { Vector v0 = v_j - v_i; Vector v1 = v_k - v_i; Vector v2 = coordinate - v_i; float d00 = dot( v0, v0 ); float d01 = dot( v0, v1 ); float d11 = dot( v1, v1 ); float d20 = dot( v2, v0 ); float d21 = dot( v2, v1 ); float denom = d00 * d11 - d01 * d01; a_j = (d11 * d20 - d01 * d21) / denom; a_k = (d00 * d21 - d01 * d20) / denom; a_i = 1.0f - a_j - a_k; assert( 0. <= a_i && a_i <= 1. && "Coordinate lies outside of triangle!" ); assert( 0. <= a_j && a_j <= 1. && "Coordinate lies outside of triangle!" ); assert( 0. <= a_k && a_k <= 1. && "Coordinate lies outside of triangle!" ); } /* For Details, see Design of Tangent Vector Fields [Fisher et alia 07] k / \ C_ki / \ C_jk / \ i ------- j C_ij Barycentric Coords: a_i, a_j, a_k Triangle Fact Area: Area = face.area() Perpendicular Edge Vectors: P_ij, P_jk, P_ki 90 degrees rotation about plane of triangle: theta = PI/2; Q90 = Quaternion( cos(theta/2), sin(theta/2)* Face_normal ); P_ij = ( Q90 ( Pj - Pi ) Q90.conj() ).im() Interpolated Vector: u( a_i, a_j, a_k ) = ( ( C_ki*a_k - C_ij*a_j ) * P_jk + ( C_ij*a_i - C_jk*a_k ) * P_ki + ( C_jk*a_j - C_ki*a_i ) * P_ij ) / ( 2 * Area ); */ Vector Fluid :: whitneyInterpolate( const Vector& coordinate, const HalfEdgeIter& he ) { // compute whitney interpolation vector quantity for a point inside a triangle // Find barycentric weights of coordinate: float a_i, a_j, a_k; Vector i = he->vertex->position; Vector j = he->next->vertex->position; Vector k = he->next->next->vertex->position; BarycentricWeights( coordinate, i, j, k, a_i, a_j, a_k ); // Already asserts coordinate lies on triangle face // Compute Perpendicular Edge Vectors: double theta = M_PI / 2; Quaternion Q_perp = Quaternion( cos(theta/2), sin(theta/2) * he->face->normal() ); Vector P_ij = ( Q_perp * ( j - i ) * Q_perp.conj() ).im(); Vector P_jk = ( Q_perp * ( k - j ) * Q_perp.conj() ).im(); Vector P_ki = ( Q_perp * ( i - k ) * Q_perp.conj() ).im(); assert( std::abs( dot( P_ij, ( j - i ) ) ) <= EPSILON ); assert( std::abs( dot( P_jk, ( k - j ) ) ) <= EPSILON ); assert( std::abs( dot( P_ki, ( i - k ) ) ) <= EPSILON ); //Retrieve edge weights double C_ij = he->edge->getCoef(); double C_jk = he->next->edge->getCoef(); double C_ki = he->next->next->edge->getCoef(); // Return Interpolated Vector Vector interp_vec = ( ( C_ki * a_k - C_ij * a_j ) * P_jk + ( C_ij * a_i - C_jk * a_k ) * P_ki + ( C_jk * a_j - C_ki * a_i ) * P_ij ) / ( 2 * he->face->area() ); assert( std::abs( dot( he->face->normal(), interp_vec ) ) <= EPSILON ); // vector lies on the plane of the triangle face return interp_vec; } } <commit_msg>RayEdgeIntersection<commit_after> #include "Fluid.h" #include "HalfEdge.h" #include "Quaternion.h" #include "Vector.h" #include <Math.h> /* pi */ #define EPSILON 1e-6 namespace DDG { Fluid :: Fluid( Mesh*& surface_ptr, const ProjectionComponent& projectType ) :fluid_ptr( surface_ptr ) { // Initiate anything else? buildOperators( ); // Project pressure to guarantee initially divergence free field: if( projectType == CURL ){ projectCurl( ); } else if( projectType == DIV ){ projectDivergence( ); } else if ( projectType == HARMONIC ){ projectHarmonic( ); } else{ std::cerr << "Projection Component not implemented, exiting" << std::endl; return; } } Fluid :: ~Fluid( void ) {} void Fluid :: buildOperators( ) { HodgeStar0Form<Real>::build(*fluid_ptr, star0); HodgeStar1Form<Real>::build(*fluid_ptr, star1); HodgeStar2Form<Real>::build(*fluid_ptr, star2); ExteriorDerivative0Form<Real>::build(*fluid_ptr, d0); ExteriorDerivative1Form<Real>::build(*fluid_ptr, d1); } /* void Fluid :: flow( const float& dt, const AdvectionScheme& advectType, const ProjectionComponent& projectType, const Interpolation& interpType ) { assert( dt > 0. ); //TODO: check for interaction/input/Forces //advect velocity field if( advectType == SEMI_LAGRANGIAN ) { advectSemiLagrangian( dt ); } else{ std::cerr << "Advection Scheme not implemeted, exiting" << std::endl; return; } updateEdgeWeights( ); //project pressure under some criteria: if( projectType == CURL ){ projectCurl( ); } else if( projectType == DIV ){ projectDivergence( ); } else if ( projectType == HARMONIC ){ projectHarmonic( ); } else{ std::cerr << "Projection Component not implemented, exiting" << std::endl; return; } updateEdgeWeights( ); //advectMarker along the flow... update visualization (here? or in view?) advectMarkers( dt ); } */ void Fluid :: advectSemiLagrangian( const float& dt ) { for( EdgeIter e = fluid_ptr->edges.begin(); e != fluid_ptr->edges.end(); ++e ) { // Get center of edge Vector edge_vec = e->he->flip->vertex->position - e->he->vertex->position; Vector edge_crossing_coord = e->he->vertex->position + ( edge_vec / 2 ); // Integrate the velocity along the edge (get velocity at edge midpoint) // by interpolating one of the two bordering triangle faces Vector original_velocity = whitneyInterpolate( edge_crossing_coord, e ); // Determine which halfEdge to use (face associated with velocity direction) HalfEdgeIter current_he = dot( cross( edge_vec, original_velocity ), e->he->face->normal() ) > 0.0 ? e->he : e->he->flip; // TODO: Clean this up // Walk along this direction for distance [ h = v*dt ] Quaternion accumulated_angle; Vector final_coordinate; // Keep track of how much distance is left and the direction you are going (which must be tangent to the surface) // This assumes for small timesteps velocity is constant and so we step straight in one direction double h_remains = original_velocity.norm() * dt; Vector direction = original_velocity; direction.normalize(); while( h_remains > 0 ) ////what happens at mesh boundaries??? { // determine which of two other edges would be intersected first double counter = rayLineIntersectDistance( edge_crossing_coord, direction, current_he->next ); double clockwise = rayLineIntersectDistance( edge_crossing_coord, direction, current_he->next->next ); HalfEdgeIter crossing_he = counter < clockwise ? current_he->next : current_he->next->next; double distance = counter < clockwise ? counter : clockwise; if( h_remains > distance ) // Flip to the next face, continue to travel remaider of h { edge_crossing_coord += distance * direction; double theta = acos( dot( crossing_he->flip->face->normal(), current_he->face->normal() ) ); Quaternion angleChange = Quaternion( cos(theta/2), sin(theta/2)*direction); accumulated_angle = accumulated_angle * angleChange; direction = ( angleChange * Quaternion( direction ) * angleChange.conj() ).im(); //TODO: At every crossing should I also change direction to follow new field direction at crossing (?) // If we do this then we are curving along the field path as we travel a distance h, removing the small timestep assumption (!) // Although this is more advanced/accurate, if dt is small enough this will introduce unnecessary computation // This can be done simply by recomputing the velocity (WhitneyInterp) at edge crossings everytime instead of turning/curving the direction vec current_he = crossing_he->flip; } else{ final_coordinate = edge_crossing_coord + h_remains * direction; } h_remains -= distance; } // Compute interpolated velocity at this point Vector acquired_velocity = whitneyInterpolate( final_coordinate, current_he ); // current_he is now inside triangle face we care about // Parallel transport the velocity back to the original face // (rotate direction vector back by accumulated angle) acquired_velocity = ( accumulated_angle.conj() * Quaternion( acquired_velocity ) * accumulated_angle ).im(); assert( std::abs( dot( acquired_velocity, e->he->face->normal() ) ) <= EPSILON ); // acquired_velocity lives on plane of original face // Update the velocity at initial edge to be the dot product of aquired velocity with original velocity double advectedWeight = dot( acquired_velocity, edge_vec ); e->setCoef( advectedWeight ); } } void Fluid :: projectCurl( void ) { std::cerr << "Projection of Curl is not yet implemented, exiting" << std::endl; return; } void Fluid :: projectDivergence( void ) // first solve [ d * dp = d * u ] then solve [ u_new = u - dp ] { unsigned V = fluid_ptr->vertices.size(); unsigned E = fluid_ptr->edges.size(); // retrive vector of edge weights ( u ) DenseMatrix<Real> u = DenseMatrix<Real>(E, 1); for( EdgeIter e = fluid_ptr->edges.begin(); e != fluid_ptr->edges.end(); ++e ){ assert( 0 <= e->index && e->index < E ); u( e->getID() ) = fluid_ptr->edges[ e->getID() ].getCoef(); } SparseMatrix<Real> A( V, V ); A = ( d0.transpose() ) * star1 * d0; A.shift( 1e-15 ); SparseFactor<Real> L; L.build( A ); DenseMatrix<Real> divU( V, 1 ); divU = ( d0.transpose() ) * star1 * u; DenseMatrix<Real> p( V, 1 ); backsolvePositiveDefinite( L, p, divU ); DenseMatrix<Real> gradP( E, 1 ); gradP = d0 * p; for( EdgeIter e = fluid_ptr->edges.begin(); e != fluid_ptr->edges.end(); ++e ){ double u_new = e->getCoef() - gradP( e->getID() ); e->setCoef( u_new ); } } void Fluid :: projectHarmonic( void ) { std::cerr << "Projection of Harmonic is not yet implemented, exiting" << std::endl; return; } double Fluid :: rayLineIntersectDistance( const Vector& coordinate, const Vector& direction, const HalfEdgeIter& half_edge ) // ray should never negatively intersect with halfEdge // since rays are emitted internally to a triangle from the border { Vector e1 = half_edge->flip->vertex - half_edge->vertex; Vector v1 = half_edge->vertex - direction; double t1 = cross( v1, e1 ) / cross( direction, e1 ); Vector e2 = half_edge->next->flip->vertex - half_edge->next->vertex; Vector v2 = half_edge->next->vertex - direction; double t2 = cross( v2, e2 ) / cross( direction, e2 ); if ( t1 < t2 ) { coordinate = coordinate + direction * t1; return t1; } coordinate = coordinate + direction * t2; return t2; } void Fluid :: updateEdgeWeights( ) { for( EdgeIter e = fluid_ptr->edges.begin(); e != fluid_ptr->edges.end(); ++e ) { e->updateRefCoef(); } } Vector Fluid :: whitneyInterpolate( const Vector& coordinate, const EdgeIter& edge ) { assert( coordinate lies on plane created by the edges neighboring triangle faces ); // Calls whitneyInterpolate( coordinate, HALF_EDGE ) twice for neighboring triangles of edge Vector left = whitneyInterpolate( coordinate, edge->he ); Vector right = whitneyInterpolate( coordinate, edge->he->flip ); // check if edge_wise components of vectors are the same assert( dot( left, ( e->he->flip->vertex->position - e->he->vertex->position ) ) == dot( right, ( e->he->flip->vertex->position - e->he->vertex->position ) ) ); // averages the flux/normal components to the edge and keeps the same edgewise component? // need to take the averaged component and project it down onto the face that dominates (otherwise the edge_normal component is off the surface) // TODO: if we find we get a lot of viscosity/damping on our flow, we might find taking the MAX or Min side here is better (?) // ...For now we just take the largest. return left.norm() > right.norm() ? left : right; } void Fluid :: BarycentricWeights( const Vector coordinate, const Vector v_i, const Vector v_j, const Vector v_k, float &a_i, float &a_j, float &a_k) { Vector v0 = v_j - v_i; Vector v1 = v_k - v_i; Vector v2 = coordinate - v_i; float d00 = dot( v0, v0 ); float d01 = dot( v0, v1 ); float d11 = dot( v1, v1 ); float d20 = dot( v2, v0 ); float d21 = dot( v2, v1 ); float denom = d00 * d11 - d01 * d01; a_j = (d11 * d20 - d01 * d21) / denom; a_k = (d00 * d21 - d01 * d20) / denom; a_i = 1.0f - a_j - a_k; assert( 0. <= a_i && a_i <= 1. && "Coordinate lies outside of triangle!" ); assert( 0. <= a_j && a_j <= 1. && "Coordinate lies outside of triangle!" ); assert( 0. <= a_k && a_k <= 1. && "Coordinate lies outside of triangle!" ); } /* For Details, see Design of Tangent Vector Fields [Fisher et alia 07] k / \ C_ki / \ C_jk / \ i ------- j C_ij Barycentric Coords: a_i, a_j, a_k Triangle Fact Area: Area = face.area() Perpendicular Edge Vectors: P_ij, P_jk, P_ki 90 degrees rotation about plane of triangle: theta = PI/2; Q90 = Quaternion( cos(theta/2), sin(theta/2)* Face_normal ); P_ij = ( Q90 ( Pj - Pi ) Q90.conj() ).im() Interpolated Vector: u( a_i, a_j, a_k ) = ( ( C_ki*a_k - C_ij*a_j ) * P_jk + ( C_ij*a_i - C_jk*a_k ) * P_ki + ( C_jk*a_j - C_ki*a_i ) * P_ij ) / ( 2 * Area ); */ Vector Fluid :: whitneyInterpolate( const Vector& coordinate, const HalfEdgeIter& he ) { // compute whitney interpolation vector quantity for a point inside a triangle // Find barycentric weights of coordinate: float a_i, a_j, a_k; Vector i = he->vertex->position; Vector j = he->next->vertex->position; Vector k = he->next->next->vertex->position; BarycentricWeights( coordinate, i, j, k, a_i, a_j, a_k ); // Already asserts coordinate lies on triangle face // Compute Perpendicular Edge Vectors: double theta = M_PI / 2; Quaternion Q_perp = Quaternion( cos(theta/2), sin(theta/2) * he->face->normal() ); Vector P_ij = ( Q_perp * ( j - i ) * Q_perp.conj() ).im(); Vector P_jk = ( Q_perp * ( k - j ) * Q_perp.conj() ).im(); Vector P_ki = ( Q_perp * ( i - k ) * Q_perp.conj() ).im(); assert( std::abs( dot( P_ij, ( j - i ) ) ) <= EPSILON ); assert( std::abs( dot( P_jk, ( k - j ) ) ) <= EPSILON ); assert( std::abs( dot( P_ki, ( i - k ) ) ) <= EPSILON ); //Retrieve edge weights double C_ij = he->edge->getCoef(); double C_jk = he->next->edge->getCoef(); double C_ki = he->next->next->edge->getCoef(); // Return Interpolated Vector Vector interp_vec = ( ( C_ki * a_k - C_ij * a_j ) * P_jk + ( C_ij * a_i - C_jk * a_k ) * P_ki + ( C_jk * a_j - C_ki * a_i ) * P_ij ) / ( 2 * he->face->area() ); assert( std::abs( dot( he->face->normal(), interp_vec ) ) <= EPSILON ); // vector lies on the plane of the triangle face return interp_vec; } } <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: bulkDataNTStream.cpp,v 1.10 2011/08/03 15:06:32 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * bjeram 2011-04-19 created */ #include "bulkDataNTStream.h" #include <iostream> using namespace ACS_BD_Errors; using namespace ACSErrTypeCommon; using namespace ACS_DDS_Errors; using namespace AcsBulkdata; BulkDataNTStream::BulkDataNTStream(const char* name, const StreamConfiguration &cfg) : streamName_m(name), configuration_m(cfg), factory_m(0), participant_m(0) { AUTO_TRACE(__PRETTY_FUNCTION__); try { createDDSFactory(); createDDSParticipant(); //should be somewhere else in initialize or createStream }catch(const ACSErr::ACSbaseExImpl &e) { if (factory_m!=0) DDS::DomainParticipantFactory::finalize_instance(); StreamCreateProblemExImpl ex (e, __FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setStreamName(name); throw ex; }//try-catch }//BulkDataNTStream BulkDataNTStream::~BulkDataNTStream() { AUTO_TRACE(__PRETTY_FUNCTION__); destroyDDSParticipant(); DDS::DomainParticipantFactory::finalize_instance(); }//~BulkDataNTStream void BulkDataNTStream::createDDSFactory() { AUTO_TRACE(__PRETTY_FUNCTION__); DDS::ReturnCode_t ret; DDS::DomainParticipantFactoryQos factory_qos; factory_m = DDS::DomainParticipantFactory::get_instance(); factory_m->set_default_library(configuration_m.libraryQos.c_str()); factory_m->set_default_profile(configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str()); // needed by RTI only ret = factory_m->get_qos(factory_qos); if (ret!=DDS::RETCODE_OK) { DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setDDSTypeCode(ret); ex.setQoS("factory_m->get_qos"); throw ex; }//if factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE; ret = factory_m->set_qos(factory_qos); if (ret!=DDS::RETCODE_OK) { DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setDDSTypeCode(ret); ex.setQoS("factory_m->set_qos"); throw ex; }//if //RTI logging NDDSConfigLogger::get_instance()->set_verbosity_by_category( NDDS_CONFIG_LOG_CATEGORY_API, (NDDS_Config_LogVerbosity)(configuration_m.DDSLogVerbosity)); }//createDDSFactory void BulkDataNTStream::createDDSParticipant() { AUTO_TRACE(__PRETTY_FUNCTION__); DDS::ReturnCode_t ret; DDS::DomainParticipantQos participant_qos; int domainID=0; //TBD: where to get domain ID if (factory_m==NULL) { NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setVariable("factory_m"); throw ex; } if (participant_m!=NULL) { printf("participant already created\n"); return; } /* is now read from XML ret = factory_m->get_default_participant_qos(participant_qos); if (ret!=DDS::RETCODE_OK) { DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setDDSTypeCode(ret); ex.setQoS("get_default_participant_qos"); throw ex; }//if // Configure built in IPv4 transport to handle large messages // RTI specific participant_qos.transport_builtin.mask = 0; // clear all xport first participant_qos.transport_builtin.mask |= DDS_TRANSPORTBUILTIN_UDPv4; participant_qos.receiver_pool.buffer_size = 65536; participant_qos.event.max_count = 1024*16; //participant_m =factory_m->create_participant(domainID, participant_qos, NULL, DDS::STATUS_MASK_NONE ); */ participant_m =factory_m->create_participant_with_profile(domainID, configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str(), NULL, DDS::STATUS_MASK_NONE ); if (participant_m==NULL) { DDSParticipantCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setDomainID(domainID); throw ex; } /* // TRANSPORT // RTI struct NDDS_Transport_UDPv4_Property_t udpv4TransportProperty = NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT; ret = NDDSTransportSupport::get_builtin_transport_property(participant_m, DDS_TRANSPORTBUILTIN_UDPv4, (struct NDDS_Transport_Property_t&)udpv4TransportProperty); udpv4TransportProperty.parent.message_size_max = 65536; //UDP_SIZE_MAX; udpv4TransportProperty.send_socket_buffer_size = 65536; //UDP_SOCKET_SEND_BUFFER_SIZE; udpv4TransportProperty.recv_socket_buffer_size = 65536*2; //UDP_SOCKET_RECV_BUFFER_SIZE; udpv4TransportProperty.multicast_ttl = 1; ret = NDDSTransportSupport::set_builtin_transport_property(participant_m, DDS_TRANSPORTBUILTIN_UDPv4, (struct NDDS_Transport_Property_t&)udpv4TransportProperty); if (ret != DDS_RETCODE_OK) { printf("Error in setting built-in transport UDPv4 " "property\n"); } int max_gather_send_buffers = udpv4TransportProperty.parent.gather_send_buffer_count_max; */ ret = participant_m->enable(); }//createDDSParticipant void BulkDataNTStream::destroyDDSParticipant() { DDS::ReturnCode_t ret; AUTO_TRACE(__PRETTY_FUNCTION__); ret = factory_m->delete_participant(participant_m); if (ret != DDS_RETCODE_OK) { DDSParticipantDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.log(); }//if }//destroyDDSParticipant <commit_msg>we read QoS from file/profile<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: bulkDataNTStream.cpp,v 1.11 2011/08/04 11:22:08 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * bjeram 2011-04-19 created */ #include "bulkDataNTStream.h" #include <iostream> using namespace ACS_BD_Errors; using namespace ACSErrTypeCommon; using namespace ACS_DDS_Errors; using namespace AcsBulkdata; BulkDataNTStream::BulkDataNTStream(const char* name, const StreamConfiguration &cfg) : streamName_m(name), configuration_m(cfg), factory_m(0), participant_m(0) { AUTO_TRACE(__PRETTY_FUNCTION__); try { createDDSFactory(); createDDSParticipant(); //should be somewhere else in initialize or createStream }catch(const ACSErr::ACSbaseExImpl &e) { if (factory_m!=0) DDS::DomainParticipantFactory::finalize_instance(); StreamCreateProblemExImpl ex (e, __FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setStreamName(name); throw ex; }//try-catch }//BulkDataNTStream BulkDataNTStream::~BulkDataNTStream() { AUTO_TRACE(__PRETTY_FUNCTION__); destroyDDSParticipant(); DDS::DomainParticipantFactory::finalize_instance(); }//~BulkDataNTStream void BulkDataNTStream::createDDSFactory() { AUTO_TRACE(__PRETTY_FUNCTION__); DDS::ReturnCode_t ret; DDS::DomainParticipantFactoryQos factory_qos; factory_m = DDS::DomainParticipantFactory::get_instance(); factory_m->set_default_library(configuration_m.libraryQos.c_str()); factory_m->set_default_profile(configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str()); // needed by RTI only ret = factory_m->get_qos(factory_qos); if (ret!=DDS::RETCODE_OK) { DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setDDSTypeCode(ret); ex.setQoS("factory_m->get_qos"); throw ex; }//if factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE; ret = factory_m->set_qos(factory_qos); if (ret!=DDS::RETCODE_OK) { DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setDDSTypeCode(ret); ex.setQoS("factory_m->set_qos"); throw ex; }//if //RTI logging NDDSConfigLogger::get_instance()->set_verbosity_by_category( NDDS_CONFIG_LOG_CATEGORY_API, (NDDS_Config_LogVerbosity)(configuration_m.DDSLogVerbosity)); }//createDDSFactory void BulkDataNTStream::createDDSParticipant() { AUTO_TRACE(__PRETTY_FUNCTION__); DDS::ReturnCode_t ret; DDS::DomainParticipantQos participant_qos; int domainID=0; //TBD: where to get domain ID if (factory_m==NULL) { NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setVariable("factory_m"); throw ex; } if (participant_m!=NULL) { printf("participant already created\n"); return; } ret = factory_m->get_participant_qos_from_profile(participant_qos, configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str()); if (ret!=DDS::RETCODE_OK) { DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setDDSTypeCode(ret); ex.setQoS("get_default_participant_qos"); throw ex; }//if /* is now read from XML // Configure built in IPv4 transport to handle large messages // RTI specific participant_qos.transport_builtin.mask = 0; // clear all xport first participant_qos.transport_builtin.mask |= DDS_TRANSPORTBUILTIN_UDPv4; participant_qos.receiver_pool.buffer_size = 65536; participant_qos.event.max_count = 1024*16; */ participant_m =factory_m->create_participant(domainID, participant_qos, NULL, DDS::STATUS_MASK_NONE ); if (participant_m==NULL) { DDSParticipantCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.setDomainID(domainID); throw ex; } /* // TRANSPORT // RTI struct NDDS_Transport_UDPv4_Property_t udpv4TransportProperty = NDDS_TRANSPORT_UDPV4_PROPERTY_DEFAULT; ret = NDDSTransportSupport::get_builtin_transport_property(participant_m, DDS_TRANSPORTBUILTIN_UDPv4, (struct NDDS_Transport_Property_t&)udpv4TransportProperty); udpv4TransportProperty.parent.message_size_max = 65536; //UDP_SIZE_MAX; udpv4TransportProperty.send_socket_buffer_size = 65536; //UDP_SOCKET_SEND_BUFFER_SIZE; udpv4TransportProperty.recv_socket_buffer_size = 65536*2; //UDP_SOCKET_RECV_BUFFER_SIZE; udpv4TransportProperty.multicast_ttl = 1; ret = NDDSTransportSupport::set_builtin_transport_property(participant_m, DDS_TRANSPORTBUILTIN_UDPv4, (struct NDDS_Transport_Property_t&)udpv4TransportProperty); if (ret != DDS_RETCODE_OK) { printf("Error in setting built-in transport UDPv4 " "property\n"); } int max_gather_send_buffers = udpv4TransportProperty.parent.gather_send_buffer_count_max; */ ret = participant_m->enable(); }//createDDSParticipant void BulkDataNTStream::destroyDDSParticipant() { DDS::ReturnCode_t ret; AUTO_TRACE(__PRETTY_FUNCTION__); ret = factory_m->delete_participant(participant_m); if (ret != DDS_RETCODE_OK) { DDSParticipantDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__); ex.log(); }//if }//destroyDDSParticipant <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #include "../StroikaPreComp.h" #include <cstdio> #if qPlatform_MacOS #include <libproc.h> #include <mach-o/dyld.h> #endif #if qPlatform_POSIX && qSupport_Proc_Filesystem #include <unistd.h> #endif #if qPlatform_Windows #include <windows.h> #endif #include "../Execution/Exceptions.h" #include "../Execution/Synchronized.h" #include "../Execution/Throw.h" #include "../IO/FileSystem/PathName.h" #include "../Memory/SmallStackBuffer.h" #include "Module.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ***************************** Execution::GetEXEDir ***************************** ******************************************************************************** */ filesystem::path Execution::GetEXEDir () { return GetEXEPath ().parent_path (); } /* ******************************************************************************** **************************** Execution::GetEXEDirT ***************************** ******************************************************************************** */ SDKString Execution::GetEXEDirT () { // Currently this impl depends on String - we may want to redo one cleanly without any dependency on String()... // Docs call for this - but I'm not sure its needed return GetEXEDir ().native (); } /* ******************************************************************************** **************************** Execution::GetEXEPath ***************************** ******************************************************************************** */ filesystem::path Execution::GetEXEPath () { // See also http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe // Mac OS X: _NSGetExecutablePath() (man 3 dyld) // Linux: readlink /proc/self/exe // Solaris: getexecname() // FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1 // BSD with procfs: readlink /proc/curproc/file // Windows: GetModuleFileName() with hModule = nullptr // #if qPlatform_MacOS uint32_t bufSize = 0; Verify (_NSGetExecutablePath (nullptr, &bufSize) == -1); Assert (bufSize > 0); Memory::SmallStackBuffer<char> buf (bufSize); Verify (_NSGetExecutablePath (buf.begin (), &bufSize) == 0); Assert (buf[bufSize - 1] == '\0'); return buf.begin (); #elif qPlatform_POSIX && qSupport_Proc_Filesystem // readlink () isn't clear about finding the right size. The only way to tell it wasn't enuf (maybe) is // if all the bytes passed in are used. That COULD mean it all fit, or there was more. If we get that - // double buf size and try again Memory::SmallStackBuffer<Characters::SDKChar> buf (1024); ssize_t n; while ((n = ::readlink ("/proc/self/exe", buf, buf.GetSize ())) == buf.GetSize ()) { buf.GrowToSize_uninitialized (buf.GetSize () * 2); } if (n < 0) { ThrowPOSIXErrNo (errno); } Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed return SDKString (buf.begin (), buf.begin () + n); #elif qPlatform_Windows Characters::SDKChar buf[MAX_PATH]; //memset (buf, 0, sizeof (buf)); Verify (::GetModuleFileName (nullptr, buf, static_cast<DWORD> (NEltsOf (buf)))); buf[NEltsOf (buf) - 1] = '\0'; // cheaper and just as safe as memset() - more even. Buffer always nul-terminated, and if GetModuleFileName succeeds will be nul-terminated return buf; #else AssertNotImplemented (); return filesystem::path{}; #endif } /* ******************************************************************************** **************************** Execution::GetEXEPathT **************************** ******************************************************************************** */ SDKString Execution::GetEXEPathT () //***DEPRECATED*** { return GetEXEPath ().native (); } filesystem::path Execution::GetEXEPath ([[maybe_unused]] pid_t processID) { #if qPlatform_MacOS char pathbuf[PROC_PIDPATHINFO_MAXSIZE]; int ret = ::proc_pidpath (processID, pathbuf, sizeof (pathbuf)); if (ret <= 0) { Execution::Throw (Exception (L"proc_pidpath failed"sv)); // @todo - horrible reporting, but not obvious what this API is? proc_pidpath? } else { return pathbuf; } #elif qPlatform_POSIX && qSupport_Proc_Filesystem // readlink () isn't clear about finding the right size. The only way to tell it wasn't enuf (maybe) is // if all the bytes passed in are used. That COULD mean it all fit, or there was more. If we get that - // double buf size and try again Memory::SmallStackBuffer<Characters::SDKChar> buf (1024); ssize_t n; char linkNameBuf[1024]; (void)std::snprintf (linkNameBuf, sizeof (linkNameBuf), "/proc/%ld/exe", static_cast<long> (processID)); while ((n = ::readlink (linkNameBuf, buf, buf.GetSize ())) == buf.GetSize ()) { buf.GrowToSize_uninitialized (buf.GetSize () * 2); } if (n < 0) { ThrowPOSIXErrNo (errno); } Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed return SDKString (buf.begin (), buf.begin () + n); #elif qPlatform_Windows // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682621(v=vs.85).aspx but a bit of work // not needed yet AssertNotImplemented (); return filesystem::path{}; #else AssertNotImplemented (); return filesystem::path{}; #endif } <commit_msg>cosmetic<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #include "../StroikaPreComp.h" #include <cstdio> #if qPlatform_MacOS #include <libproc.h> #include <mach-o/dyld.h> #endif #if qPlatform_POSIX && qSupport_Proc_Filesystem #include <unistd.h> #endif #if qPlatform_Windows #include <windows.h> #endif #include "../Execution/Exceptions.h" #include "../Execution/Synchronized.h" #include "../Execution/Throw.h" #include "../IO/FileSystem/PathName.h" #include "../Memory/SmallStackBuffer.h" #include "Module.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 /* ******************************************************************************** ***************************** Execution::GetEXEDir ***************************** ******************************************************************************** */ filesystem::path Execution::GetEXEDir () { return GetEXEPath ().parent_path (); } /* ******************************************************************************** **************************** Execution::GetEXEDirT ***************************** ******************************************************************************** */ SDKString Execution::GetEXEDirT () { // Currently this impl depends on String - we may want to redo one cleanly without any dependency on String()... // Docs call for this - but I'm not sure its needed return GetEXEDir ().native (); } /* ******************************************************************************** **************************** Execution::GetEXEPath ***************************** ******************************************************************************** */ filesystem::path Execution::GetEXEPath () { // See also http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe // Mac OS X: _NSGetExecutablePath() (man 3 dyld) // Linux: readlink /proc/self/exe // Solaris: getexecname() // FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1 // BSD with procfs: readlink /proc/curproc/file // Windows: GetModuleFileName() with hModule = nullptr // #if qPlatform_MacOS uint32_t bufSize = 0; Verify (_NSGetExecutablePath (nullptr, &bufSize) == -1); Assert (bufSize > 0); Memory::SmallStackBuffer<char> buf (bufSize); Verify (_NSGetExecutablePath (buf.begin (), &bufSize) == 0); Assert (buf[bufSize - 1] == '\0'); return buf.begin (); #elif qPlatform_POSIX && qSupport_Proc_Filesystem // readlink () isn't clear about finding the right size. The only way to tell it wasn't enuf (maybe) is // if all the bytes passed in are used. That COULD mean it all fit, or there was more. If we get that - // double buf size and try again Memory::SmallStackBuffer<Characters::SDKChar> buf (1024); ssize_t n; while ((n = ::readlink ("/proc/self/exe", buf, buf.GetSize ())) == buf.GetSize ()) { buf.GrowToSize_uninitialized (buf.GetSize () * 2); } if (n < 0) { ThrowPOSIXErrNo (errno); } Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed return SDKString (buf.begin (), buf.begin () + n); #elif qPlatform_Windows Characters::SDKChar buf[MAX_PATH]; //memset (buf, 0, sizeof (buf)); Verify (::GetModuleFileName (nullptr, buf, static_cast<DWORD> (NEltsOf (buf)))); buf[NEltsOf (buf) - 1] = '\0'; // cheaper and just as safe as memset() - more even. Buffer always nul-terminated, and if GetModuleFileName succeeds will be nul-terminated return buf; #else AssertNotImplemented (); return filesystem::path{}; #endif } /* ******************************************************************************** **************************** Execution::GetEXEPathT **************************** ******************************************************************************** */ SDKString Execution::GetEXEPathT () //***DEPRECATED*** { return GetEXEPath ().native (); } filesystem::path Execution::GetEXEPath ([[maybe_unused]] pid_t processID) { #if qPlatform_MacOS char pathbuf[PROC_PIDPATHINFO_MAXSIZE]; int ret = ::proc_pidpath (processID, pathbuf, sizeof (pathbuf)); if (ret <= 0) { Execution::Throw (Exception{L"proc_pidpath failed"sv}); // @todo - horrible reporting, but not obvious what this API is? proc_pidpath? } else { return pathbuf; } #elif qPlatform_POSIX && qSupport_Proc_Filesystem // readlink () isn't clear about finding the right size. The only way to tell it wasn't enuf (maybe) is // if all the bytes passed in are used. That COULD mean it all fit, or there was more. If we get that - // double buf size and try again Memory::SmallStackBuffer<Characters::SDKChar> buf (1024); ssize_t n; char linkNameBuf[1024]; (void)std::snprintf (linkNameBuf, sizeof (linkNameBuf), "/proc/%ld/exe", static_cast<long> (processID)); while ((n = ::readlink (linkNameBuf, buf, buf.GetSize ())) == buf.GetSize ()) { buf.GrowToSize_uninitialized (buf.GetSize () * 2); } if (n < 0) { ThrowPOSIXErrNo (errno); } Assert (n <= buf.GetSize ()); // could leave no room for NUL-byte, but not needed return SDKString (buf.begin (), buf.begin () + n); #elif qPlatform_Windows // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682621(v=vs.85).aspx but a bit of work // not needed yet AssertNotImplemented (); return filesystem::path{}; #else AssertNotImplemented (); return filesystem::path{}; #endif } <|endoftext|>
<commit_before>// Copyright 2009 Minor Gordon. // This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions). #include "org/xtreemfs/client/proxy.h" #include "policy_container.h" #include "platform_exception_event.h" using namespace org::xtreemfs::client; #include "org/xtreemfs/interfaces/constants.h" #include <errno.h> #ifdef _WIN32 #include "yield/ipc/sockets.h" #define ETIMEDOUT WSAETIMEDOUT #endif #include <openssl/err.h> #include <openssl/pkcs12.h> #include <openssl/ssl.h> Proxy::Proxy( const YIELD::URI& uri, uint16_t default_oncrpc_port ) : uri( uri ) { if ( strcmp( uri.get_scheme(), org::xtreemfs::interfaces::ONCRPC_SCHEME ) == 0 ) { if ( this->uri.get_port() == 0 ) this->uri.set_port( default_oncrpc_port ); ssl_ctx = NULL; init(); } else throw YIELD::Exception( "invalid URI scheme" ); } Proxy::Proxy( const YIELD::URI& uri, const YIELD::Path& pkcs12_file_path, const std::string& pkcs12_passphrase, uint16_t default_oncrpcs_port ) : uri( uri ) { if ( strcmp( uri.get_scheme(), org::xtreemfs::interfaces::ONCRPCS_SCHEME ) == 0 ) { if ( this->uri.get_port() == 0 ) this->uri.set_port( default_oncrpcs_port ); SSL_library_init(); OpenSSL_add_all_algorithms(); // TODO: this should be in a shared main class in the binaries BIO* bio = BIO_new_file( pkcs12_file_path.getHostCharsetPath().c_str(), "rb" ); if ( bio != NULL ) { PKCS12* p12 = d2i_PKCS12_bio( bio, NULL ); if ( p12 != NULL ) { EVP_PKEY* pkey = NULL; X509* cert = NULL; STACK_OF( X509 )* ca = NULL; PKCS12_parse( p12, pkcs12_passphrase.c_str(), &pkey, &cert, &ca ); if ( pkey != NULL && cert != NULL && ca != NULL ) { ssl_ctx = SSL_CTX_new( SSLv3_client_method() ); if ( ssl_ctx != NULL ) { SSL_CTX_use_certificate( ssl_ctx, cert ); SSL_CTX_use_PrivateKey( ssl_ctx, pkey ); X509_STORE* store = SSL_CTX_get_cert_store( ssl_ctx ); for ( int i = 0; i < sk_X509_num( ca ); i++ ) { X509* store_cert = sk_X509_value( ca, i ); X509_STORE_add_cert( store, store_cert ); } SSL_CTX_set_verify( ssl_ctx, SSL_VERIFY_PEER, NULL ); init(); return; } } } } SSL_load_error_strings(); throw YIELD::Exception( ERR_get_error(), ERR_error_string( ERR_get_error(), NULL ) ); } else throw YIELD::Exception( "invalid URI scheme" ); } void Proxy::init() { this->flags = PROXY_DEFAULT_FLAGS; this->reconnect_tries_max = PROXY_DEFAULT_RECONNECT_TRIES_MAX; this->operation_timeout_ms = PROXY_DEFAULT_OPERATION_TIMEOUT_MS; this->peer_ip = 0; this->conn = 0; org::xtreemfs::interfaces::Exceptions().registerSerializableFactories( serializable_factories ); } Proxy::~Proxy() { delete conn; } void Proxy::handleEvent( YIELD::Event& ev ) { switch ( ev.getTypeId() ) { case TYPE_ID( YIELD::StageStartupEvent ): case TYPE_ID( YIELD::StageShutdownEvent ): YIELD::SharedObject::decRef( ev ); break; default: { switch ( ev.getGeneralType() ) { case YIELD::RTTI::REQUEST: { YIELD::Request& req = static_cast<YIELD::Request&>( ev ); if ( ( flags & PROXY_FLAG_PRINT_OPERATIONS ) == PROXY_FLAG_PRINT_OPERATIONS ) { YIELD::PrettyPrintOutputStream pretty_print_output_stream( std::cout ); pretty_print_output_stream.writeSerializable( YIELD::PrettyPrintOutputStream::Declaration( req.getTypeName() ), req ); } try { org::xtreemfs::interfaces::UserCredentials user_credentials; bool have_user_credentials = getCurrentUserCredentials( user_credentials ); YIELD::ONCRPCRequest oncrpc_req( YIELD::SharedObject::incRef( req ), serializable_factories, have_user_credentials ? org::xtreemfs::interfaces::ONCRPC_AUTH_FLAVOR : 0, &user_credentials ); uint8_t reconnect_tries_left = reconnect_tries_max; if ( conn == NULL ) reconnect_tries_left = reconnect( reconnect_tries_left ); if ( operation_timeout_ms == static_cast<uint64_t>( -1 ) || ssl_ctx != NULL ) // Blocking { YIELD::SocketLib::setBlocking( conn->get_socket() ); for ( uint8_t serialize_tries = 0; serialize_tries < 2; serialize_tries++ ) // Try, allow for one reconnect, then try again { oncrpc_req.serialize( *conn, NULL ); if ( conn->get_status() == YIELD::SocketConnection::SCS_READY ) { for ( uint8_t deserialize_tries = 0; deserialize_tries < 2; deserialize_tries++ ) { oncrpc_req.deserialize( *conn ); if ( conn->get_status() == YIELD::SocketConnection::SCS_READY ) { req.respond( static_cast<YIELD::Event&>( YIELD::SharedObject::incRef( *oncrpc_req.getInBody() ) ) ); YIELD::SharedObject::decRef( req ); return; } else if ( conn->get_status() == YIELD::SocketConnection::SCS_CLOSED ) reconnect_tries_left = reconnect( reconnect_tries_left ); else YIELD::DebugBreak(); } YIELD::SharedObject::decRef( req ); return; } else if ( conn->get_status() == YIELD::SocketConnection::SCS_CLOSED ) reconnect_tries_left = reconnect( reconnect_tries_left ); else YIELD::DebugBreak(); } YIELD::SharedObject::decRef( req ); return; } else // Non-blocking/timed { uint64_t remaining_operation_timeout_ms = operation_timeout_ms; YIELD::SocketLib::setNonBlocking( conn->get_socket() ); bool have_written = false; // Use the variable so the read and write attempt loops can be combined and eliminate some code duplication for ( ;; ) // Loop for read and write attempts { if ( !have_written ) oncrpc_req.serialize( *conn ); else oncrpc_req.deserialize( *conn ); // Use if statements instead of a switch so the break after a successful read will exit the loop if ( conn->get_status() == YIELD::SocketConnection::SCS_READY ) { if ( !have_written ) have_written = true; else { YIELD::SharedObject::decRef( req ); return; } } else if ( conn->get_status() == YIELD::SocketConnection::SCS_CLOSED ) reconnect_tries_left = reconnect( reconnect_tries_left ); else if ( remaining_operation_timeout_ms > 0 ) { bool enable_read = conn->get_status() == YIELD::SocketConnection::SCS_BLOCKED_ON_READ; fd_event_queue.toggleSocketEvent( conn->get_socket(), conn, enable_read, !enable_read ); double start_epoch_time_ms = YIELD::Time::getCurrentUnixTimeMS(); YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( remaining_operation_timeout_ms ) * NS_IN_MS ) ); if ( fd_event ) { if ( fd_event->error_code == 0 ) remaining_operation_timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentUnixTimeMS() - start_epoch_time_ms ), remaining_operation_timeout_ms ); else reconnect_tries_left = reconnect( reconnect_tries_left ); } else throwExceptionEvent( new PlatformExceptionEvent( ETIMEDOUT ) ); } else throwExceptionEvent( new PlatformExceptionEvent( ETIMEDOUT ) ); } } } catch ( YIELD::ExceptionEvent* exc_ev ) { req.respond( *exc_ev ); YIELD::SharedObject::decRef( req ); } } break; default: YIELD::DebugBreak(); break; } } break; } } uint8_t Proxy::reconnect( uint8_t reconnect_tries_left ) { if ( peer_ip == 0 ) { peer_ip = YIELD::SocketLib::resolveHost( uri.get_host() ); if ( peer_ip == 0 && ( strcmp( uri.get_host(), "localhost" ) == 0 || strcmp( uri.get_host(), "127.0.0.1" ) == 0 ) ) peer_ip = YIELD::SocketLib::resolveHost( YIELD::SocketLib::getLocalHostFQDN() ); if ( peer_ip == 0 ) throw new PlatformExceptionEvent(); } if ( conn != NULL ) // This is a reconnect, not the first connect { fd_event_queue.detachSocket( conn->get_socket(), conn ); conn->close(); delete conn; conn = NULL; } while ( reconnect_tries_left > 0 ) { reconnect_tries_left--; // Create the conn object based on the URI type if ( ssl_ctx == NULL ) conn = new YIELD::TCPConnection( peer_ip, uri.get_port(), NULL ); else conn = new YIELD::SSLConnection( peer_ip, uri.get_port(), ssl_ctx ); // Attach the socket to the fd_event_queue even if we're doing a blocking connect, in case a later read/write is non-blocking fd_event_queue.attachSocket( conn->get_socket(), conn, false, false ); // Attach without read or write notifications enabled // Now try the actual connect if ( operation_timeout_ms == static_cast<uint64_t>( -1 ) || ssl_ctx != NULL ) // Blocking { YIELD::SocketLib::setBlocking( conn->get_socket() ); if ( conn->connect() == YIELD::SocketConnection::SCS_READY ) return reconnect_tries_left; } else // Non-blocking/timed { uint64_t remaining_operation_timeout_ms = operation_timeout_ms; YIELD::SocketLib::setNonBlocking( conn->get_socket() ); switch ( conn->connect() ) { case YIELD::SocketConnection::SCS_READY: break; case YIELD::SocketConnection::SCS_BLOCKED_ON_WRITE: { fd_event_queue.toggleSocketEvent( conn->get_socket(), conn, false, true ); // Write readiness = the connect() operation is complete double start_epoch_time_ms = YIELD::Time::getCurrentUnixTimeMS(); YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( remaining_operation_timeout_ms ) * NS_IN_MS ) ); if ( fd_event && fd_event->error_code == 0 && conn->connect() == YIELD::SocketConnection::SCS_READY ) { fd_event_queue.toggleSocketEvent( conn->get_socket(), conn, false, false ); return reconnect_tries_left; } else { remaining_operation_timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentUnixTimeMS() - start_epoch_time_ms ), remaining_operation_timeout_ms ); if ( remaining_operation_timeout_ms == 0 ) { reconnect_tries_left = 0; break; } } } } } // Clear the connection state for the next try fd_event_queue.detachSocket( conn->get_socket(), conn ); conn->close(); delete conn; conn = NULL; } unsigned long error_code = YIELD::PlatformException::errno_(); if ( error_code == 0 ) error_code = ETIMEDOUT; throw new PlatformExceptionEvent( error_code ); } void Proxy::throwExceptionEvent( YIELD::ExceptionEvent* exc_ev ) { if ( conn ) { fd_event_queue.detachSocket( conn->get_socket(), conn ); conn->close(); delete conn; conn = NULL; } throw exc_ev; } <commit_msg>client: incantations for OpenSSL on Windows<commit_after>// Copyright 2009 Minor Gordon. // This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions). #include "org/xtreemfs/client/proxy.h" #include "policy_container.h" #include "platform_exception_event.h" using namespace org::xtreemfs::client; #include "org/xtreemfs/interfaces/constants.h" #include <errno.h> #ifdef _WIN32 #include "yield/ipc/sockets.h" #define ETIMEDOUT WSAETIMEDOUT #endif #include <openssl/err.h> #include <openssl/pkcs12.h> #include <openssl/ssl.h> Proxy::Proxy( const YIELD::URI& uri, uint16_t default_oncrpc_port ) : uri( uri ) { if ( strcmp( uri.get_scheme(), org::xtreemfs::interfaces::ONCRPC_SCHEME ) == 0 ) { if ( this->uri.get_port() == 0 ) this->uri.set_port( default_oncrpc_port ); ssl_ctx = NULL; init(); } else throw YIELD::Exception( "invalid URI scheme" ); } Proxy::Proxy( const YIELD::URI& uri, const YIELD::Path& pkcs12_file_path, const std::string& pkcs12_passphrase, uint16_t default_oncrpcs_port ) : uri( uri ) { if ( strcmp( uri.get_scheme(), org::xtreemfs::interfaces::ONCRPCS_SCHEME ) == 0 ) { if ( this->uri.get_port() == 0 ) this->uri.set_port( default_oncrpcs_port ); SSL_library_init(); OpenSSL_add_all_algorithms(); // TODO: this should be in a shared main class in the binaries BIO* bio = BIO_new_file( pkcs12_file_path.getHostCharsetPath().c_str(), "rb" ); if ( bio != NULL ) { PKCS12* p12 = d2i_PKCS12_bio( bio, NULL ); if ( p12 != NULL ) { EVP_PKEY* pkey = NULL; X509* cert = NULL; STACK_OF( X509 )* ca = NULL; PKCS12_parse( p12, pkcs12_passphrase.c_str(), &pkey, &cert, &ca ); if ( pkey != NULL && cert != NULL && ca != NULL ) { ssl_ctx = SSL_CTX_new( SSLv3_client_method() ); if ( ssl_ctx != NULL ) { #ifdef SSL_OP_NO_TICKET SSL_CTX_set_options( ssl_ctx, SSL_OP_ALL|SSL_OP_NO_TICKET ); #else SSL_CTX_set_options( ssl_ctx, SSL_OP_ALL ); #endif SSL_CTX_use_certificate( ssl_ctx, cert ); SSL_CTX_use_PrivateKey( ssl_ctx, pkey ); X509_STORE* store = SSL_CTX_get_cert_store( ssl_ctx ); for ( int i = 0; i < sk_X509_num( ca ); i++ ) { X509* store_cert = sk_X509_value( ca, i ); X509_STORE_add_cert( store, store_cert ); } // SSL_CTX_set_verify( ssl_ctx, SSL_VERIFY_PEER, NULL ); SSL_CTX_set_verify( ssl_ctx, SSL_VERIFY_NONE, NULL ); init(); return; } } } } SSL_load_error_strings(); throw YIELD::Exception( ERR_get_error(), ERR_error_string( ERR_get_error(), NULL ) ); } else throw YIELD::Exception( "invalid URI scheme" ); } void Proxy::init() { this->flags = PROXY_DEFAULT_FLAGS; this->reconnect_tries_max = PROXY_DEFAULT_RECONNECT_TRIES_MAX; this->operation_timeout_ms = PROXY_DEFAULT_OPERATION_TIMEOUT_MS; this->peer_ip = 0; this->conn = 0; org::xtreemfs::interfaces::Exceptions().registerSerializableFactories( serializable_factories ); } Proxy::~Proxy() { delete conn; } void Proxy::handleEvent( YIELD::Event& ev ) { switch ( ev.getTypeId() ) { case TYPE_ID( YIELD::StageStartupEvent ): case TYPE_ID( YIELD::StageShutdownEvent ): YIELD::SharedObject::decRef( ev ); break; default: { switch ( ev.getGeneralType() ) { case YIELD::RTTI::REQUEST: { YIELD::Request& req = static_cast<YIELD::Request&>( ev ); if ( ( flags & PROXY_FLAG_PRINT_OPERATIONS ) == PROXY_FLAG_PRINT_OPERATIONS ) { YIELD::PrettyPrintOutputStream pretty_print_output_stream( std::cout ); pretty_print_output_stream.writeSerializable( YIELD::PrettyPrintOutputStream::Declaration( req.getTypeName() ), req ); } try { org::xtreemfs::interfaces::UserCredentials user_credentials; bool have_user_credentials = getCurrentUserCredentials( user_credentials ); YIELD::ONCRPCRequest oncrpc_req( YIELD::SharedObject::incRef( req ), serializable_factories, have_user_credentials ? org::xtreemfs::interfaces::ONCRPC_AUTH_FLAVOR : 0, &user_credentials ); uint8_t reconnect_tries_left = reconnect_tries_max; if ( conn == NULL ) reconnect_tries_left = reconnect( reconnect_tries_left ); if ( operation_timeout_ms == static_cast<uint64_t>( -1 ) || ssl_ctx != NULL ) // Blocking { YIELD::SocketLib::setBlocking( conn->get_socket() ); for ( uint8_t serialize_tries = 0; serialize_tries < 2; serialize_tries++ ) // Try, allow for one reconnect, then try again { oncrpc_req.serialize( *conn, NULL ); if ( conn->get_status() == YIELD::SocketConnection::SCS_READY ) { for ( uint8_t deserialize_tries = 0; deserialize_tries < 2; deserialize_tries++ ) { oncrpc_req.deserialize( *conn ); if ( conn->get_status() == YIELD::SocketConnection::SCS_READY ) { req.respond( static_cast<YIELD::Event&>( YIELD::SharedObject::incRef( *oncrpc_req.getInBody() ) ) ); YIELD::SharedObject::decRef( req ); return; } else if ( conn->get_status() == YIELD::SocketConnection::SCS_CLOSED ) reconnect_tries_left = reconnect( reconnect_tries_left ); else YIELD::DebugBreak(); } YIELD::SharedObject::decRef( req ); return; } else if ( conn->get_status() == YIELD::SocketConnection::SCS_CLOSED ) reconnect_tries_left = reconnect( reconnect_tries_left ); else YIELD::DebugBreak(); } YIELD::SharedObject::decRef( req ); return; } else // Non-blocking/timed { uint64_t remaining_operation_timeout_ms = operation_timeout_ms; YIELD::SocketLib::setNonBlocking( conn->get_socket() ); bool have_written = false; // Use the variable so the read and write attempt loops can be combined and eliminate some code duplication for ( ;; ) // Loop for read and write attempts { if ( !have_written ) oncrpc_req.serialize( *conn ); else oncrpc_req.deserialize( *conn ); // Use if statements instead of a switch so the break after a successful read will exit the loop if ( conn->get_status() == YIELD::SocketConnection::SCS_READY ) { if ( !have_written ) have_written = true; else { YIELD::SharedObject::decRef( req ); return; } } else if ( conn->get_status() == YIELD::SocketConnection::SCS_CLOSED ) reconnect_tries_left = reconnect( reconnect_tries_left ); else if ( remaining_operation_timeout_ms > 0 ) { bool enable_read = conn->get_status() == YIELD::SocketConnection::SCS_BLOCKED_ON_READ; fd_event_queue.toggleSocketEvent( conn->get_socket(), conn, enable_read, !enable_read ); double start_epoch_time_ms = YIELD::Time::getCurrentUnixTimeMS(); YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( remaining_operation_timeout_ms ) * NS_IN_MS ) ); if ( fd_event ) { if ( fd_event->error_code == 0 ) remaining_operation_timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentUnixTimeMS() - start_epoch_time_ms ), remaining_operation_timeout_ms ); else reconnect_tries_left = reconnect( reconnect_tries_left ); } else throwExceptionEvent( new PlatformExceptionEvent( ETIMEDOUT ) ); } else throwExceptionEvent( new PlatformExceptionEvent( ETIMEDOUT ) ); } } } catch ( YIELD::ExceptionEvent* exc_ev ) { req.respond( *exc_ev ); YIELD::SharedObject::decRef( req ); } } break; default: YIELD::DebugBreak(); break; } } break; } } uint8_t Proxy::reconnect( uint8_t reconnect_tries_left ) { if ( peer_ip == 0 ) { peer_ip = YIELD::SocketLib::resolveHost( uri.get_host() ); if ( peer_ip == 0 && ( strcmp( uri.get_host(), "localhost" ) == 0 || strcmp( uri.get_host(), "127.0.0.1" ) == 0 ) ) peer_ip = YIELD::SocketLib::resolveHost( YIELD::SocketLib::getLocalHostFQDN() ); if ( peer_ip == 0 ) throw new PlatformExceptionEvent(); } if ( conn != NULL ) // This is a reconnect, not the first connect { fd_event_queue.detachSocket( conn->get_socket(), conn ); conn->close(); delete conn; conn = NULL; } while ( reconnect_tries_left > 0 ) { reconnect_tries_left--; // Create the conn object based on the URI type if ( ssl_ctx == NULL ) conn = new YIELD::TCPConnection( peer_ip, uri.get_port(), NULL ); else conn = new YIELD::SSLConnection( peer_ip, uri.get_port(), ssl_ctx ); // Attach the socket to the fd_event_queue even if we're doing a blocking connect, in case a later read/write is non-blocking fd_event_queue.attachSocket( conn->get_socket(), conn, false, false ); // Attach without read or write notifications enabled // Now try the actual connect if ( operation_timeout_ms == static_cast<uint64_t>( -1 ) || ssl_ctx != NULL ) // Blocking { YIELD::SocketLib::setBlocking( conn->get_socket() ); if ( conn->connect() == YIELD::SocketConnection::SCS_READY ) return reconnect_tries_left; } else // Non-blocking/timed { uint64_t remaining_operation_timeout_ms = operation_timeout_ms; YIELD::SocketLib::setNonBlocking( conn->get_socket() ); switch ( conn->connect() ) { case YIELD::SocketConnection::SCS_READY: break; case YIELD::SocketConnection::SCS_BLOCKED_ON_WRITE: { fd_event_queue.toggleSocketEvent( conn->get_socket(), conn, false, true ); // Write readiness = the connect() operation is complete double start_epoch_time_ms = YIELD::Time::getCurrentUnixTimeMS(); YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( remaining_operation_timeout_ms ) * NS_IN_MS ) ); if ( fd_event && fd_event->error_code == 0 && conn->connect() == YIELD::SocketConnection::SCS_READY ) { fd_event_queue.toggleSocketEvent( conn->get_socket(), conn, false, false ); return reconnect_tries_left; } else { remaining_operation_timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentUnixTimeMS() - start_epoch_time_ms ), remaining_operation_timeout_ms ); if ( remaining_operation_timeout_ms == 0 ) { reconnect_tries_left = 0; break; } } } } } // Clear the connection state for the next try fd_event_queue.detachSocket( conn->get_socket(), conn ); conn->close(); delete conn; conn = NULL; } unsigned long error_code = YIELD::PlatformException::errno_(); if ( error_code == 0 ) error_code = ETIMEDOUT; throw new PlatformExceptionEvent( error_code ); } void Proxy::throwExceptionEvent( YIELD::ExceptionEvent* exc_ev ) { if ( conn ) { fd_event_queue.detachSocket( conn->get_socket(), conn ); conn->close(); delete conn; conn = NULL; } throw exc_ev; } <|endoftext|>