text
stringlengths
54
60.6k
<commit_before>#include "XMLDataParser.h" #include "utils/ConstValues.h" #include "core/DragonBones.h" #include "utils/DBDataUtil.h" #include <stdexcept> namespace dragonBones { TextureAtlasData* XMLDataParser::parseTextureAtlasData(const dragonBones::XMLElement *rootElement, Number scale) { TextureAtlasData* textureAtlasData = new TextureAtlasData(); textureAtlasData->name = rootElement->Attribute(ConstValues::A_NAME.c_str()); textureAtlasData->imagePath = rootElement->Attribute(ConstValues::A_IMAGE_PATH.c_str()); for(const dragonBones::XMLElement* subTextureXML = rootElement->FirstChildElement(ConstValues::SUB_TEXTURE.c_str()) ; subTextureXML ; subTextureXML = subTextureXML->NextSiblingElement(ConstValues::SUB_TEXTURE.c_str())) { String subTextureName = subTextureXML->Attribute(ConstValues::A_NAME.c_str()); Rectangle subTextureData; subTextureData.x = int(subTextureXML->IntAttribute(ConstValues::A_X.c_str()) / scale); subTextureData.y = int(subTextureXML->IntAttribute(ConstValues::A_Y.c_str()) / scale); subTextureData.width = int(subTextureXML->IntAttribute(ConstValues::A_WIDTH.c_str()) / scale); subTextureData.height = int(subTextureXML->IntAttribute(ConstValues::A_HEIGHT.c_str()) / scale); textureAtlasData->addRect(subTextureName , subTextureData); } return textureAtlasData; } /** * Parse the SkeletonData. * @param xml The SkeletonData xml to parse. * @return A SkeletonData instance. */ SkeletonData *XMLDataParser::parseSkeletonData(const dragonBones::XMLElement *rootElement) { String version = rootElement->Attribute(ConstValues::A_VERSION.c_str()); if(version != DragonBones::DATA_VERSION) { throw std::invalid_argument("Nonsupport version!"); } uint frameRate = rootElement->IntAttribute(ConstValues::A_FRAME_RATE.c_str()); SkeletonData *data = new SkeletonData(); data->name = rootElement->Attribute(ConstValues::A_NAME.c_str()); for(const dragonBones::XMLElement* armatureXML = rootElement->FirstChildElement(ConstValues::ARMATURE.c_str()) ; armatureXML ; armatureXML = armatureXML->NextSiblingElement(ConstValues::ARMATURE.c_str())) { data->addArmatureData(parseArmatureData(armatureXML, data, frameRate)); } return data; } ArmatureData *XMLDataParser::parseArmatureData(const dragonBones::XMLElement *armatureXML, SkeletonData *data, uint frameRate) { ArmatureData *armatureData = new ArmatureData(); armatureData->name = armatureXML->Attribute(ConstValues::A_NAME.c_str()); for(const dragonBones::XMLElement* boneXML = armatureXML->FirstChildElement(ConstValues::BONE.c_str()) ; boneXML ; boneXML = boneXML->NextSiblingElement(ConstValues::BONE.c_str())) { armatureData->addBoneData(parseBoneData(boneXML)); } for(const dragonBones::XMLElement* skinXML = armatureXML->FirstChildElement(ConstValues::SKIN.c_str()) ; skinXML ; skinXML = skinXML->NextSiblingElement(ConstValues::SKIN.c_str())) { armatureData->addSkinData(parseSkinData(skinXML, data)); } DBDataUtil::transformArmatureData(armatureData); armatureData->sortBoneDataList(); for(const dragonBones::XMLElement* animationXML = armatureXML->FirstChildElement(ConstValues::ANIMATION.c_str()) ; animationXML ; animationXML = animationXML->NextSiblingElement(ConstValues::ANIMATION.c_str())) { armatureData->addAnimationData(parseAnimationData(animationXML, armatureData, frameRate)); } return armatureData; } BoneData *XMLDataParser::parseBoneData(const dragonBones::XMLElement *boneXML) { BoneData *boneData = new BoneData(); boneData->name = boneXML->Attribute(ConstValues::A_NAME.c_str()); const char *parent = boneXML->Attribute(ConstValues::A_PARENT.c_str()); if(parent) { boneData->parent = parent; } boneData->length = Number(boneXML->DoubleAttribute(ConstValues::A_LENGTH.c_str())); const char *inheritScale = boneXML->Attribute(ConstValues::A_SCALE_MODE.c_str()); if (inheritScale) { boneData->scaleMode = atoi(inheritScale); } const char* fixedRotation = boneXML->Attribute(ConstValues::A_FIXED_ROTATION.c_str()); if(fixedRotation) { if(strcmp(fixedRotation , "0") == 0 || strcmp(fixedRotation , "false") == 0 || strcmp(fixedRotation , "no") == 0 || strcmp(fixedRotation , "") == 0 ) { boneData->fixedRotation = false; } else { boneData->fixedRotation = true; } } else { boneData->fixedRotation = false; } parseTransform(boneXML->FirstChildElement(ConstValues::TRANSFORM.c_str()), &boneData->global); boneData->transform = boneData->global; return boneData; } SkinData *XMLDataParser::parseSkinData(const dragonBones::XMLElement *skinXML, SkeletonData *data) { SkinData *skinData = new SkinData(); skinData->name = skinXML->Attribute(ConstValues::A_NAME.c_str()); for(const dragonBones::XMLElement* slotXML = skinXML->FirstChildElement(ConstValues::SLOT.c_str()) ; slotXML ; slotXML = slotXML->NextSiblingElement(ConstValues::SLOT.c_str())) { skinData->addSlotData(parseSlotData(slotXML, data)); } return skinData; } SlotData* XMLDataParser::parseSlotData(const dragonBones::XMLElement *slotXML, SkeletonData *data) { SlotData *slotData = new SlotData(); slotData->name = slotXML->Attribute(ConstValues::A_NAME.c_str()); slotData->parent = slotXML->Attribute(ConstValues::A_PARENT.c_str()); slotData->zOrder = Number(slotXML->DoubleAttribute(ConstValues::A_Z_ORDER.c_str())); const char *blendMode = slotXML->Attribute(ConstValues::A_BLENDMODE.c_str()); if(blendMode) { slotData->blendMode = blendMode; } else { slotData->blendMode = "normal"; } for(const dragonBones::XMLElement* displayXML = slotXML->FirstChildElement(ConstValues::DISPLAY.c_str()) ; displayXML ; displayXML = displayXML->NextSiblingElement(ConstValues::DISPLAY.c_str())) { slotData->addDisplayData(parseDisplayData(displayXML, data)); } return slotData; } DisplayData *XMLDataParser::parseDisplayData(const dragonBones::XMLElement *displayXML, SkeletonData *data) { DisplayData *displayData = new DisplayData(); displayData->name = displayXML->Attribute(ConstValues::A_NAME.c_str()); displayData->type = displayXML->Attribute(ConstValues::A_TYPE.c_str()); displayData->pivot = data->addSubTexturePivot( 0, 0, displayData->name ); parseTransform(displayXML->FirstChildElement(ConstValues::TRANSFORM.c_str()), &displayData->transform, &displayData->pivot); return displayData; } /** @private */ AnimationData *XMLDataParser::parseAnimationData(const dragonBones::XMLElement *animationXML, ArmatureData *armatureData, uint frameRate) { AnimationData *animationData = new AnimationData(); animationData->name = animationXML->Attribute(ConstValues::A_NAME.c_str()); animationData->frameRate = frameRate; animationData->loop = int(animationXML->IntAttribute(ConstValues::A_LOOP.c_str())); animationData->setFadeInTime(Number(animationXML->DoubleAttribute(ConstValues::A_FADE_IN_TIME.c_str()))); animationData->duration = Number(animationXML->DoubleAttribute(ConstValues::A_DURATION.c_str())) / (Number)frameRate; animationData->scale = Number(animationXML->DoubleAttribute(ConstValues::A_SCALE.c_str())); if(strcmp(animationXML->Attribute(ConstValues::A_TWEEN_EASING.c_str()) , "NaN") == 0) { animationData->tweenEasing = NaN; } else { animationData->tweenEasing = Number(animationXML->DoubleAttribute(ConstValues::A_TWEEN_EASING.c_str())); } parseTimeline(animationXML, animationData, parseMainFrame, frameRate); TransformTimeline *timeline = 0; String timelineName; for(const dragonBones::XMLElement* timelineXML = animationXML->FirstChildElement(ConstValues::TIMELINE.c_str()) ; timelineXML ; timelineXML = timelineXML->NextSiblingElement(ConstValues::TIMELINE.c_str())) { timeline = parseTransformTimeline(timelineXML, animationData->duration, frameRate); timelineName = timelineXML->Attribute(ConstValues::A_NAME.c_str()); animationData->addTimeline(timeline, timelineName); } DBDataUtil::addHideTimeline(animationData, armatureData); DBDataUtil::transformAnimationData(animationData, armatureData); return animationData; } void XMLDataParser::parseTimeline(const dragonBones::XMLElement *timelineXML, Timeline *timeline, FrameParser frameParser, uint frameRate) { Number position = 0; Frame *frame = 0; for(const dragonBones::XMLElement* frameXML = timelineXML->FirstChildElement(ConstValues::FRAME.c_str()) ; frameXML ; frameXML = frameXML->NextSiblingElement(ConstValues::FRAME.c_str())) { frame = frameParser(frameXML, frameRate); frame->position = position; timeline->addFrame(frame); position += frame->duration; } if(frame) { frame->duration = timeline->duration - frame->position; } } TransformTimeline *XMLDataParser::parseTransformTimeline(const dragonBones::XMLElement *timelineXML, Number duration, uint frameRate) { TransformTimeline *timeline = new TransformTimeline(); timeline->duration = duration; parseTimeline(timelineXML, timeline, parseTransformFrame, frameRate); timeline->scale = Number(timelineXML->DoubleAttribute(ConstValues::A_SCALE.c_str())); timeline->offset = Number(timelineXML->DoubleAttribute(ConstValues::A_OFFSET.c_str())); return timeline; } void XMLDataParser::parseFrame(const dragonBones::XMLElement *frameXML, Frame *frame, uint frameRate) { frame->duration = Number(frameXML->DoubleAttribute(ConstValues::A_DURATION.c_str())) / frameRate; const char *action = frameXML->Attribute(ConstValues::A_ACTION.c_str()); if(action) { frame->action = action; } const char *event = frameXML->Attribute(ConstValues::A_EVENT.c_str()); if(event) { frame->event = event; } const char *sound = frameXML->Attribute(ConstValues::A_SOUND.c_str()); if(sound) { frame->sound = sound; } } Frame *XMLDataParser::parseMainFrame(const dragonBones::XMLElement *frameXML, uint frameRate) { Frame *frame = new Frame(); parseFrame(frameXML, frame, frameRate); return frame; } Frame *XMLDataParser::parseTransformFrame(const dragonBones::XMLElement *frameXML, uint frameRate) { TransformFrame *frame = new TransformFrame(); parseFrame(frameXML, frame, frameRate); frame->visible = uint(frameXML->IntAttribute(ConstValues::A_HIDE.c_str())) != 1; frame->tweenEasing = Number(frameXML->DoubleAttribute(ConstValues::A_TWEEN_EASING.c_str())); frame->tweenRotate = int(frameXML->DoubleAttribute(ConstValues::A_TWEEN_ROTATE.c_str())); frame->displayIndex = int(frameXML->DoubleAttribute(ConstValues::A_DISPLAY_INDEX.c_str())); // frame->zOrder = Number(frameXML->DoubleAttribute(ConstValues::A_Z_ORDER.c_str())); parseTransform(frameXML->FirstChildElement(ConstValues::TRANSFORM.c_str()), &frame->global, &frame->pivot); frame->transform = frame->global; const dragonBones::XMLElement * colorTransformXML = frameXML->FirstChildElement(ConstValues::COLOR_TRANSFORM.c_str()); if(colorTransformXML) { frame->color = new ColorTransform(); frame->color->alphaOffset = Number(colorTransformXML->DoubleAttribute(ConstValues::A_ALPHA_OFFSET.c_str())); frame->color->redOffset = Number(colorTransformXML->DoubleAttribute(ConstValues::A_RED_OFFSET.c_str())); frame->color->greenOffset = Number(colorTransformXML->DoubleAttribute(ConstValues::A_GREEN_OFFSET.c_str())); frame->color->blueOffset = Number(colorTransformXML->DoubleAttribute(ConstValues::A_BLUE_OFFSET.c_str())); frame->color->alphaMultiplier = Number(colorTransformXML->DoubleAttribute(ConstValues::A_ALPHA_MULTIPLIER.c_str())) * 0.01f; frame->color->redMultiplier = Number(colorTransformXML->DoubleAttribute(ConstValues::A_RED_MULTIPLIER.c_str())) * 0.01f; frame->color->greenMultiplier = Number(colorTransformXML->DoubleAttribute(ConstValues::A_GREEN_MULTIPLIER.c_str())) * 0.01f; frame->color->blueMultiplier = Number(colorTransformXML->DoubleAttribute(ConstValues::A_BLUE_MULTIPLIER.c_str())) * 0.01f; } return frame; } void XMLDataParser::parseTransform(const dragonBones::XMLElement *transformXML, DBTransform *transform, Point *pivot) { if(transformXML) { if(transform) { transform->x = Number(transformXML->DoubleAttribute(ConstValues::A_X.c_str())); transform->y = Number(transformXML->DoubleAttribute(ConstValues::A_Y.c_str())); transform->skewX = Number(transformXML->DoubleAttribute(ConstValues::A_SKEW_X.c_str())) * ConstValues::ANGLE_TO_RADIAN; transform->skewY = Number(transformXML->DoubleAttribute(ConstValues::A_SKEW_Y.c_str())) * ConstValues::ANGLE_TO_RADIAN; transform->scaleX = Number(transformXML->DoubleAttribute(ConstValues::A_SCALE_X.c_str())); transform->scaleY = Number(transformXML->DoubleAttribute(ConstValues::A_SCALE_Y.c_str())); } if(pivot) { pivot->x = Number(transformXML->DoubleAttribute(ConstValues::A_PIVOT_X.c_str())); pivot->y = Number(transformXML->DoubleAttribute(ConstValues::A_PIVOT_Y.c_str())); } } } } <commit_msg>Fixed the variable "tweenEasing" value error.<commit_after>#include "XMLDataParser.h" #include "utils/ConstValues.h" #include "core/DragonBones.h" #include "utils/DBDataUtil.h" #include <stdexcept> namespace dragonBones { TextureAtlasData* XMLDataParser::parseTextureAtlasData(const dragonBones::XMLElement *rootElement, Number scale) { TextureAtlasData* textureAtlasData = new TextureAtlasData(); textureAtlasData->name = rootElement->Attribute(ConstValues::A_NAME.c_str()); textureAtlasData->imagePath = rootElement->Attribute(ConstValues::A_IMAGE_PATH.c_str()); for(const dragonBones::XMLElement* subTextureXML = rootElement->FirstChildElement(ConstValues::SUB_TEXTURE.c_str()) ; subTextureXML ; subTextureXML = subTextureXML->NextSiblingElement(ConstValues::SUB_TEXTURE.c_str())) { String subTextureName = subTextureXML->Attribute(ConstValues::A_NAME.c_str()); Rectangle subTextureData; subTextureData.x = int(subTextureXML->IntAttribute(ConstValues::A_X.c_str()) / scale); subTextureData.y = int(subTextureXML->IntAttribute(ConstValues::A_Y.c_str()) / scale); subTextureData.width = int(subTextureXML->IntAttribute(ConstValues::A_WIDTH.c_str()) / scale); subTextureData.height = int(subTextureXML->IntAttribute(ConstValues::A_HEIGHT.c_str()) / scale); textureAtlasData->addRect(subTextureName , subTextureData); } return textureAtlasData; } /** * Parse the SkeletonData. * @param xml The SkeletonData xml to parse. * @return A SkeletonData instance. */ SkeletonData *XMLDataParser::parseSkeletonData(const dragonBones::XMLElement *rootElement) { String version = rootElement->Attribute(ConstValues::A_VERSION.c_str()); if(version != DragonBones::DATA_VERSION) { throw std::invalid_argument("Nonsupport version!"); } uint frameRate = rootElement->IntAttribute(ConstValues::A_FRAME_RATE.c_str()); SkeletonData *data = new SkeletonData(); data->name = rootElement->Attribute(ConstValues::A_NAME.c_str()); for(const dragonBones::XMLElement* armatureXML = rootElement->FirstChildElement(ConstValues::ARMATURE.c_str()) ; armatureXML ; armatureXML = armatureXML->NextSiblingElement(ConstValues::ARMATURE.c_str())) { data->addArmatureData(parseArmatureData(armatureXML, data, frameRate)); } return data; } ArmatureData *XMLDataParser::parseArmatureData(const dragonBones::XMLElement *armatureXML, SkeletonData *data, uint frameRate) { ArmatureData *armatureData = new ArmatureData(); armatureData->name = armatureXML->Attribute(ConstValues::A_NAME.c_str()); for(const dragonBones::XMLElement* boneXML = armatureXML->FirstChildElement(ConstValues::BONE.c_str()) ; boneXML ; boneXML = boneXML->NextSiblingElement(ConstValues::BONE.c_str())) { armatureData->addBoneData(parseBoneData(boneXML)); } for(const dragonBones::XMLElement* skinXML = armatureXML->FirstChildElement(ConstValues::SKIN.c_str()) ; skinXML ; skinXML = skinXML->NextSiblingElement(ConstValues::SKIN.c_str())) { armatureData->addSkinData(parseSkinData(skinXML, data)); } DBDataUtil::transformArmatureData(armatureData); armatureData->sortBoneDataList(); for(const dragonBones::XMLElement* animationXML = armatureXML->FirstChildElement(ConstValues::ANIMATION.c_str()) ; animationXML ; animationXML = animationXML->NextSiblingElement(ConstValues::ANIMATION.c_str())) { armatureData->addAnimationData(parseAnimationData(animationXML, armatureData, frameRate)); } return armatureData; } BoneData *XMLDataParser::parseBoneData(const dragonBones::XMLElement *boneXML) { BoneData *boneData = new BoneData(); boneData->name = boneXML->Attribute(ConstValues::A_NAME.c_str()); const char *parent = boneXML->Attribute(ConstValues::A_PARENT.c_str()); if(parent) { boneData->parent = parent; } boneData->length = Number(boneXML->DoubleAttribute(ConstValues::A_LENGTH.c_str())); const char *inheritScale = boneXML->Attribute(ConstValues::A_SCALE_MODE.c_str()); if (inheritScale) { boneData->scaleMode = atoi(inheritScale); } const char* fixedRotation = boneXML->Attribute(ConstValues::A_FIXED_ROTATION.c_str()); if(fixedRotation) { if(strcmp(fixedRotation , "0") == 0 || strcmp(fixedRotation , "false") == 0 || strcmp(fixedRotation , "no") == 0 || strcmp(fixedRotation , "") == 0 ) { boneData->fixedRotation = false; } else { boneData->fixedRotation = true; } } else { boneData->fixedRotation = false; } parseTransform(boneXML->FirstChildElement(ConstValues::TRANSFORM.c_str()), &boneData->global); boneData->transform = boneData->global; return boneData; } SkinData *XMLDataParser::parseSkinData(const dragonBones::XMLElement *skinXML, SkeletonData *data) { SkinData *skinData = new SkinData(); skinData->name = skinXML->Attribute(ConstValues::A_NAME.c_str()); for(const dragonBones::XMLElement* slotXML = skinXML->FirstChildElement(ConstValues::SLOT.c_str()) ; slotXML ; slotXML = slotXML->NextSiblingElement(ConstValues::SLOT.c_str())) { skinData->addSlotData(parseSlotData(slotXML, data)); } return skinData; } SlotData* XMLDataParser::parseSlotData(const dragonBones::XMLElement *slotXML, SkeletonData *data) { SlotData *slotData = new SlotData(); slotData->name = slotXML->Attribute(ConstValues::A_NAME.c_str()); slotData->parent = slotXML->Attribute(ConstValues::A_PARENT.c_str()); slotData->zOrder = Number(slotXML->DoubleAttribute(ConstValues::A_Z_ORDER.c_str())); const char *blendMode = slotXML->Attribute(ConstValues::A_BLENDMODE.c_str()); if(blendMode) { slotData->blendMode = blendMode; } else { slotData->blendMode = "normal"; } for(const dragonBones::XMLElement* displayXML = slotXML->FirstChildElement(ConstValues::DISPLAY.c_str()) ; displayXML ; displayXML = displayXML->NextSiblingElement(ConstValues::DISPLAY.c_str())) { slotData->addDisplayData(parseDisplayData(displayXML, data)); } return slotData; } DisplayData *XMLDataParser::parseDisplayData(const dragonBones::XMLElement *displayXML, SkeletonData *data) { DisplayData *displayData = new DisplayData(); displayData->name = displayXML->Attribute(ConstValues::A_NAME.c_str()); displayData->type = displayXML->Attribute(ConstValues::A_TYPE.c_str()); displayData->pivot = data->addSubTexturePivot( 0, 0, displayData->name ); parseTransform(displayXML->FirstChildElement(ConstValues::TRANSFORM.c_str()), &displayData->transform, &displayData->pivot); return displayData; } /** @private */ AnimationData *XMLDataParser::parseAnimationData(const dragonBones::XMLElement *animationXML, ArmatureData *armatureData, uint frameRate) { AnimationData *animationData = new AnimationData(); animationData->name = animationXML->Attribute(ConstValues::A_NAME.c_str()); animationData->frameRate = frameRate; animationData->loop = int(animationXML->IntAttribute(ConstValues::A_LOOP.c_str())); animationData->setFadeInTime(Number(animationXML->DoubleAttribute(ConstValues::A_FADE_IN_TIME.c_str()))); animationData->duration = Number(animationXML->DoubleAttribute(ConstValues::A_DURATION.c_str())) / (Number)frameRate; animationData->scale = Number(animationXML->DoubleAttribute(ConstValues::A_SCALE.c_str())); if(strcmp(animationXML->Attribute(ConstValues::A_TWEEN_EASING.c_str()) , "NaN") == 0) { animationData->tweenEasing = NaN; } else { animationData->tweenEasing = Number(animationXML->DoubleAttribute(ConstValues::A_TWEEN_EASING.c_str())); } parseTimeline(animationXML, animationData, parseMainFrame, frameRate); TransformTimeline *timeline = 0; String timelineName; for(const dragonBones::XMLElement* timelineXML = animationXML->FirstChildElement(ConstValues::TIMELINE.c_str()) ; timelineXML ; timelineXML = timelineXML->NextSiblingElement(ConstValues::TIMELINE.c_str())) { timeline = parseTransformTimeline(timelineXML, animationData->duration, frameRate); timelineName = timelineXML->Attribute(ConstValues::A_NAME.c_str()); animationData->addTimeline(timeline, timelineName); } DBDataUtil::addHideTimeline(animationData, armatureData); DBDataUtil::transformAnimationData(animationData, armatureData); return animationData; } void XMLDataParser::parseTimeline(const dragonBones::XMLElement *timelineXML, Timeline *timeline, FrameParser frameParser, uint frameRate) { Number position = 0; Frame *frame = 0; for(const dragonBones::XMLElement* frameXML = timelineXML->FirstChildElement(ConstValues::FRAME.c_str()) ; frameXML ; frameXML = frameXML->NextSiblingElement(ConstValues::FRAME.c_str())) { frame = frameParser(frameXML, frameRate); frame->position = position; timeline->addFrame(frame); position += frame->duration; } if(frame) { frame->duration = timeline->duration - frame->position; } } TransformTimeline *XMLDataParser::parseTransformTimeline(const dragonBones::XMLElement *timelineXML, Number duration, uint frameRate) { TransformTimeline *timeline = new TransformTimeline(); timeline->duration = duration; parseTimeline(timelineXML, timeline, parseTransformFrame, frameRate); timeline->scale = Number(timelineXML->DoubleAttribute(ConstValues::A_SCALE.c_str())); timeline->offset = Number(timelineXML->DoubleAttribute(ConstValues::A_OFFSET.c_str())); return timeline; } void XMLDataParser::parseFrame(const dragonBones::XMLElement *frameXML, Frame *frame, uint frameRate) { frame->duration = Number(frameXML->DoubleAttribute(ConstValues::A_DURATION.c_str())) / frameRate; const char *action = frameXML->Attribute(ConstValues::A_ACTION.c_str()); if(action) { frame->action = action; } const char *event = frameXML->Attribute(ConstValues::A_EVENT.c_str()); if(event) { frame->event = event; } const char *sound = frameXML->Attribute(ConstValues::A_SOUND.c_str()); if(sound) { frame->sound = sound; } } Frame *XMLDataParser::parseMainFrame(const dragonBones::XMLElement *frameXML, uint frameRate) { Frame *frame = new Frame(); parseFrame(frameXML, frame, frameRate); return frame; } Frame *XMLDataParser::parseTransformFrame(const dragonBones::XMLElement *frameXML, uint frameRate) { TransformFrame *frame = new TransformFrame(); parseFrame(frameXML, frame, frameRate); frame->visible = uint(frameXML->IntAttribute(ConstValues::A_HIDE.c_str())) != 1; //frame->tweenEasing = Number(frameXML->DoubleAttribute(ConstValues::A_TWEEN_EASING.c_str())); const char * tweenEasing = frameXML->Attribute(ConstValues::A_TWEEN_EASING.c_str()); if(tweenEasing && strcmp( tweenEasing , "NaN" ) == 0) { frame->tweenEasing = NaN; } else { frame->tweenEasing = Number(frameXML->DoubleAttribute(ConstValues::A_TWEEN_EASING.c_str())); } frame->tweenRotate = int(frameXML->DoubleAttribute(ConstValues::A_TWEEN_ROTATE.c_str())); frame->displayIndex = int(frameXML->DoubleAttribute(ConstValues::A_DISPLAY_INDEX.c_str())); // frame->zOrder = Number(frameXML->DoubleAttribute(ConstValues::A_Z_ORDER.c_str())); parseTransform(frameXML->FirstChildElement(ConstValues::TRANSFORM.c_str()), &frame->global, &frame->pivot); frame->transform = frame->global; const dragonBones::XMLElement * colorTransformXML = frameXML->FirstChildElement(ConstValues::COLOR_TRANSFORM.c_str()); if(colorTransformXML) { frame->color = new ColorTransform(); frame->color->alphaOffset = Number(colorTransformXML->DoubleAttribute(ConstValues::A_ALPHA_OFFSET.c_str())); frame->color->redOffset = Number(colorTransformXML->DoubleAttribute(ConstValues::A_RED_OFFSET.c_str())); frame->color->greenOffset = Number(colorTransformXML->DoubleAttribute(ConstValues::A_GREEN_OFFSET.c_str())); frame->color->blueOffset = Number(colorTransformXML->DoubleAttribute(ConstValues::A_BLUE_OFFSET.c_str())); frame->color->alphaMultiplier = Number(colorTransformXML->DoubleAttribute(ConstValues::A_ALPHA_MULTIPLIER.c_str())) * 0.01f; frame->color->redMultiplier = Number(colorTransformXML->DoubleAttribute(ConstValues::A_RED_MULTIPLIER.c_str())) * 0.01f; frame->color->greenMultiplier = Number(colorTransformXML->DoubleAttribute(ConstValues::A_GREEN_MULTIPLIER.c_str())) * 0.01f; frame->color->blueMultiplier = Number(colorTransformXML->DoubleAttribute(ConstValues::A_BLUE_MULTIPLIER.c_str())) * 0.01f; } return frame; } void XMLDataParser::parseTransform(const dragonBones::XMLElement *transformXML, DBTransform *transform, Point *pivot) { if(transformXML) { if(transform) { transform->x = Number(transformXML->DoubleAttribute(ConstValues::A_X.c_str())); transform->y = Number(transformXML->DoubleAttribute(ConstValues::A_Y.c_str())); transform->skewX = Number(transformXML->DoubleAttribute(ConstValues::A_SKEW_X.c_str())) * ConstValues::ANGLE_TO_RADIAN; transform->skewY = Number(transformXML->DoubleAttribute(ConstValues::A_SKEW_Y.c_str())) * ConstValues::ANGLE_TO_RADIAN; transform->scaleX = Number(transformXML->DoubleAttribute(ConstValues::A_SCALE_X.c_str())); transform->scaleY = Number(transformXML->DoubleAttribute(ConstValues::A_SCALE_Y.c_str())); } if(pivot) { pivot->x = Number(transformXML->DoubleAttribute(ConstValues::A_PIVOT_X.c_str())); pivot->y = Number(transformXML->DoubleAttribute(ConstValues::A_PIVOT_Y.c_str())); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2018 Sony Corporation. 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 // 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 nnabla header files #include <climits> #include <random> #include <nbla/context.hpp> #include <nbla/exception.hpp> #include <nbla/initializer.hpp> using std::make_shared; namespace nbla { using namespace std; std::random_device seed_gen; std::default_random_engine engine(seed_gen()); std::uniform_real_distribution<> uniform_real(0.0, 1.0); std::normal_distribution<> normal(0.0, 1.0); std::uniform_int_distribution<> uniform_int(0, INT_MAX); nbla::Context cpu_ctx{{"cpu:float"}, "CpuCachedArray", "0"}; float calc_normal_std_he_forward(int n_map_in, int n_map_out, int kernel_dim_product) { return sqrt(2. / (kernel_dim_product * n_map_in)); } float calc_normal_std_he_backward(int n_map_in, int n_map_out, int kernel_dim_product) { return sqrt(2. / (kernel_dim_product * n_map_out)); } float calc_normal_std_glorot(int n_map_in, int n_map_out, int kernel_dim_product) { return sqrt(2. / (kernel_dim_product * n_map_in + n_map_out)); } float calc_uniform_lim_glorot(int n_map_in, int n_map_out, int kernel_dim_product) { return sqrt(6. / (kernel_dim_product * n_map_in + n_map_out)); } Initializer::Initializer() {} Initializer::~Initializer() {} void Initializer::initialize(NdArrayPtr parameter) {} UniformInitializer::UniformInitializer() : Initializer(), lower_(-1.0), upper_(1.0) {} UniformInitializer::UniformInitializer(float lower, float upper) : Initializer(), lower_(lower), upper_(upper) { NBLA_CHECK(lower_ <= upper_, error_code::value, "lower must be smaller than upper (lower: (%f), upper: (%f))", lower_, upper_); } void UniformInitializer::initialize(NdArrayPtr param) { const int size = param->size(); Array *arr = param->cast(get_dtype<float_t>(), cpu_ctx, false); float_t *param_d = arr->pointer<float_t>(); for (int i = 0; i < size; i++) param_d[i] = (upper_ - lower_) * uniform_real(engine) + lower_; } ConstantInitializer::ConstantInitializer() : Initializer(), value_(0.0) {} ConstantInitializer::ConstantInitializer(float value) : Initializer(), value_(value) {} void ConstantInitializer::initialize(NdArrayPtr param) { const int size = param->size(); Array *arr = param->cast(get_dtype<float_t>(), cpu_ctx, false); float_t *param_d = arr->pointer<float_t>(); for (int i = 0; i < size; i++) param_d[i] = value_; } NormalInitializer::NormalInitializer() : Initializer(), mu_(0.0), sigma_(1.0) {} NormalInitializer::NormalInitializer(float mu, float sigma) : Initializer(), mu_(mu), sigma_(sigma) { NBLA_CHECK(sigma >= 0, error_code::value, "sigma must be positive (sigma: (%f))", sigma_); } void NormalInitializer::initialize(NdArrayPtr param) { const int size = param->size(); Array *arr = param->cast(get_dtype<float_t>(), cpu_ctx, false); float_t *param_d = arr->pointer<float_t>(); for (int i = 0; i < size; i++) param_d[i] = mu_ + sigma_ * normal(engine); } UniformIntInitializer::UniformIntInitializer() : Initializer(), lower_(0), upper_(INT_MAX) {} UniformIntInitializer::UniformIntInitializer(int lower, int upper) : Initializer(), lower_(lower), upper_(upper) { NBLA_CHECK(lower_ <= upper_, error_code::value, "lower must be smaller than upper (lower: (%d), upper: (%d))", lower_, upper_); } void UniformIntInitializer::initialize(NdArrayPtr param) { const int size = param->size(); Array *arr = param->cast(get_dtype<int>(), cpu_ctx, false); int range = upper_ - lower_; int *param_d = arr->pointer<int>(); for (int i = 0; i < size; i++) if (range == 0) { param_d[i] = lower_; } else { param_d[i] = uniform_int(engine) % range + lower_; } } } <commit_msg>Add RandomManager generator to initializer<commit_after>// Copyright (c) 2018 Sony Corporation. 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 // 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 nnabla header files #include <climits> #include <random> #include <nbla/context.hpp> #include <nbla/exception.hpp> #include <nbla/initializer.hpp> #include <nbla/random_manager.hpp> using std::make_shared; namespace nbla { using namespace std; std::uniform_real_distribution<> uniform_real(0.0, 1.0); std::normal_distribution<> normal(0.0, 1.0); std::uniform_int_distribution<> uniform_int(0, INT_MAX); nbla::Context cpu_ctx{{"cpu:float"}, "CpuCachedArray", "0"}; float calc_normal_std_he_forward(int n_map_in, int n_map_out, int kernel_dim_product) { return sqrt(2. / (kernel_dim_product * n_map_in)); } float calc_normal_std_he_backward(int n_map_in, int n_map_out, int kernel_dim_product) { return sqrt(2. / (kernel_dim_product * n_map_out)); } float calc_normal_std_glorot(int n_map_in, int n_map_out, int kernel_dim_product) { return sqrt(2. / (kernel_dim_product * n_map_in + n_map_out)); } float calc_uniform_lim_glorot(int n_map_in, int n_map_out, int kernel_dim_product) { return sqrt(6. / (kernel_dim_product * n_map_in + n_map_out)); } Initializer::Initializer() {} Initializer::~Initializer() {} void Initializer::initialize(NdArrayPtr parameter) {} UniformInitializer::UniformInitializer() : Initializer(), lower_(-1.0), upper_(1.0) {} UniformInitializer::UniformInitializer(float lower, float upper) : Initializer(), lower_(lower), upper_(upper) { NBLA_CHECK(lower_ <= upper_, error_code::value, "lower must be smaller than upper (lower: (%f), upper: (%f))", lower_, upper_); } void UniformInitializer::initialize(NdArrayPtr param) { std::mt19937 &rgen = SingletonManager::get<RandomManager>()->get_rand_generator(); const int size = param->size(); Array *arr = param->cast(get_dtype<float_t>(), cpu_ctx, false); float_t *param_d = arr->pointer<float_t>(); for (int i = 0; i < size; i++) param_d[i] = (upper_ - lower_) * uniform_real(rgen) + lower_; } ConstantInitializer::ConstantInitializer() : Initializer(), value_(0.0) {} ConstantInitializer::ConstantInitializer(float value) : Initializer(), value_(value) {} void ConstantInitializer::initialize(NdArrayPtr param) { const int size = param->size(); Array *arr = param->cast(get_dtype<float_t>(), cpu_ctx, false); float_t *param_d = arr->pointer<float_t>(); for (int i = 0; i < size; i++) param_d[i] = value_; } NormalInitializer::NormalInitializer() : Initializer(), mu_(0.0), sigma_(1.0) {} NormalInitializer::NormalInitializer(float mu, float sigma) : Initializer(), mu_(mu), sigma_(sigma) { NBLA_CHECK(sigma >= 0, error_code::value, "sigma must be positive (sigma: (%f))", sigma_); } void NormalInitializer::initialize(NdArrayPtr param) { std::mt19937 &rgen = SingletonManager::get<RandomManager>()->get_rand_generator(); const int size = param->size(); Array *arr = param->cast(get_dtype<float_t>(), cpu_ctx, false); float_t *param_d = arr->pointer<float_t>(); for (int i = 0; i < size; i++) param_d[i] = mu_ + sigma_ * normal(rgen); } UniformIntInitializer::UniformIntInitializer() : Initializer(), lower_(0), upper_(INT_MAX) {} UniformIntInitializer::UniformIntInitializer(int lower, int upper) : Initializer(), lower_(lower), upper_(upper) { NBLA_CHECK(lower_ <= upper_, error_code::value, "lower must be smaller than upper (lower: (%d), upper: (%d))", lower_, upper_); } void UniformIntInitializer::initialize(NdArrayPtr param) { std::mt19937 &rgen = SingletonManager::get<RandomManager>()->get_rand_generator(); const int size = param->size(); Array *arr = param->cast(get_dtype<int>(), cpu_ctx, false); int range = upper_ - lower_; int *param_d = arr->pointer<int>(); for (int i = 0; i < size; i++) if (range == 0) { param_d[i] = lower_; } else { param_d[i] = uniform_int(rgen) % range + lower_; } } } <|endoftext|>
<commit_before>/** * @file * @author Jason Lingle * @date 2012.02.11 * @brief Implements the network testing functions */ #include <string> #include <vector> #include <iostream> #include <fstream> #include <cstdlib> #include <SDL.h> #include <asio.hpp> #include "antenna.hxx" #include "tuner.hxx" #include "network_assembly.hxx" #include "network_connection.hxx" #include "network_geraet.hxx" #include "connection_listener.hxx" #include "synchronous_control_geraet.hxx" #include "block_geraet.hxx" #include "src/sim/game_field.hxx" #include "src/core/game_state.hxx" #include "src/graphics/asgi.hxx" #include "src/globals.hxx" using namespace std; class NetworkTestBase { public: virtual ~NetworkTestBase() {} void draw() { const vector<byte>& data = getData(); for (unsigned x = 0; x < 1000; ++x) { asgi::begin(asgi::Points); for (unsigned y = 0; y < 1000; ++y) { float c = data[y*1000+x]/1000.0f; asgi::colour(c,c,c,1); asgi::vertex(x/1000.0f, y*vheight/1000.0f); } asgi::end(); } } protected: virtual const vector<byte>& getData() const = 0; }; class NetworkTestListen: public GameState, public OutputBlockGeraet, private NetworkTestBase { public: bool randomising; NetworkAssembly* assembly; GameState* ret; NetworkTestListen(NetworkAssembly* na, AsyncAckGeraet* aag) : OutputBlockGeraet(1000000, aag, DSIntrinsic), randomising(false), assembly(na), ret(NULL) { } virtual const vector<byte>& getData() const { return state; } virtual GameState* update(float et) noth { //GameState::update assembly->update((unsigned)et); if (randomising) { for (unsigned i=0; i<16; ++i) state[rand()%state.size()] = rand(); dirty = true; } return ret; } virtual void draw() noth { NetworkTestBase::draw(); } virtual void keyboard(SDL_KeyboardEvent* e) { if (e->type == SDL_KEYDOWN) { switch (e->keysym.sym) { case SDLK_q: ret = this; break; case SDLK_s: { //Sierpinski triangle memset(&state[0], 0, state.size()); signed x = rand()%1000, y = rand()%1000; for (unsigned i=0; i<1000000; ++i) { signed vx, vy; switch (rand()%3) { case 0: vx = 0; vy = 0; break; case 1: vx = 1000; vy = 0; break; case 2: vx = 500; vy = 1000; break; } x += (vx-x)/2; y += (vy-y)/2; if (x >= 0 && x < 1000 && y >= 0 && y < 1000) state[y*1000+x] = 255; } dirty = true; } break; case SDLK_r: { randomising ^= true; } break; case SDLK_w: { memset(&state[0], 255, state.size()); dirty = true; } break; case SDLK_b: { memset(&state[0], 0, state.size()); dirty = true; } break; case SDLK_g: { for (unsigned y=0; y<1000; ++y) for (unsigned x=0; x<1000; ++x) state[y*1000+x] = y/4; dirty = true; } break; default: break; } } } }; static NetworkAssembly* ntr_assembly; class NetworkTestRun: public GameState, public NetworkTestBase, public InputBlockGeraet { NetworkAssembly* assembly; public: NetworkTestRun(AsyncAckGeraet* aag, NetworkAssembly* na) : InputBlockGeraet(1000000, aag, DSIntrinsic), assembly(na) { ::state = this; } virtual GameState* update(float et) { assembly->update(et); if (assembly->getConnection(0)->getStatus() == NetworkConnection::Zombie) return this; else return NULL; } virtual void draw() { NetworkTestBase::draw(); } virtual const vector<byte>& getData() const { return state; } static InputNetworkGeraet* create(NetworkConnection* cxn) { return new NetworkTestRun(cxn->aag, ntr_assembly); } }; class TestListener: public ConnectionListener { NetworkAssembly* nasm; public: TestListener(NetworkAssembly* nas, Tuner* tuner) : ConnectionListener(tuner), nasm(nas) { } virtual bool acceptConnection(const Antenna::endpoint& source, Antenna* antenna, Tuner* tuner, std::string& errmsg, std::string& errl10n) noth { NetworkConnection* cxn = new NetworkConnection(nasm, source, true); nasm->addConnection(cxn); cxn->scg->openChannel(cxn->aag, cxn->aag->num); NetworkTestListen* that = new NetworkTestListen(nasm, cxn->aag); cxn->scg->openChannel(that, 999); state = that; return true; } }; void networkTestListen() { static GameField field(1,1); static NetworkAssembly assembly(&field, &antenna); static bool init = false; if (!init) { assembly.addPacketProcessor( new TestListener(&assembly, assembly.getTuner())); init = true; } while (assembly.numConnections() == 0) { assembly.update(5); SDL_Delay(5); } } unsigned networkTestRun(const char* addrstr, unsigned portn) { static GameField field(1,1); static NetworkAssembly assembly(&field, &antenna); ntr_assembly = &assembly; static unsigned num = 0; if (!num) num = NetworkConnection::registerGeraetCreator(&NetworkTestRun::create, 999); asio::ip::udp::endpoint endpoint(asio::ip::address::from_string(addrstr), portn); NetworkConnection* cxn = new NetworkConnection(&assembly, endpoint, false); assembly.addConnection(cxn); cxn->scg->openChannel(cxn->aag, cxn->aag->num); state = NULL; while (!state) { assembly.update(5); SDL_Delay(5); } return 0; } <commit_msg>Add testing option to network test.<commit_after>/** * @file * @author Jason Lingle * @date 2012.02.11 * @brief Implements the network testing functions */ #include <string> #include <vector> #include <iostream> #include <fstream> #include <cstdlib> #include <SDL.h> #include <asio.hpp> #include "antenna.hxx" #include "tuner.hxx" #include "network_assembly.hxx" #include "network_connection.hxx" #include "network_geraet.hxx" #include "connection_listener.hxx" #include "synchronous_control_geraet.hxx" #include "block_geraet.hxx" #include "src/sim/game_field.hxx" #include "src/core/game_state.hxx" #include "src/graphics/asgi.hxx" #include "src/globals.hxx" using namespace std; class NetworkTestBase { public: virtual ~NetworkTestBase() {} void draw() { const vector<byte>& data = getData(); for (unsigned x = 0; x < 1000; ++x) { asgi::begin(asgi::Points); for (unsigned y = 0; y < 1000; ++y) { float c = data[y*1000+x]/1000.0f; asgi::colour(c,c,c,1); asgi::vertex(x/1000.0f, y*vheight/1000.0f); } asgi::end(); } } protected: virtual const vector<byte>& getData() const = 0; }; class NetworkTestListen: public GameState, public OutputBlockGeraet, private NetworkTestBase { public: bool randomising; NetworkAssembly* assembly; GameState* ret; NetworkTestListen(NetworkAssembly* na, AsyncAckGeraet* aag) : OutputBlockGeraet(1000000, aag, DSIntrinsic), randomising(false), assembly(na), ret(NULL) { } virtual const vector<byte>& getData() const { return state; } virtual GameState* update(float et) noth { //GameState::update assembly->update((unsigned)et); if (randomising) { for (unsigned i=0; i<16; ++i) state[rand()%state.size()] = rand(); dirty = true; } return ret; } virtual void draw() noth { NetworkTestBase::draw(); } virtual void keyboard(SDL_KeyboardEvent* e) { if (e->type == SDL_KEYDOWN) { switch (e->keysym.sym) { case SDLK_q: ret = this; break; case SDLK_s: { //Sierpinski triangle memset(&state[0], 0, state.size()); signed x = rand()%1000, y = rand()%1000; for (unsigned i=0; i<1000000; ++i) { signed vx, vy; switch (rand()%3) { case 0: vx = 0; vy = 0; break; case 1: vx = 1000; vy = 0; break; case 2: vx = 500; vy = 1000; break; } x += (vx-x)/2; y += (vy-y)/2; if (x >= 0 && x < 1000 && y >= 0 && y < 1000) state[y*1000+x] = 255; } dirty = true; } break; case SDLK_r: { randomising ^= true; } break; case SDLK_w: { memset(&state[0], 255, state.size()); dirty = true; } break; case SDLK_b: { memset(&state[0], 0, state.size()); dirty = true; } break; case SDLK_g: { for (unsigned y=0; y<1000; ++y) for (unsigned x=0; x<1000; ++x) state[y*1000+x] = y/4; dirty = true; } break; case SDLK_i: { for (unsigned y=0; y<100; ++y) for (unsigned x=0; x<1000; ++x) state[y*1000+x] += 32; dirty = true; } break; default: break; } } } }; static NetworkAssembly* ntr_assembly; class NetworkTestRun: public GameState, public NetworkTestBase, public InputBlockGeraet { NetworkAssembly* assembly; public: NetworkTestRun(AsyncAckGeraet* aag, NetworkAssembly* na) : InputBlockGeraet(1000000, aag, DSIntrinsic), assembly(na) { ::state = this; } virtual GameState* update(float et) { assembly->update(et); if (assembly->getConnection(0)->getStatus() == NetworkConnection::Zombie) return this; else return NULL; } virtual void draw() { NetworkTestBase::draw(); } virtual const vector<byte>& getData() const { return state; } static InputNetworkGeraet* create(NetworkConnection* cxn) { return new NetworkTestRun(cxn->aag, ntr_assembly); } }; class TestListener: public ConnectionListener { NetworkAssembly* nasm; public: TestListener(NetworkAssembly* nas, Tuner* tuner) : ConnectionListener(tuner), nasm(nas) { } virtual bool acceptConnection(const Antenna::endpoint& source, Antenna* antenna, Tuner* tuner, std::string& errmsg, std::string& errl10n) noth { NetworkConnection* cxn = new NetworkConnection(nasm, source, true); nasm->addConnection(cxn); cxn->scg->openChannel(cxn->aag, cxn->aag->num); NetworkTestListen* that = new NetworkTestListen(nasm, cxn->aag); cxn->scg->openChannel(that, 999); state = that; return true; } }; void networkTestListen() { static GameField field(1,1); static NetworkAssembly assembly(&field, &antenna); static bool init = false; if (!init) { assembly.addPacketProcessor( new TestListener(&assembly, assembly.getTuner())); init = true; } while (assembly.numConnections() == 0) { assembly.update(5); SDL_Delay(5); } } unsigned networkTestRun(const char* addrstr, unsigned portn) { static GameField field(1,1); static NetworkAssembly assembly(&field, &antenna); ntr_assembly = &assembly; static unsigned num = 0; if (!num) num = NetworkConnection::registerGeraetCreator(&NetworkTestRun::create, 999); asio::ip::udp::endpoint endpoint(asio::ip::address::from_string(addrstr), portn); NetworkConnection* cxn = new NetworkConnection(&assembly, endpoint, false); assembly.addConnection(cxn); cxn->scg->openChannel(cxn->aag, cxn->aag->num); state = NULL; while (!state) { assembly.update(5); SDL_Delay(5); } return 0; } <|endoftext|>
<commit_before>#include "nw_screen_api.h" #include "base/lazy_instance.h" #include "base/values.h" #include "content/nw/src/api/nw_screen.h" #include "extensions/browser/extensions_browser_client.h" #include "ui/display/display_observer.h" #include "ui/display/display.h" #include "ui/display/screen.h" // For desktop capture APIs #include "base/base64.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/media/webrtc/desktop_media_list_observer.h" #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" #include "chrome/browser/media/webrtc/native_desktop_media_list.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" using namespace extensions::nwapi::nw__screen; using namespace content; namespace extensions { class NwDesktopCaptureMonitor : public DesktopMediaListObserver { public: static NwDesktopCaptureMonitor* GetInstance(); NwDesktopCaptureMonitor(); void Start(bool screens, bool windows); void Stop(); bool IsStarted(); private: int GetPrimaryMonitorIndex(); // DesktopMediaListObserver implementation. void OnSourceAdded(DesktopMediaList* list, int index) override; void OnSourceRemoved(DesktopMediaList* list, int index) override; void OnSourceMoved(DesktopMediaList* list, int old_index, int new_index) override; void OnSourceNameChanged(DesktopMediaList* list, int index) override; void OnSourceThumbnailChanged(DesktopMediaList* list, int index) override; bool started_; std::vector<std::unique_ptr<DesktopMediaList>> media_list_; DISALLOW_COPY_AND_ASSIGN(NwDesktopCaptureMonitor); }; class NwScreenDisplayObserver: public display::DisplayObserver { public: static NwScreenDisplayObserver* GetInstance(); NwScreenDisplayObserver(); private: ~NwScreenDisplayObserver() override; // gfx::DisplayObserver implementation. void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; void OnDisplayAdded(const display::Display& new_display) override; void OnDisplayRemoved(const display::Display& old_display) override; DISALLOW_COPY_AND_ASSIGN(NwScreenDisplayObserver); }; namespace { // Helper function to convert display::Display to nwapi::nw__screen::Display std::unique_ptr<nwapi::nw__screen::Display> ConvertGfxDisplay(const display::Display& gfx_display) { std::unique_ptr<nwapi::nw__screen::Display> displayResult(new nwapi::nw__screen::Display); displayResult->id = gfx_display.id(); displayResult->scale_factor = gfx_display.device_scale_factor(); displayResult->is_built_in = gfx_display.IsInternal(); displayResult->rotation = gfx_display.RotationAsDegree(); displayResult->touch_support = (int)gfx_display.touch_support(); gfx::Rect rect = gfx_display.bounds(); DisplayGeometry& bounds = displayResult->bounds; bounds.x = rect.x(); bounds.y = rect.y(); bounds.width = rect.width(); bounds.height = rect.height(); rect = gfx_display.work_area(); DisplayGeometry& work_area = displayResult->work_area; work_area.x = rect.x(); work_area.y = rect.y(); work_area.width = rect.width(); work_area.height = rect.height(); return displayResult; } void DispatchEvent( events::HistogramValue histogram_value, const std::string& event_name, std::unique_ptr<base::ListValue> args) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ExtensionsBrowserClient::Get()->BroadcastEventToRenderers( histogram_value, event_name, std::move(args), false); } // Lazy initialize screen event listeners until first call base::LazyInstance<NwScreenDisplayObserver>::Leaky g_display_observer = LAZY_INSTANCE_INITIALIZER; base::LazyInstance<NwDesktopCaptureMonitor>::Leaky g_desktop_capture_monitor = LAZY_INSTANCE_INITIALIZER; } // static NwScreenDisplayObserver* NwScreenDisplayObserver::GetInstance() { return g_display_observer.Pointer(); } NwScreenDisplayObserver::NwScreenDisplayObserver() { display::Screen* screen = display::Screen::GetScreen(); if (screen) { screen->AddObserver(this); } } NwScreenDisplayObserver::~NwScreenDisplayObserver() { display::Screen* screen = display::Screen::GetScreen(); if (screen) { screen->RemoveObserver(this); } } // Called when the |display|'s bound has changed. void NwScreenDisplayObserver::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayBoundsChanged::Create(*ConvertGfxDisplay(display), changed_metrics); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayBoundsChanged::kEventName, std::move(args)); } // Called when |new_display| has been added. void NwScreenDisplayObserver::OnDisplayAdded(const display::Display& new_display) { std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayAdded::Create(*ConvertGfxDisplay(new_display)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayAdded::kEventName, std::move(args)); } // Called when |old_display| has been removed. void NwScreenDisplayObserver::OnDisplayRemoved(const display::Display& old_display) { std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayRemoved::Create(*ConvertGfxDisplay(old_display)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayRemoved::kEventName, std::move(args)); } NwScreenGetScreensFunction::NwScreenGetScreensFunction() {} bool NwScreenGetScreensFunction::RunNWSync(base::ListValue* response, std::string* error) { const std::vector<display::Display>& displays = display::Screen::GetScreen()->GetAllDisplays(); for (size_t i=0; i<displays.size(); i++) { response->Append(ConvertGfxDisplay(displays[i])->ToValue()); } return true; } NwScreenInitEventListenersFunction::NwScreenInitEventListenersFunction() {} bool NwScreenInitEventListenersFunction::RunNWSync(base::ListValue* response, std::string* error) { NwScreenDisplayObserver::GetInstance(); return true; } NwDesktopCaptureMonitor* NwDesktopCaptureMonitor::GetInstance() { return g_desktop_capture_monitor.Pointer(); } NwDesktopCaptureMonitor::NwDesktopCaptureMonitor() : started_(false) { } void NwDesktopCaptureMonitor::Start(bool screens, bool windows) { if (started_) { return; } started_ = true; webrtc::DesktopCaptureOptions options = webrtc::DesktopCaptureOptions::CreateDefault(); options.set_disable_effects(false); if (screens) { std::unique_ptr<DesktopMediaList> screen_media_list = std::make_unique<NativeDesktopMediaList>( content::DesktopMediaID::TYPE_SCREEN, webrtc::DesktopCapturer::CreateScreenCapturer(options)); media_list_.push_back(std::move(screen_media_list)); } if (windows) { std::unique_ptr<DesktopMediaList> window_media_list = std::make_unique<NativeDesktopMediaList>( content::DesktopMediaID::TYPE_WINDOW, webrtc::DesktopCapturer::CreateWindowCapturer(options)); media_list_.push_back(std::move(window_media_list)); } for (auto& media_list : media_list_) { media_list->StartUpdating(this); } } void NwDesktopCaptureMonitor::Stop() { started_ = false; media_list_.clear(); } bool NwDesktopCaptureMonitor::IsStarted() { return started_; } int NwDesktopCaptureMonitor::GetPrimaryMonitorIndex() { #ifdef _WIN32 int count=0; for (int i = 0;; ++i) { DISPLAY_DEVICE device; device.cb = sizeof(device); BOOL ret = EnumDisplayDevices(NULL, i, &device, 0); if(!ret) break; if (device.StateFlags & DISPLAY_DEVICE_ACTIVE){ if (device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE){ return count; } count++; } } #endif return -1; } void NwDesktopCaptureMonitor::OnSourceAdded(DesktopMediaList* list, int index) { DesktopMediaList::Source src = list->GetSource(index); std::string type; switch(src.id.type) { case content::DesktopMediaID::TYPE_WINDOW: type = "window"; break; case content::DesktopMediaID::TYPE_SCREEN: type = "screen"; break; case content::DesktopMediaID::TYPE_NONE: type = "none"; break; default: type = "unknown"; break; } std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceAdded::Create( src.id.ToString(), base::UTF16ToUTF8(src.name), index, type, src.id.type == content::DesktopMediaID::TYPE_SCREEN && GetPrimaryMonitorIndex() == index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceAdded::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceRemoved(DesktopMediaList* list, int index) { std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceRemoved::Create(index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceRemoved::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceMoved(DesktopMediaList* list, int old_index, int new_index) { DesktopMediaList::Source src = list->GetSource(new_index); std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceOrderChanged::Create( src.id.ToString(), new_index, old_index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceOrderChanged::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceNameChanged(DesktopMediaList* list, int index) { DesktopMediaList::Source src = list->GetSource(index); std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceNameChanged::Create( src.id.ToString(), base::UTF16ToUTF8(src.name)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceNameChanged::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceThumbnailChanged(DesktopMediaList* list, int index) { std::string base64; DesktopMediaList::Source src = list->GetSource(index); SkBitmap bitmap = src.thumbnail.GetRepresentation(1).GetBitmap(); std::vector<unsigned char> data; bool success = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &data); if (success){ base::StringPiece raw_str(reinterpret_cast<const char*>(&data[0]), data.size()); base::Base64Encode(raw_str, &base64); } std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceThumbnailChanged::Create( src.id.ToString(), base64); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceThumbnailChanged::kEventName, std::move(args)); } NwScreenStartMonitorFunction::NwScreenStartMonitorFunction() {} bool NwScreenStartMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) { bool screens, windows; EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(0, &screens)); EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(1, &windows)); NwDesktopCaptureMonitor::GetInstance()->Start(screens, windows); return true; } NwScreenStopMonitorFunction::NwScreenStopMonitorFunction() {} bool NwScreenStopMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) { NwDesktopCaptureMonitor::GetInstance()->Stop(); return true; } NwScreenIsMonitorStartedFunction::NwScreenIsMonitorStartedFunction() {} bool NwScreenIsMonitorStartedFunction::RunNWSync(base::ListValue* response, std::string* error) { response->AppendBoolean(NwDesktopCaptureMonitor::GetInstance()->IsStarted()); return true; } NwScreenRegisterStreamFunction::NwScreenRegisterStreamFunction() {} bool NwScreenRegisterStreamFunction::RunNWSync(base::ListValue* response, std::string* error) { std::string id; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &id)); // following code is modified from `DesktopCaptureChooseDesktopMediaFunctionBase::OnPickerDialogResults` // in chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc content::DesktopMediaID source = content::DesktopMediaID::Parse(id); content::WebContents* web_contents = GetSenderWebContents(); if (!source.is_null() && web_contents) { std::string result; source.audio_share = true; content::DesktopStreamsRegistry* registry = content::DesktopStreamsRegistry::GetInstance(); // TODO(miu): Once render_frame_host() is being set, we should register the // exact RenderFrame requesting the stream, not the main RenderFrame. With // that change, also update // MediaCaptureDevicesDispatcher::ProcessDesktopCaptureAccessRequest(). // http://crbug.com/304341 content::RenderFrameHost* const main_frame = web_contents->GetMainFrame(); result = registry->RegisterStream(main_frame->GetProcess()->GetID(), main_frame->GetRoutingID(), url::Origin::Create(web_contents->GetURL().GetOrigin()), source, extension()->name(), content::kRegistryStreamTypeDesktop); response->AppendString(result); } return true; } } // extensions <commit_msg>Update nw_screen_api.cc: Create DesktopMediaList::Type<commit_after>#include "nw_screen_api.h" #include "base/lazy_instance.h" #include "base/values.h" #include "content/nw/src/api/nw_screen.h" #include "extensions/browser/extensions_browser_client.h" #include "ui/display/display_observer.h" #include "ui/display/display.h" #include "ui/display/screen.h" // For desktop capture APIs #include "base/base64.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/media/webrtc/desktop_media_list_observer.h" #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" #include "chrome/browser/media/webrtc/native_desktop_media_list.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" using namespace extensions::nwapi::nw__screen; using namespace content; namespace extensions { class NwDesktopCaptureMonitor : public DesktopMediaListObserver { public: static NwDesktopCaptureMonitor* GetInstance(); NwDesktopCaptureMonitor(); void Start(bool screens, bool windows); void Stop(); bool IsStarted(); private: int GetPrimaryMonitorIndex(); // DesktopMediaListObserver implementation. void OnSourceAdded(DesktopMediaList* list, int index) override; void OnSourceRemoved(DesktopMediaList* list, int index) override; void OnSourceMoved(DesktopMediaList* list, int old_index, int new_index) override; void OnSourceNameChanged(DesktopMediaList* list, int index) override; void OnSourceThumbnailChanged(DesktopMediaList* list, int index) override; bool started_; std::vector<std::unique_ptr<DesktopMediaList>> media_list_; DISALLOW_COPY_AND_ASSIGN(NwDesktopCaptureMonitor); }; class NwScreenDisplayObserver: public display::DisplayObserver { public: static NwScreenDisplayObserver* GetInstance(); NwScreenDisplayObserver(); private: ~NwScreenDisplayObserver() override; // gfx::DisplayObserver implementation. void OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) override; void OnDisplayAdded(const display::Display& new_display) override; void OnDisplayRemoved(const display::Display& old_display) override; DISALLOW_COPY_AND_ASSIGN(NwScreenDisplayObserver); }; namespace { // Helper function to convert display::Display to nwapi::nw__screen::Display std::unique_ptr<nwapi::nw__screen::Display> ConvertGfxDisplay(const display::Display& gfx_display) { std::unique_ptr<nwapi::nw__screen::Display> displayResult(new nwapi::nw__screen::Display); displayResult->id = gfx_display.id(); displayResult->scale_factor = gfx_display.device_scale_factor(); displayResult->is_built_in = gfx_display.IsInternal(); displayResult->rotation = gfx_display.RotationAsDegree(); displayResult->touch_support = (int)gfx_display.touch_support(); gfx::Rect rect = gfx_display.bounds(); DisplayGeometry& bounds = displayResult->bounds; bounds.x = rect.x(); bounds.y = rect.y(); bounds.width = rect.width(); bounds.height = rect.height(); rect = gfx_display.work_area(); DisplayGeometry& work_area = displayResult->work_area; work_area.x = rect.x(); work_area.y = rect.y(); work_area.width = rect.width(); work_area.height = rect.height(); return displayResult; } void DispatchEvent( events::HistogramValue histogram_value, const std::string& event_name, std::unique_ptr<base::ListValue> args) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ExtensionsBrowserClient::Get()->BroadcastEventToRenderers( histogram_value, event_name, std::move(args), false); } // Lazy initialize screen event listeners until first call base::LazyInstance<NwScreenDisplayObserver>::Leaky g_display_observer = LAZY_INSTANCE_INITIALIZER; base::LazyInstance<NwDesktopCaptureMonitor>::Leaky g_desktop_capture_monitor = LAZY_INSTANCE_INITIALIZER; } // static NwScreenDisplayObserver* NwScreenDisplayObserver::GetInstance() { return g_display_observer.Pointer(); } NwScreenDisplayObserver::NwScreenDisplayObserver() { display::Screen* screen = display::Screen::GetScreen(); if (screen) { screen->AddObserver(this); } } NwScreenDisplayObserver::~NwScreenDisplayObserver() { display::Screen* screen = display::Screen::GetScreen(); if (screen) { screen->RemoveObserver(this); } } // Called when the |display|'s bound has changed. void NwScreenDisplayObserver::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayBoundsChanged::Create(*ConvertGfxDisplay(display), changed_metrics); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayBoundsChanged::kEventName, std::move(args)); } // Called when |new_display| has been added. void NwScreenDisplayObserver::OnDisplayAdded(const display::Display& new_display) { std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayAdded::Create(*ConvertGfxDisplay(new_display)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayAdded::kEventName, std::move(args)); } // Called when |old_display| has been removed. void NwScreenDisplayObserver::OnDisplayRemoved(const display::Display& old_display) { std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnDisplayRemoved::Create(*ConvertGfxDisplay(old_display)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnDisplayRemoved::kEventName, std::move(args)); } NwScreenGetScreensFunction::NwScreenGetScreensFunction() {} bool NwScreenGetScreensFunction::RunNWSync(base::ListValue* response, std::string* error) { const std::vector<display::Display>& displays = display::Screen::GetScreen()->GetAllDisplays(); for (size_t i=0; i<displays.size(); i++) { response->Append(ConvertGfxDisplay(displays[i])->ToValue()); } return true; } NwScreenInitEventListenersFunction::NwScreenInitEventListenersFunction() {} bool NwScreenInitEventListenersFunction::RunNWSync(base::ListValue* response, std::string* error) { NwScreenDisplayObserver::GetInstance(); return true; } NwDesktopCaptureMonitor* NwDesktopCaptureMonitor::GetInstance() { return g_desktop_capture_monitor.Pointer(); } NwDesktopCaptureMonitor::NwDesktopCaptureMonitor() : started_(false) { } void NwDesktopCaptureMonitor::Start(bool screens, bool windows) { if (started_) { return; } started_ = true; webrtc::DesktopCaptureOptions options = webrtc::DesktopCaptureOptions::CreateDefault(); options.set_disable_effects(false); if (screens) { std::unique_ptr<DesktopMediaList> screen_media_list = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kScreen, webrtc::DesktopCapturer::CreateScreenCapturer(options)); media_list_.push_back(std::move(screen_media_list)); } if (windows) { std::unique_ptr<DesktopMediaList> window_media_list = std::make_unique<NativeDesktopMediaList>( DesktopMediaList::Type::kWindow, webrtc::DesktopCapturer::CreateWindowCapturer(options)); media_list_.push_back(std::move(window_media_list)); } for (auto& media_list : media_list_) { media_list->StartUpdating(this); } } void NwDesktopCaptureMonitor::Stop() { started_ = false; media_list_.clear(); } bool NwDesktopCaptureMonitor::IsStarted() { return started_; } int NwDesktopCaptureMonitor::GetPrimaryMonitorIndex() { #ifdef _WIN32 int count=0; for (int i = 0;; ++i) { DISPLAY_DEVICE device; device.cb = sizeof(device); BOOL ret = EnumDisplayDevices(NULL, i, &device, 0); if(!ret) break; if (device.StateFlags & DISPLAY_DEVICE_ACTIVE){ if (device.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE){ return count; } count++; } } #endif return -1; } void NwDesktopCaptureMonitor::OnSourceAdded(DesktopMediaList* list, int index) { DesktopMediaList::Source src = list->GetSource(index); std::string type; switch(src.id.type) { case content::DesktopMediaID::TYPE_WINDOW: type = "window"; break; case content::DesktopMediaID::TYPE_SCREEN: type = "screen"; break; case content::DesktopMediaID::TYPE_NONE: type = "none"; break; default: type = "unknown"; break; } std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceAdded::Create( src.id.ToString(), base::UTF16ToUTF8(src.name), index, type, src.id.type == content::DesktopMediaID::TYPE_SCREEN && GetPrimaryMonitorIndex() == index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceAdded::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceRemoved(DesktopMediaList* list, int index) { std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceRemoved::Create(index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceRemoved::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceMoved(DesktopMediaList* list, int old_index, int new_index) { DesktopMediaList::Source src = list->GetSource(new_index); std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceOrderChanged::Create( src.id.ToString(), new_index, old_index); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceOrderChanged::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceNameChanged(DesktopMediaList* list, int index) { DesktopMediaList::Source src = list->GetSource(index); std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceNameChanged::Create( src.id.ToString(), base::UTF16ToUTF8(src.name)); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceNameChanged::kEventName, std::move(args)); } void NwDesktopCaptureMonitor::OnSourceThumbnailChanged(DesktopMediaList* list, int index) { std::string base64; DesktopMediaList::Source src = list->GetSource(index); SkBitmap bitmap = src.thumbnail.GetRepresentation(1).GetBitmap(); std::vector<unsigned char> data; bool success = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &data); if (success){ base::StringPiece raw_str(reinterpret_cast<const char*>(&data[0]), data.size()); base::Base64Encode(raw_str, &base64); } std::unique_ptr<base::ListValue> args = nwapi::nw__screen::OnSourceThumbnailChanged::Create( src.id.ToString(), base64); DispatchEvent( events::HistogramValue::UNKNOWN, nwapi::nw__screen::OnSourceThumbnailChanged::kEventName, std::move(args)); } NwScreenStartMonitorFunction::NwScreenStartMonitorFunction() {} bool NwScreenStartMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) { bool screens, windows; EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(0, &screens)); EXTENSION_FUNCTION_VALIDATE(args_->GetBoolean(1, &windows)); NwDesktopCaptureMonitor::GetInstance()->Start(screens, windows); return true; } NwScreenStopMonitorFunction::NwScreenStopMonitorFunction() {} bool NwScreenStopMonitorFunction::RunNWSync(base::ListValue* response, std::string* error) { NwDesktopCaptureMonitor::GetInstance()->Stop(); return true; } NwScreenIsMonitorStartedFunction::NwScreenIsMonitorStartedFunction() {} bool NwScreenIsMonitorStartedFunction::RunNWSync(base::ListValue* response, std::string* error) { response->AppendBoolean(NwDesktopCaptureMonitor::GetInstance()->IsStarted()); return true; } NwScreenRegisterStreamFunction::NwScreenRegisterStreamFunction() {} bool NwScreenRegisterStreamFunction::RunNWSync(base::ListValue* response, std::string* error) { std::string id; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &id)); // following code is modified from `DesktopCaptureChooseDesktopMediaFunctionBase::OnPickerDialogResults` // in chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc content::DesktopMediaID source = content::DesktopMediaID::Parse(id); content::WebContents* web_contents = GetSenderWebContents(); if (!source.is_null() && web_contents) { std::string result; source.audio_share = true; content::DesktopStreamsRegistry* registry = content::DesktopStreamsRegistry::GetInstance(); // TODO(miu): Once render_frame_host() is being set, we should register the // exact RenderFrame requesting the stream, not the main RenderFrame. With // that change, also update // MediaCaptureDevicesDispatcher::ProcessDesktopCaptureAccessRequest(). // http://crbug.com/304341 content::RenderFrameHost* const main_frame = web_contents->GetMainFrame(); result = registry->RegisterStream(main_frame->GetProcess()->GetID(), main_frame->GetRoutingID(), url::Origin::Create(web_contents->GetURL().GetOrigin()), source, extension()->name(), content::kRegistryStreamTypeDesktop); response->AppendString(result); } return true; } } // extensions <|endoftext|>
<commit_before>// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "Differentiator.h" #include <better/map.h> #include <react/core/LayoutableShadowNode.h> #include <react/debug/SystraceSection.h> #include "ShadowView.h" namespace facebook { namespace react { static void sliceChildShadowNodeViewPairsRecursively( ShadowViewNodePair::List &pairList, Point layoutOffset, ShadowNode const &shadowNode) { for (auto const &childShadowNode : shadowNode.getChildren()) { auto shadowView = ShadowView(*childShadowNode); auto const layoutableShadowNode = dynamic_cast<LayoutableShadowNode const *>(childShadowNode.get()); #ifndef ANDROID // New approach (iOS): // Non-view components are treated as layout-only views (they aren't // represented as `ShadowView`s). if (!layoutableShadowNode || layoutableShadowNode->isLayoutOnly()) { #else // Previous approach (Android): // Non-view components are treated as normal views with an empty layout // (they are represented as `ShadowView`s). if (layoutableShadowNode && layoutableShadowNode->isLayoutOnly()) { #endif sliceChildShadowNodeViewPairsRecursively( pairList, layoutOffset + shadowView.layoutMetrics.frame.origin, *childShadowNode); } else { shadowView.layoutMetrics.frame.origin += layoutOffset; pairList.push_back({shadowView, childShadowNode.get()}); } } } static ShadowViewNodePair::List sliceChildShadowNodeViewPairs( ShadowNode const &shadowNode) { auto pairList = ShadowViewNodePair::List{}; sliceChildShadowNodeViewPairsRecursively(pairList, {0, 0}, shadowNode); return pairList; } static void calculateShadowViewMutations( ShadowViewMutation::List &mutations, ShadowView const &parentShadowView, ShadowViewNodePair::List const &oldChildPairs, ShadowViewNodePair::List const &newChildPairs) { // The current version of the algorithm is otimized for simplicity, // not for performance or optimal result. if (oldChildPairs == newChildPairs) { return; } if (oldChildPairs.size() == 0 && newChildPairs.size() == 0) { return; } auto index = int{0}; // Maps inserted node tags to pointers to them in `newChildPairs`. auto insertedPairs = better::map<Tag, ShadowViewNodePair const *>{}; // Lists of mutations auto createMutations = ShadowViewMutation::List{}; auto deleteMutations = ShadowViewMutation::List{}; auto insertMutations = ShadowViewMutation::List{}; auto removeMutations = ShadowViewMutation::List{}; auto updateMutations = ShadowViewMutation::List{}; auto downwardMutations = ShadowViewMutation::List{}; auto destructiveDownwardMutations = ShadowViewMutation::List{}; // Stage 1: Collecting `Update` mutations for (index = 0; index < oldChildPairs.size() && index < newChildPairs.size(); index++) { auto const &oldChildPair = oldChildPairs[index]; auto const &newChildPair = newChildPairs[index]; if (oldChildPair.shadowView.tag != newChildPair.shadowView.tag) { // Totally different nodes, updating is impossible. break; } if (oldChildPair.shadowView != newChildPair.shadowView) { updateMutations.push_back(ShadowViewMutation::UpdateMutation( parentShadowView, oldChildPair.shadowView, newChildPair.shadowView, index)); } auto const oldGrandChildPairs = sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode); auto const newGrandChildPairs = sliceChildShadowNodeViewPairs(*newChildPair.shadowNode); calculateShadowViewMutations( *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), oldChildPair.shadowView, oldGrandChildPairs, newGrandChildPairs); } int lastIndexAfterFirstStage = index; // Stage 2: Collecting `Insert` mutations for (; index < newChildPairs.size(); index++) { auto const &newChildPair = newChildPairs[index]; insertMutations.push_back(ShadowViewMutation::InsertMutation( parentShadowView, newChildPair.shadowView, index)); insertedPairs.insert({newChildPair.shadowView.tag, &newChildPair}); } // Stage 3: Collecting `Delete` and `Remove` mutations for (index = lastIndexAfterFirstStage; index < oldChildPairs.size(); index++) { auto const &oldChildPair = oldChildPairs[index]; // Even if the old view was (re)inserted, we have to generate `remove` // mutation. removeMutations.push_back(ShadowViewMutation::RemoveMutation( parentShadowView, oldChildPair.shadowView, index)); auto const it = insertedPairs.find(oldChildPair.shadowView.tag); if (it == insertedPairs.end()) { // The old view was *not* (re)inserted. // We have to generate `delete` mutation and apply the algorithm // recursively. deleteMutations.push_back( ShadowViewMutation::DeleteMutation(oldChildPair.shadowView)); // We also have to call the algorithm recursively to clean up the entire // subtree starting from the removed view. calculateShadowViewMutations( destructiveDownwardMutations, oldChildPair.shadowView, sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode), {}); } else { // The old view *was* (re)inserted. // We have to call the algorithm recursively if the inserted view // is *not* the same as removed one. auto const &newChildPair = *it->second; if (newChildPair != oldChildPair) { auto const oldGrandChildPairs = sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode); auto const newGrandChildPairs = sliceChildShadowNodeViewPairs(*newChildPair.shadowNode); calculateShadowViewMutations( *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), newChildPair.shadowView, oldGrandChildPairs, newGrandChildPairs); } // In any case we have to remove the view from `insertedPairs` as // indication that the view was actually removed (which means that // the view existed before), hence we don't have to generate // `create` mutation. insertedPairs.erase(it); } } // Stage 4: Collecting `Create` mutations for (index = lastIndexAfterFirstStage; index < newChildPairs.size(); index++) { auto const &newChildPair = newChildPairs[index]; if (insertedPairs.find(newChildPair.shadowView.tag) == insertedPairs.end()) { // The new view was (re)inserted, so there is no need to create it. continue; } createMutations.push_back( ShadowViewMutation::CreateMutation(newChildPair.shadowView)); calculateShadowViewMutations( downwardMutations, newChildPair.shadowView, {}, sliceChildShadowNodeViewPairs(*newChildPair.shadowNode)); } // All mutations in an optimal order: std::move( destructiveDownwardMutations.begin(), destructiveDownwardMutations.end(), std::back_inserter(mutations)); std::move( updateMutations.begin(), updateMutations.end(), std::back_inserter(mutations)); std::move( removeMutations.rbegin(), removeMutations.rend(), std::back_inserter(mutations)); std::move( deleteMutations.begin(), deleteMutations.end(), std::back_inserter(mutations)); std::move( createMutations.begin(), createMutations.end(), std::back_inserter(mutations)); std::move( downwardMutations.begin(), downwardMutations.end(), std::back_inserter(mutations)); std::move( insertMutations.begin(), insertMutations.end(), std::back_inserter(mutations)); } ShadowViewMutation::List calculateShadowViewMutations( ShadowNode const &oldRootShadowNode, ShadowNode const &newRootShadowNode) { SystraceSection s("calculateShadowViewMutations"); // Root shadow nodes must be belong the same family. assert(ShadowNode::sameFamily(oldRootShadowNode, newRootShadowNode)); auto mutations = ShadowViewMutation::List{}; mutations.reserve(256); auto oldRootShadowView = ShadowView(oldRootShadowNode); auto newRootShadowView = ShadowView(newRootShadowNode); if (oldRootShadowView != newRootShadowView) { mutations.push_back(ShadowViewMutation::UpdateMutation( ShadowView(), oldRootShadowView, newRootShadowView, -1)); } calculateShadowViewMutations( mutations, ShadowView(oldRootShadowNode), sliceChildShadowNodeViewPairs(oldRootShadowNode), sliceChildShadowNodeViewPairs(newRootShadowNode)); return mutations; } } // namespace react } // namespace facebook <commit_msg>Fabric: TinyMap in Differentiator<commit_after>// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "Differentiator.h" #include <better/map.h> #include <better/small_vector.h> #include <react/core/LayoutableShadowNode.h> #include <react/debug/SystraceSection.h> #include "ShadowView.h" namespace facebook { namespace react { /* * Extremely simple and naive implementation of a map. * The map is simple but it's optimized for particular constraints that we have * here. * * A regular map implementation (e.g. `std::unordered_map`) has some basic * performance guarantees like constant average insertion and lookup complexity. * This is nice, but it's *average* complexity measured on a non-trivial amount * of data. The regular map is a very complex data structure that using hashing, * buckets, multiple comprising operations, multiple allocations and so on. * * In our particular case, we need a map for `int` to `void *` with a dozen * values. In these conditions, nothing can beat a naive implementation using a * stack-allocated vector. And this implementation is exactly this: no * allocation, no hashing, no complex branching, no buckets, no iterators, no * rehashing, no other guarantees. It's crazy limited, unsafe, and performant on * a trivial amount of data. * * Besides that, we also need to optimize for insertion performance (the case * where a bunch of views appears on the screen first time); in this * implementation, this is as performant as vector `push_back`. */ template <typename KeyT, typename ValueT, int DefaultSize = 16> class TinyMap final { public: using Pair = std::pair<KeyT, ValueT>; using Iterator = Pair *; inline Iterator begin() { return (Pair *)vector_; } inline Iterator end() { return nullptr; } inline Iterator find(KeyT key) { for (auto &item : vector_) { if (item.first == key) { return &item; } } return end(); } inline void insert(Pair pair) { assert(pair.first != 0); vector_.push_back(pair); } inline void erase(Iterator iterator) { static_assert( std::is_same<KeyT, Tag>::value, "The collection is designed to store only `Tag`s as keys."); // Zero is a invalid tag. iterator->first = 0; } private: better::small_vector<Pair, DefaultSize> vector_; }; static void sliceChildShadowNodeViewPairsRecursively( ShadowViewNodePair::List &pairList, Point layoutOffset, ShadowNode const &shadowNode) { for (auto const &childShadowNode : shadowNode.getChildren()) { auto shadowView = ShadowView(*childShadowNode); auto const layoutableShadowNode = dynamic_cast<LayoutableShadowNode const *>(childShadowNode.get()); #ifndef ANDROID // New approach (iOS): // Non-view components are treated as layout-only views (they aren't // represented as `ShadowView`s). if (!layoutableShadowNode || layoutableShadowNode->isLayoutOnly()) { #else // Previous approach (Android): // Non-view components are treated as normal views with an empty layout // (they are represented as `ShadowView`s). if (layoutableShadowNode && layoutableShadowNode->isLayoutOnly()) { #endif sliceChildShadowNodeViewPairsRecursively( pairList, layoutOffset + shadowView.layoutMetrics.frame.origin, *childShadowNode); } else { shadowView.layoutMetrics.frame.origin += layoutOffset; pairList.push_back({shadowView, childShadowNode.get()}); } } } static ShadowViewNodePair::List sliceChildShadowNodeViewPairs( ShadowNode const &shadowNode) { auto pairList = ShadowViewNodePair::List{}; sliceChildShadowNodeViewPairsRecursively(pairList, {0, 0}, shadowNode); return pairList; } static void calculateShadowViewMutations( ShadowViewMutation::List &mutations, ShadowView const &parentShadowView, ShadowViewNodePair::List const &oldChildPairs, ShadowViewNodePair::List const &newChildPairs) { // The current version of the algorithm is otimized for simplicity, // not for performance or optimal result. if (oldChildPairs == newChildPairs) { return; } if (oldChildPairs.size() == 0 && newChildPairs.size() == 0) { return; } auto index = int{0}; // Maps inserted node tags to pointers to them in `newChildPairs`. auto insertedPairs = TinyMap<Tag, ShadowViewNodePair const *>{}; // Lists of mutations auto createMutations = ShadowViewMutation::List{}; auto deleteMutations = ShadowViewMutation::List{}; auto insertMutations = ShadowViewMutation::List{}; auto removeMutations = ShadowViewMutation::List{}; auto updateMutations = ShadowViewMutation::List{}; auto downwardMutations = ShadowViewMutation::List{}; auto destructiveDownwardMutations = ShadowViewMutation::List{}; // Stage 1: Collecting `Update` mutations for (index = 0; index < oldChildPairs.size() && index < newChildPairs.size(); index++) { auto const &oldChildPair = oldChildPairs[index]; auto const &newChildPair = newChildPairs[index]; if (oldChildPair.shadowView.tag != newChildPair.shadowView.tag) { // Totally different nodes, updating is impossible. break; } if (oldChildPair.shadowView != newChildPair.shadowView) { updateMutations.push_back(ShadowViewMutation::UpdateMutation( parentShadowView, oldChildPair.shadowView, newChildPair.shadowView, index)); } auto const oldGrandChildPairs = sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode); auto const newGrandChildPairs = sliceChildShadowNodeViewPairs(*newChildPair.shadowNode); calculateShadowViewMutations( *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), oldChildPair.shadowView, oldGrandChildPairs, newGrandChildPairs); } int lastIndexAfterFirstStage = index; // Stage 2: Collecting `Insert` mutations for (; index < newChildPairs.size(); index++) { auto const &newChildPair = newChildPairs[index]; insertMutations.push_back(ShadowViewMutation::InsertMutation( parentShadowView, newChildPair.shadowView, index)); insertedPairs.insert({newChildPair.shadowView.tag, &newChildPair}); } // Stage 3: Collecting `Delete` and `Remove` mutations for (index = lastIndexAfterFirstStage; index < oldChildPairs.size(); index++) { auto const &oldChildPair = oldChildPairs[index]; // Even if the old view was (re)inserted, we have to generate `remove` // mutation. removeMutations.push_back(ShadowViewMutation::RemoveMutation( parentShadowView, oldChildPair.shadowView, index)); auto const it = insertedPairs.find(oldChildPair.shadowView.tag); if (it == insertedPairs.end()) { // The old view was *not* (re)inserted. // We have to generate `delete` mutation and apply the algorithm // recursively. deleteMutations.push_back( ShadowViewMutation::DeleteMutation(oldChildPair.shadowView)); // We also have to call the algorithm recursively to clean up the entire // subtree starting from the removed view. calculateShadowViewMutations( destructiveDownwardMutations, oldChildPair.shadowView, sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode), {}); } else { // The old view *was* (re)inserted. // We have to call the algorithm recursively if the inserted view // is *not* the same as removed one. auto const &newChildPair = *it->second; if (newChildPair != oldChildPair) { auto const oldGrandChildPairs = sliceChildShadowNodeViewPairs(*oldChildPair.shadowNode); auto const newGrandChildPairs = sliceChildShadowNodeViewPairs(*newChildPair.shadowNode); calculateShadowViewMutations( *(newGrandChildPairs.size() ? &downwardMutations : &destructiveDownwardMutations), newChildPair.shadowView, oldGrandChildPairs, newGrandChildPairs); } // In any case we have to remove the view from `insertedPairs` as // indication that the view was actually removed (which means that // the view existed before), hence we don't have to generate // `create` mutation. insertedPairs.erase(it); } } // Stage 4: Collecting `Create` mutations for (index = lastIndexAfterFirstStage; index < newChildPairs.size(); index++) { auto const &newChildPair = newChildPairs[index]; if (insertedPairs.find(newChildPair.shadowView.tag) == insertedPairs.end()) { // The new view was (re)inserted, so there is no need to create it. continue; } createMutations.push_back( ShadowViewMutation::CreateMutation(newChildPair.shadowView)); calculateShadowViewMutations( downwardMutations, newChildPair.shadowView, {}, sliceChildShadowNodeViewPairs(*newChildPair.shadowNode)); } // All mutations in an optimal order: std::move( destructiveDownwardMutations.begin(), destructiveDownwardMutations.end(), std::back_inserter(mutations)); std::move( updateMutations.begin(), updateMutations.end(), std::back_inserter(mutations)); std::move( removeMutations.rbegin(), removeMutations.rend(), std::back_inserter(mutations)); std::move( deleteMutations.begin(), deleteMutations.end(), std::back_inserter(mutations)); std::move( createMutations.begin(), createMutations.end(), std::back_inserter(mutations)); std::move( downwardMutations.begin(), downwardMutations.end(), std::back_inserter(mutations)); std::move( insertMutations.begin(), insertMutations.end(), std::back_inserter(mutations)); } ShadowViewMutation::List calculateShadowViewMutations( ShadowNode const &oldRootShadowNode, ShadowNode const &newRootShadowNode) { SystraceSection s("calculateShadowViewMutations"); // Root shadow nodes must be belong the same family. assert(ShadowNode::sameFamily(oldRootShadowNode, newRootShadowNode)); auto mutations = ShadowViewMutation::List{}; mutations.reserve(256); auto oldRootShadowView = ShadowView(oldRootShadowNode); auto newRootShadowView = ShadowView(newRootShadowNode); if (oldRootShadowView != newRootShadowView) { mutations.push_back(ShadowViewMutation::UpdateMutation( ShadowView(), oldRootShadowView, newRootShadowView, -1)); } calculateShadowViewMutations( mutations, ShadowView(oldRootShadowNode), sliceChildShadowNodeViewPairs(oldRootShadowNode), sliceChildShadowNodeViewPairs(newRootShadowNode)); return mutations; } } // namespace react } // namespace facebook <|endoftext|>
<commit_before> /*============================================================================ ^XNǗ(?) ==============================================================================*/ #include <cassert> #include <algorithm> #include <typeinfo> #include "task.h" namespace GTF { using namespace std; CTaskManager::CTaskManager() { // _~[f[^} const auto it = tasks.emplace(tasks.end(), make_shared<CTaskBase>()); ex_stack.emplace(exNext, it); } void CTaskManager::Destroy() { //ʏ^XNTerminate auto i = tasks.begin(); const auto ied = tasks.end(); for (; i != ied; ++i){ (*i)->Terminate(); } tasks.clear(); //obNOEh^XNTerminate auto ib = bg_tasks.begin(); const auto ibed = bg_tasks.end(); for (; ib != ibed; ++ib){ (*ib)->Terminate(); } bg_tasks.clear(); //r^XNTerminate while (ex_stack.size() != 0 && ex_stack.top().value){ ex_stack.top().value->Terminate(); ex_stack.pop(); } } CTaskManager::TaskPtr CTaskManager::AddTask(CTaskBase *newTask) { assert(newTask); CExclusiveTaskBase *pext = dynamic_cast<CExclusiveTaskBase*>(newTask); if (pext){ //r^XNƂAdd return AddTask(pext); } if (newTask->GetID() != 0){ RemoveTaskByID(newTask->GetID()); } CBackgroundTaskBase *pbgt = dynamic_cast<CBackgroundTaskBase*>(newTask); if (pbgt){ //풓^XNƂAdd return AddTask(pbgt); } //ʏ^XNƂAdd tasks.emplace_back(newTask); auto& pnew = tasks.back(); newTask->Initialize(); if (newTask->GetID() != 0) indices[newTask->GetID()] = pnew; if (pnew->GetDrawPriority() >= 0) ex_stack.top().drawList.emplace(pnew->GetDrawPriority(), pnew); return pnew; } CTaskManager::ExTaskPtr CTaskManager::AddTask(CExclusiveTaskBase *newTask) { //r^XNƂAdd //ExecuteȂ̂ŁA|C^ۑ̂ if (exNext){ OutputLog("ALERT r^XN2ˆȏAddꂽ : %s / %s", typeid(*exNext).name(), typeid(*newTask).name()); } exNext = shared_ptr<CExclusiveTaskBase>(newTask); return exNext; } CTaskManager::BgTaskPtr CTaskManager::AddTask(CBackgroundTaskBase *newTask) { if (newTask->GetID() != 0){ RemoveTaskByID(newTask->GetID()); } bg_tasks.emplace_back(newTask); // bIȌ^ϊ auto pbgt = bg_tasks.back(); //풓^XNƂAdd pbgt->Initialize(); if (newTask->GetID() != 0) bg_indices[newTask->GetID()] = pbgt; if (pbgt->GetDrawPriority() >= 0) drawListBG.emplace(pbgt->GetDrawPriority(), pbgt); return pbgt; } void CTaskManager::Execute(double elapsedTime) { #ifdef ARRAYBOUNDARY_DEBUG if(!AfxCheckMemory()){ OutputLog("AfxCheckMemory() failed"); return; } #endif //r^XNAtop̂Execute assert(ex_stack.size() != 0); shared_ptr<CExclusiveTaskBase> exTsk = ex_stack.top().value; if (exTsk) { bool ex_ret = true; #ifdef _CATCH_WHILE_EXEC try{ #endif ex_ret = exTsk->Execute(elapsedTime); #ifdef _CATCH_WHILE_EXEC }catch(...){ if (ex_stack.top() == NULL)OutputLog("catch while execute3 : NULL", SYSLOG_ERROR); else OutputLog("catch while execute3 : %X %s",ex_stack.top(),typeid(*ex_stack.top()).name()); } #endif if (!ex_ret) { if (!exNext){ //ݔr^XN̕ύX #ifdef _CATCH_WHILE_EXEC try{ #endif //ʏ^XNSĔj CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos); #ifdef _CATCH_WHILE_EXEC }catch(...){ if ((*i) == NULL)OutputLog("catch while terminate1 : NULL", SYSLOG_ERROR); else OutputLog("catch while terminate1 : %X %s", (*i), typeid(*(*i)).name()); } #endif #ifdef _CATCH_WHILE_EXEC try{ #endif //ݔr^XN̔j unsigned int prvID = exTsk->GetID(); exTsk->Terminate(); exTsk = nullptr; ex_stack.pop(); #ifdef _CATCH_WHILE_EXEC }catch(...){ if (exTsk == NULL)OutputLog("catch while terminate2 : NULL", SYSLOG_ERROR); else OutputLog("catch while terminate : %X %s", exTsk, typeid(*exTsk).name()); } #endif #ifdef _CATCH_WHILE_EXEC try{ #endif //̔r^XNActivate assert(ex_stack.size() != 0); exTsk = ex_stack.top().value; if (exTsk) exTsk->Activate(prvID); #ifdef _CATCH_WHILE_EXEC }catch(...){ if (exTsk == NULL)OutputLog("catch while activate : NULL", SYSLOG_ERROR); else OutputLog("catch while activate : %X %s", exTsk, typeid(*exTsk).name()); } #endif return; } } } //ʏ^XNExecute assert(!ex_stack.empty()); taskExecute(tasks, ex_stack.top().SubTaskStartPos, tasks.end(), elapsedTime); //풓^XNExecute taskExecute(bg_tasks, bg_tasks.begin(), bg_tasks.end(), elapsedTime); // V^XNꍇ if (exNext){ //ݔr^XNInactivate assert(ex_stack.size() != 0); auto& exTsk = ex_stack.top().value; if (exTsk && !exTsk->Inactivate(exNext->GetID())){ //ʏ^XNSĔj CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos); exTsk->Terminate(); ex_stack.pop(); } //Addꂽ^XNInitializeē˂ const auto it = tasks.emplace(tasks.end(), make_shared<CTaskBase>()); // _~[^XN} ex_stack.emplace(move(exNext), it); ex_stack.top().value->Initialize(); exNext = nullptr; } } void CTaskManager::Draw() { shared_ptr<CExclusiveTaskBase> pex = nullptr; //r^XN擾 assert(ex_stack.size() != 0); if (ex_stack.top().value && ex_stack.top().value->GetDrawPriority() >= 0){ pex = ex_stack.top().value; } auto iv = ex_stack.top().drawList.begin(); auto iedv = pex ? ex_stack.top().drawList.upper_bound(pex->GetDrawPriority()) : ex_stack.top().drawList.end(); auto ivBG = drawListBG.begin(); const auto iedvBG = drawListBG.end(); auto DrawAndProceed = [](DrawPriorityMap::iterator& iv, DrawPriorityMap& drawList) { auto is = iv->second.lock(); if (is) { is->Draw(); ++iv; } else drawList.erase(iv++); }; auto DrawAll = [&]() // `֐ { while (iv != iedv) { #ifdef _CATCH_WHILE_RENDER try{ #endif while (ivBG != iedvBG && ivBG->first <= iv->first) DrawAndProceed(ivBG, drawListBG); DrawAndProceed(iv, ex_stack.top().drawList); #ifdef _CATCH_WHILE_RENDER }catch(...){ OutputLog("catch while draw : %X %s", *iv, typeid(*(*iv).lock()).name()); } #endif } }; //` DrawAll(); // r^XNDraw if (pex) pex->Draw(); //` assert(iv == iedv); iedv = ex_stack.top().drawList.end(); DrawAll(); // c풓^XN while (ivBG != iedvBG) DrawAndProceed(ivBG, drawListBG); } void CTaskManager::RemoveTaskByID(unsigned int id) { //ʏ^XN`FbN if (indices.count(id) != 0) { auto i = tasks.begin(); const auto ied = tasks.end(); for (; i != ied; ++i){ if (id == (*i)->GetID()){ (*i)->Terminate(); tasks.erase(i); return; } } } //obNOEh^XNTerminate if (bg_indices.count(id) != 0) { auto i = bg_tasks.begin(); const auto ied = bg_tasks.end(); for (; i != ied; ++i){ if (id == (*i)->GetID()){ (*i)->Terminate(); bg_tasks.erase(i); return; } } } } //wID̔r^XN܂Terminate/pop void CTaskManager::RevertExclusiveTaskByID(unsigned int id) { bool act = false; unsigned int previd = 0; assert(ex_stack.size() != 0); while (ex_stack.top().value){ const shared_ptr<CExclusiveTaskBase>& task = ex_stack.top().value; if (task->GetID() == id){ if (act){ task->Activate(previd); } return; } else{ previd = task->GetID(); act = true; CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos); task->Terminate(); ex_stack.pop(); assert(ex_stack.size() != 0); } } } //ʏ^XNꕔj void CTaskManager::CleanupPartialSubTasks(TaskList::iterator it_task) { TaskList::iterator i = it_task, ied = tasks.end(); for (; i != ied; ++i){ shared_ptr<CTaskBase>& delTgt = (*i); delTgt->Terminate(); } tasks.erase(it_task, ied); } //fobOE^XNꗗ\ void CTaskManager::DebugOutputTaskList() { OutputLog("\n\nCTaskManager::DebugOutputTaskList() - start"); OutputLog("ʏ^XNꗗ"); //ʏ^XN auto i = tasks.begin(); const auto ied = tasks.end(); for (; i != ied; ++i){ OutputLog(typeid(**i).name()); } OutputLog("풓^XNꗗ"); //obNOEh^XN auto ib = bg_tasks.begin(); const auto ibed = bg_tasks.end(); for (; ib != ibed; ++ib){ OutputLog(typeid(**ib).name()); } //r^XN OutputLog("\n"); OutputLog("݂̃^XNF"); if (ex_stack.empty()) OutputLog("Ȃ"); else OutputLog(typeid(*ex_stack.top().value).name()); OutputLog("\n\nCTaskManager::DebugOutputTaskList() - end\n\n"); } } <commit_msg>コメント除去<commit_after> /*============================================================================ ^XNǗ(?) ==============================================================================*/ #include <cassert> #include <algorithm> #include <typeinfo> #include "task.h" namespace GTF { using namespace std; CTaskManager::CTaskManager() { // _~[f[^} const auto it = tasks.emplace(tasks.end(), make_shared<CTaskBase>()); ex_stack.emplace(exNext, it); } void CTaskManager::Destroy() { //ʏ^XNTerminate auto i = tasks.begin(); const auto ied = tasks.end(); for (; i != ied; ++i){ (*i)->Terminate(); } tasks.clear(); //obNOEh^XNTerminate auto ib = bg_tasks.begin(); const auto ibed = bg_tasks.end(); for (; ib != ibed; ++ib){ (*ib)->Terminate(); } bg_tasks.clear(); //r^XNTerminate while (ex_stack.size() != 0 && ex_stack.top().value){ ex_stack.top().value->Terminate(); ex_stack.pop(); } } CTaskManager::TaskPtr CTaskManager::AddTask(CTaskBase *newTask) { assert(newTask); CExclusiveTaskBase *pext = dynamic_cast<CExclusiveTaskBase*>(newTask); if (pext){ //r^XNƂAdd return AddTask(pext); } if (newTask->GetID() != 0){ RemoveTaskByID(newTask->GetID()); } CBackgroundTaskBase *pbgt = dynamic_cast<CBackgroundTaskBase*>(newTask); if (pbgt){ //풓^XNƂAdd return AddTask(pbgt); } //ʏ^XNƂAdd tasks.emplace_back(newTask); auto& pnew = tasks.back(); newTask->Initialize(); if (newTask->GetID() != 0) indices[newTask->GetID()] = pnew; if (pnew->GetDrawPriority() >= 0) ex_stack.top().drawList.emplace(pnew->GetDrawPriority(), pnew); return pnew; } CTaskManager::ExTaskPtr CTaskManager::AddTask(CExclusiveTaskBase *newTask) { //r^XNƂAdd //ExecuteȂ̂ŁA|C^ۑ̂ if (exNext){ OutputLog("ALERT r^XN2ˆȏAddꂽ : %s / %s", typeid(*exNext).name(), typeid(*newTask).name()); } exNext = shared_ptr<CExclusiveTaskBase>(newTask); return exNext; } CTaskManager::BgTaskPtr CTaskManager::AddTask(CBackgroundTaskBase *newTask) { if (newTask->GetID() != 0){ RemoveTaskByID(newTask->GetID()); } bg_tasks.emplace_back(newTask); auto pbgt = bg_tasks.back(); //풓^XNƂAdd pbgt->Initialize(); if (newTask->GetID() != 0) bg_indices[newTask->GetID()] = pbgt; if (pbgt->GetDrawPriority() >= 0) drawListBG.emplace(pbgt->GetDrawPriority(), pbgt); return pbgt; } void CTaskManager::Execute(double elapsedTime) { #ifdef ARRAYBOUNDARY_DEBUG if(!AfxCheckMemory()){ OutputLog("AfxCheckMemory() failed"); return; } #endif //r^XNAtop̂Execute assert(ex_stack.size() != 0); shared_ptr<CExclusiveTaskBase> exTsk = ex_stack.top().value; if (exTsk) { bool ex_ret = true; #ifdef _CATCH_WHILE_EXEC try{ #endif ex_ret = exTsk->Execute(elapsedTime); #ifdef _CATCH_WHILE_EXEC }catch(...){ if (ex_stack.top() == NULL)OutputLog("catch while execute3 : NULL", SYSLOG_ERROR); else OutputLog("catch while execute3 : %X %s",ex_stack.top(),typeid(*ex_stack.top()).name()); } #endif if (!ex_ret) { if (!exNext){ //ݔr^XN̕ύX #ifdef _CATCH_WHILE_EXEC try{ #endif //ʏ^XNSĔj CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos); #ifdef _CATCH_WHILE_EXEC }catch(...){ if ((*i) == NULL)OutputLog("catch while terminate1 : NULL", SYSLOG_ERROR); else OutputLog("catch while terminate1 : %X %s", (*i), typeid(*(*i)).name()); } #endif #ifdef _CATCH_WHILE_EXEC try{ #endif //ݔr^XN̔j unsigned int prvID = exTsk->GetID(); exTsk->Terminate(); exTsk = nullptr; ex_stack.pop(); #ifdef _CATCH_WHILE_EXEC }catch(...){ if (exTsk == NULL)OutputLog("catch while terminate2 : NULL", SYSLOG_ERROR); else OutputLog("catch while terminate : %X %s", exTsk, typeid(*exTsk).name()); } #endif #ifdef _CATCH_WHILE_EXEC try{ #endif //̔r^XNActivate assert(ex_stack.size() != 0); exTsk = ex_stack.top().value; if (exTsk) exTsk->Activate(prvID); #ifdef _CATCH_WHILE_EXEC }catch(...){ if (exTsk == NULL)OutputLog("catch while activate : NULL", SYSLOG_ERROR); else OutputLog("catch while activate : %X %s", exTsk, typeid(*exTsk).name()); } #endif return; } } } //ʏ^XNExecute assert(!ex_stack.empty()); taskExecute(tasks, ex_stack.top().SubTaskStartPos, tasks.end(), elapsedTime); //풓^XNExecute taskExecute(bg_tasks, bg_tasks.begin(), bg_tasks.end(), elapsedTime); // V^XNꍇ if (exNext){ //ݔr^XNInactivate assert(ex_stack.size() != 0); auto& exTsk = ex_stack.top().value; if (exTsk && !exTsk->Inactivate(exNext->GetID())){ //ʏ^XNSĔj CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos); exTsk->Terminate(); ex_stack.pop(); } //Addꂽ^XNInitializeē˂ const auto it = tasks.emplace(tasks.end(), make_shared<CTaskBase>()); // _~[^XN} ex_stack.emplace(move(exNext), it); ex_stack.top().value->Initialize(); exNext = nullptr; } } void CTaskManager::Draw() { shared_ptr<CExclusiveTaskBase> pex = nullptr; //r^XN擾 assert(ex_stack.size() != 0); if (ex_stack.top().value && ex_stack.top().value->GetDrawPriority() >= 0){ pex = ex_stack.top().value; } auto iv = ex_stack.top().drawList.begin(); auto iedv = pex ? ex_stack.top().drawList.upper_bound(pex->GetDrawPriority()) : ex_stack.top().drawList.end(); auto ivBG = drawListBG.begin(); const auto iedvBG = drawListBG.end(); auto DrawAndProceed = [](DrawPriorityMap::iterator& iv, DrawPriorityMap& drawList) { auto is = iv->second.lock(); if (is) { is->Draw(); ++iv; } else drawList.erase(iv++); }; auto DrawAll = [&]() // `֐ { while (iv != iedv) { #ifdef _CATCH_WHILE_RENDER try{ #endif while (ivBG != iedvBG && ivBG->first <= iv->first) DrawAndProceed(ivBG, drawListBG); DrawAndProceed(iv, ex_stack.top().drawList); #ifdef _CATCH_WHILE_RENDER }catch(...){ OutputLog("catch while draw : %X %s", *iv, typeid(*(*iv).lock()).name()); } #endif } }; //` DrawAll(); // r^XNDraw if (pex) pex->Draw(); //` assert(iv == iedv); iedv = ex_stack.top().drawList.end(); DrawAll(); // c풓^XN while (ivBG != iedvBG) DrawAndProceed(ivBG, drawListBG); } void CTaskManager::RemoveTaskByID(unsigned int id) { //ʏ^XN`FbN if (indices.count(id) != 0) { auto i = tasks.begin(); const auto ied = tasks.end(); for (; i != ied; ++i){ if (id == (*i)->GetID()){ (*i)->Terminate(); tasks.erase(i); return; } } } //obNOEh^XNTerminate if (bg_indices.count(id) != 0) { auto i = bg_tasks.begin(); const auto ied = bg_tasks.end(); for (; i != ied; ++i){ if (id == (*i)->GetID()){ (*i)->Terminate(); bg_tasks.erase(i); return; } } } } //wID̔r^XN܂Terminate/pop void CTaskManager::RevertExclusiveTaskByID(unsigned int id) { bool act = false; unsigned int previd = 0; assert(ex_stack.size() != 0); while (ex_stack.top().value){ const shared_ptr<CExclusiveTaskBase>& task = ex_stack.top().value; if (task->GetID() == id){ if (act){ task->Activate(previd); } return; } else{ previd = task->GetID(); act = true; CleanupPartialSubTasks(ex_stack.top().SubTaskStartPos); task->Terminate(); ex_stack.pop(); assert(ex_stack.size() != 0); } } } //ʏ^XNꕔj void CTaskManager::CleanupPartialSubTasks(TaskList::iterator it_task) { TaskList::iterator i = it_task, ied = tasks.end(); for (; i != ied; ++i){ shared_ptr<CTaskBase>& delTgt = (*i); delTgt->Terminate(); } tasks.erase(it_task, ied); } //fobOE^XNꗗ\ void CTaskManager::DebugOutputTaskList() { OutputLog("\n\nCTaskManager::DebugOutputTaskList() - start"); OutputLog("ʏ^XNꗗ"); //ʏ^XN auto i = tasks.begin(); const auto ied = tasks.end(); for (; i != ied; ++i){ OutputLog(typeid(**i).name()); } OutputLog("풓^XNꗗ"); //obNOEh^XN auto ib = bg_tasks.begin(); const auto ibed = bg_tasks.end(); for (; ib != ibed; ++ib){ OutputLog(typeid(**ib).name()); } //r^XN OutputLog("\n"); OutputLog("݂̃^XNF"); if (ex_stack.empty()) OutputLog("Ȃ"); else OutputLog(typeid(*ex_stack.top().value).name()); OutputLog("\n\nCTaskManager::DebugOutputTaskList() - end\n\n"); } } <|endoftext|>
<commit_before>/* Jabra Browser Integration https://github.com/gnaudio/jabra-browser-integration MIT License Copyright (c) 2017 GN Audio A/S (Jabra) 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 <climits> #include "stdafx.h" #include "HeadsetIntegrationService.h" #include "CmdOffHook.h" #include "CmdOnHook.h" #include "CmdRing.h" #include "CmdMute.h" #include "CmdUnmute.h" #include "CmdHold.h" #include "CmdResume.h" #include "CmdGetDevices.h" #include "CmdGetActiveDevice.h" #include "CmdSetActiveDevice.h" #include "CmdGetVersion.h" #include "EventMicMute.h" #include "EventOffHook.h" #include "EventOnline.h" #include "EventLineBusy.h" #include "EventReject.h" #include "EventFlash.h" HeadsetIntegrationService* g_thisHeadsetIntegrationService; HeadsetIntegrationService::HeadsetIntegrationService() { g_thisHeadsetIntegrationService = this; m_currentDeviceId = 0; m_commands.push_back(new CmdOffHook(this)); m_commands.push_back(new CmdOnHook(this)); m_commands.push_back(new CmdRing(this)); m_commands.push_back(new CmdMute(this)); m_commands.push_back(new CmdUnmute(this)); m_commands.push_back(new CmdHold(this)); m_commands.push_back(new CmdResume(this)); m_commands.push_back(new CmdGetDevices(this)); m_commands.push_back(new CmdGetActiveDevice(this)); m_commands.push_back(new CmdSetActiveDevice(this)); m_commands.push_back(new CmdGetVersion(this)); m_events[Jabra_HidInput::Mute] = new EventMicMute(this); m_events[Jabra_HidInput::OffHook] = new EventOffHook(this); m_events[Jabra_HidInput::Online] = new EventOnline(this); m_events[Jabra_HidInput::LineBusy] = new EventLineBusy(this); m_events[Jabra_HidInput::RejectCall] = new EventReject(this); m_events[Jabra_HidInput::Flash] = new EventFlash(this); } HeadsetIntegrationService::~HeadsetIntegrationService() { // TODO: Cleanup m_commands and m_events // Stop Jabra USB stack SDK Jabra_SetSoftphoneReady(false); Jabra_DisconnectFromJabraApplication(); Jabra_Uninitialize(); } void HeadsetIntegrationService::SendCmd(std::string msg) { std::lock_guard<std::mutex> lock(m_mtx); using Iter = std::vector<CmdInterface*>::const_iterator; for (Iter it = m_commands.begin(); it != m_commands.end(); ++it) { if ((*it)->CanExecute(msg)) { (*it)->Execute(msg); return; } } Error("Unknown cmd"); } void HeadsetIntegrationService::AddHandler(std::function<void(std::string)> callback) { m_callback = callback; } bool HeadsetIntegrationService::Start() { Jabra_SetAppID(const_cast<char*>("HKiKNeRIdH/8s+aIRdIVuRoi0vs5TkCXaOmwIqr0rMM=")); Jabra_Initialize( NULL, StaticJabraDeviceAttachedFunc, StaticJabraDeviceRemovedFunc, NULL, StaticButtonInDataTranslatedFunc, 0 ); Jabra_ConnectToJabraApplication( "D6B42896-E65B-4EC1-A037-27C65E8CFDE1", "Google Chrome Browser" ); Jabra_SetSoftphoneReady(true); return true; } unsigned short HeadsetIntegrationService::GetCurrentDeviceId() { if (m_devices.size() == 0) return USHRT_MAX; return m_currentDeviceId; } void HeadsetIntegrationService::SetCurrentDeviceId(unsigned short id) { m_currentDeviceId = id; } std::string HeadsetIntegrationService::GetDevicesAsString() { std::string devicesAsString; for (std::vector<int>::size_type i = 0; i != m_devices.size(); i++) { if (devicesAsString.length() > 0) { devicesAsString += ","; } devicesAsString += std::to_string(m_devices[i].deviceID); devicesAsString += ","; devicesAsString += m_devices[i].deviceName; } return "devices " + devicesAsString; } void HeadsetIntegrationService::Error(std::string msg) { m_callback("Error: " + msg); } void HeadsetIntegrationService::Event(std::string msg) { m_callback("Event: " + msg); } void HeadsetIntegrationService::SetHookStatus(unsigned short id, bool mute) { m_HookStatus[id] = mute; } bool HeadsetIntegrationService::GetHookStatus(unsigned short id) { return m_HookStatus[id]; } void HeadsetIntegrationService::SetRingerStatus(unsigned short id, bool ringer) { m_RingerStatus[id] = ringer; } bool HeadsetIntegrationService::GetRingerStatus(unsigned short id) { return m_RingerStatus[id]; } void HeadsetIntegrationService::JabraDeviceAttachedFunc(Jabra_DeviceInfo deviceInfo) { std::lock_guard<std::mutex> lock(m_mtx); m_devices.push_back(deviceInfo); std::string deviceName(deviceInfo.deviceName); Event("device attached"); } void HeadsetIntegrationService::JabraDeviceRemovedFunc(unsigned short deviceID) { std::lock_guard<std::mutex> lock(m_mtx); int index = -1; using Iter = std::vector<Jabra_DeviceInfo>::const_iterator; for (Iter it = m_devices.begin(); it != m_devices.end(); ++it) { index++; if ((*it).deviceID == deviceID) { std::string deviceName((*it).deviceName); Event("device detached"); m_devices.erase(m_devices.begin() + index); break; } } // If the removed device was the active device, assign a new active device (if any) if (m_currentDeviceId == deviceID) { if (m_devices.size() > 0) { SetCurrentDeviceId(m_devices[0].deviceID); } } } void HeadsetIntegrationService::ButtonInDataTranslatedFunc(unsigned short deviceID, Jabra_HidInput translatedInData, bool buttonInData) { std::lock_guard<std::mutex> lock(m_mtx); // Only handle input data from current device if (deviceID != GetCurrentDeviceId()) return; EventInterface *event = m_events[translatedInData]; if (event != NULL) { event->Execute(buttonInData); } else { std::string inDatastring = std::to_string(translatedInData); Error("No handler impelmented for " + inDatastring); } } void HeadsetIntegrationService::StaticJabraDeviceAttachedFunc(Jabra_DeviceInfo deviceInfo) { g_thisHeadsetIntegrationService->JabraDeviceAttachedFunc(deviceInfo); } void HeadsetIntegrationService::StaticJabraDeviceRemovedFunc(unsigned short deviceID) { g_thisHeadsetIntegrationService->JabraDeviceRemovedFunc(deviceID); } void HeadsetIntegrationService::StaticButtonInDataTranslatedFunc(unsigned short deviceID, Jabra_HidInput translatedInData, bool buttonInData) { g_thisHeadsetIntegrationService->ButtonInDataTranslatedFunc(deviceID, translatedInData, buttonInData); }<commit_msg>Fix issue setting new active device<commit_after>/* Jabra Browser Integration https://github.com/gnaudio/jabra-browser-integration MIT License Copyright (c) 2017 GN Audio A/S (Jabra) 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 <climits> #include "stdafx.h" #include "HeadsetIntegrationService.h" #include "CmdOffHook.h" #include "CmdOnHook.h" #include "CmdRing.h" #include "CmdMute.h" #include "CmdUnmute.h" #include "CmdHold.h" #include "CmdResume.h" #include "CmdGetDevices.h" #include "CmdGetActiveDevice.h" #include "CmdSetActiveDevice.h" #include "CmdGetVersion.h" #include "EventMicMute.h" #include "EventOffHook.h" #include "EventOnline.h" #include "EventLineBusy.h" #include "EventReject.h" #include "EventFlash.h" HeadsetIntegrationService* g_thisHeadsetIntegrationService; HeadsetIntegrationService::HeadsetIntegrationService() { g_thisHeadsetIntegrationService = this; m_currentDeviceId = 0; m_commands.push_back(new CmdOffHook(this)); m_commands.push_back(new CmdOnHook(this)); m_commands.push_back(new CmdRing(this)); m_commands.push_back(new CmdMute(this)); m_commands.push_back(new CmdUnmute(this)); m_commands.push_back(new CmdHold(this)); m_commands.push_back(new CmdResume(this)); m_commands.push_back(new CmdGetDevices(this)); m_commands.push_back(new CmdGetActiveDevice(this)); m_commands.push_back(new CmdSetActiveDevice(this)); m_commands.push_back(new CmdGetVersion(this)); m_events[Jabra_HidInput::Mute] = new EventMicMute(this); m_events[Jabra_HidInput::OffHook] = new EventOffHook(this); m_events[Jabra_HidInput::Online] = new EventOnline(this); m_events[Jabra_HidInput::LineBusy] = new EventLineBusy(this); m_events[Jabra_HidInput::RejectCall] = new EventReject(this); m_events[Jabra_HidInput::Flash] = new EventFlash(this); } HeadsetIntegrationService::~HeadsetIntegrationService() { // TODO: Cleanup m_commands and m_events // Stop Jabra USB stack SDK Jabra_SetSoftphoneReady(false); Jabra_DisconnectFromJabraApplication(); Jabra_Uninitialize(); } void HeadsetIntegrationService::SendCmd(std::string msg) { std::lock_guard<std::mutex> lock(m_mtx); using Iter = std::vector<CmdInterface*>::const_iterator; for (Iter it = m_commands.begin(); it != m_commands.end(); ++it) { if ((*it)->CanExecute(msg)) { (*it)->Execute(msg); return; } } Error("Unknown cmd"); } void HeadsetIntegrationService::AddHandler(std::function<void(std::string)> callback) { m_callback = callback; } bool HeadsetIntegrationService::Start() { Jabra_SetAppID(const_cast<char*>("HKiKNeRIdH/8s+aIRdIVuRoi0vs5TkCXaOmwIqr0rMM=")); Jabra_Initialize( NULL, StaticJabraDeviceAttachedFunc, StaticJabraDeviceRemovedFunc, NULL, StaticButtonInDataTranslatedFunc, 0 ); Jabra_ConnectToJabraApplication( "D6B42896-E65B-4EC1-A037-27C65E8CFDE1", "Google Chrome Browser" ); Jabra_SetSoftphoneReady(true); return true; } unsigned short HeadsetIntegrationService::GetCurrentDeviceId() { if (m_devices.size() == 0) return USHRT_MAX; return m_currentDeviceId; } void HeadsetIntegrationService::SetCurrentDeviceId(unsigned short id) { m_currentDeviceId = id; } std::string HeadsetIntegrationService::GetDevicesAsString() { std::string devicesAsString; for (std::vector<int>::size_type i = 0; i != m_devices.size(); i++) { if (devicesAsString.length() > 0) { devicesAsString += ","; } devicesAsString += std::to_string(m_devices[i].deviceID); devicesAsString += ","; devicesAsString += m_devices[i].deviceName; } return "devices " + devicesAsString; } void HeadsetIntegrationService::Error(std::string msg) { m_callback("Error: " + msg); } void HeadsetIntegrationService::Event(std::string msg) { m_callback("Event: " + msg); } void HeadsetIntegrationService::SetHookStatus(unsigned short id, bool mute) { m_HookStatus[id] = mute; } bool HeadsetIntegrationService::GetHookStatus(unsigned short id) { return m_HookStatus[id]; } void HeadsetIntegrationService::SetRingerStatus(unsigned short id, bool ringer) { m_RingerStatus[id] = ringer; } bool HeadsetIntegrationService::GetRingerStatus(unsigned short id) { return m_RingerStatus[id]; } void HeadsetIntegrationService::JabraDeviceAttachedFunc(Jabra_DeviceInfo deviceInfo) { std::lock_guard<std::mutex> lock(m_mtx); m_devices.push_back(deviceInfo); std::string deviceName(deviceInfo.deviceName); Event("device attached"); } void HeadsetIntegrationService::JabraDeviceRemovedFunc(unsigned short deviceID) { std::lock_guard<std::mutex> lock(m_mtx); int index = -1; using Iter = std::vector<Jabra_DeviceInfo>::const_iterator; for (Iter it = m_devices.begin(); it != m_devices.end(); ++it) { index++; if ((*it).deviceID == deviceID) { std::string deviceName((*it).deviceName); Event("device detached"); m_devices.erase(m_devices.begin() + index); break; } } // If the removed device was the active device, assign a new active device (if any) if (m_currentDeviceId == deviceID) { if (m_devices.size() == 0) { SetCurrentDeviceId(0); } else { SetCurrentDeviceId(m_devices[0].deviceID); } } } void HeadsetIntegrationService::ButtonInDataTranslatedFunc(unsigned short deviceID, Jabra_HidInput translatedInData, bool buttonInData) { std::lock_guard<std::mutex> lock(m_mtx); // Only handle input data from current device if (deviceID != GetCurrentDeviceId()) return; EventInterface *event = m_events[translatedInData]; if (event != NULL) { event->Execute(buttonInData); } else { std::string inDatastring = std::to_string(translatedInData); Error("No handler impelmented for " + inDatastring); } } void HeadsetIntegrationService::StaticJabraDeviceAttachedFunc(Jabra_DeviceInfo deviceInfo) { g_thisHeadsetIntegrationService->JabraDeviceAttachedFunc(deviceInfo); } void HeadsetIntegrationService::StaticJabraDeviceRemovedFunc(unsigned short deviceID) { g_thisHeadsetIntegrationService->JabraDeviceRemovedFunc(deviceID); } void HeadsetIntegrationService::StaticButtonInDataTranslatedFunc(unsigned short deviceID, Jabra_HidInput translatedInData, bool buttonInData) { g_thisHeadsetIntegrationService->ButtonInDataTranslatedFunc(deviceID, translatedInData, buttonInData); }<|endoftext|>
<commit_before>#include <QUrl> #include <QDateTime> #include <QFileInfo> #include <QSqlRecord> #include <QSqlField> #include "ilwis.h" #include "kernel.h" #include "issuelogger.h" #include "connectorinterface.h" #include "factory.h" #include "abstractfactory.h" #include "connectorfactory.h" #include "ilwisobjectfactory.h" #include "ilwisdata.h" #include "resource.h" #include "ilwisobjectconnector.h" #include "ilwiscontext.h" #include "version.h" using namespace Ilwis; QVector<IlwisTypeFunction> IlwisObject::_typeFunctions; //------------------------------------------------- IlwisObject::IlwisObject() : _valid(false), _readOnly(false), _changed(false) { Identity::prepare(); } IlwisObject::IlwisObject(const Resource& resource) : Identity(resource.name(), resource.id(), resource.code(), resource.description()) , _readOnly(false), _changed(false) { if (!resource.isValid()) Identity::prepare(); } IlwisObject::~IlwisObject() { // qDeleteAll(_factories); } IlwisObject *IlwisObject::create(const Resource& item) { const IlwisObjectFactory *factory = kernel()->factory<IlwisObjectFactory>("IlwisObjectFactory",item); if ( factory) return factory->create(item); else { kernel()->issues()->log(TR("Cann't find suitable factory for %1 ").arg(item.name())); } return 0; } void IlwisObject::connectTo(const QUrl& url, const QString& format, const QString& fnamespace, ConnectorMode cmode) { Locker lock(_mutex); Resource resource; resource = mastercatalog()->id2Resource(id()); if ( !resource.isValid()) resource = Resource(url,ilwisType(), false); // if ( url == QUrl()) { resource.setName(name()); } const Ilwis::ConnectorFactory *factory = kernel()->factory<Ilwis::ConnectorFactory>("ilwis::ConnectorFactory"); if ( !factory) return; Ilwis::ConnectorInterface *conn = factory->createFromFormat(resource, format,fnamespace); if (!conn) return; setConnector(conn, cmode); if ( name() == sUNDEF) setName(resource.name()); } bool IlwisObject::prepare( ) { _valid = true; return true; } QDateTime IlwisObject::modifiedTime() const { return _modifiedTime; } void IlwisObject::setModifiedTime(const Time &tme) { _modifiedTime = tme; } Time IlwisObject::createTime() const { return _createTime; } void IlwisObject::setCreateTime(const Time &time) { _createTime = time; } QString IlwisObject::toString() { //TODO return ""; } bool IlwisObject::isEqual(const IlwisObject &obj) const { //TODO overrule this method for object types that need to do more checking return id() == obj.id(); } bool IlwisObject::isValid() const { return _valid; } bool IlwisObject::setValid(bool yesno) { _valid = yesno; return _valid; } bool IlwisObject::isReadOnly() const { if ( !connector(cmOUTPUT).isNull()) return connector(cmOUTPUT)->isReadOnly() && _readOnly; return _readOnly; } bool IlwisObject::hasChanged() const { return _changed; } bool IlwisObject::prepare(const QString &) { return true; } void IlwisObject::setConnector(ConnectorInterface *connector, ConnectorMode mode) { if (mode == cmINPUT || mode == cmINOUT){ quint64 pointer = (quint64) ( _outConnector.data()); quint64 npointer = (quint64) ( connector); if ( pointer != npointer || npointer == 0) _connector.reset(connector); else { _valid = false; ERROR1("Duplicate connector assignement for input/output in %1", name()); } } if ( mode == cmOUTPUT){ quint64 pointer = (quint64) ( _connector.data()); quint64 npointer = (quint64) ( connector); if ( pointer != npointer || npointer == 0) _outConnector.reset(connector); else { _valid = false; ERROR1("Duplicate connector assignement for input/output in %1", name()); } } } QScopedPointer<ConnectorInterface> &IlwisObject::connector(ConnectorMode mode) { if ( mode == cmINPUT) return _connector; else if ( mode == cmOUTPUT) if ( _outConnector.data() != 0) return _outConnector; return _connector; } const QScopedPointer<ConnectorInterface> &IlwisObject::connector(ConnectorMode mode) const { if ( mode == cmINPUT) return _connector; else if ( mode == cmOUTPUT) if ( _outConnector.data() != 0) return _outConnector; return _connector; } bool operator==(const IlwisObject& obj1, const IlwisObject& obj2) { return obj1.id() == obj2.id(); } bool IlwisObject::fromInternal(const QSqlRecord &rec) { setName(rec.field("name").value().toString()); setDescription(rec.field("description").value().toString()); setCode(rec.field("code").value().toString()); setConnector(0); return true; } QUrl IlwisObject::source() const { if ( _connector.isNull() == false) return _connector->source(); return QUrl(); } QUrl IlwisObject::target() const { if ( _outConnector.isNull()) return source(); return _outConnector->source(); } void IlwisObject::setSerializationOptions(const SerializationOptions &opt) { _serializationOptions = opt; } SerializationOptions IlwisObject::serializationOptions() const { return _serializationOptions; } bool IlwisObject::storeMetaData() { if ( !connector(cmOUTPUT).isNull()) return connector(cmOUTPUT)->storeMetaData(this); return ERROR1(ERR_NO_INITIALIZED_1,"connector"); } bool IlwisObject::storeBinaryData() { if (!connector(cmOUTPUT).isNull()) return connector(cmOUTPUT)->storeBinaryData(this); return ERROR1(ERR_NO_INITIALIZED_1,"connector"); } bool IlwisObject::store(int storemode) { bool ok = true; if ( storemode & smMETADATA) ok &= storeMetaData(); if ( storemode & smBINARYDATA) ok &= storeBinaryData(); return ok; } //------ statics ---------------------------------------------- QString IlwisObject::type2Name(IlwisTypes t) { switch(t) { case itGRIDCOVERAGE: return "GridCoverage"; case itPOLYGONCOVERAGE: return "PolygonCoverage"; case itSEGMENTCOVERAGE: return "LineCoverage"; case itPOINTCOVERAGE: return "PointCoverage"; case itNUMERICDOMAIN: return "ValueDomain"; case itITEMDOMAIN: return "ItemDomain"; case itTIMEDOMAIN: return "TimeDomain"; case itREPRESENTATION: return "Representation"; case itCOORDSYSTEM: return "CoordinateSystem"; case itCONVENTIONALCOORDSYSTEM: return "ConventionalCoordinateSystem"; case itGEOREF: return "Georeference"; case itCORNERSGEOREF: return "CornersGeoreference"; case itTIEPOINTGEOREF: return "TiePointsCornersGeoreference"; case itTABLE: return "Table"; case itPROJECTION: return "Projection"; case itELLIPSOID: return "Ellipsoid"; case itGEODETICDATUM: return "GeodeticDatum"; case itCATALOG: return "Catalog"; case itOPERATIONMETADATA: return "OperationMetaData"; } return sUNDEF; } IlwisTypes IlwisObject::name2Type(const QString& dname) { QString name = dname; int index; if ( (index = name.indexOf("::")) != -1){ name = dname.right(name.size() - index - 2); } if ( name.compare("GridCoverage",Qt::CaseInsensitive) == 0) return itGRIDCOVERAGE; if ( name.compare( "PolygonCoverage",Qt::CaseInsensitive) == 0) return itPOLYGONCOVERAGE; if ( name.compare( "LineCoverage",Qt::CaseInsensitive) == 0) return itSEGMENTCOVERAGE; if ( name.compare( "PointCoverage",Qt::CaseInsensitive) == 0) return itPOINTCOVERAGE; if ( name.compare( "FeatureCoverage",Qt::CaseInsensitive) == 0) return itFEATURECOVERAGE; if ( name.compare( "ValueDomain",Qt::CaseInsensitive) == 0) return itNUMERICDOMAIN; if ( name.mid(0,10) == "ItemDomain") // contains template construct, so different comparison return itITEMDOMAIN; if ( name.compare( "Domain",Qt::CaseInsensitive) == 0) return itDOMAIN; if ( name.compare( "Representation",Qt::CaseInsensitive) == 0) return itREPRESENTATION; if ( name.compare( "CoordinateSystem",Qt::CaseInsensitive) == 0) return itCOORDSYSTEM; if ( name.compare( "ConventionalCoordinateSystem",Qt::CaseInsensitive) == 0) return itCONVENTIONALCOORDSYSTEM; if ( name.compare( "Georeference",Qt::CaseInsensitive) == 0) return itGEOREF; if ( name.compare( "Table",Qt::CaseInsensitive) == 0) return itTABLE; if ( name.compare( "FlatTable",Qt::CaseInsensitive) == 0) return itFLATTABLE; if ( name.compare( "DatabaseTable",Qt::CaseInsensitive) == 0) return itDATABASETABLE; if ( name.compare( "Projection",Qt::CaseInsensitive) == 0) return itPROJECTION; if ( name.compare( "Ellipsoid",Qt::CaseInsensitive) == 0) return itELLIPSOID; if ( name.compare( "GeodeticDatum",Qt::CaseInsensitive) == 0) return itGEODETICDATUM; if ( name.compare( "Catalog",Qt::CaseInsensitive) == 0) return itCATALOG; if ( name.compare( "OperationMetaData",Qt::CaseInsensitive) == 0) return itOPERATIONMETADATA; return itUNKNOWN; } void IlwisObject::addTypeFunction(IlwisTypeFunction func) { _typeFunctions.push_back(func); } IlwisTypes IlwisObject::findType(const QString &resource) { foreach(IlwisTypeFunction func, _typeFunctions) { IlwisTypes tp = func(resource); if ( tp != itUNKNOWN) return tp; } return itUNKNOWN; } <commit_msg>there is no name field in the numeric domain table; code needs to be used for the name<commit_after>#include <QUrl> #include <QDateTime> #include <QFileInfo> #include <QSqlRecord> #include <QSqlField> #include "ilwis.h" #include "kernel.h" #include "issuelogger.h" #include "connectorinterface.h" #include "factory.h" #include "abstractfactory.h" #include "connectorfactory.h" #include "ilwisobjectfactory.h" #include "ilwisdata.h" #include "resource.h" #include "ilwisobjectconnector.h" #include "ilwiscontext.h" #include "version.h" using namespace Ilwis; QVector<IlwisTypeFunction> IlwisObject::_typeFunctions; //------------------------------------------------- IlwisObject::IlwisObject() : _valid(false), _readOnly(false), _changed(false) { Identity::prepare(); } IlwisObject::IlwisObject(const Resource& resource) : Identity(resource.name(), resource.id(), resource.code(), resource.description()) , _readOnly(false), _changed(false) { if (!resource.isValid()) Identity::prepare(); } IlwisObject::~IlwisObject() { // qDeleteAll(_factories); } IlwisObject *IlwisObject::create(const Resource& item) { const IlwisObjectFactory *factory = kernel()->factory<IlwisObjectFactory>("IlwisObjectFactory",item); if ( factory) return factory->create(item); else { kernel()->issues()->log(TR("Cann't find suitable factory for %1 ").arg(item.name())); } return 0; } void IlwisObject::connectTo(const QUrl& url, const QString& format, const QString& fnamespace, ConnectorMode cmode) { Locker lock(_mutex); Resource resource; resource = mastercatalog()->id2Resource(id()); if ( !resource.isValid()) resource = Resource(url,ilwisType(), false); // if ( url == QUrl()) { resource.setName(name()); } const Ilwis::ConnectorFactory *factory = kernel()->factory<Ilwis::ConnectorFactory>("ilwis::ConnectorFactory"); if ( !factory) return; Ilwis::ConnectorInterface *conn = factory->createFromFormat(resource, format,fnamespace); if (!conn) return; setConnector(conn, cmode); if ( name() == sUNDEF) setName(resource.name()); } bool IlwisObject::prepare( ) { _valid = true; return true; } QDateTime IlwisObject::modifiedTime() const { return _modifiedTime; } void IlwisObject::setModifiedTime(const Time &tme) { _modifiedTime = tme; } Time IlwisObject::createTime() const { return _createTime; } void IlwisObject::setCreateTime(const Time &time) { _createTime = time; } QString IlwisObject::toString() { //TODO return ""; } bool IlwisObject::isEqual(const IlwisObject &obj) const { //TODO overrule this method for object types that need to do more checking return id() == obj.id(); } bool IlwisObject::isValid() const { return _valid; } bool IlwisObject::setValid(bool yesno) { _valid = yesno; return _valid; } bool IlwisObject::isReadOnly() const { if ( !connector(cmOUTPUT).isNull()) return connector(cmOUTPUT)->isReadOnly() && _readOnly; return _readOnly; } bool IlwisObject::hasChanged() const { return _changed; } bool IlwisObject::prepare(const QString &) { return true; } void IlwisObject::setConnector(ConnectorInterface *connector, ConnectorMode mode) { if (mode == cmINPUT || mode == cmINOUT){ quint64 pointer = (quint64) ( _outConnector.data()); quint64 npointer = (quint64) ( connector); if ( pointer != npointer || npointer == 0) _connector.reset(connector); else { _valid = false; ERROR1("Duplicate connector assignement for input/output in %1", name()); } } if ( mode == cmOUTPUT){ quint64 pointer = (quint64) ( _connector.data()); quint64 npointer = (quint64) ( connector); if ( pointer != npointer || npointer == 0) _outConnector.reset(connector); else { _valid = false; ERROR1("Duplicate connector assignement for input/output in %1", name()); } } } QScopedPointer<ConnectorInterface> &IlwisObject::connector(ConnectorMode mode) { if ( mode == cmINPUT) return _connector; else if ( mode == cmOUTPUT) if ( _outConnector.data() != 0) return _outConnector; return _connector; } const QScopedPointer<ConnectorInterface> &IlwisObject::connector(ConnectorMode mode) const { if ( mode == cmINPUT) return _connector; else if ( mode == cmOUTPUT) if ( _outConnector.data() != 0) return _outConnector; return _connector; } bool operator==(const IlwisObject& obj1, const IlwisObject& obj2) { return obj1.id() == obj2.id(); } bool IlwisObject::fromInternal(const QSqlRecord &rec) { setName(rec.field("code").value().toString()); // name and code are the same here setDescription(rec.field("description").value().toString()); setCode(rec.field("code").value().toString()); setConnector(0); return true; } QUrl IlwisObject::source() const { if ( _connector.isNull() == false) return _connector->source(); return QUrl(); } QUrl IlwisObject::target() const { if ( _outConnector.isNull()) return source(); return _outConnector->source(); } void IlwisObject::setSerializationOptions(const SerializationOptions &opt) { _serializationOptions = opt; } SerializationOptions IlwisObject::serializationOptions() const { return _serializationOptions; } bool IlwisObject::storeMetaData() { if ( !connector(cmOUTPUT).isNull()) return connector(cmOUTPUT)->storeMetaData(this); return ERROR1(ERR_NO_INITIALIZED_1,"connector"); } bool IlwisObject::storeBinaryData() { if (!connector(cmOUTPUT).isNull()) return connector(cmOUTPUT)->storeBinaryData(this); return ERROR1(ERR_NO_INITIALIZED_1,"connector"); } bool IlwisObject::store(int storemode) { bool ok = true; if ( storemode & smMETADATA) ok &= storeMetaData(); if ( storemode & smBINARYDATA) ok &= storeBinaryData(); return ok; } //------ statics ---------------------------------------------- QString IlwisObject::type2Name(IlwisTypes t) { switch(t) { case itGRIDCOVERAGE: return "GridCoverage"; case itPOLYGONCOVERAGE: return "PolygonCoverage"; case itSEGMENTCOVERAGE: return "LineCoverage"; case itPOINTCOVERAGE: return "PointCoverage"; case itNUMERICDOMAIN: return "ValueDomain"; case itITEMDOMAIN: return "ItemDomain"; case itTIMEDOMAIN: return "TimeDomain"; case itREPRESENTATION: return "Representation"; case itCOORDSYSTEM: return "CoordinateSystem"; case itCONVENTIONALCOORDSYSTEM: return "ConventionalCoordinateSystem"; case itGEOREF: return "Georeference"; case itCORNERSGEOREF: return "CornersGeoreference"; case itTIEPOINTGEOREF: return "TiePointsCornersGeoreference"; case itTABLE: return "Table"; case itPROJECTION: return "Projection"; case itELLIPSOID: return "Ellipsoid"; case itGEODETICDATUM: return "GeodeticDatum"; case itCATALOG: return "Catalog"; case itOPERATIONMETADATA: return "OperationMetaData"; } return sUNDEF; } IlwisTypes IlwisObject::name2Type(const QString& dname) { QString name = dname; int index; if ( (index = name.indexOf("::")) != -1){ name = dname.right(name.size() - index - 2); } if ( name.compare("GridCoverage",Qt::CaseInsensitive) == 0) return itGRIDCOVERAGE; if ( name.compare( "PolygonCoverage",Qt::CaseInsensitive) == 0) return itPOLYGONCOVERAGE; if ( name.compare( "LineCoverage",Qt::CaseInsensitive) == 0) return itSEGMENTCOVERAGE; if ( name.compare( "PointCoverage",Qt::CaseInsensitive) == 0) return itPOINTCOVERAGE; if ( name.compare( "FeatureCoverage",Qt::CaseInsensitive) == 0) return itFEATURECOVERAGE; if ( name.compare( "ValueDomain",Qt::CaseInsensitive) == 0) return itNUMERICDOMAIN; if ( name.mid(0,10) == "ItemDomain") // contains template construct, so different comparison return itITEMDOMAIN; if ( name.compare( "Domain",Qt::CaseInsensitive) == 0) return itDOMAIN; if ( name.compare( "Representation",Qt::CaseInsensitive) == 0) return itREPRESENTATION; if ( name.compare( "CoordinateSystem",Qt::CaseInsensitive) == 0) return itCOORDSYSTEM; if ( name.compare( "ConventionalCoordinateSystem",Qt::CaseInsensitive) == 0) return itCONVENTIONALCOORDSYSTEM; if ( name.compare( "Georeference",Qt::CaseInsensitive) == 0) return itGEOREF; if ( name.compare( "Table",Qt::CaseInsensitive) == 0) return itTABLE; if ( name.compare( "FlatTable",Qt::CaseInsensitive) == 0) return itFLATTABLE; if ( name.compare( "DatabaseTable",Qt::CaseInsensitive) == 0) return itDATABASETABLE; if ( name.compare( "Projection",Qt::CaseInsensitive) == 0) return itPROJECTION; if ( name.compare( "Ellipsoid",Qt::CaseInsensitive) == 0) return itELLIPSOID; if ( name.compare( "GeodeticDatum",Qt::CaseInsensitive) == 0) return itGEODETICDATUM; if ( name.compare( "Catalog",Qt::CaseInsensitive) == 0) return itCATALOG; if ( name.compare( "OperationMetaData",Qt::CaseInsensitive) == 0) return itOPERATIONMETADATA; return itUNKNOWN; } void IlwisObject::addTypeFunction(IlwisTypeFunction func) { _typeFunctions.push_back(func); } IlwisTypes IlwisObject::findType(const QString &resource) { foreach(IlwisTypeFunction func, _typeFunctions) { IlwisTypes tp = func(resource); if ( tp != itUNKNOWN) return tp; } return itUNKNOWN; } <|endoftext|>
<commit_before> #include "Session.hpp" #include "../Mirror.hpp" #include <onions-common/Common.hpp> #include <onions-common/containers/Cache.hpp> #include <onions-common/Log.hpp> #include <onions-common/Utils.hpp> #include <onions-common/tcp/MemAllocator.hpp> #include <botan/sha2_64.h> #include <botan/base64.h> #include <boost/bind.hpp> template <typename Handler> inline MemAllocator<Handler> makeHandler(HandleAlloc& a, Handler h) { return MemAllocator<Handler>(a, h); } Session::Session(boost::asio::io_service& ios) : socket_(ios), subscribed_(false) { } boost::asio::ip::tcp::socket& Session::getSocket() { return socket_; } void Session::asyncRead() { // std::cout << "Reading... "; socket_.async_read_some( boost::asio::buffer(buffer_), makeHandler(allocator_, boost::bind(&Session::processRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void Session::asyncWrite(const Json::Value& val) { Json::FastWriter writer; asyncWrite(writer.write(val)); } void Session::asyncWrite(const std::string& str) { for (std::size_t j = 0; j < str.size(); j++) buffer_[j] = str[j]; // std::cout << "Writing... "; boost::asio::async_write( socket_, boost::asio::buffer(buffer_, str.size()), makeHandler(allocator_, boost::bind(&Session::processWrite, shared_from_this(), boost::asio::placeholders::error))); } bool Session::isSubscriber() { return subscribed_; } // ***************************** PRIVATE METHODS ***************************** void Session::handlePing(Json::Value& in, Json::Value& out) { out["response"] = "pong"; } void Session::handleUpload(Json::Value& in, Json::Value& out) { auto r = Common::parseRecord(in["value"]); if (Cache::add(r)) // if successfully added to the Cache Mirror::broadcastEvent("record", in["value"]); else out["error"] = "Name already taken."; } void Session::handleDomainQuery(Json::Value& in, Json::Value& out) { std::string domain = in["value"].asString(); if (Utils::strEndsWith(domain, ".tor")) { // resolve .tor -> .onion auto record = Cache::get(domain); if (record) { out["response"] = record->asJSON(); Log::get().notice("Found Record for \"" + domain + "\""); } else { out["error"] = "404"; Log::get().notice("404ed request for \"" + domain + "\""); } } else out["error"] = "Invalid request."; } void Session::handleSubscribe(Json::Value& in, Json::Value& out) { subscribed_ = true; } // called by Asio whenever the socket has been read into the buffer void Session::processRead(const boost::system::error_code& error, size_t n) { if (n == 0) { Log::get().warn("Received empty message."); return; } else if (error) { Log::get().warn(error.message()); return; } Json::Value in, out; Json::Reader reader; std::string inputStr(buffer_.begin(), buffer_.begin() + n); if (!reader.parse(inputStr, in)) out["error"] = "Failed to parse message!"; else if (!in.isMember("command")) out["error"] = "Message is missing the \"command\" field!"; else if (!in.isMember("value")) out["error"] = "Message is missing the \"value\" field!"; else { std::string command(in["command"].asString()); if (command == "ping") handlePing(in, out); else if (command == "upload") handleUpload(in, out); else if (command == "domainQuery") handleDomainQuery(in, out); else if (command == "subscribe") handleSubscribe(in, out); else out["error"] = "Unknown command \"" + command + "\""; } if (out.isMember("error")) Log::get().warn(out["error"].asString()); else if (!out.isMember("response")) out["response"] = "success"; asyncWrite(out); } // called by Asio when the buffer has been written to the socket void Session::processWrite(const boost::system::error_code& error) { if (error) { Log::get().warn(error.message()); return; } // std::cout << "done." << std::endl; asyncRead(); } <commit_msg>Clarify connection-termination message<commit_after> #include "Session.hpp" #include "../Mirror.hpp" #include <onions-common/Common.hpp> #include <onions-common/containers/Cache.hpp> #include <onions-common/Log.hpp> #include <onions-common/Utils.hpp> #include <onions-common/tcp/MemAllocator.hpp> #include <botan/sha2_64.h> #include <botan/base64.h> #include <boost/bind.hpp> template <typename Handler> inline MemAllocator<Handler> makeHandler(HandleAlloc& a, Handler h) { return MemAllocator<Handler>(a, h); } Session::Session(boost::asio::io_service& ios) : socket_(ios), subscribed_(false) { } boost::asio::ip::tcp::socket& Session::getSocket() { return socket_; } void Session::asyncRead() { // std::cout << "Reading... "; socket_.async_read_some( boost::asio::buffer(buffer_), makeHandler(allocator_, boost::bind(&Session::processRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void Session::asyncWrite(const Json::Value& val) { Json::FastWriter writer; asyncWrite(writer.write(val)); } void Session::asyncWrite(const std::string& str) { for (std::size_t j = 0; j < str.size(); j++) buffer_[j] = str[j]; // std::cout << "Writing... "; boost::asio::async_write( socket_, boost::asio::buffer(buffer_, str.size()), makeHandler(allocator_, boost::bind(&Session::processWrite, shared_from_this(), boost::asio::placeholders::error))); } bool Session::isSubscriber() { return subscribed_; } // ***************************** PRIVATE METHODS ***************************** void Session::handlePing(Json::Value& in, Json::Value& out) { out["response"] = "pong"; } void Session::handleUpload(Json::Value& in, Json::Value& out) { auto r = Common::parseRecord(in["value"]); if (Cache::add(r)) // if successfully added to the Cache Mirror::broadcastEvent("record", in["value"]); else out["error"] = "Name already taken."; } void Session::handleDomainQuery(Json::Value& in, Json::Value& out) { std::string domain = in["value"].asString(); if (Utils::strEndsWith(domain, ".tor")) { // resolve .tor -> .onion auto record = Cache::get(domain); if (record) { out["response"] = record->asJSON(); Log::get().notice("Found Record for \"" + domain + "\""); } else { out["error"] = "404"; Log::get().notice("404ed request for \"" + domain + "\""); } } else out["error"] = "Invalid request."; } void Session::handleSubscribe(Json::Value& in, Json::Value& out) { subscribed_ = true; } // called by Asio whenever the socket has been read into the buffer void Session::processRead(const boost::system::error_code& error, size_t n) { if (n == 0) { Log::get().notice("Connection closed."); return; } else if (error) { Log::get().warn(error.message()); return; } Json::Value in, out; Json::Reader reader; std::string inputStr(buffer_.begin(), buffer_.begin() + n); if (!reader.parse(inputStr, in)) out["error"] = "Failed to parse message!"; else if (!in.isMember("command")) out["error"] = "Message is missing the \"command\" field!"; else if (!in.isMember("value")) out["error"] = "Message is missing the \"value\" field!"; else { std::string command(in["command"].asString()); if (command == "ping") handlePing(in, out); else if (command == "upload") handleUpload(in, out); else if (command == "domainQuery") handleDomainQuery(in, out); else if (command == "subscribe") handleSubscribe(in, out); else out["error"] = "Unknown command \"" + command + "\""; } if (out.isMember("error")) Log::get().warn(out["error"].asString()); else if (!out.isMember("response")) out["response"] = "success"; asyncWrite(out); } // called by Asio when the buffer has been written to the socket void Session::processWrite(const boost::system::error_code& error) { if (error) { Log::get().warn(error.message()); return; } // std::cout << "done." << std::endl; asyncRead(); } <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/policy_document_request.h" #include "google/cloud/storage/internal/curl_handle.h" #include "google/cloud/storage/internal/openssl_util.h" #include "google/cloud/internal/format_time_point.h" #include <nlohmann/json.hpp> #include <codecvt> #include <iomanip> #include <locale> #include <sstream> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { nlohmann::json TransformConditions( std::vector<PolicyDocumentCondition> const& conditions) { CurlHandle curl; auto res = nlohmann::json::array(); for (auto const& kv : conditions) { std::vector<std::string> elements = kv.elements(); /** * If the elements is of size 2, we've encountered an exact match in * object form. So we create a json object using the first element as the * key and the second element as the value. */ if (elements.size() == 2) { nlohmann::json object; object[elements.at(0)] = elements.at(1); res.emplace_back(std::move(object)); } else { if (elements.at(0) == "content-length-range") { res.push_back({elements.at(0), std::stol(elements.at(1)), std::stol(elements.at(2))}); } else { res.push_back({elements.at(0), elements.at(1), elements.at(2)}); } } } return res; } /// If c is ASCII escape it and append it to result. Return if it is ASCII. bool EscapeAsciiChar(std::string& result, char32_t c) { switch (c) { case '\b': result.append("\\b"); return true; case '\f': result.append("\\f"); return true; case '\n': result.append("\\n"); return true; case '\r': result.append("\\r"); return true; case '\t': result.append("\\t"); return true; case '\v': result.append("\\v"); return true; } char32_t constexpr kMaxAsciiChar = 127; if (c > kMaxAsciiChar) { return false; } result.append(1, static_cast<char>(c)); return true; } } // namespace #if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS StatusOr<std::string> PostPolicyV4EscapeUTF8(std::string const& utf8_bytes) { std::string result; #if (_MSC_VER >= 1900) // Working around missing std::codecvt_utf8<char32_t> symbols in MSVC // Microsoft bug number: VSO#143857 // Context: // https://social.msdn.microsoft.com/Forums/en-US/8f40dcd8-c67f-4eba-9134-a19b9178e481/vs-2015-rc-linker-stdcodecvt-error?forum=vcgeneral using WideChar = __int32; #else // (_MSC_VER >= 1900) using WideChar = char32_t; #endif // (_MSC_VER >= 1900) std::wstring_convert<std::codecvt_utf8<WideChar>, WideChar> conv; std::basic_string<WideChar> utf32; try { utf32 = conv.from_bytes(utf8_bytes); } catch (std::exception const& ex) { return Status(StatusCode::kInvalidArgument, std::string("string failed to parse as UTF-8: ") + ex.what()); } utf32 = conv.from_bytes(utf8_bytes); for (auto c : utf32) { bool is_ascii = EscapeAsciiChar(result, c); if (!is_ascii) { // All unicode characters should be encoded as \udead. std::ostringstream os; os << "\\u" << std::setw(4) << std::setfill('0') << std::hex << static_cast<std::uint32_t>(c); result.append(os.str()); } } return result; } #else // GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS StatusOr<std::string> PostPolicyV4EscapeUTF8(std::string const&) { return Status(StatusCode::kUnimplemented, "Signing POST policies is unavailable with this compiler due " "to the lack of exception support."); } #endif // GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS StatusOr<std::string> PostPolicyV4Escape(std::string const& utf8_bytes) { std::string result; for (char32_t c : utf8_bytes) { bool is_ascii = EscapeAsciiChar(result, c); if (!is_ascii) { // We first try to escape the string assuming it's plain ASCII. If it // turns out that there are non-ASCII characters, we fall back to // interpreting it as proper UTF-8. We do it because it will be faster in // the common case and, more importantly, this allows the common case to // work properly on compilers which don't have UTF8 support. return PostPolicyV4EscapeUTF8(utf8_bytes); } } return result; } std::string PolicyDocumentRequest::StringToSign() const { using nlohmann::json; auto const document = policy_document(); json j; j["expiration"] = google::cloud::internal::FormatRfc3339(document.expiration); j["conditions"] = TransformConditions(document.conditions); return std::move(j).dump(); } std::ostream& operator<<(std::ostream& os, PolicyDocumentRequest const& r) { return os << "PolicyDocumentRequest={" << r.StringToSign() << "}"; } void PolicyDocumentV4Request::SetOption(AddExtensionFieldOption const& o) { if (!o.has_value()) { return; } extension_fields_.emplace_back( std::make_pair(std::move(o.value().first), std::move(o.value().second))); } void PolicyDocumentV4Request::SetOption(PredefinedAcl const& o) { if (!o.has_value()) { return; } extension_fields_.emplace_back(std::make_pair("acl", o.HeaderName())); } void PolicyDocumentV4Request::SetOption(BucketBoundHostname const& o) { if (!o.has_value()) { bucket_bound_domain_.reset(); return; } bucket_bound_domain_ = o.value(); } void PolicyDocumentV4Request::SetOption(Scheme const& o) { if (!o.has_value()) { return; } scheme_ = o.value(); } void PolicyDocumentV4Request::SetOption(VirtualHostname const& o) { virtual_host_name_ = o.has_value() && o.value(); } std::chrono::system_clock::time_point PolicyDocumentV4Request::ExpirationDate() const { return document_.timestamp + document_.expiration; } std::string PolicyDocumentV4Request::Url() const { if (bucket_bound_domain_) { return scheme_ + "://" + *bucket_bound_domain_ + "/"; } if (virtual_host_name_) { return scheme_ + "://" + policy_document().bucket + ".storage.googleapis.com/"; } return scheme_ + "://storage.googleapis.com/" + policy_document().bucket + "/"; } std::string PolicyDocumentV4Request::Credentials() const { return signing_email_ + "/" + google::cloud::internal::FormatV4SignedUrlScope(document_.timestamp) + "/auto/storage/goog4_request"; } std::vector<PolicyDocumentCondition> PolicyDocumentV4Request::GetAllConditions() const { std::vector<PolicyDocumentCondition> conditions; for (auto const& field : extension_fields_) { conditions.push_back(PolicyDocumentCondition({field.first, field.second})); } std::sort(conditions.begin(), conditions.end()); auto const& document = policy_document(); std::copy(document.conditions.begin(), document.conditions.end(), std::back_inserter(conditions)); conditions.push_back(PolicyDocumentCondition({"bucket", document.bucket})); conditions.push_back(PolicyDocumentCondition({"key", document.object})); conditions.push_back(PolicyDocumentCondition( {"x-goog-date", google::cloud::internal::FormatV4SignedUrlTimestamp( document_.timestamp)})); conditions.push_back( PolicyDocumentCondition({"x-goog-credential", Credentials()})); conditions.push_back( PolicyDocumentCondition({"x-goog-algorithm", "GOOG4-RSA-SHA256"})); return conditions; } std::string PolicyDocumentV4Request::StringToSign() const { using nlohmann::json; json j; j["conditions"] = TransformConditions(GetAllConditions()); j["expiration"] = google::cloud::internal::FormatRfc3339(ExpirationDate()); return std::move(j).dump(); } std::map<std::string, std::string> PolicyDocumentV4Request::RequiredFormFields() const { std::map<std::string, std::string> res; for (auto const& condition : GetAllConditions()) { auto const& elements = condition.elements(); // According to conformance tests, bucket should not be present. if (elements.size() == 2 && elements[0] == "bucket") { continue; } if (elements.size() == 2) { res[elements[0]] = elements[1]; continue; } if (elements.size() == 3 && elements[0] == "eq" && elements[1].size() > 1 && elements[1][0] == '$') { res[elements[1].substr(1)] = elements[2]; } } return res; } std::ostream& operator<<(std::ostream& os, PolicyDocumentV4Request const& r) { return os << "PolicyDocumentRequest={" << r.StringToSign() << "}"; } } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google <commit_msg>fix(storage): no workaround needed with libc++ and MSVC (#9768)<commit_after>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/policy_document_request.h" #include "google/cloud/storage/internal/curl_handle.h" #include "google/cloud/storage/internal/openssl_util.h" #include "google/cloud/internal/format_time_point.h" #include <nlohmann/json.hpp> #include <codecvt> #include <iomanip> #include <locale> #include <sstream> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { nlohmann::json TransformConditions( std::vector<PolicyDocumentCondition> const& conditions) { CurlHandle curl; auto res = nlohmann::json::array(); for (auto const& kv : conditions) { std::vector<std::string> elements = kv.elements(); /** * If the elements is of size 2, we've encountered an exact match in * object form. So we create a json object using the first element as the * key and the second element as the value. */ if (elements.size() == 2) { nlohmann::json object; object[elements.at(0)] = elements.at(1); res.emplace_back(std::move(object)); } else { if (elements.at(0) == "content-length-range") { res.push_back({elements.at(0), std::stol(elements.at(1)), std::stol(elements.at(2))}); } else { res.push_back({elements.at(0), elements.at(1), elements.at(2)}); } } } return res; } /// If c is ASCII escape it and append it to result. Return if it is ASCII. bool EscapeAsciiChar(std::string& result, char32_t c) { switch (c) { case '\b': result.append("\\b"); return true; case '\f': result.append("\\f"); return true; case '\n': result.append("\\n"); return true; case '\r': result.append("\\r"); return true; case '\t': result.append("\\t"); return true; case '\v': result.append("\\v"); return true; } char32_t constexpr kMaxAsciiChar = 127; if (c > kMaxAsciiChar) { return false; } result.append(1, static_cast<char>(c)); return true; } } // namespace #if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS StatusOr<std::string> PostPolicyV4EscapeUTF8(std::string const& utf8_bytes) { std::string result; #if (_MSC_VER >= 1900) && !defined(_LIBCPP_VERSION) // Working around missing std::codecvt_utf8<char32_t> symbols in MSVC // Microsoft bug number: VSO#143857 // Context: // https://social.msdn.microsoft.com/Forums/en-US/8f40dcd8-c67f-4eba-9134-a19b9178e481/vs-2015-rc-linker-stdcodecvt-error?forum=vcgeneral using WideChar = __int32; #else // (_MSC_VER >= 1900) using WideChar = char32_t; #endif // (_MSC_VER >= 1900) std::wstring_convert<std::codecvt_utf8<WideChar>, WideChar> conv; std::basic_string<WideChar> utf32; try { utf32 = conv.from_bytes(utf8_bytes); } catch (std::exception const& ex) { return Status(StatusCode::kInvalidArgument, std::string("string failed to parse as UTF-8: ") + ex.what()); } utf32 = conv.from_bytes(utf8_bytes); for (auto c : utf32) { bool is_ascii = EscapeAsciiChar(result, c); if (!is_ascii) { // All unicode characters should be encoded as \udead. std::ostringstream os; os << "\\u" << std::setw(4) << std::setfill('0') << std::hex << static_cast<std::uint32_t>(c); result.append(os.str()); } } return result; } #else // GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS StatusOr<std::string> PostPolicyV4EscapeUTF8(std::string const&) { return Status(StatusCode::kUnimplemented, "Signing POST policies is unavailable with this compiler due " "to the lack of exception support."); } #endif // GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS StatusOr<std::string> PostPolicyV4Escape(std::string const& utf8_bytes) { std::string result; for (char32_t c : utf8_bytes) { bool is_ascii = EscapeAsciiChar(result, c); if (!is_ascii) { // We first try to escape the string assuming it's plain ASCII. If it // turns out that there are non-ASCII characters, we fall back to // interpreting it as proper UTF-8. We do it because it will be faster in // the common case and, more importantly, this allows the common case to // work properly on compilers which don't have UTF8 support. return PostPolicyV4EscapeUTF8(utf8_bytes); } } return result; } std::string PolicyDocumentRequest::StringToSign() const { using nlohmann::json; auto const document = policy_document(); json j; j["expiration"] = google::cloud::internal::FormatRfc3339(document.expiration); j["conditions"] = TransformConditions(document.conditions); return std::move(j).dump(); } std::ostream& operator<<(std::ostream& os, PolicyDocumentRequest const& r) { return os << "PolicyDocumentRequest={" << r.StringToSign() << "}"; } void PolicyDocumentV4Request::SetOption(AddExtensionFieldOption const& o) { if (!o.has_value()) { return; } extension_fields_.emplace_back( std::make_pair(std::move(o.value().first), std::move(o.value().second))); } void PolicyDocumentV4Request::SetOption(PredefinedAcl const& o) { if (!o.has_value()) { return; } extension_fields_.emplace_back(std::make_pair("acl", o.HeaderName())); } void PolicyDocumentV4Request::SetOption(BucketBoundHostname const& o) { if (!o.has_value()) { bucket_bound_domain_.reset(); return; } bucket_bound_domain_ = o.value(); } void PolicyDocumentV4Request::SetOption(Scheme const& o) { if (!o.has_value()) { return; } scheme_ = o.value(); } void PolicyDocumentV4Request::SetOption(VirtualHostname const& o) { virtual_host_name_ = o.has_value() && o.value(); } std::chrono::system_clock::time_point PolicyDocumentV4Request::ExpirationDate() const { return document_.timestamp + document_.expiration; } std::string PolicyDocumentV4Request::Url() const { if (bucket_bound_domain_) { return scheme_ + "://" + *bucket_bound_domain_ + "/"; } if (virtual_host_name_) { return scheme_ + "://" + policy_document().bucket + ".storage.googleapis.com/"; } return scheme_ + "://storage.googleapis.com/" + policy_document().bucket + "/"; } std::string PolicyDocumentV4Request::Credentials() const { return signing_email_ + "/" + google::cloud::internal::FormatV4SignedUrlScope(document_.timestamp) + "/auto/storage/goog4_request"; } std::vector<PolicyDocumentCondition> PolicyDocumentV4Request::GetAllConditions() const { std::vector<PolicyDocumentCondition> conditions; for (auto const& field : extension_fields_) { conditions.push_back(PolicyDocumentCondition({field.first, field.second})); } std::sort(conditions.begin(), conditions.end()); auto const& document = policy_document(); std::copy(document.conditions.begin(), document.conditions.end(), std::back_inserter(conditions)); conditions.push_back(PolicyDocumentCondition({"bucket", document.bucket})); conditions.push_back(PolicyDocumentCondition({"key", document.object})); conditions.push_back(PolicyDocumentCondition( {"x-goog-date", google::cloud::internal::FormatV4SignedUrlTimestamp( document_.timestamp)})); conditions.push_back( PolicyDocumentCondition({"x-goog-credential", Credentials()})); conditions.push_back( PolicyDocumentCondition({"x-goog-algorithm", "GOOG4-RSA-SHA256"})); return conditions; } std::string PolicyDocumentV4Request::StringToSign() const { using nlohmann::json; json j; j["conditions"] = TransformConditions(GetAllConditions()); j["expiration"] = google::cloud::internal::FormatRfc3339(ExpirationDate()); return std::move(j).dump(); } std::map<std::string, std::string> PolicyDocumentV4Request::RequiredFormFields() const { std::map<std::string, std::string> res; for (auto const& condition : GetAllConditions()) { auto const& elements = condition.elements(); // According to conformance tests, bucket should not be present. if (elements.size() == 2 && elements[0] == "bucket") { continue; } if (elements.size() == 2) { res[elements[0]] = elements[1]; continue; } if (elements.size() == 3 && elements[0] == "eq" && elements[1].size() > 1 && elements[1][0] == '$') { res[elements[1].substr(1)] = elements[2]; } } return res; } std::ostream& operator<<(std::ostream& os, PolicyDocumentV4Request const& r) { return os << "PolicyDocumentRequest={" << r.StringToSign() << "}"; } } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google <|endoftext|>
<commit_before> #include "vio/timegrabber.h" #include "vio/eigen_utils.h" #include <sstream> using namespace std; namespace vio{ TimeGrabber::TimeGrabber(): last_line_index(-1), last_line_time(-1){ } TimeGrabber::TimeGrabber(const string time_file_name, int headerLines):time_file(time_file_name), time_stream(time_file_name.c_str()), last_line_index(-1), last_line_time(-1){ if(!time_stream.is_open()) { std::cout << "Error opening timestamp file!"<<endl; } else { std::string tempStr; for(int jack=0; jack<headerLines; ++jack) getline(time_stream, tempStr); } } TimeGrabber::~TimeGrabber(){ time_stream.close(); } bool TimeGrabber::init(const string time_file_name, int headerLines){ time_file=time_file_name; time_stream.open(time_file_name.c_str()); last_line_index=-1; last_line_time=-1; if(!time_stream.is_open()) { std::cout << "Error opening timestamp file!"<<endl; return false; }else { std::string tempStr; for(int jack=0; jack<headerLines; ++jack) getline(time_stream, tempStr); } return true; } // this reading function only works for KITTI timestamp files double TimeGrabber::readTimestamp(int line_number) { string tempStr; double precursor(-1); if(last_line_index>line_number){ cerr<<"Reading previous timestamps is unsupported!"<<endl; return -1; } if(last_line_index==line_number) return last_line_time; while(last_line_index<line_number){ time_stream>>precursor; if(time_stream.fail()) break; getline(time_stream, tempStr); //remove the remaining part, this works even when it is empty ++last_line_index; } if(last_line_index<line_number) { cerr<<"Failed to find "<<line_number<<"th line in time file!"<<endl; return -1; } last_line_time=precursor; return last_line_time; } //extract time from a text file // for malaga dataset whose timestamps are in /*_IMAGE.txt file, // every two lines are the left and right image names, typically with the same timestamp, e.g., // img_CAMERA1_1261228749.918590_left.jpg // img_CAMERA1_1261228749.918590_right.jpg // img_CAMERA1_1261228749.968589_left.jpg // img_CAMERA1_1261228749.968589_right.jpg // Thus, frame number is 0 for the first two lines in the /*_IMAGE.txt file // for indexed time file, each line is frame number, time in millisec double TimeGrabber::extractTimestamp(int frame_number, bool isMalagaDataset) { string tempStr; double timestamp(-1); if(last_line_index>frame_number){ cerr<<"Read previous timestamps is unsupported!"<<endl; return -1; } if(last_line_index==frame_number) { return last_line_time; } while(last_line_index<frame_number){ getline(time_stream, tempStr); if(time_stream.fail()) break; if(isMalagaDataset){ last_left_image_name=tempStr; getline(time_stream, tempStr); //read in the right image name timestamp= -1; timestamp=atof(tempStr.substr(12, 17).c_str()); }else{//frame index and timestamp in millisec std::istringstream iss(tempStr); int frameIndex(-1); timestamp =-1; iss>>frameIndex>> timestamp; timestamp*= 0.001; } ++last_line_index; } if(last_line_index<frame_number) { cerr<<"Failed to find "<<line_number<<"th line in time file!"<<endl; return -1; } last_line_time=timestamp; return last_line_time; } } <commit_msg>correct a typo in extractTimestamp<commit_after> #include "vio/timegrabber.h" #include "vio/eigen_utils.h" #include <sstream> using namespace std; namespace vio{ TimeGrabber::TimeGrabber(): last_line_index(-1), last_line_time(-1){ } TimeGrabber::TimeGrabber(const string time_file_name, int headerLines):time_file(time_file_name), time_stream(time_file_name.c_str()), last_line_index(-1), last_line_time(-1){ if(!time_stream.is_open()) { std::cout << "Error opening timestamp file!"<<endl; } else { std::string tempStr; for(int jack=0; jack<headerLines; ++jack) getline(time_stream, tempStr); } } TimeGrabber::~TimeGrabber(){ time_stream.close(); } bool TimeGrabber::init(const string time_file_name, int headerLines){ time_file=time_file_name; time_stream.open(time_file_name.c_str()); last_line_index=-1; last_line_time=-1; if(!time_stream.is_open()) { std::cout << "Error opening timestamp file!"<<endl; return false; }else { std::string tempStr; for(int jack=0; jack<headerLines; ++jack) getline(time_stream, tempStr); } return true; } // this reading function only works for KITTI timestamp files double TimeGrabber::readTimestamp(int line_number) { string tempStr; double precursor(-1); if(last_line_index>line_number){ cerr<<"Reading previous timestamps is unsupported!"<<endl; return -1; } if(last_line_index==line_number) return last_line_time; while(last_line_index<line_number){ time_stream>>precursor; if(time_stream.fail()) break; getline(time_stream, tempStr); //remove the remaining part, this works even when it is empty ++last_line_index; } if(last_line_index<line_number) { cerr<<"Failed to find "<<line_number<<"th line in time file!"<<endl; return -1; } last_line_time=precursor; return last_line_time; } //extract time from a text file // for malaga dataset whose timestamps are in /*_IMAGE.txt file, // every two lines are the left and right image names, typically with the same timestamp, e.g., // img_CAMERA1_1261228749.918590_left.jpg // img_CAMERA1_1261228749.918590_right.jpg // img_CAMERA1_1261228749.968589_left.jpg // img_CAMERA1_1261228749.968589_right.jpg // Thus, frame number is 0 for the first two lines in the /*_IMAGE.txt file // for indexed time file, each line is frame number, time in millisec double TimeGrabber::extractTimestamp(int frame_number, bool isMalagaDataset) { string tempStr; double timestamp(-1); if(last_line_index>frame_number){ cerr<<"Read previous timestamps is unsupported!"<<endl; return -1; } if(last_line_index==frame_number) { return last_line_time; } while(last_line_index<frame_number){ getline(time_stream, tempStr); if(time_stream.fail()) break; if(isMalagaDataset){ last_left_image_name=tempStr; getline(time_stream, tempStr); //read in the right image name timestamp= -1; timestamp=atof(tempStr.substr(12, 17).c_str()); }else{//frame index and timestamp in millisec std::istringstream iss(tempStr); int frameIndex(-1); timestamp =-1; iss>>frameIndex>> timestamp; timestamp*= 0.001; } ++last_line_index; } if(last_line_index<frame_number) { cerr<<"Failed to find "<<frame_number<<"th line in time file!"<<endl; return -1; } last_line_time=timestamp; return last_line_time; } } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Andreas Fett. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <errno.h> #include <cstdlib> #include <cstring> #include <ostream> #include <stdexcept> #include "auto-locale.h" #include "token-stream.h" #include "utf8stream.h" namespace { bool is_ws(int c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } } namespace jsonp { // LCOV_EXCL_START std::ostream & operator<<(std::ostream & os, Token::Type type) { #define CASE_TOKEN_TYPE(name) case name: os << # name; break switch (type) { CASE_TOKEN_TYPE(Token::INVALID); CASE_TOKEN_TYPE(Token::BEGIN_ARRAY); CASE_TOKEN_TYPE(Token::END_ARRAY); CASE_TOKEN_TYPE(Token::BEGIN_OBJECT); CASE_TOKEN_TYPE(Token::END_OBJECT); CASE_TOKEN_TYPE(Token::NAME_SEPARATOR); CASE_TOKEN_TYPE(Token::VALUE_SEPARATOR); CASE_TOKEN_TYPE(Token::TRUE_LITERAL); CASE_TOKEN_TYPE(Token::FALSE_LITERAL); CASE_TOKEN_TYPE(Token::NULL_LITERAL); CASE_TOKEN_TYPE(Token::STRING); CASE_TOKEN_TYPE(Token::NUMBER); } #undef CASE_TOKEN_TYPE return os; } // LCOV_EXCL_STOP TokenStream::TokenStream(Utf8Stream & stream) : stream_(stream) { } void TokenStream::scan() { token.reset(); int c; do { c = stream_.getc(); } while (is_ws(c)); if (c == int(Utf8Stream::SEOF)) { return; } if (stream_.state() == Utf8Stream::SBAD) { return; } try { (this->*select_scanner(c))(); } catch (std::runtime_error const& e) { throw; } } TokenStream::scanner TokenStream::select_scanner(int c) { scanner res(0); switch (c) { case '[': case '{': case ']': case '}': case ':': case ',': res = &TokenStream::scan_structural; break; case 't': res = &TokenStream::scan_true; break; case 'n': res = &TokenStream::scan_null; break; case 'f': res = &TokenStream::scan_false; break; case '"': res = &TokenStream::scan_string; break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c = '0'; stream_.ungetc(); res = &TokenStream::scan_number; break; default: c = 0; res = &TokenStream::invalid_token; break; } token.type = Token::Type(c); return res; } void TokenStream::invalid_token() { throw std::runtime_error("invalid token"); } void TokenStream::scan_structural() { /* NOOP */ } void TokenStream::scan_true() { scan_literal("true"); } void TokenStream::scan_false() { scan_literal("false"); } void TokenStream::scan_null() { scan_literal("null"); } void TokenStream::scan_literal(const char *literal) { for (const char *p(&literal[1]); *p; p++) { if (stream_.getc() != *p) { throw std::runtime_error(literal); } } } enum StringState { SREGULAR, SESCAPED, SUESCAPE, SDONES, // errors SREGULAR_INVALID, SESCAPED_INVALID, SUESCAPE_INVALID, SUESCAPE_SURROGATE, SUNTERMINATED, SZERO, }; StringState scan_regular(int c, std::string & str) { if (c == '"') { return SDONES; } else if (c == '\\') { return SESCAPED; } else if (c >= 0x0000 && c <= 0x001F) { // control char must be escaped return SREGULAR_INVALID; } str.push_back(c); return SREGULAR; } StringState scan_escaped(int c, std::string & str) { switch (c) { case '\\': case '/': case '"': break; case 'b': c = 0x0008; break; case 'f': c = 0x000C; break; case 'n': c = 0x000A; break; case 'r': c = 0x000D; break; case 't': c = 0x0009; break; case 'u': return SUESCAPE; default: // invalid escape char return SESCAPED_INVALID; } str.push_back(c); return SREGULAR; } struct UEscape { public: UEscape() : count_(0), value_(0) { } StringState scan(int c, std::string & str) { value_ *= 0x10; if (c >= '0' && c <= '9') { value_ += c - '0'; } else if (c >= 'a' && c <= 'f') { value_ += 0x0a + c - 'a'; } else if (c >= 'A' && c <= 'F') { value_ += 0x0a + c - 'A'; } else { return SUESCAPE_INVALID; } if (++count_ == 4) { StringState res(utf8encode(str)); count_ = value_ = 0; return res; } return SUESCAPE; } private: StringState utf8encode(std::string & str) const { if (value_ == 0x0000) { // ASCII 0 return SZERO; } else if (value_ <= 0x007f) { str.push_back(value_); } else if (value_ <= 0x07ff) { str.push_back(0xc0 | (value_ >> 6)); str.push_back(0x80 | (value_ & 0x3f)); } else if (value_ >= 0xd800 && value_ <= 0xdfff) { // utf16 surrogate return SUESCAPE_SURROGATE; } else { str.push_back(0xe0 | (value_ >> 12)); str.push_back(0x80 | ((value_ >> 6) & 0x3f)); str.push_back(0x80 | (value_ & 0x3f)); } return SREGULAR; } size_t count_; uint16_t value_; }; void TokenStream::scan_string() { StringState state(SREGULAR); UEscape unicode; while (state != SDONES) { int c(stream_.getc()); if (stream_.state() != Utf8Stream::SGOOD) { // unterminated string state = SUNTERMINATED; } switch (state) { case SREGULAR: state = scan_regular(c, token.str_value); break; case SESCAPED: state = scan_escaped(c, token.str_value); break; case SUESCAPE: state = unicode.scan(c, token.str_value); break; case SREGULAR_INVALID: case SESCAPED_INVALID: case SUESCAPE_INVALID: case SUESCAPE_SURROGATE: case SUNTERMINATED: case SZERO: token.reset(); return; case SDONES: break; } } } bool make_int(const char *str, int64_t *res) { errno = 0; char *endp(0); *res = strtoll(str, &endp, 10); if (*endp != '\0') { return false; } if (errno != 0) { return false; } return true; } bool make_float(const char *str, long double *res) { errno = 0; char *endp(0); AutoLocale lc("C"); *res = strtold(str, &endp); if (*endp != '\0') { return false; } if (errno != 0) { return false; } return true; } enum NumberState { SSTART = 0, SMINUS, SINT_ZERO, SINT_DIGIT, SINT_DIGIT19, SDEC_POINT, SFRAC_DIGIT, SE, SE_PLUS, SE_MINUS, SE_DIGIT, SDONE, SERROR, }; NumberState number_state(int c, NumberState state) { #define DIGIT19 "123456789" #define DIGIT "0" DIGIT19 struct { const char *match; NumberState state; } transitions[][4] = { /* SSTART */ {{"-", SMINUS}, {"0", SINT_ZERO}, {DIGIT19, SINT_DIGIT19}, {0, SERROR}}, /* SMINUS */ { {"0", SINT_ZERO}, {DIGIT19, SINT_DIGIT19}, {0, SERROR}}, /* SINT_ZERO */ {{"eE", SE}, {".", SDEC_POINT}, {0, SDONE} }, /* SINT_DIGIT */ {{"eE", SE}, {".", SDEC_POINT}, {DIGIT, SINT_DIGIT}, {0, SDONE} }, /* SINT_DIGIT19 */ {{"eE", SE}, {".", SDEC_POINT}, {DIGIT, SINT_DIGIT}, {0, SDONE} }, /* SDEC_POINT */ {{"eE", SE}, {DIGIT, SFRAC_DIGIT}, {0, SERROR}}, /* SFRAC_DIGIT */ {{"eE", SE}, {DIGIT, SFRAC_DIGIT}, {0, SDONE} }, /* SE */ {{"-", SE_MINUS}, {"+", SE_PLUS}, {DIGIT, SE_DIGIT}, {0, SERROR}}, /* SE_PLUS */ { {DIGIT, SE_DIGIT}, {0, SERROR}}, /* SE_MINUS */ { {DIGIT, SE_DIGIT}, {0, SERROR}}, /* SE_DIGIT */ { {DIGIT, SE_DIGIT}, {0, SDONE} }, }; for (size_t t(0); true; ++t) { const char *match(transitions[state][t].match); if (!match || strchr(match, c)) { return transitions[state][t].state; } } return SERROR; } Token::NumberType validate_number(Utf8Stream & stream, char *buf, size_t size) { NumberState state(SSTART); Token::NumberType res(Token::INT); size_t i(0); for (;;) { int c(stream.getc()); state = number_state(c, state); switch (state) { case SSTART: break; case SDEC_POINT: case SE: res = Token::FLOAT; // fallthrough case SMINUS: case SINT_ZERO: case SINT_DIGIT: case SINT_DIGIT19: case SFRAC_DIGIT: case SE_MINUS: case SE_PLUS: case SE_DIGIT: buf[i] = c; if (++i == size) { buf[i - 1] = '\0'; return Token::NONE; } break; case SERROR: res = Token::NONE; // fallthrough case SDONE: buf[i] = '\0'; stream.ungetc(); return res; } } return Token::NONE; } void TokenStream::scan_number() { char buf[1024]; token.number_type = validate_number(stream_, buf, sizeof(buf)); switch (token.number_type) { case Token::INT: if (!make_int(buf, &token.int_value)) { token.reset(); return; } break; case Token::FLOAT: if (!make_float(buf, &token.float_value)) { token.reset(); return; } break; case Token::NONE: token.reset(); break; } } } <commit_msg>TokenStream: stop if Utf8Stream is bad<commit_after>/* Copyright (c) 2015, Andreas Fett. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <errno.h> #include <cstdlib> #include <cstring> #include <ostream> #include <stdexcept> #include "auto-locale.h" #include "token-stream.h" #include "utf8stream.h" namespace { bool is_ws(int c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } } namespace jsonp { // LCOV_EXCL_START std::ostream & operator<<(std::ostream & os, Token::Type type) { #define CASE_TOKEN_TYPE(name) case name: os << # name; break switch (type) { CASE_TOKEN_TYPE(Token::INVALID); CASE_TOKEN_TYPE(Token::BEGIN_ARRAY); CASE_TOKEN_TYPE(Token::END_ARRAY); CASE_TOKEN_TYPE(Token::BEGIN_OBJECT); CASE_TOKEN_TYPE(Token::END_OBJECT); CASE_TOKEN_TYPE(Token::NAME_SEPARATOR); CASE_TOKEN_TYPE(Token::VALUE_SEPARATOR); CASE_TOKEN_TYPE(Token::TRUE_LITERAL); CASE_TOKEN_TYPE(Token::FALSE_LITERAL); CASE_TOKEN_TYPE(Token::NULL_LITERAL); CASE_TOKEN_TYPE(Token::STRING); CASE_TOKEN_TYPE(Token::NUMBER); } #undef CASE_TOKEN_TYPE return os; } // LCOV_EXCL_STOP TokenStream::TokenStream(Utf8Stream & stream) : stream_(stream) { } void TokenStream::scan() { if (stream_.state() == Utf8Stream::SBAD) { return; } token.reset(); int c; do { c = stream_.getc(); } while (is_ws(c)); if (c == int(Utf8Stream::SEOF)) { return; } if (stream_.state() == Utf8Stream::SBAD) { return; } try { (this->*select_scanner(c))(); } catch (std::runtime_error const& e) { throw; } } TokenStream::scanner TokenStream::select_scanner(int c) { scanner res(0); switch (c) { case '[': case '{': case ']': case '}': case ':': case ',': res = &TokenStream::scan_structural; break; case 't': res = &TokenStream::scan_true; break; case 'n': res = &TokenStream::scan_null; break; case 'f': res = &TokenStream::scan_false; break; case '"': res = &TokenStream::scan_string; break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c = '0'; stream_.ungetc(); res = &TokenStream::scan_number; break; default: c = 0; res = &TokenStream::invalid_token; break; } token.type = Token::Type(c); return res; } void TokenStream::invalid_token() { throw std::runtime_error("invalid token"); } void TokenStream::scan_structural() { /* NOOP */ } void TokenStream::scan_true() { scan_literal("true"); } void TokenStream::scan_false() { scan_literal("false"); } void TokenStream::scan_null() { scan_literal("null"); } void TokenStream::scan_literal(const char *literal) { for (const char *p(&literal[1]); *p; p++) { if (stream_.getc() != *p) { throw std::runtime_error(literal); } } } enum StringState { SREGULAR, SESCAPED, SUESCAPE, SDONES, // errors SREGULAR_INVALID, SESCAPED_INVALID, SUESCAPE_INVALID, SUESCAPE_SURROGATE, SUNTERMINATED, SZERO, }; StringState scan_regular(int c, std::string & str) { if (c == '"') { return SDONES; } else if (c == '\\') { return SESCAPED; } else if (c >= 0x0000 && c <= 0x001F) { // control char must be escaped return SREGULAR_INVALID; } str.push_back(c); return SREGULAR; } StringState scan_escaped(int c, std::string & str) { switch (c) { case '\\': case '/': case '"': break; case 'b': c = 0x0008; break; case 'f': c = 0x000C; break; case 'n': c = 0x000A; break; case 'r': c = 0x000D; break; case 't': c = 0x0009; break; case 'u': return SUESCAPE; default: // invalid escape char return SESCAPED_INVALID; } str.push_back(c); return SREGULAR; } struct UEscape { public: UEscape() : count_(0), value_(0) { } StringState scan(int c, std::string & str) { value_ *= 0x10; if (c >= '0' && c <= '9') { value_ += c - '0'; } else if (c >= 'a' && c <= 'f') { value_ += 0x0a + c - 'a'; } else if (c >= 'A' && c <= 'F') { value_ += 0x0a + c - 'A'; } else { return SUESCAPE_INVALID; } if (++count_ == 4) { StringState res(utf8encode(str)); count_ = value_ = 0; return res; } return SUESCAPE; } private: StringState utf8encode(std::string & str) const { if (value_ == 0x0000) { // ASCII 0 return SZERO; } else if (value_ <= 0x007f) { str.push_back(value_); } else if (value_ <= 0x07ff) { str.push_back(0xc0 | (value_ >> 6)); str.push_back(0x80 | (value_ & 0x3f)); } else if (value_ >= 0xd800 && value_ <= 0xdfff) { // utf16 surrogate return SUESCAPE_SURROGATE; } else { str.push_back(0xe0 | (value_ >> 12)); str.push_back(0x80 | ((value_ >> 6) & 0x3f)); str.push_back(0x80 | (value_ & 0x3f)); } return SREGULAR; } size_t count_; uint16_t value_; }; void TokenStream::scan_string() { StringState state(SREGULAR); UEscape unicode; while (state != SDONES) { int c(stream_.getc()); if (stream_.state() != Utf8Stream::SGOOD) { // unterminated string state = SUNTERMINATED; } switch (state) { case SREGULAR: state = scan_regular(c, token.str_value); break; case SESCAPED: state = scan_escaped(c, token.str_value); break; case SUESCAPE: state = unicode.scan(c, token.str_value); break; case SREGULAR_INVALID: case SESCAPED_INVALID: case SUESCAPE_INVALID: case SUESCAPE_SURROGATE: case SUNTERMINATED: case SZERO: token.reset(); return; case SDONES: break; } } } bool make_int(const char *str, int64_t *res) { errno = 0; char *endp(0); *res = strtoll(str, &endp, 10); if (*endp != '\0') { return false; } if (errno != 0) { return false; } return true; } bool make_float(const char *str, long double *res) { errno = 0; char *endp(0); AutoLocale lc("C"); *res = strtold(str, &endp); if (*endp != '\0') { return false; } if (errno != 0) { return false; } return true; } enum NumberState { SSTART = 0, SMINUS, SINT_ZERO, SINT_DIGIT, SINT_DIGIT19, SDEC_POINT, SFRAC_DIGIT, SE, SE_PLUS, SE_MINUS, SE_DIGIT, SDONE, SERROR, }; NumberState number_state(int c, NumberState state) { #define DIGIT19 "123456789" #define DIGIT "0" DIGIT19 struct { const char *match; NumberState state; } transitions[][4] = { /* SSTART */ {{"-", SMINUS}, {"0", SINT_ZERO}, {DIGIT19, SINT_DIGIT19}, {0, SERROR}}, /* SMINUS */ { {"0", SINT_ZERO}, {DIGIT19, SINT_DIGIT19}, {0, SERROR}}, /* SINT_ZERO */ {{"eE", SE}, {".", SDEC_POINT}, {0, SDONE} }, /* SINT_DIGIT */ {{"eE", SE}, {".", SDEC_POINT}, {DIGIT, SINT_DIGIT}, {0, SDONE} }, /* SINT_DIGIT19 */ {{"eE", SE}, {".", SDEC_POINT}, {DIGIT, SINT_DIGIT}, {0, SDONE} }, /* SDEC_POINT */ {{"eE", SE}, {DIGIT, SFRAC_DIGIT}, {0, SERROR}}, /* SFRAC_DIGIT */ {{"eE", SE}, {DIGIT, SFRAC_DIGIT}, {0, SDONE} }, /* SE */ {{"-", SE_MINUS}, {"+", SE_PLUS}, {DIGIT, SE_DIGIT}, {0, SERROR}}, /* SE_PLUS */ { {DIGIT, SE_DIGIT}, {0, SERROR}}, /* SE_MINUS */ { {DIGIT, SE_DIGIT}, {0, SERROR}}, /* SE_DIGIT */ { {DIGIT, SE_DIGIT}, {0, SDONE} }, }; for (size_t t(0); true; ++t) { const char *match(transitions[state][t].match); if (!match || strchr(match, c)) { return transitions[state][t].state; } } return SERROR; } Token::NumberType validate_number(Utf8Stream & stream, char *buf, size_t size) { NumberState state(SSTART); Token::NumberType res(Token::INT); size_t i(0); for (;;) { int c(stream.getc()); state = number_state(c, state); switch (state) { case SSTART: break; case SDEC_POINT: case SE: res = Token::FLOAT; // fallthrough case SMINUS: case SINT_ZERO: case SINT_DIGIT: case SINT_DIGIT19: case SFRAC_DIGIT: case SE_MINUS: case SE_PLUS: case SE_DIGIT: buf[i] = c; if (++i == size) { buf[i - 1] = '\0'; return Token::NONE; } break; case SERROR: res = Token::NONE; // fallthrough case SDONE: buf[i] = '\0'; stream.ungetc(); return res; } } return Token::NONE; } void TokenStream::scan_number() { char buf[1024]; token.number_type = validate_number(stream_, buf, sizeof(buf)); switch (token.number_type) { case Token::INT: if (!make_int(buf, &token.int_value)) { token.reset(); return; } break; case Token::FLOAT: if (!make_float(buf, &token.float_value)) { token.reset(); return; } break; case Token::NONE: token.reset(); break; } } } <|endoftext|>
<commit_before>#include "constant_buffer.h" #include <malloc.h> #include <memory> #include <d3d11.h> #include <wrl.h> #include <dxfw/dxfw.h> #include "core/resource_array.h" #include "core/handle_cache.h" namespace Rendering { namespace ConstantBuffer { struct ConstantBufferGpuBufferTag {}; using GpuBufferHandle = Core::Handle<8, 24, ConstantBufferGpuBufferTag>; struct GpuStorage { public: GpuStorage() = default; ~GpuStorage() = default; GpuStorage(const GpuStorage&) = delete; GpuStorage& operator=(const GpuStorage&) = delete; GpuStorage(GpuStorage&&) = default; GpuStorage& operator=(GpuStorage&&) = default; bool Initialize(size_t size, void* initial_data, ID3D11Device* device) { D3D11_BUFFER_DESC desc; desc.ByteWidth = size; desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; desc.StructureByteStride = 0; HRESULT cb_result; if (initial_data != nullptr) { D3D11_SUBRESOURCE_DATA data; data.pSysMem = initial_data; data.SysMemPitch = 0; data.SysMemSlicePitch = 0; cb_result = device->CreateBuffer(&desc, &data, m_gpu_buffer_.GetAddressOf()); } else { cb_result = device->CreateBuffer(&desc, nullptr, m_gpu_buffer_.GetAddressOf()); } if (FAILED(cb_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, true, cb_result); return false; } return true; } Microsoft::WRL::ComPtr<ID3D11Buffer> GetGpuBuffer() { return m_gpu_buffer_; } bool SendToGpu(void* data, size_t size, ID3D11DeviceContext* device_context) { if (data == nullptr) { return false; } D3D11_MAPPED_SUBRESOURCE mapped_subresource; auto map_result = device_context->Map(m_gpu_buffer_.Get(), 0, D3D11_MAP::D3D11_MAP_WRITE_DISCARD, 0, &mapped_subresource); if (FAILED(map_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, true, map_result); return false; } memcpy(mapped_subresource.pData, data, size); device_context->Unmap(m_gpu_buffer_.Get(), 0); return true; } private: Microsoft::WRL::ComPtr<ID3D11Buffer> m_gpu_buffer_ = {}; }; struct CpuStorage { public: CpuStorage(size_t size, size_t align, void* initial_data, GpuBufferHandle handle) : m_size_(size), m_align_(align), m_cpu_buffer_(_aligned_malloc(size, align)), m_gpu_handle_(handle) { if (initial_data != nullptr) { std::memcpy(m_cpu_buffer_.get(), initial_data, m_size_); } } ~CpuStorage() = default; CpuStorage(const CpuStorage&) = delete; CpuStorage& operator=(const CpuStorage&) = delete; CpuStorage(CpuStorage&&) = default; CpuStorage& operator=(CpuStorage&&) = default; size_t GetSize() const { return m_size_; } size_t GetAlign() const { return m_align_; } void* GetCpuBuffer() const { return m_cpu_buffer_.get(); } GpuBufferHandle GetGpuBufferHandle() const { return m_gpu_handle_; } private: struct CpuBufferDeleter { void operator()(void* ptr) { _aligned_free(ptr); } }; size_t m_size_ = 0; size_t m_align_ = 0; std::unique_ptr<void, CpuBufferDeleter> m_cpu_buffer_ = {}; GpuBufferHandle m_gpu_handle_; }; Core::ResourceArray<GpuBufferHandle, GpuStorage, 255> g_gpu_storage_; Core::HandleCache<size_t, GpuBufferHandle> g_gpu_cache_; Core::ResourceArray<Handle, CpuStorage, 255> g_cpu_storage_; Core::HandleCache<size_t, Handle> g_cpu_cache_; GpuBufferHandle CreateGpuBuffer(size_t name_hash, size_t type_hash, size_t type_size, void* initial_data, ID3D11Device* device) { auto cache_key = name_hash; hash_combine(cache_key, type_hash); auto cached_handle = g_gpu_cache_.Get(cache_key); if (cached_handle.IsValid()) { return cached_handle; } GpuStorage storage; bool init_ok = storage.Initialize(type_size, initial_data, device); if (!init_ok) { return {}; } auto new_handle = g_gpu_storage_.Add(std::move(storage)); g_gpu_cache_.Set(cache_key, new_handle); return new_handle; } Handle Create(size_t cpu_name_hash, size_t gpu_name_hash, size_t type_hash, size_t type_size, size_t type_alignment, void* initial_data, ID3D11Device* device) { auto cache_key = cpu_name_hash; hash_combine(cache_key, type_hash); auto cached_handle = g_cpu_cache_.Get(cache_key); if (cached_handle.IsValid()) { return cached_handle; } auto gpu_handle = CreateGpuBuffer(gpu_name_hash, type_hash, type_size, initial_data, device); CpuStorage storage(type_size, type_alignment, initial_data, gpu_handle); auto new_handle = g_cpu_storage_.Add(std::move(storage)); g_cpu_cache_.Set(cache_key, new_handle); return new_handle; } Handle Create(const std::string& cpu_name, const std::string& gpu_name, size_t type_hash, size_t type_size, size_t type_alignment, void* initial_data, ID3D11Device* device) { std::hash<std::string> hasher; return Create(hasher(cpu_name), hasher(gpu_name), type_hash, type_size, type_alignment, initial_data, device); } Handle Create(size_t name_hash, size_t type_hash, size_t type_size, size_t type_alignment, void* initial_data, ID3D11Device* device) { return Create(name_hash, name_hash, type_hash, type_size, type_alignment, initial_data, device); } Handle Create(const std::string& name, size_t type_hash, size_t type_size, size_t type_alignment, void* initial_data, ID3D11Device* device) { std::hash<std::string> hasher; return Create(hasher(name), type_hash, type_size, type_alignment, initial_data, device); } void* GetCpuBuffer(Handle handle) { return g_cpu_storage_.Get(handle).GetCpuBuffer(); } Microsoft::WRL::ComPtr<ID3D11Buffer> GetGpuBuffer(Handle handle) { auto gpu_handle = g_cpu_storage_.Get(handle).GetGpuBufferHandle(); return g_gpu_storage_.Get(gpu_handle).GetGpuBuffer(); } bool SendToGpu(Handle handle, ID3D11DeviceContext* device_context) { auto& cpu_storage = g_cpu_storage_.Get(handle); auto size = cpu_storage.GetSize(); auto data = cpu_storage.GetCpuBuffer(); auto gpu_handle = cpu_storage.GetGpuBufferHandle(); return g_gpu_storage_.Get(gpu_handle).SendToGpu(data, size, device_context); } } // namespace ConstantBuffer } // namespace Rendering<commit_msg>Use buffer as a backing for the constant buffer storage<commit_after>#include "constant_buffer.h" #include <malloc.h> #include <memory> #include <d3d11.h> #include <wrl.h> #include <dxfw/dxfw.h> #include "core/buffer.h" #include "core/resource_array.h" #include "core/handle_cache.h" namespace Rendering { namespace ConstantBuffer { struct ConstantBufferGpuBufferTag {}; using GpuBufferHandle = Core::Handle<8, 24, ConstantBufferGpuBufferTag>; struct GpuStorage { public: GpuStorage() = default; ~GpuStorage() = default; GpuStorage(const GpuStorage&) = delete; GpuStorage& operator=(const GpuStorage&) = delete; GpuStorage(GpuStorage&&) = default; GpuStorage& operator=(GpuStorage&&) = default; bool Initialize(size_t size, void* initial_data, ID3D11Device* device) { D3D11_BUFFER_DESC desc; desc.ByteWidth = size; desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; desc.StructureByteStride = 0; HRESULT cb_result; if (initial_data != nullptr) { D3D11_SUBRESOURCE_DATA data; data.pSysMem = initial_data; data.SysMemPitch = 0; data.SysMemSlicePitch = 0; cb_result = device->CreateBuffer(&desc, &data, m_gpu_buffer_.GetAddressOf()); } else { cb_result = device->CreateBuffer(&desc, nullptr, m_gpu_buffer_.GetAddressOf()); } if (FAILED(cb_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, true, cb_result); return false; } return true; } Microsoft::WRL::ComPtr<ID3D11Buffer> GetGpuBuffer() { return m_gpu_buffer_; } bool SendToGpu(void* data, size_t size, ID3D11DeviceContext* device_context) { if (data == nullptr) { return false; } D3D11_MAPPED_SUBRESOURCE mapped_subresource; auto map_result = device_context->Map(m_gpu_buffer_.Get(), 0, D3D11_MAP::D3D11_MAP_WRITE_DISCARD, 0, &mapped_subresource); if (FAILED(map_result)) { DXFW_DIRECTX_TRACE(__FILE__, __LINE__, true, map_result); return false; } memcpy(mapped_subresource.pData, data, size); device_context->Unmap(m_gpu_buffer_.Get(), 0); return true; } private: Microsoft::WRL::ComPtr<ID3D11Buffer> m_gpu_buffer_ = {}; }; struct CpuStorage { public: CpuStorage(size_t size, size_t align, void* initial_data, GpuBufferHandle handle) : m_buffer_(size, align, initial_data), m_gpu_handle_(handle) { } ~CpuStorage() = default; CpuStorage(const CpuStorage&) = delete; CpuStorage& operator=(const CpuStorage&) = delete; CpuStorage(CpuStorage&&) = default; CpuStorage& operator=(CpuStorage&&) = default; size_t GetSize() const { return m_buffer_.GetSize(); } size_t GetAlign() const { return m_buffer_.GetAlign(); } void* GetCpuBuffer() const { return m_buffer_.GetBuffer(); } GpuBufferHandle GetGpuBufferHandle() const { return m_gpu_handle_; } private: Core::Buffer m_buffer_; GpuBufferHandle m_gpu_handle_; }; Core::ResourceArray<GpuBufferHandle, GpuStorage, 255> g_gpu_storage_; Core::HandleCache<size_t, GpuBufferHandle> g_gpu_cache_; Core::ResourceArray<Handle, CpuStorage, 255> g_cpu_storage_; Core::HandleCache<size_t, Handle> g_cpu_cache_; GpuBufferHandle CreateGpuBuffer(size_t name_hash, size_t type_hash, size_t type_size, void* initial_data, ID3D11Device* device) { auto cache_key = name_hash; hash_combine(cache_key, type_hash); auto cached_handle = g_gpu_cache_.Get(cache_key); if (cached_handle.IsValid()) { return cached_handle; } GpuStorage storage; bool init_ok = storage.Initialize(type_size, initial_data, device); if (!init_ok) { return {}; } auto new_handle = g_gpu_storage_.Add(std::move(storage)); g_gpu_cache_.Set(cache_key, new_handle); return new_handle; } Handle Create(size_t cpu_name_hash, size_t gpu_name_hash, size_t type_hash, size_t type_size, size_t type_alignment, void* initial_data, ID3D11Device* device) { auto cache_key = cpu_name_hash; hash_combine(cache_key, type_hash); auto cached_handle = g_cpu_cache_.Get(cache_key); if (cached_handle.IsValid()) { return cached_handle; } auto gpu_handle = CreateGpuBuffer(gpu_name_hash, type_hash, type_size, initial_data, device); CpuStorage storage(type_size, type_alignment, initial_data, gpu_handle); auto new_handle = g_cpu_storage_.Add(std::move(storage)); g_cpu_cache_.Set(cache_key, new_handle); return new_handle; } Handle Create(const std::string& cpu_name, const std::string& gpu_name, size_t type_hash, size_t type_size, size_t type_alignment, void* initial_data, ID3D11Device* device) { std::hash<std::string> hasher; return Create(hasher(cpu_name), hasher(gpu_name), type_hash, type_size, type_alignment, initial_data, device); } Handle Create(size_t name_hash, size_t type_hash, size_t type_size, size_t type_alignment, void* initial_data, ID3D11Device* device) { return Create(name_hash, name_hash, type_hash, type_size, type_alignment, initial_data, device); } Handle Create(const std::string& name, size_t type_hash, size_t type_size, size_t type_alignment, void* initial_data, ID3D11Device* device) { std::hash<std::string> hasher; return Create(hasher(name), type_hash, type_size, type_alignment, initial_data, device); } void* GetCpuBuffer(Handle handle) { return g_cpu_storage_.Get(handle).GetCpuBuffer(); } Microsoft::WRL::ComPtr<ID3D11Buffer> GetGpuBuffer(Handle handle) { auto gpu_handle = g_cpu_storage_.Get(handle).GetGpuBufferHandle(); return g_gpu_storage_.Get(gpu_handle).GetGpuBuffer(); } bool SendToGpu(Handle handle, ID3D11DeviceContext* device_context) { auto& cpu_storage = g_cpu_storage_.Get(handle); auto size = cpu_storage.GetSize(); auto data = cpu_storage.GetCpuBuffer(); auto gpu_handle = cpu_storage.GetGpuBufferHandle(); return g_gpu_storage_.Get(gpu_handle).SendToGpu(data, size, device_context); } } // namespace ConstantBuffer } // namespace Rendering<|endoftext|>
<commit_before>/** * A Node.js (and io.js and NW.js) binding for Csound. This interface should * mirror the Csound JavaScript interface for the Chromium Embedded Framework * and Android. In JavaScript environments, Csound has already been * instantiated and initialized, and is named "csound" in the default * JavaScript context. * * int getVersion () * void compileOrc (String orchestracode) * double evalCode (String orchestracode) * void readScore (String scorelines) * void setControlChannel (String channelName, double value) * double getControlChannel (String channelName) * void message (String text) * int getSr () * int getKsmps () * int getNchnls () * int isPlaying () * * Copyright (C) 2015 by Michael Gogins. * * This software 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Must do this on Windows: https://connect.microsoft.com/VisualStudio/feedback/details/811347/compiling-vc-12-0-with-has-exceptions-0-and-including-concrt-h-causes-a-compiler-error #include <csound.h> #include <node.h> #include <string> #include <thread> #include <v8.h> using namespace v8; void Method(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world")); } void init(Handle<Object> target) { NODE_SET_METHOD(target, "This is Csound!", Method); } NODE_MODULE(binding, init); <commit_msg>Test actual instantiation of Csound.<commit_after>/** * A Node.js (and io.js and NW.js) binding for Csound. This interface should * mirror the Csound JavaScript interface for the Chromium Embedded Framework * and Android. In JavaScript environments, Csound has already been * instantiated and initialized, and is named "csound" in the user's * JavaScript context. * * int getVersion () * void compileOrc (String orchestracode) * double evalCode (String orchestracode) * void readScore (String scorelines) * void setControlChannel (String channelName, double value) * double getControlChannel (String channelName) * void message (String text) * int getSr () * int getKsmps () * int getNchnls () * int isPlaying () * * Copyright (C) 2015 by Michael Gogins. * * This software 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Must do this on Windows: https://connect.microsoft.com/VisualStudio/feedback/details/811347/compiling-vc-12-0-with-has-exceptions-0-and-including-concrt-h-causes-a-compiler-error #include <csound.h> #include <node.h> #include <string> #include <thread> #include <v8.h> using namespace v8; static CSOUND* csound = nullptr; void Method(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); char buffer[0x100]; std::sprintf(buffer, "Hello, world! This is Csound 0x%p.", csound); args.GetReturnValue().Set(String::NewFromUtf8(isolate, buffer)); } void init(Handle<Object> target) { csound = csoundCreate(0); NODE_SET_METHOD(target, "hello", Method); } NODE_MODULE(binding, init); <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include <assert.h> #include "webrtc/base/win32.h" #include "webrtc/modules/desktop_capture/desktop_frame_win.h" #include "webrtc/modules/desktop_capture/win/window_capture_utils.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { namespace { typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled); BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) { WindowCapturer::WindowList* list = reinterpret_cast<WindowCapturer::WindowList*>(param); // Skip windows that are invisible, minimized, have no title, or are owned, // unless they have the app window style set. int len = GetWindowTextLength(hwnd); HWND owner = GetWindow(hwnd, GW_OWNER); LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) || (owner && !(exstyle & WS_EX_APPWINDOW))) { return TRUE; } // Skip the Program Manager window and the Start button. const size_t kClassLength = 256; WCHAR class_name[kClassLength]; GetClassName(hwnd, class_name, kClassLength); // Skip Program Manager window and the Start button. This is the same logic // that's used in Win32WindowPicker in libjingle. Consider filtering other // windows as well (e.g. toolbars). if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0) return TRUE; WindowCapturer::Window window; window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd); const size_t kTitleLength = 500; WCHAR window_title[kTitleLength]; // Truncate the title if it's longer than kTitleLength. GetWindowText(hwnd, window_title, kTitleLength); window.title = rtc::ToUtf8(window_title); // Skip windows when we failed to convert the title or it is empty. if (window.title.empty()) return TRUE; list->push_back(window); return TRUE; } class WindowCapturerWin : public WindowCapturer { public: WindowCapturerWin(); virtual ~WindowCapturerWin(); // WindowCapturer interface. virtual bool GetWindowList(WindowList* windows) OVERRIDE; virtual bool SelectWindow(WindowId id) OVERRIDE; virtual bool BringSelectedWindowToFront() OVERRIDE; // DesktopCapturer interface. virtual void Start(Callback* callback) OVERRIDE; virtual void Capture(const DesktopRegion& region) OVERRIDE; private: bool IsAeroEnabled(); Callback* callback_; // HWND and HDC for the currently selected window or NULL if window is not // selected. HWND window_; // dwmapi.dll is used to determine if desktop compositing is enabled. HMODULE dwmapi_library_; DwmIsCompositionEnabledFunc is_composition_enabled_func_; DesktopSize previous_size_; DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin); }; WindowCapturerWin::WindowCapturerWin() : callback_(NULL), window_(NULL) { // Try to load dwmapi.dll dynamically since it is not available on XP. dwmapi_library_ = LoadLibrary(L"dwmapi.dll"); if (dwmapi_library_) { is_composition_enabled_func_ = reinterpret_cast<DwmIsCompositionEnabledFunc>( GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled")); assert(is_composition_enabled_func_); } else { is_composition_enabled_func_ = NULL; } } WindowCapturerWin::~WindowCapturerWin() { if (dwmapi_library_) FreeLibrary(dwmapi_library_); } bool WindowCapturerWin::IsAeroEnabled() { BOOL result = FALSE; if (is_composition_enabled_func_) is_composition_enabled_func_(&result); return result != FALSE; } bool WindowCapturerWin::GetWindowList(WindowList* windows) { WindowList result; LPARAM param = reinterpret_cast<LPARAM>(&result); if (!EnumWindows(&WindowsEnumerationHandler, param)) return false; windows->swap(result); return true; } bool WindowCapturerWin::SelectWindow(WindowId id) { HWND window = reinterpret_cast<HWND>(id); if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window)) return false; window_ = window; previous_size_.set(0, 0); return true; } bool WindowCapturerWin::BringSelectedWindowToFront() { if (!window_) return false; if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_)) return false; return SetForegroundWindow(window_) != 0; } void WindowCapturerWin::Start(Callback* callback) { assert(!callback_); assert(callback); callback_ = callback; } void WindowCapturerWin::Capture(const DesktopRegion& region) { if (!window_) { LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } // Stop capturing if the window has been closed or hidden. if (!IsWindow(window_) || !IsWindowVisible(window_)) { callback_->OnCaptureCompleted(NULL); return; } DesktopRect original_rect; DesktopRect cropped_rect; if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) { LOG(LS_WARNING) << "Failed to get window info: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } HDC window_dc = GetWindowDC(window_); if (!window_dc) { LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create( cropped_rect.size(), NULL, window_dc)); if (!frame.get()) { ReleaseDC(window_, window_dc); callback_->OnCaptureCompleted(NULL); return; } HDC mem_dc = CreateCompatibleDC(window_dc); HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap()); BOOL result = FALSE; // When desktop composition (Aero) is enabled each window is rendered to a // private buffer allowing BitBlt() to get the window content even if the // window is occluded. PrintWindow() is slower but lets rendering the window // contents to an off-screen device context when Aero is not available. // PrintWindow() is not supported by some applications. // // If Aero is enabled, we prefer BitBlt() because it's faster and avoids // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may // render occluding windows on top of the desired window. // // When composition is enabled the DC returned by GetWindowDC() doesn't always // have window frame rendered correctly. Windows renders it only once and then // caches the result between captures. We hack it around by calling // PrintWindow() whenever window size changes, including the first time of // capturing - it somehow affects what we get from BitBlt() on the subsequent // captures. if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) { result = PrintWindow(window_, mem_dc, 0); } // Aero is enabled or PrintWindow() failed, use BitBlt. if (!result) { result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(), window_dc, cropped_rect.left() - original_rect.left(), cropped_rect.top() - original_rect.top(), SRCCOPY); } SelectObject(mem_dc, previous_object); DeleteDC(mem_dc); ReleaseDC(window_, window_dc); previous_size_ = frame->size(); frame->mutable_updated_region()->SetRect( DesktopRect::MakeSize(frame->size())); if (!result) { LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed."; frame.reset(); } callback_->OnCaptureCompleted(frame.release()); } } // namespace // static WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) { return new WindowCapturerWin(); } } // namespace webrtc <commit_msg>Fix window capturing on Windows when the window is minimized.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include <assert.h> #include "webrtc/base/win32.h" #include "webrtc/modules/desktop_capture/desktop_frame_win.h" #include "webrtc/modules/desktop_capture/win/window_capture_utils.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { namespace { typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled); BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) { WindowCapturer::WindowList* list = reinterpret_cast<WindowCapturer::WindowList*>(param); // Skip windows that are invisible, minimized, have no title, or are owned, // unless they have the app window style set. int len = GetWindowTextLength(hwnd); HWND owner = GetWindow(hwnd, GW_OWNER); LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) || (owner && !(exstyle & WS_EX_APPWINDOW))) { return TRUE; } // Skip the Program Manager window and the Start button. const size_t kClassLength = 256; WCHAR class_name[kClassLength]; GetClassName(hwnd, class_name, kClassLength); // Skip Program Manager window and the Start button. This is the same logic // that's used in Win32WindowPicker in libjingle. Consider filtering other // windows as well (e.g. toolbars). if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0) return TRUE; WindowCapturer::Window window; window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd); const size_t kTitleLength = 500; WCHAR window_title[kTitleLength]; // Truncate the title if it's longer than kTitleLength. GetWindowText(hwnd, window_title, kTitleLength); window.title = rtc::ToUtf8(window_title); // Skip windows when we failed to convert the title or it is empty. if (window.title.empty()) return TRUE; list->push_back(window); return TRUE; } class WindowCapturerWin : public WindowCapturer { public: WindowCapturerWin(); virtual ~WindowCapturerWin(); // WindowCapturer interface. virtual bool GetWindowList(WindowList* windows) OVERRIDE; virtual bool SelectWindow(WindowId id) OVERRIDE; virtual bool BringSelectedWindowToFront() OVERRIDE; // DesktopCapturer interface. virtual void Start(Callback* callback) OVERRIDE; virtual void Capture(const DesktopRegion& region) OVERRIDE; private: bool IsAeroEnabled(); Callback* callback_; // HWND and HDC for the currently selected window or NULL if window is not // selected. HWND window_; // dwmapi.dll is used to determine if desktop compositing is enabled. HMODULE dwmapi_library_; DwmIsCompositionEnabledFunc is_composition_enabled_func_; DesktopSize previous_size_; DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin); }; WindowCapturerWin::WindowCapturerWin() : callback_(NULL), window_(NULL) { // Try to load dwmapi.dll dynamically since it is not available on XP. dwmapi_library_ = LoadLibrary(L"dwmapi.dll"); if (dwmapi_library_) { is_composition_enabled_func_ = reinterpret_cast<DwmIsCompositionEnabledFunc>( GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled")); assert(is_composition_enabled_func_); } else { is_composition_enabled_func_ = NULL; } } WindowCapturerWin::~WindowCapturerWin() { if (dwmapi_library_) FreeLibrary(dwmapi_library_); } bool WindowCapturerWin::IsAeroEnabled() { BOOL result = FALSE; if (is_composition_enabled_func_) is_composition_enabled_func_(&result); return result != FALSE; } bool WindowCapturerWin::GetWindowList(WindowList* windows) { WindowList result; LPARAM param = reinterpret_cast<LPARAM>(&result); if (!EnumWindows(&WindowsEnumerationHandler, param)) return false; windows->swap(result); return true; } bool WindowCapturerWin::SelectWindow(WindowId id) { HWND window = reinterpret_cast<HWND>(id); if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window)) return false; window_ = window; previous_size_.set(0, 0); return true; } bool WindowCapturerWin::BringSelectedWindowToFront() { if (!window_) return false; if (!IsWindow(window_) || !IsWindowVisible(window_) || IsIconic(window_)) return false; return SetForegroundWindow(window_) != 0; } void WindowCapturerWin::Start(Callback* callback) { assert(!callback_); assert(callback); callback_ = callback; } void WindowCapturerWin::Capture(const DesktopRegion& region) { if (!window_) { LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } // Stop capturing if the window has been closed or hidden. if (!IsWindow(window_) || !IsWindowVisible(window_)) { callback_->OnCaptureCompleted(NULL); return; } // Return a 2x2 black frame if the window is minimized. The size is 2x2 so it // can be subsampled to I420 downstream. if (IsIconic(window_)) { BasicDesktopFrame* frame = new BasicDesktopFrame(DesktopSize(2, 2)); memset(frame->data(), 0, frame->stride() * frame->size().height()); previous_size_ = frame->size(); callback_->OnCaptureCompleted(frame); return; } DesktopRect original_rect; DesktopRect cropped_rect; if (!GetCroppedWindowRect(window_, &cropped_rect, &original_rect)) { LOG(LS_WARNING) << "Failed to get window info: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } HDC window_dc = GetWindowDC(window_); if (!window_dc) { LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create( cropped_rect.size(), NULL, window_dc)); if (!frame.get()) { ReleaseDC(window_, window_dc); callback_->OnCaptureCompleted(NULL); return; } HDC mem_dc = CreateCompatibleDC(window_dc); HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap()); BOOL result = FALSE; // When desktop composition (Aero) is enabled each window is rendered to a // private buffer allowing BitBlt() to get the window content even if the // window is occluded. PrintWindow() is slower but lets rendering the window // contents to an off-screen device context when Aero is not available. // PrintWindow() is not supported by some applications. // // If Aero is enabled, we prefer BitBlt() because it's faster and avoids // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may // render occluding windows on top of the desired window. // // When composition is enabled the DC returned by GetWindowDC() doesn't always // have window frame rendered correctly. Windows renders it only once and then // caches the result between captures. We hack it around by calling // PrintWindow() whenever window size changes, including the first time of // capturing - it somehow affects what we get from BitBlt() on the subsequent // captures. if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) { result = PrintWindow(window_, mem_dc, 0); } // Aero is enabled or PrintWindow() failed, use BitBlt. if (!result) { result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(), window_dc, cropped_rect.left() - original_rect.left(), cropped_rect.top() - original_rect.top(), SRCCOPY); } SelectObject(mem_dc, previous_object); DeleteDC(mem_dc); ReleaseDC(window_, window_dc); previous_size_ = frame->size(); frame->mutable_updated_region()->SetRect( DesktopRect::MakeSize(frame->size())); if (!result) { LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed."; frame.reset(); } callback_->OnCaptureCompleted(frame.release()); } } // namespace // static WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) { return new WindowCapturerWin(); } } // namespace webrtc <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: aqua_clipboard.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _AQUA_CLIPBOARD_HXX_ #define _AQUA_CLIPBOARD_HXX_ #include "DataFlavorMapping.hxx" #include <rtl/ustring.hxx> #include <sal/types.h> #include <cppuhelper/compbase4.hxx> #include <com/sun/star/datatransfer/XTransferable.hpp> #include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp> #include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp> #include <com/sun/star/datatransfer/clipboard/XClipboardListener.hpp> #include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp> #include <com/sun/star/datatransfer/XMimeContentTypeFactory.hpp> #include <com/sun/star/datatransfer/clipboard/XFlushableClipboard.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <cppuhelper/basemutex.hxx> #include <com/sun/star/lang/XMultiComponentFactory.hpp> #include <boost/utility.hpp> #include <list> #include <premac.h> #import <Cocoa/Cocoa.h> #include <postmac.h> class AquaClipboard; @interface EventListener : NSObject { AquaClipboard* pAquaClipboard; } // Init the pasteboard change listener with a reference to the OfficeClipboard // instance - (EventListener*)initWithAquaClipboard: (AquaClipboard*) pcb; // Promiss resolver function - (void)pasteboard:(NSPasteboard*)sender provideDataForType:(NSString *)type; -(void)applicationDidBecomeActive:(NSNotification*)aNotification; @end class AquaClipboard : public ::cppu::BaseMutex, public ::cppu::WeakComponentImplHelper4< com::sun::star::datatransfer::clipboard::XClipboardEx, com::sun::star::datatransfer::clipboard::XClipboardNotifier, com::sun::star::datatransfer::clipboard::XFlushableClipboard, com::sun::star::lang::XServiceInfo >, private ::boost::noncopyable { public: /* Create a clipboard instance. @param pasteboard If not equal NULL the instance will be instantiated with the provided pasteboard reference and 'bUseSystemClipboard' will be ignored @param bUseSystemClipboard If 'pasteboard' is NULL 'bUseSystemClipboard' determines whether the system clipboard will be created (bUseSystemClipboard == true) or if the DragPasteboard if bUseSystemClipboard == false */ AquaClipboard(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& context, NSPasteboard* pasteboard = NULL, bool bUseSystemClipboard = true); ~AquaClipboard(); //------------------------------------------------ // XClipboard //------------------------------------------------ virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > SAL_CALL getContents() throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setContents( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable >& xTransferable, const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardOwner >& xClipboardOwner ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getName() throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XClipboardEx //------------------------------------------------ virtual sal_Int8 SAL_CALL getRenderingCapabilities() throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XClipboardNotifier //------------------------------------------------ virtual void SAL_CALL addClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XFlushableClipboard //------------------------------------------------ virtual void SAL_CALL flushClipboard( ) throw( com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XServiceInfo //------------------------------------------------ virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); /* Get a reference to the used pastboard. */ NSPasteboard* getPasteboard() const; /* Notify the current clipboard owner that he is no longer the clipboard owner. */ void fireLostClipboardOwnershipEvent(::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardOwner> oldOwner, ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > oldContent); void pasteboardChangedOwner(); void provideDataForType(NSPasteboard* sender, NSString* type); void applicationDidBecomeActive(NSNotification* aNotification); private: /* Notify all registered XClipboardListener that the clipboard content has changed. */ void fireClipboardChangedEvent(); private: const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mXComponentContext; ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XMimeContentTypeFactory > mrXMimeCntFactory; ::std::list< ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener > > mClipboardListeners; ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > mXClipboardContent; com::sun::star::uno::Reference< com::sun::star::datatransfer::clipboard::XClipboardOwner > mXClipboardOwner; DataFlavorMapperPtr_t mpDataFlavorMapper; bool mIsSystemPasteboard; NSPasteboard* mPasteboard; int mPasteboardChangeCount; EventListener* mEventListener; }; #endif <commit_msg>INTEGRATION: CWS aquavcl07 (1.7.8); FILE MERGED 2008/04/17 05:39:42 pl 1.7.8.2: RESYNC: (1.7-1.8); FILE MERGED 2008/04/16 12:07:10 pl 1.7.8.1: #i87595# don not call on destroyed objects<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: aqua_clipboard.hxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _AQUA_CLIPBOARD_HXX_ #define _AQUA_CLIPBOARD_HXX_ #include "DataFlavorMapping.hxx" #include <rtl/ustring.hxx> #include <sal/types.h> #include <cppuhelper/compbase4.hxx> #include <com/sun/star/datatransfer/XTransferable.hpp> #include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp> #include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp> #include <com/sun/star/datatransfer/clipboard/XClipboardListener.hpp> #include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp> #include <com/sun/star/datatransfer/XMimeContentTypeFactory.hpp> #include <com/sun/star/datatransfer/clipboard/XFlushableClipboard.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <cppuhelper/basemutex.hxx> #include <com/sun/star/lang/XMultiComponentFactory.hpp> #include <boost/utility.hpp> #include <list> #include <premac.h> #import <Cocoa/Cocoa.h> #include <postmac.h> class AquaClipboard; @interface EventListener : NSObject { AquaClipboard* pAquaClipboard; } // Init the pasteboard change listener with a reference to the OfficeClipboard // instance - (EventListener*)initWithAquaClipboard: (AquaClipboard*) pcb; // Promiss resolver function - (void)pasteboard:(NSPasteboard*)sender provideDataForType:(NSString *)type; -(void)applicationDidBecomeActive:(NSNotification*)aNotification; -(void)disposing; @end class AquaClipboard : public ::cppu::BaseMutex, public ::cppu::WeakComponentImplHelper4< com::sun::star::datatransfer::clipboard::XClipboardEx, com::sun::star::datatransfer::clipboard::XClipboardNotifier, com::sun::star::datatransfer::clipboard::XFlushableClipboard, com::sun::star::lang::XServiceInfo >, private ::boost::noncopyable { public: /* Create a clipboard instance. @param pasteboard If not equal NULL the instance will be instantiated with the provided pasteboard reference and 'bUseSystemClipboard' will be ignored @param bUseSystemClipboard If 'pasteboard' is NULL 'bUseSystemClipboard' determines whether the system clipboard will be created (bUseSystemClipboard == true) or if the DragPasteboard if bUseSystemClipboard == false */ AquaClipboard(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& context, NSPasteboard* pasteboard = NULL, bool bUseSystemClipboard = true); ~AquaClipboard(); //------------------------------------------------ // XClipboard //------------------------------------------------ virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > SAL_CALL getContents() throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setContents( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable >& xTransferable, const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardOwner >& xClipboardOwner ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getName() throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XClipboardEx //------------------------------------------------ virtual sal_Int8 SAL_CALL getRenderingCapabilities() throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XClipboardNotifier //------------------------------------------------ virtual void SAL_CALL addClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XFlushableClipboard //------------------------------------------------ virtual void SAL_CALL flushClipboard( ) throw( com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XServiceInfo //------------------------------------------------ virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); /* Get a reference to the used pastboard. */ NSPasteboard* getPasteboard() const; /* Notify the current clipboard owner that he is no longer the clipboard owner. */ void fireLostClipboardOwnershipEvent(::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardOwner> oldOwner, ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > oldContent); void pasteboardChangedOwner(); void provideDataForType(NSPasteboard* sender, NSString* type); void applicationDidBecomeActive(NSNotification* aNotification); private: /* Notify all registered XClipboardListener that the clipboard content has changed. */ void fireClipboardChangedEvent(); private: const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mXComponentContext; ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XMimeContentTypeFactory > mrXMimeCntFactory; ::std::list< ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener > > mClipboardListeners; ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > mXClipboardContent; com::sun::star::uno::Reference< com::sun::star::datatransfer::clipboard::XClipboardOwner > mXClipboardOwner; DataFlavorMapperPtr_t mpDataFlavorMapper; bool mIsSystemPasteboard; NSPasteboard* mPasteboard; int mPasteboardChangeCount; EventListener* mEventListener; }; #endif <|endoftext|>
<commit_before>#include <config.h> #include <assert.h> #include <boost/assert.hpp> #include <dune/common/exceptions.hh> #include <dune/common/timer.hh> #include <dune/multiscale/common/righthandside_assembler.hh> #include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh> #include <dune/multiscale/msfem/msfem_grid_specifier.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/parameter/configcontainer.hh> #include <dune/stuff/common/profiler.hh> #include <dune/stuff/discretefunction/projection/heterogenous.hh> #include <sstream> #include "dune/multiscale/common/dirichletconstraints.hh" #include "dune/multiscale/common/traits.hh" #include "dune/multiscale/msfem/msfem_traits.hh" #include "msfem_solver.hh" namespace Dune { namespace Multiscale { namespace MsFEM { Elliptic_MsFEM_Solver::Elliptic_MsFEM_Solver(const DiscreteFunctionSpace& discreteFunctionSpace) : discreteFunctionSpace_(discreteFunctionSpace) {} void Elliptic_MsFEM_Solver::subgrid_to_hostrid_projection(const SubgridDiscreteFunctionType& sub_func, DiscreteFunctionType& host_func) const { host_func.clear(); const SubgridDiscreteFunctionSpaceType& subDiscreteFunctionSpace = sub_func.space(); const SubGridType& subGrid = subDiscreteFunctionSpace.grid(); typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator; typedef typename SubgridIterator::Entity SubgridEntity; typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction; const SubgridIterator sub_endit = subDiscreteFunctionSpace.end(); for (SubgridIterator sub_it = subDiscreteFunctionSpace.begin(); sub_it != sub_endit; ++sub_it) { const SubgridEntity& sub_entity = *sub_it; const HostEntityPointer host_entity_pointer = subGrid.getHostEntity<0>(*sub_it); const HostEntity& host_entity = *host_entity_pointer; const SubgridLocalFunction sub_loc_value = sub_func.localFunction(sub_entity); auto host_loc_value = host_func.localFunction(host_entity); const auto numBaseFunctions = sub_loc_value.basisFunctionSet().size(); for (unsigned int i = 0; i < numBaseFunctions; ++i) { host_loc_value[i] = sub_loc_value[i]; } } } // subgrid_to_hostrid_projection void Elliptic_MsFEM_Solver::projectCoarseToFineScale(MacroMicroGridSpecifier& /*specifier*/, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& coarse_scale_part) const { DSC_LOG_INFO << "Indentifying coarse scale part of the MsFEM solution... "; coarse_scale_part.clear(); Dune::Stuff::HeterogenousProjection<> projection; projection.project(coarse_msfem_solution, coarse_scale_part); DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::identify_fine_scale_part(MacroMicroGridSpecifier& specifier, MsFEMTraits::SubGridListType& subgrid_list, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& fine_scale_part) const { fine_scale_part.clear(); const GridPart& gridPart = discreteFunctionSpace_.gridPart(); const HostGrid& grid = gridPart.grid(); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarse_space.gridPart().grid().leafIndexSet(); const int number_of_nodes = grid.size(2 /*codim*/); std::vector<std::vector<HostEntityPointer>> entities_sharing_same_node(number_of_nodes); DSC_LOG_INFO << "Indentifying fine scale part of the MsFEM solution... "; // traverse coarse space for (auto& coarseCell : coarse_space) { const auto coarseCellIndex = coarseGridLeafIndexSet.index(coarseCell); LocalSolutionManager localSolManager(coarseCell, subgrid_list, specifier); localSolManager.loadLocalSolutions(); auto& localSolutions = localSolManager.getLocalSolutions(); auto coarseSolutionLF = coarse_msfem_solution.localFunction(coarseCell); if ((specifier.getOversamplingStrategy() == 3) || specifier.simplexCoarseGrid()) { BOOST_ASSERT_MSG(localSolutions.size() == Dune::GridSelector::dimgrid, "We should have dim local solutions per coarse element on triangular meshes!"); JacobianRangeType grad_coarse_msfem_on_entity; // We only need the gradient of the coarse scale part on the element, which is a constant. coarseSolutionLF.jacobian(coarseCell.geometry().center(), grad_coarse_msfem_on_entity); // get the coarse gradient on T, multiply it with the local correctors and sum it up. for (int spaceDimension = 0; spaceDimension < Dune::GridSelector::dimgrid; ++spaceDimension) { *localSolutions[spaceDimension] *= grad_coarse_msfem_on_entity[0][spaceDimension]; if (spaceDimension > 0) *localSolutions[0] += *localSolutions[spaceDimension]; } } else { //! @warning At this point, we assume to have the same types of elements in the coarse and fine grid! BOOST_ASSERT_MSG( static_cast<long long>(localSolutions.size() - localSolManager.numBoundaryCorrectors()) == static_cast<long long>(coarseSolutionLF.numDofs()), "The current implementation relies on having thesame types of elements on coarse and fine level!"); for (int dof = 0; dof < coarseSolutionLF.numDofs(); ++dof) { *localSolutions[dof] *= coarseSolutionLF[dof]; if (dof > 0) *localSolutions[0] += *localSolutions[dof]; } // add dirichlet corrector DiscreteFunctionType boundaryCorrector("Boundary Corrector", discreteFunctionSpace_); boundaryCorrector.clear(); subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs() + 1], boundaryCorrector); fine_scale_part += boundaryCorrector; // substract neumann corrector // boundaryCorrector.clear(); // subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()], boundaryCorrector); // fine_scale_part -= boundaryCorrector; } // oversampling strategy 3: just sum up the local correctors: if ((specifier.getOversamplingStrategy() == 3)) { DiscreteFunctionType correction_on_U_T("correction_on_U_T", discreteFunctionSpace_); subgrid_to_hostrid_projection(*localSolutions[0], correction_on_U_T); fine_scale_part += correction_on_U_T; } // oversampling strategy 1 or 2: restrict the local correctors to the element T, sum them up and apply a conforming // projection: if ((specifier.getOversamplingStrategy() == 1) || (specifier.getOversamplingStrategy() == 2)) { BOOST_ASSERT_MSG(localSolManager.getLocalDiscreteFunctionSpace().gridPart().grid().maxLevel() == discreteFunctionSpace_.gridPart().grid().maxLevel(), "Error: MaxLevel of SubGrid not identical to MaxLevel of FineGrid."); const auto& nodeToEntityMap = subgrid_list.getNodeEntityMap(); for (auto& subgridEntity : localSolManager.getLocalDiscreteFunctionSpace()) { //! MARK actual subgrid usage const auto fine_host_entity_pointer = localSolManager.getSubGridPart().grid().getHostEntity<0>(subgridEntity); const auto& fine_host_entity = *fine_host_entity_pointer; const auto hostFatherIndex = subgrid_list.getEnclosingMacroCellIndex(fine_host_entity_pointer); if (hostFatherIndex == coarseCellIndex) { const auto sub_loc_value = localSolutions[0]->localFunction(subgridEntity); assert(localSolutions.size() == coarseSolutionLF.numDofs() + localSolManager.numBoundaryCorrectors()); auto host_loc_value = fine_scale_part.localFunction(fine_host_entity); const auto number_of_nodes_entity = subgridEntity.count<HostGrid::dimension>(); for (auto i : DSC::valueRange(number_of_nodes_entity)) { const auto node = fine_host_entity.subEntity<HostGrid::dimension>(i); const auto global_index_node = gridPart.grid().leafIndexSet().index(*node); // count the number of different coarse-grid-entities that share the above node std::unordered_set<SubGridListType::IdType> coarse_entities; const auto numEntitiesSharingNode = nodeToEntityMap[global_index_node].size(); for (size_t j = 0; j < numEntitiesSharingNode; ++j) { // get the id of the macro element enclosing the current element const auto innerId = subgrid_list.getEnclosingMacroCellId(nodeToEntityMap[global_index_node][j]); // the following will only add the entity index if it is not yet present coarse_entities.insert(innerId); } host_loc_value[i] += (sub_loc_value[i] / coarse_entities.size()); } } } } } DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::solve_dirichlet_zero( const CommonTraits::DiffusionType& diffusion_op, const CommonTraits::FirstSourceType& f, // number of layers per coarse grid entity T: U(T) is created by enrichting T with // n(T)-layers. MacroMicroGridSpecifier& specifier, MsFEMTraits::SubGridListType& subgrid_list, DiscreteFunctionType& coarse_scale_part, DiscreteFunctionType& fine_scale_part, DiscreteFunctionType& solution) const { DSC::Profiler::ScopedTiming st("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero"); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); DiscreteFunctionType coarse_msfem_solution("Coarse Part MsFEM Solution", coarse_space); coarse_msfem_solution.clear(); //! define the right hand side assembler tool // (for linear and non-linear elliptic and parabolic problems, for sources f and/or G ) typedef RightHandSideAssembler RhsAssembler; //! define the discrete (elliptic) operator that describes our problem // discrete elliptic MsFEM operator (corresponds with MsFEM Matrix) // ( effect of the discretized differential operator on a certain discrete function ) // This will assemble and solve the local problems const DiscreteEllipticMsFEMOperator elliptic_msfem_op(specifier, coarse_space, subgrid_list, diffusion_op); // discrete elliptic operator (corresponds with FEM Matrix) //! (stiffness) matrix MsLinearOperatorTypeType msfem_matrix("MsFEM stiffness matrix", coarse_space, coarse_space); //! right hand side vector // right hand side for the finite element method: DiscreteFunctionType msfem_rhs("MsFEM right hand side", coarse_space); msfem_rhs.clear(); DSC_LOG_INFO << std::endl << "Solving MsFEM problem." << std::endl << "Solving linear problem with MsFEM and maximum coarse grid level " << coarse_space.gridPart().grid().maxLevel() << "." << std::endl << "------------------------------------------------------------------------------" << std::endl; // to assemble the computational time Dune::Timer assembleTimer; // assemble the MsFEM stiffness matrix elliptic_msfem_op.assemble_matrix(msfem_matrix); DSC_LOG_INFO << "Time to assemble MsFEM stiffness matrix: " << assembleTimer.elapsed() << "s" << std::endl; // assemble right hand side if (DSC_CONFIG_GET("msfem.petrov_galerkin", 1)) { RhsAssembler::assemble(f, msfem_rhs); } else { RhsAssembler::assemble_for_MsFEM_symmetric(f, specifier, subgrid_list, msfem_rhs); } msfem_rhs.communicate(); BOOST_ASSERT_MSG(msfem_rhs.dofsValid(), "Coarse scale RHS DOFs need to be valid!"); const InverseOperatorType msfem_biCGStab(msfem_matrix, 1e-8, 1e-8, 2000, true, "bcgs", DSC_CONFIG_GET("preconditioner_type", std::string("sor"))); msfem_biCGStab(msfem_rhs, coarse_msfem_solution); DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl; DSC_LOG_INFO << "MsFEM problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl << std::endl; if (!coarse_msfem_solution.dofsValid()) DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!"); // get the dirichlet values solution.clear(); Dune::Multiscale::copyDirichletValues(coarse_space, solution); //! copy coarse scale part of MsFEM solution into a function defined on the fine grid projectCoarseToFineScale(specifier, coarse_msfem_solution, coarse_scale_part); //! identify fine scale part of MsFEM solution (including the projection!) identify_fine_scale_part(specifier, subgrid_list, coarse_msfem_solution, fine_scale_part); { DSC::Profiler::ScopedTiming commFSTimer("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero.comm_fine_scale_part"); fine_scale_part.communicate(); } BOOST_ASSERT_MSG(coarse_scale_part.dofsValid(), "Coarse scale part DOFs need to be valid!"); BOOST_ASSERT_MSG(fine_scale_part.dofsValid(), "Fine scale part DOFs need to be valid!"); // add coarse and fine scale part to solution solution += coarse_scale_part; solution += fine_scale_part; } // solve_dirichlet_zero } // namespace MsFEM { } // namespace Multiscale { } // namespace Dune { <commit_msg>Fixed a bug where a wrong index set was used<commit_after>#include <config.h> #include <assert.h> #include <boost/assert.hpp> #include <dune/common/exceptions.hh> #include <dune/common/timer.hh> #include <dune/multiscale/common/righthandside_assembler.hh> #include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh> #include <dune/multiscale/msfem/msfem_grid_specifier.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/parameter/configcontainer.hh> #include <dune/stuff/common/profiler.hh> #include <dune/stuff/discretefunction/projection/heterogenous.hh> #include <sstream> #include "dune/multiscale/common/dirichletconstraints.hh" #include "dune/multiscale/common/traits.hh" #include "dune/multiscale/msfem/msfem_traits.hh" #include "msfem_solver.hh" namespace Dune { namespace Multiscale { namespace MsFEM { Elliptic_MsFEM_Solver::Elliptic_MsFEM_Solver(const DiscreteFunctionSpace& discreteFunctionSpace) : discreteFunctionSpace_(discreteFunctionSpace) {} void Elliptic_MsFEM_Solver::subgrid_to_hostrid_projection(const SubgridDiscreteFunctionType& sub_func, DiscreteFunctionType& host_func) const { host_func.clear(); const SubgridDiscreteFunctionSpaceType& subDiscreteFunctionSpace = sub_func.space(); const SubGridType& subGrid = subDiscreteFunctionSpace.grid(); typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator; typedef typename SubgridIterator::Entity SubgridEntity; typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction; const SubgridIterator sub_endit = subDiscreteFunctionSpace.end(); for (SubgridIterator sub_it = subDiscreteFunctionSpace.begin(); sub_it != sub_endit; ++sub_it) { const SubgridEntity& sub_entity = *sub_it; const HostEntityPointer host_entity_pointer = subGrid.getHostEntity<0>(*sub_it); const HostEntity& host_entity = *host_entity_pointer; const SubgridLocalFunction sub_loc_value = sub_func.localFunction(sub_entity); auto host_loc_value = host_func.localFunction(host_entity); const auto numBaseFunctions = sub_loc_value.basisFunctionSet().size(); for (unsigned int i = 0; i < numBaseFunctions; ++i) { host_loc_value[i] = sub_loc_value[i]; } } } // subgrid_to_hostrid_projection void Elliptic_MsFEM_Solver::projectCoarseToFineScale(MacroMicroGridSpecifier& /*specifier*/, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& coarse_scale_part) const { DSC_LOG_INFO << "Indentifying coarse scale part of the MsFEM solution... "; coarse_scale_part.clear(); Dune::Stuff::HeterogenousProjection<> projection; projection.project(coarse_msfem_solution, coarse_scale_part); DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::identify_fine_scale_part(MacroMicroGridSpecifier& specifier, MsFEMTraits::SubGridListType& subgrid_list, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& fine_scale_part) const { fine_scale_part.clear(); const GridPart& gridPart = discreteFunctionSpace_.gridPart(); const HostGrid& grid = gridPart.grid(); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarse_space.gridPart().grid().leafIndexSet(); const int number_of_nodes = grid.size(2 /*codim*/); std::vector<std::vector<HostEntityPointer>> entities_sharing_same_node(number_of_nodes); DSC_LOG_INFO << "Indentifying fine scale part of the MsFEM solution... "; // traverse coarse space for (auto& coarseCell : coarse_space) { const auto coarseCellIndex = coarseGridLeafIndexSet.index(coarseCell); LocalSolutionManager localSolManager(coarseCell, subgrid_list, specifier); localSolManager.loadLocalSolutions(); auto& localSolutions = localSolManager.getLocalSolutions(); auto coarseSolutionLF = coarse_msfem_solution.localFunction(coarseCell); if ((specifier.getOversamplingStrategy() == 3) || specifier.simplexCoarseGrid()) { BOOST_ASSERT_MSG(localSolutions.size() == Dune::GridSelector::dimgrid, "We should have dim local solutions per coarse element on triangular meshes!"); JacobianRangeType grad_coarse_msfem_on_entity; // We only need the gradient of the coarse scale part on the element, which is a constant. coarseSolutionLF.jacobian(coarseCell.geometry().center(), grad_coarse_msfem_on_entity); // get the coarse gradient on T, multiply it with the local correctors and sum it up. for (int spaceDimension = 0; spaceDimension < Dune::GridSelector::dimgrid; ++spaceDimension) { *localSolutions[spaceDimension] *= grad_coarse_msfem_on_entity[0][spaceDimension]; if (spaceDimension > 0) *localSolutions[0] += *localSolutions[spaceDimension]; } } else { //! @warning At this point, we assume to have the same types of elements in the coarse and fine grid! BOOST_ASSERT_MSG( static_cast<long long>(localSolutions.size() - localSolManager.numBoundaryCorrectors()) == static_cast<long long>(coarseSolutionLF.numDofs()), "The current implementation relies on having thesame types of elements on coarse and fine level!"); for (int dof = 0; dof < coarseSolutionLF.numDofs(); ++dof) { *localSolutions[dof] *= coarseSolutionLF[dof]; if (dof > 0) *localSolutions[0] += *localSolutions[dof]; } // add dirichlet corrector DiscreteFunctionType boundaryCorrector("Boundary Corrector", discreteFunctionSpace_); boundaryCorrector.clear(); subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs() + 1], boundaryCorrector); fine_scale_part += boundaryCorrector; // substract neumann corrector // boundaryCorrector.clear(); // subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()], boundaryCorrector); // fine_scale_part -= boundaryCorrector; } // oversampling strategy 3: just sum up the local correctors: if ((specifier.getOversamplingStrategy() == 3)) { DiscreteFunctionType correction_on_U_T("correction_on_U_T", discreteFunctionSpace_); subgrid_to_hostrid_projection(*localSolutions[0], correction_on_U_T); fine_scale_part += correction_on_U_T; } // oversampling strategy 1 or 2: restrict the local correctors to the element T, sum them up and apply a conforming // projection: if ((specifier.getOversamplingStrategy() == 1) || (specifier.getOversamplingStrategy() == 2)) { BOOST_ASSERT_MSG(localSolManager.getLocalDiscreteFunctionSpace().gridPart().grid().maxLevel() == discreteFunctionSpace_.gridPart().grid().maxLevel(), "Error: MaxLevel of SubGrid not identical to MaxLevel of FineGrid."); const auto& nodeToEntityMap = subgrid_list.getNodeEntityMap(); for (auto& subgridEntity : localSolManager.getLocalDiscreteFunctionSpace()) { //! MARK actual subgrid usage const auto fine_host_entity_pointer = localSolManager.getSubGridPart().grid().getHostEntity<0>(subgridEntity); const auto& fine_host_entity = *fine_host_entity_pointer; const auto hostFatherIndex = subgrid_list.getEnclosingMacroCellIndex(fine_host_entity_pointer); if (hostFatherIndex == coarseCellIndex) { const auto sub_loc_value = localSolutions[0]->localFunction(subgridEntity); assert(localSolutions.size() == coarseSolutionLF.numDofs() + localSolManager.numBoundaryCorrectors()); auto host_loc_value = fine_scale_part.localFunction(fine_host_entity); const auto number_of_nodes_entity = subgridEntity.count<HostGrid::dimension>(); for (auto i : DSC::valueRange(number_of_nodes_entity)) { const auto node = fine_host_entity.subEntity<HostGrid::dimension>(i); const auto global_index_node = gridPart.indexSet().index(*node); // count the number of different coarse-grid-entities that share the above node std::unordered_set<SubGridListType::IdType> coarse_entities; const auto numEntitiesSharingNode = nodeToEntityMap[global_index_node].size(); for (size_t j = 0; j < numEntitiesSharingNode; ++j) { // get the id of the macro element enclosing the current element const auto innerId = subgrid_list.getEnclosingMacroCellId(nodeToEntityMap[global_index_node][j]); // the following will only add the entity index if it is not yet present coarse_entities.insert(innerId); } host_loc_value[i] += (sub_loc_value[i] / coarse_entities.size()); } } } } } DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::solve_dirichlet_zero( const CommonTraits::DiffusionType& diffusion_op, const CommonTraits::FirstSourceType& f, // number of layers per coarse grid entity T: U(T) is created by enrichting T with // n(T)-layers. MacroMicroGridSpecifier& specifier, MsFEMTraits::SubGridListType& subgrid_list, DiscreteFunctionType& coarse_scale_part, DiscreteFunctionType& fine_scale_part, DiscreteFunctionType& solution) const { DSC::Profiler::ScopedTiming st("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero"); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); DiscreteFunctionType coarse_msfem_solution("Coarse Part MsFEM Solution", coarse_space); coarse_msfem_solution.clear(); //! define the right hand side assembler tool // (for linear and non-linear elliptic and parabolic problems, for sources f and/or G ) typedef RightHandSideAssembler RhsAssembler; //! define the discrete (elliptic) operator that describes our problem // discrete elliptic MsFEM operator (corresponds with MsFEM Matrix) // ( effect of the discretized differential operator on a certain discrete function ) // This will assemble and solve the local problems const DiscreteEllipticMsFEMOperator elliptic_msfem_op(specifier, coarse_space, subgrid_list, diffusion_op); // discrete elliptic operator (corresponds with FEM Matrix) //! (stiffness) matrix MsLinearOperatorTypeType msfem_matrix("MsFEM stiffness matrix", coarse_space, coarse_space); //! right hand side vector // right hand side for the finite element method: DiscreteFunctionType msfem_rhs("MsFEM right hand side", coarse_space); msfem_rhs.clear(); DSC_LOG_INFO << std::endl << "Solving MsFEM problem." << std::endl << "Solving linear problem with MsFEM and maximum coarse grid level " << coarse_space.gridPart().grid().maxLevel() << "." << std::endl << "------------------------------------------------------------------------------" << std::endl; // to assemble the computational time Dune::Timer assembleTimer; // assemble the MsFEM stiffness matrix elliptic_msfem_op.assemble_matrix(msfem_matrix); DSC_LOG_INFO << "Time to assemble MsFEM stiffness matrix: " << assembleTimer.elapsed() << "s" << std::endl; // assemble right hand side if (DSC_CONFIG_GET("msfem.petrov_galerkin", 1)) { RhsAssembler::assemble(f, msfem_rhs); } else { RhsAssembler::assemble_for_MsFEM_symmetric(f, specifier, subgrid_list, msfem_rhs); } msfem_rhs.communicate(); BOOST_ASSERT_MSG(msfem_rhs.dofsValid(), "Coarse scale RHS DOFs need to be valid!"); const InverseOperatorType msfem_biCGStab(msfem_matrix, 1e-8, 1e-8, 2000, true, "bcgs", DSC_CONFIG_GET("preconditioner_type", std::string("sor"))); msfem_biCGStab(msfem_rhs, coarse_msfem_solution); DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl; DSC_LOG_INFO << "MsFEM problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl << std::endl; if (!coarse_msfem_solution.dofsValid()) DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!"); // get the dirichlet values solution.clear(); Dune::Multiscale::copyDirichletValues(coarse_space, solution); //! copy coarse scale part of MsFEM solution into a function defined on the fine grid projectCoarseToFineScale(specifier, coarse_msfem_solution, coarse_scale_part); //! identify fine scale part of MsFEM solution (including the projection!) identify_fine_scale_part(specifier, subgrid_list, coarse_msfem_solution, fine_scale_part); { DSC::Profiler::ScopedTiming commFSTimer("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero.comm_fine_scale_part"); fine_scale_part.communicate(); } BOOST_ASSERT_MSG(coarse_scale_part.dofsValid(), "Coarse scale part DOFs need to be valid!"); BOOST_ASSERT_MSG(fine_scale_part.dofsValid(), "Fine scale part DOFs need to be valid!"); // add coarse and fine scale part to solution solution += coarse_scale_part; solution += fine_scale_part; } // solve_dirichlet_zero } // namespace MsFEM { } // namespace Multiscale { } // namespace Dune { <|endoftext|>
<commit_before>#include "msfem_solver.hh" #include <unordered_set> #include <dune/multiscale/common/righthandside_assembler.hh> #include <dune/multiscale/msfem/localproblems/subgrid-list.hh> #include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh> #include <dune/multiscale/tools/misc/linear-lagrange-interpolation.hh> #include <dune/multiscale/msfem/msfem_grid_specifier.hh> #include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh> #include <dune/stuff/discretefunction/projection/heterogenous.hh> #include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh> #include <dune/multiscale/fem/fem_traits.hh> namespace Dune { namespace Multiscale { namespace MsFEM { Elliptic_MsFEM_Solver::Elliptic_MsFEM_Solver(const DiscreteFunctionSpace& discreteFunctionSpace) : discreteFunctionSpace_(discreteFunctionSpace) {} void Elliptic_MsFEM_Solver::subgrid_to_hostrid_projection(const SubgridDiscreteFunctionType& sub_func, DiscreteFunctionType &host_func) const { host_func.clear(); const SubgridDiscreteFunctionSpaceType& subDiscreteFunctionSpace = sub_func.space(); const SubGridType& subGrid = subDiscreteFunctionSpace.grid(); typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator; typedef typename SubgridIterator::Entity SubgridEntity; typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction; const SubgridIterator sub_endit = subDiscreteFunctionSpace.end(); for (SubgridIterator sub_it = subDiscreteFunctionSpace.begin(); sub_it != sub_endit; ++sub_it) { const SubgridEntity& sub_entity = *sub_it; const HostEntityPointer host_entity_pointer = subGrid.getHostEntity< 0 >(*sub_it); const HostEntity& host_entity = *host_entity_pointer; const SubgridLocalFunction sub_loc_value = sub_func.localFunction(sub_entity); LocalFunction host_loc_value = host_func.localFunction(host_entity); const auto numBaseFunctions = sub_loc_value.basisFunctionSet().size(); for (unsigned int i = 0; i < numBaseFunctions; ++i) { host_loc_value[i] = sub_loc_value[i]; } } } // subgrid_to_hostrid_projection void Elliptic_MsFEM_Solver::identify_coarse_scale_part( MacroMicroGridSpecifier& /*specifier*/, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& coarse_scale_part ) const { DSC_LOG_INFO << "Indentifying coarse scale part of the MsFEM solution... "; coarse_scale_part.clear(); Dune::Stuff::HeterogenousProjection<> projection; projection.project(coarse_msfem_solution, coarse_scale_part); DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::identify_fine_scale_part( MacroMicroGridSpecifier& specifier, MsFEMTraits::SubGridListType& subgrid_list, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& fine_scale_part ) const { fine_scale_part.clear(); const HostGrid& grid = discreteFunctionSpace_.gridPart().grid(); const GridPart& gridPart = discreteFunctionSpace_.gridPart(); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarse_space.gridPart().grid().leafIndexSet(); const int number_of_nodes = grid.size(2 /*codim*/); std::vector< std::vector< HostEntityPointer > > entities_sharing_same_node(number_of_nodes); DSC_LOG_INFO << "Indentifying fine scale part of the MsFEM solution... "; // traverse coarse space for (auto& coarseCell : coarse_space) { const int coarseCellIndex = coarseGridLeafIndexSet.index(coarseCell); LocalSolutionManager localSolManager(coarseCell, subgrid_list, specifier); localSolManager.loadLocalSolutions(); auto& localSolutions = localSolManager.getLocalSolutions(); LocalFunction coarseSolutionLF = coarse_msfem_solution.localFunction(coarseCell); if ((specifier.getOversamplingStrategy()==3) || specifier.simplexCoarseGrid()) { assert(localSolutions.size()==Dune::GridSelector::dimgrid && "We should have dim local solutions per coarse element on triangular meshes!"); JacobianRangeType grad_coarse_msfem_on_entity; // We only need the gradient of the coarse scale part on the element, which is a constant. coarseSolutionLF.jacobian(coarseCell.geometry().center(), grad_coarse_msfem_on_entity); // get the coarse gradient on T, multiply it with the local correctors and sum it up. for (int spaceDimension=0; spaceDimension<Dune::GridSelector::dimgrid; ++spaceDimension) { *localSolutions[spaceDimension] *= grad_coarse_msfem_on_entity[0][spaceDimension]; if (spaceDimension>0) *localSolutions[0] += *localSolutions[spaceDimension]; } } else { //! @warning At this point, we assume to have the same types of elements in the coarse and fine grid! assert(localSolutions.size()-localSolManager.numBoundaryCorrectors() == coarseSolutionLF.numDofs() && "The current implementation relies on having the \ same types of elements on coarse and fine level!"); for (int dof=0; dof< coarseSolutionLF.numDofs(); ++dof) { *localSolutions[dof] *= coarseSolutionLF[dof]; if (dof>0) *localSolutions[0] += *localSolutions[dof]; } // add dirichlet corrector DiscreteFunction boundaryCorrector("Boundary Corrector", discreteFunctionSpace_); boundaryCorrector.clear(); subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()+1], boundaryCorrector); fine_scale_part += boundaryCorrector; // substract neumann corrector // boundaryCorrector.clear(); // subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()], boundaryCorrector); // fine_scale_part -= boundaryCorrector; } // oversampling strategy 3: just sum up the local correctors: if ( (specifier.getOversamplingStrategy() == 3) ) { DiscreteFunctionType correction_on_U_T("correction_on_U_T", discreteFunctionSpace_); subgrid_to_hostrid_projection(*localSolutions[0], correction_on_U_T); fine_scale_part += correction_on_U_T; } // oversampling strategy 1 or 2: restrict the local correctors to the element T, sum them up and apply a conforming projection: if ( ( specifier.getOversamplingStrategy() == 1 ) || ( specifier.getOversamplingStrategy() == 2 ) ) { assert(localSolManager.getLocalDiscreteFunctionSpace().gridPart().grid().maxLevel() == discreteFunctionSpace_.gridPart().grid().maxLevel() && "Error: MaxLevel of SubGrid not identical to MaxLevel of FineGrid."); const auto& nodeToEntityMap = subgrid_list.getNodeEntityMap(); typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator; typedef typename SubgridIterator::Entity SubgridEntity; typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction; for (auto& subgridEntity : localSolManager.getLocalDiscreteFunctionSpace()) { //! MARK actual subgrid usage const HostEntityPointer fine_host_entity_pointer = localSolManager.getSubGridPart().grid().getHostEntity< 0 >(subgridEntity); const HostEntity& fine_host_entity = *fine_host_entity_pointer; const int hostFatherIndex = subgrid_list.getEnclosingMacroCellIndex(fine_host_entity_pointer); if (hostFatherIndex== coarseCellIndex) { const SubgridLocalFunction sub_loc_value = localSolutions[0]->localFunction(subgridEntity); assert(localSolutions.size()==coarseSolutionLF.numDofs()+localSolManager.numBoundaryCorrectors()); const SubgridLocalFunction dirichletLF = localSolutions[coarseSolutionLF.numDofs()+1]->localFunction(subgridEntity); LocalFunction host_loc_value = fine_scale_part.localFunction(fine_host_entity); int number_of_nodes_entity = subgridEntity.count<HostGrid::dimension>(); for (int i = 0; i < number_of_nodes_entity; ++i) { const typename HostEntity::Codim< HostGrid::dimension >::EntityPointer node = fine_host_entity.subEntity< HostGrid::dimension >(i); const int global_index_node = gridPart.grid().leafIndexSet().index(*node); // count the number of different coarse-grid-entities that share the above node std::unordered_set< SubGridListType::IdType > coarse_entities; const int numEntitiesSharingNode = nodeToEntityMap[global_index_node].size(); for (size_t j = 0; j < numEntitiesSharingNode; ++j) { // get the id of the macro element enclosing the current element const auto innerId = subgrid_list.getEnclosingMacroCellId(nodeToEntityMap[global_index_node][j]); // the following will only add the entity index if it is not yet present coarse_entities.insert(innerId); } host_loc_value[i] += ( sub_loc_value[i] / coarse_entities.size() ); } } } } } DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::solve_dirichlet_zero(const CommonTraits::DiffusionType& diffusion_op, const CommonTraits::FirstSourceType& f, // number of layers per coarse grid entity T: U(T) is created by enrichting T with // n(T)-layers. MacroMicroGridSpecifier& specifier, MsFEMTraits::SubGridListType& subgrid_list, DiscreteFunctionType& coarse_scale_part, DiscreteFunctionType& fine_scale_part, DiscreteFunctionType& solution) const { DSC::Profiler::ScopedTiming st("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero"); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); DiscreteFunctionType coarse_msfem_solution("Coarse Part MsFEM Solution", coarse_space); coarse_msfem_solution.clear(); //! define the right hand side assembler tool // (for linear and non-linear elliptic and parabolic problems, for sources f and/or G ) typedef RightHandSideAssembler< DiscreteFunctionType > RhsAssembler; //! define the discrete (elliptic) operator that describes our problem // discrete elliptic MsFEM operator (corresponds with MsFEM Matrix) // ( effect of the discretized differential operator on a certain discrete function ) // This will assemble and solve the local problems const DiscreteEllipticMsFEMOperator elliptic_msfem_op(specifier, coarse_space, subgrid_list, diffusion_op); // discrete elliptic operator (corresponds with FEM Matrix) //! (stiffness) matrix MsFEMMatrixType msfem_matrix("MsFEM stiffness matrix", coarse_space, coarse_space); //! right hand side vector // right hand side for the finite element method: DiscreteFunctionType msfem_rhs("MsFEM right hand side", coarse_space); msfem_rhs.clear(); DSC_LOG_INFO << std::endl << "Solving MsFEM problem." << std::endl << "Solving linear problem with MsFEM and maximum coarse grid level " << coarse_space.gridPart().grid().maxLevel() << "." << std::endl << "------------------------------------------------------------------------------" << std::endl; // to assemble the computational time Dune::Timer assembleTimer; // assemble the MsFEM stiffness matrix elliptic_msfem_op.assemble_matrix(msfem_matrix); DSC_LOG_INFO << "Time to assemble MsFEM stiffness matrix: " << assembleTimer.elapsed() << "s" << std::endl; // assemble right hand side if ( DSC_CONFIG_GET("msfem.petrov_galerkin", 1 ) ) { RhsAssembler::assemble< 2* DiscreteFunctionSpace::polynomialOrder + 2 >(f, msfem_rhs); } else { RhsAssembler::assemble_for_MsFEM_symmetric< 2* DiscreteFunctionSpace::polynomialOrder + 2 >(f, specifier, subgrid_list, msfem_rhs); } msfem_rhs.communicate(); assert(msfem_rhs.dofsValid() && "Coarse scale RHS DOFs need to be valid!"); const InverseOperatorType msfem_biCGStab(msfem_matrix, 1e-8, 1e-8, 2000, true, "bcgs", DSC_CONFIG_GET("preconditioner_type", std::string("sor"))); msfem_biCGStab(msfem_rhs, coarse_msfem_solution); DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl; DSC_LOG_INFO << "MsFEM problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl << std::endl; if (!coarse_msfem_solution.dofsValid()) DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!"); // get the dirichlet values solution.clear(); Dune::Multiscale::projectDirichletValues(coarse_space, solution); //! copy coarse scale part of MsFEM solution into a function defined on the fine grid projectCoarseToFineScale( specifier, coarse_msfem_solution, coarse_scale_part ); //! identify fine scale part of MsFEM solution (including the projection!) identify_fine_scale_part( specifier, subgrid_list, coarse_msfem_solution, fine_scale_part ); { DSC::Profiler::ScopedTiming commFSTimer("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero.comm_fine_scale_part"); fine_scale_part.communicate(); } assert(coarse_scale_part.dofsValid() && "Coarse scale part DOFs need to be valid!"); assert(fine_scale_part.dofsValid() && "Fine scale part DOFs need to be valid!"); // add coarse and fine scale part to solution solution += coarse_scale_part; solution += fine_scale_part; } // solve_dirichlet_zero } //namespace MsFEM { } //namespace Multiscale { } //namespace Dune { <commit_msg>Redo some more changes that got lost during merge<commit_after>#include "msfem_solver.hh" #include <unordered_set> #include <dune/multiscale/common/righthandside_assembler.hh> #include <dune/multiscale/msfem/localproblems/subgrid-list.hh> #include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh> #include <dune/multiscale/tools/misc/linear-lagrange-interpolation.hh> #include <dune/multiscale/msfem/msfem_grid_specifier.hh> #include <dune/multiscale/msfem/elliptic_msfem_matrix_assembler.hh> #include <dune/stuff/discretefunction/projection/heterogenous.hh> #include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh> #include <dune/multiscale/fem/fem_traits.hh> namespace Dune { namespace Multiscale { namespace MsFEM { Elliptic_MsFEM_Solver::Elliptic_MsFEM_Solver(const DiscreteFunctionSpace& discreteFunctionSpace) : discreteFunctionSpace_(discreteFunctionSpace) {} void Elliptic_MsFEM_Solver::subgrid_to_hostrid_projection(const SubgridDiscreteFunctionType& sub_func, DiscreteFunctionType &host_func) const { host_func.clear(); const SubgridDiscreteFunctionSpaceType& subDiscreteFunctionSpace = sub_func.space(); const SubGridType& subGrid = subDiscreteFunctionSpace.grid(); typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator; typedef typename SubgridIterator::Entity SubgridEntity; typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction; const SubgridIterator sub_endit = subDiscreteFunctionSpace.end(); for (SubgridIterator sub_it = subDiscreteFunctionSpace.begin(); sub_it != sub_endit; ++sub_it) { const SubgridEntity& sub_entity = *sub_it; const HostEntityPointer host_entity_pointer = subGrid.getHostEntity< 0 >(*sub_it); const HostEntity& host_entity = *host_entity_pointer; const SubgridLocalFunction sub_loc_value = sub_func.localFunction(sub_entity); LocalFunction host_loc_value = host_func.localFunction(host_entity); const auto numBaseFunctions = sub_loc_value.basisFunctionSet().size(); for (unsigned int i = 0; i < numBaseFunctions; ++i) { host_loc_value[i] = sub_loc_value[i]; } } } // subgrid_to_hostrid_projection void Elliptic_MsFEM_Solver::projectCoarseToFineScale( MacroMicroGridSpecifier& /*specifier*/, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& coarse_scale_part ) const { DSC_LOG_INFO << "Indentifying coarse scale part of the MsFEM solution... "; coarse_scale_part.clear(); Dune::Stuff::HeterogenousProjection<> projection; projection.project(coarse_msfem_solution, coarse_scale_part); DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::identify_fine_scale_part( MacroMicroGridSpecifier& specifier, MsFEMTraits::SubGridListType& subgrid_list, const DiscreteFunctionType& coarse_msfem_solution, DiscreteFunctionType& fine_scale_part ) const { fine_scale_part.clear(); const HostGrid& grid = discreteFunctionSpace_.gridPart().grid(); const GridPart& gridPart = discreteFunctionSpace_.gridPart(); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarse_space.gridPart().grid().leafIndexSet(); const int number_of_nodes = grid.size(2 /*codim*/); std::vector< std::vector< HostEntityPointer > > entities_sharing_same_node(number_of_nodes); DSC_LOG_INFO << "Indentifying fine scale part of the MsFEM solution... "; // traverse coarse space for (auto& coarseCell : coarse_space) { const int coarseCellIndex = coarseGridLeafIndexSet.index(coarseCell); LocalSolutionManager localSolManager(coarseCell, subgrid_list, specifier); localSolManager.loadLocalSolutions(); auto& localSolutions = localSolManager.getLocalSolutions(); LocalFunction coarseSolutionLF = coarse_msfem_solution.localFunction(coarseCell); if ((specifier.getOversamplingStrategy()==3) || specifier.simplexCoarseGrid()) { assert(localSolutions.size()==Dune::GridSelector::dimgrid && "We should have dim local solutions per coarse element on triangular meshes!"); JacobianRangeType grad_coarse_msfem_on_entity; // We only need the gradient of the coarse scale part on the element, which is a constant. coarseSolutionLF.jacobian(coarseCell.geometry().center(), grad_coarse_msfem_on_entity); // get the coarse gradient on T, multiply it with the local correctors and sum it up. for (int spaceDimension=0; spaceDimension<Dune::GridSelector::dimgrid; ++spaceDimension) { *localSolutions[spaceDimension] *= grad_coarse_msfem_on_entity[0][spaceDimension]; if (spaceDimension>0) *localSolutions[0] += *localSolutions[spaceDimension]; } } else { //! @warning At this point, we assume to have the same types of elements in the coarse and fine grid! assert(localSolutions.size()-localSolManager.numBoundaryCorrectors() == coarseSolutionLF.numDofs() && "The current implementation relies on having the \ same types of elements on coarse and fine level!"); for (int dof=0; dof< coarseSolutionLF.numDofs(); ++dof) { *localSolutions[dof] *= coarseSolutionLF[dof]; if (dof>0) *localSolutions[0] += *localSolutions[dof]; } // add dirichlet corrector DiscreteFunctionType boundaryCorrector("Boundary Corrector", discreteFunctionSpace_); boundaryCorrector.clear(); subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()+1], boundaryCorrector); fine_scale_part += boundaryCorrector; // substract neumann corrector // boundaryCorrector.clear(); // subgrid_to_hostrid_projection(*localSolutions[coarseSolutionLF.numDofs()], boundaryCorrector); // fine_scale_part -= boundaryCorrector; } // oversampling strategy 3: just sum up the local correctors: if ( (specifier.getOversamplingStrategy() == 3) ) { DiscreteFunctionType correction_on_U_T("correction_on_U_T", discreteFunctionSpace_); subgrid_to_hostrid_projection(*localSolutions[0], correction_on_U_T); fine_scale_part += correction_on_U_T; } // oversampling strategy 1 or 2: restrict the local correctors to the element T, sum them up and apply a conforming projection: if ( ( specifier.getOversamplingStrategy() == 1 ) || ( specifier.getOversamplingStrategy() == 2 ) ) { assert(localSolManager.getLocalDiscreteFunctionSpace().gridPart().grid().maxLevel() == discreteFunctionSpace_.gridPart().grid().maxLevel() && "Error: MaxLevel of SubGrid not identical to MaxLevel of FineGrid."); const auto& nodeToEntityMap = subgrid_list.getNodeEntityMap(); typedef typename SubgridDiscreteFunctionSpaceType::IteratorType SubgridIterator; typedef typename SubgridIterator::Entity SubgridEntity; typedef typename SubgridDiscreteFunctionType::LocalFunctionType SubgridLocalFunction; for (auto& subgridEntity : localSolManager.getLocalDiscreteFunctionSpace()) { //! MARK actual subgrid usage const HostEntityPointer fine_host_entity_pointer = localSolManager.getSubGridPart().grid().getHostEntity< 0 >(subgridEntity); const HostEntity& fine_host_entity = *fine_host_entity_pointer; const int hostFatherIndex = subgrid_list.getEnclosingMacroCellIndex(fine_host_entity_pointer); if (hostFatherIndex== coarseCellIndex) { const SubgridLocalFunction sub_loc_value = localSolutions[0]->localFunction(subgridEntity); assert(localSolutions.size()==coarseSolutionLF.numDofs()+localSolManager.numBoundaryCorrectors()); const SubgridLocalFunction dirichletLF = localSolutions[coarseSolutionLF.numDofs()+1]->localFunction(subgridEntity); LocalFunction host_loc_value = fine_scale_part.localFunction(fine_host_entity); int number_of_nodes_entity = subgridEntity.count<HostGrid::dimension>(); for (int i = 0; i < number_of_nodes_entity; ++i) { const typename HostEntity::Codim< HostGrid::dimension >::EntityPointer node = fine_host_entity.subEntity< HostGrid::dimension >(i); const int global_index_node = gridPart.grid().leafIndexSet().index(*node); // count the number of different coarse-grid-entities that share the above node std::unordered_set< SubGridListType::IdType > coarse_entities; const int numEntitiesSharingNode = nodeToEntityMap[global_index_node].size(); for (size_t j = 0; j < numEntitiesSharingNode; ++j) { // get the id of the macro element enclosing the current element const auto innerId = subgrid_list.getEnclosingMacroCellId(nodeToEntityMap[global_index_node][j]); // the following will only add the entity index if it is not yet present coarse_entities.insert(innerId); } host_loc_value[i] += ( sub_loc_value[i] / coarse_entities.size() ); } } } } } DSC_LOG_INFO << " done." << std::endl; } void Elliptic_MsFEM_Solver::solve_dirichlet_zero(const CommonTraits::DiffusionType& diffusion_op, const CommonTraits::FirstSourceType& f, // number of layers per coarse grid entity T: U(T) is created by enrichting T with // n(T)-layers. MacroMicroGridSpecifier& specifier, MsFEMTraits::SubGridListType& subgrid_list, DiscreteFunctionType& coarse_scale_part, DiscreteFunctionType& fine_scale_part, DiscreteFunctionType& solution) const { DSC::Profiler::ScopedTiming st("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero"); DiscreteFunctionSpace& coarse_space = specifier.coarseSpace(); DiscreteFunctionType coarse_msfem_solution("Coarse Part MsFEM Solution", coarse_space); coarse_msfem_solution.clear(); //! define the right hand side assembler tool // (for linear and non-linear elliptic and parabolic problems, for sources f and/or G ) typedef RightHandSideAssembler< DiscreteFunctionType > RhsAssembler; //! define the discrete (elliptic) operator that describes our problem // discrete elliptic MsFEM operator (corresponds with MsFEM Matrix) // ( effect of the discretized differential operator on a certain discrete function ) // This will assemble and solve the local problems const DiscreteEllipticMsFEMOperator elliptic_msfem_op(specifier, coarse_space, subgrid_list, diffusion_op); // discrete elliptic operator (corresponds with FEM Matrix) //! (stiffness) matrix MsFEMMatrixType msfem_matrix("MsFEM stiffness matrix", coarse_space, coarse_space); //! right hand side vector // right hand side for the finite element method: DiscreteFunctionType msfem_rhs("MsFEM right hand side", coarse_space); msfem_rhs.clear(); DSC_LOG_INFO << std::endl << "Solving MsFEM problem." << std::endl << "Solving linear problem with MsFEM and maximum coarse grid level " << coarse_space.gridPart().grid().maxLevel() << "." << std::endl << "------------------------------------------------------------------------------" << std::endl; // to assemble the computational time Dune::Timer assembleTimer; // assemble the MsFEM stiffness matrix elliptic_msfem_op.assemble_matrix(msfem_matrix); DSC_LOG_INFO << "Time to assemble MsFEM stiffness matrix: " << assembleTimer.elapsed() << "s" << std::endl; // assemble right hand side if ( DSC_CONFIG_GET("msfem.petrov_galerkin", 1 ) ) { RhsAssembler::assemble< 2* DiscreteFunctionSpace::polynomialOrder + 2 >(f, msfem_rhs); } else { RhsAssembler::assemble_for_MsFEM_symmetric< 2* DiscreteFunctionSpace::polynomialOrder + 2 >(f, specifier, subgrid_list, msfem_rhs); } msfem_rhs.communicate(); assert(msfem_rhs.dofsValid() && "Coarse scale RHS DOFs need to be valid!"); const InverseOperatorType msfem_biCGStab(msfem_matrix, 1e-8, 1e-8, 2000, true, "bcgs", DSC_CONFIG_GET("preconditioner_type", std::string("sor"))); msfem_biCGStab(msfem_rhs, coarse_msfem_solution); DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl; DSC_LOG_INFO << "MsFEM problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl << std::endl; if (!coarse_msfem_solution.dofsValid()) DUNE_THROW(InvalidStateException, "Degrees of freedom of coarse solution are not valid!"); // get the dirichlet values solution.clear(); Dune::Multiscale::projectDirichletValues(coarse_space, solution); //! copy coarse scale part of MsFEM solution into a function defined on the fine grid projectCoarseToFineScale( specifier, coarse_msfem_solution, coarse_scale_part ); //! identify fine scale part of MsFEM solution (including the projection!) identify_fine_scale_part( specifier, subgrid_list, coarse_msfem_solution, fine_scale_part ); { DSC::Profiler::ScopedTiming commFSTimer("msfem.Elliptic_MsFEM_Solver.solve_dirichlet_zero.comm_fine_scale_part"); fine_scale_part.communicate(); } assert(coarse_scale_part.dofsValid() && "Coarse scale part DOFs need to be valid!"); assert(fine_scale_part.dofsValid() && "Fine scale part DOFs need to be valid!"); // add coarse and fine scale part to solution solution += coarse_scale_part; solution += fine_scale_part; } // solve_dirichlet_zero } //namespace MsFEM { } //namespace Multiscale { } //namespace Dune { <|endoftext|>
<commit_before>#include "audio.h" #include <core/path.h> #include <text/text.h> #include <dirent.h> #include <stdio.h> #include <string.h> #include <taglib/mpegfile.h> #include <taglib/taglib.h> #include <taglib/vorbisfile.h> #include <taglib/mp4file.h> #include <taglib/opusfile.h> #include <unistd.h> std::string Audio::filepath(Format f) const{ std::string base = eqbeatsDir() + "/tracks/"; if(f == MP3) return base + number(track->id) + ".mp3"; if(f == Vorbis) return base + number(track->id) + ".ogg"; if(f == AAC) return base + number(track->id) + ".aac"; if(f == Opus) return base + number(track->id) + ".opus"; // Otherwise, Original DIR *dirp = opendir(base.c_str()); struct dirent *e; std::string name = number(track->id) + ".orig."; std::string ext; while((e = readdir(dirp)) != NULL){ if(strncmp(e->d_name, name.c_str(), name.size()) == 0){ ext = e->d_name + name.size(); break; } } closedir(dirp); if(ext.empty()) return std::string(); return base + name + ext; } void Audio::updateTags(Format format){ if(format == MP3 && access(filepath(MP3).c_str(), R_OK) == 0){ TagLib::MPEG::File mp3(filepath(MP3).c_str()); TagLib::Tag *t = mp3.tag(); if(!t) return; t->setTitle(TagLib::String(track->title, TagLib::String::UTF8)); t->setArtist(TagLib::String(track->artist.name, TagLib::String::UTF8)); mp3.save(TagLib::MPEG::File::ID3v1 | TagLib::MPEG::File::ID3v2); } else if(format == Vorbis && access(filepath(Vorbis).c_str(), R_OK) == 0) { TagLib::Ogg::Vorbis::File vorbis(filepath(Vorbis).c_str()); TagLib::Tag *t = vorbis.tag(); if(!t) return; t->setTitle(TagLib::String(track->title, TagLib::String::UTF8)); t->setArtist(TagLib::String(track->artist.name, TagLib::String::UTF8)); vorbis.save(); } else if(format == AAC && access(filepath(AAC).c_str(), R_OK) == 0) { TagLib::MP4::File aac(filepath(AAC).c_str()); TagLib::Tag *t = aac.tag(); if(!t) return; t->setTitle(TagLib::String(track->title)); t->setArtist(TagLib::String(track->artist.name)); aac.save(); } else if(format == Opus && access(filepath(Opus).c_str(), R_OK) == 0) { TagLib::Ogg::Opus::File opus(filepath(Opus).c_str()); TagLib::Tag *t = opus.tag(); if(!t) return; t->setTitle(track->title); t->setArtist(track->artist.name); opus.save(); } } void Audio::unlink(){ ::unlink(filepath(MP3).c_str()); ::unlink(filepath(Vorbis).c_str()); ::unlink(filepath(Original).c_str()); ::unlink(filepath(Opus).c_str()); ::unlink(filepath(AAC).c_str()); } File Audio::mp3() const{ return File("tracks/" + number(track->id) + ".mp3", track->artist.name + " - " + track->title + ".mp3"); } File Audio::vorbis() const{ return File("tracks/" + number(track->id) + ".ogg", track->artist.name + " - " + track->title + ".ogg"); } File Audio::aac() const{ return File("tracks/" + number(track->id) + ".m4a", track->artist.name + " - " + track->title + ".m4a"); } File Audio::opus() const{ return File("tracks/" + number(track->id) + ".opus", track->artist.name + " - " + track->title + ".opus"); } File Audio::original() const{ std::string path = filepath(Original); std::string ext = path.substr(path.rfind('.')); return File("tracks/" + number(track->id) + ".orig" + ext, track->title + " - " + track->artist.name + ext); } void Audio::fill(Dict *d){ std::string path = filepath(Original); // Status if(path.empty()){ // no original file -> not ready const char* status; if(access(filepath(MP3).c_str(), R_OK) == 0) // mp3 exists, but not the original file status = "Transcoding into MP3..."; else if(access(filepath(Opus).c_str(), R_OK) == 0) // Vorbis, AAC and Opus exist status = "Transcoding into Opus..."; else if(access(filepath(AAC).c_str(), R_OK) == 0) // Vorbis and AAC exist status = "Transcoding into AAC..."; else if(access(filepath(Vorbis).c_str(), R_OK) == 0) // Only vorbis exists status = "Transcoding into Vorbis..."; else // no mp3, vorbis, or original file status = "Couldn't transcode."; d->SetValueAndShowSection("STATUS", status, "HAS_STATUS"); } // Ready else{ d->ShowSection("READY"); std::string ext = path.substr(path.rfind('.')); if(ext == ".mp3") d->ShowSection("MP3_SOURCE"); else d->SetValueAndShowSection("EXTENSION", ext, "OTHER_SOURCE"); } } <commit_msg>fix: crash when downloading a track that failed transcoding<commit_after>#include "audio.h" #include <core/path.h> #include <text/text.h> #include <dirent.h> #include <stdio.h> #include <string.h> #include <taglib/mpegfile.h> #include <taglib/taglib.h> #include <taglib/vorbisfile.h> #include <taglib/mp4file.h> #include <taglib/opusfile.h> #include <unistd.h> std::string Audio::filepath(Format f) const{ std::string base = eqbeatsDir() + "/tracks/"; if(f == MP3) return base + number(track->id) + ".mp3"; if(f == Vorbis) return base + number(track->id) + ".ogg"; if(f == AAC) return base + number(track->id) + ".aac"; if(f == Opus) return base + number(track->id) + ".opus"; // Otherwise, Original DIR *dirp = opendir(base.c_str()); struct dirent *e; std::string name = number(track->id) + ".orig."; std::string ext; while((e = readdir(dirp)) != NULL){ if(strncmp(e->d_name, name.c_str(), name.size()) == 0){ ext = e->d_name + name.size(); break; } } closedir(dirp); if(ext.empty()) return std::string(); return base + name + ext; } void Audio::updateTags(Format format){ if(format == MP3 && access(filepath(MP3).c_str(), R_OK) == 0){ TagLib::MPEG::File mp3(filepath(MP3).c_str()); TagLib::Tag *t = mp3.tag(); if(!t) return; t->setTitle(TagLib::String(track->title, TagLib::String::UTF8)); t->setArtist(TagLib::String(track->artist.name, TagLib::String::UTF8)); mp3.save(TagLib::MPEG::File::ID3v1 | TagLib::MPEG::File::ID3v2); } else if(format == Vorbis && access(filepath(Vorbis).c_str(), R_OK) == 0) { TagLib::Ogg::Vorbis::File vorbis(filepath(Vorbis).c_str()); TagLib::Tag *t = vorbis.tag(); if(!t) return; t->setTitle(TagLib::String(track->title, TagLib::String::UTF8)); t->setArtist(TagLib::String(track->artist.name, TagLib::String::UTF8)); vorbis.save(); } else if(format == AAC && access(filepath(AAC).c_str(), R_OK) == 0) { TagLib::MP4::File aac(filepath(AAC).c_str()); TagLib::Tag *t = aac.tag(); if(!t) return; t->setTitle(TagLib::String(track->title)); t->setArtist(TagLib::String(track->artist.name)); aac.save(); } else if(format == Opus && access(filepath(Opus).c_str(), R_OK) == 0) { TagLib::Ogg::Opus::File opus(filepath(Opus).c_str()); TagLib::Tag *t = opus.tag(); if(!t) return; t->setTitle(track->title); t->setArtist(track->artist.name); opus.save(); } } void Audio::unlink(){ ::unlink(filepath(MP3).c_str()); ::unlink(filepath(Vorbis).c_str()); ::unlink(filepath(Original).c_str()); ::unlink(filepath(Opus).c_str()); ::unlink(filepath(AAC).c_str()); } File Audio::mp3() const{ if(access(filepath(MP3).c_str(), R_OK) != 0) return File(); return File("tracks/" + number(track->id) + ".mp3", track->artist.name + " - " + track->title + ".mp3"); } File Audio::vorbis() const{ if(access(filepath(Vorbis).c_str(), R_OK) != 0) return File(); return File("tracks/" + number(track->id) + ".ogg", track->artist.name + " - " + track->title + ".ogg"); } File Audio::aac() const{ if(access(filepath(AAC).c_str(), R_OK) != 0) return File(); return File("tracks/" + number(track->id) + ".m4a", track->artist.name + " - " + track->title + ".m4a"); } File Audio::opus() const{ if(access(filepath(Opus).c_str(), R_OK) != 0) return File(); return File("tracks/" + number(track->id) + ".opus", track->artist.name + " - " + track->title + ".opus"); } File Audio::original() const{ std::string path = filepath(Original); if(access(path.c_str(), R_OK) != 0) return File(); std::string ext = path.substr(path.rfind('.')); return File("tracks/" + number(track->id) + ".orig" + ext, track->title + " - " + track->artist.name + ext); } void Audio::fill(Dict *d){ std::string path = filepath(Original); // Status if(path.empty()){ // no original file -> not ready const char* status; if(access(filepath(MP3).c_str(), R_OK) == 0) // mp3 exists, but not the original file status = "Transcoding into MP3..."; else if(access(filepath(Opus).c_str(), R_OK) == 0) // Vorbis, AAC and Opus exist status = "Transcoding into Opus..."; else if(access(filepath(AAC).c_str(), R_OK) == 0) // Vorbis and AAC exist status = "Transcoding into AAC..."; else if(access(filepath(Vorbis).c_str(), R_OK) == 0) // Only vorbis exists status = "Transcoding into Vorbis..."; else // no mp3, vorbis, or original file status = "Couldn't transcode."; d->SetValueAndShowSection("STATUS", status, "HAS_STATUS"); } // Ready else{ d->ShowSection("READY"); std::string ext = path.substr(path.rfind('.')); if(ext == ".mp3") d->ShowSection("MP3_SOURCE"); else d->SetValueAndShowSection("EXTENSION", ext, "OTHER_SOURCE"); } } <|endoftext|>
<commit_before>// Include standard headers #include <stdio.h> #include <stdlib.h> #include "cleanup.h" // Include GLEW #ifdef __APPLE_CC__ #include <OpenGL/gl3.h> #define GLFW_INCLUDE_GLCOREARB #else #include "GL/glew.h" #endif #include "SDL.h" #undef main // Include GLM #include "glm/glm.hpp" #include <iostream> #include <common/Init.h> #include <common/Shader.h> using namespace glm; int main(int argc, char* argv[]) { //First we need to start up SDL, and make sure it went ok if (SDL_Init(SDL_INIT_VIDEO) != 0){ std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } /* Request opengl 3.3 context. * * SDL doesn't have the ability to choose which profile at this time of writing, * * but it should default to the core profile */ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); /* Turn on double buffering with a 24bit Z buffer. * * You may need to change this to 16 or 32 for your system */ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); //Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_OPENGL); //Make sure creating our window went ok if (win == nullptr){ std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; return 1; } SDL_GLContext glcontext = SDL_GL_CreateContext(win); SDL_GL_MakeCurrent(win,glcontext); Init init; init.glew(); //Initialize GLEW // glewExperimental = GL_TRUE; // GLenum glewError = glewInit(); // if( glewError != GLEW_OK ) // { // printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) ); // } //Load in shaders static ShaderProgram prog("vertShader.vert", "fragShader.frag"); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); static const GLfloat g_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); SDL_Event e; bool quit = false; while (!quit){ // Event polling while (SDL_PollEvent(&e)){ if (e.type == SDL_QUIT){ quit = true; } } glClearColor(0.3f, 0.3f, 0.3f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glCullFace(GL_BACK); prog(); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle glDisableVertexAttribArray(0); SDL_GL_SwapWindow(win); } // Check if the ESC key was pressed or the window was closed // Clean up SDL_GL_DeleteContext(glcontext); cleanup(win); SDL_Quit(); return 0; } <commit_msg>Reformat code<commit_after>// Include standard headers #include <stdio.h> #include <stdlib.h> #include "cleanup.h" // Include GLEW #ifdef __APPLE_CC__ #include <OpenGL/gl3.h> #define GLFW_INCLUDE_GLCOREARB #else #include "GL/glew.h" #endif #include "SDL.h" #undef main // Include GLM #include "glm/glm.hpp" #include <iostream> #include <common/Init.h> #include <common/Shader.h> using namespace glm; int main(int argc, char *argv[]) { //First we need to start up SDL, and make sure it went ok if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return 1; } /* Request opengl 3.3 context. * * SDL doesn't have the ability to choose which profile at this time of writing, * * but it should default to the core profile */ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); /* Turn on double buffering with a 24bit Z buffer. * * You may need to change this to 16 or 32 for your system */ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); //Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_OPENGL); //Make sure creating our window went ok if (win == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; return 1; } SDL_GLContext glcontext = SDL_GL_CreateContext(win); SDL_GL_MakeCurrent(win, glcontext); Init init; init.glew(); //Initialize GLEW // glewExperimental = GL_TRUE; // GLenum glewError = glewInit(); // if( glewError != GLEW_OK ) // { // printf( "Error initializing GLEW! %s\n", glewGetErrorString( glewError ) ); // } //Load in shaders static ShaderProgram prog("vertShader.vert", "fragShader.frag"); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); static const GLfloat g_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); SDL_Event e; bool quit = false; while (!quit) { // Event polling while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { quit = true; } } glClearColor(0.3f, 0.3f, 0.3f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glCullFace(GL_BACK); prog(); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void *) 0 // array buffer offset ); // Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 3); // 3 indices starting at 0 -> 1 triangle glDisableVertexAttribArray(0); SDL_GL_SwapWindow(win); } // Check if the ESC key was pressed or the window was closed // Clean up SDL_GL_DeleteContext(glcontext); cleanup(win); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/ForwardFramePipeline.hpp> #include <Nazara/Graphics/AbstractViewer.hpp> #include <Nazara/Graphics/FrameGraph.hpp> #include <Nazara/Graphics/Graphics.hpp> #include <Nazara/Graphics/InstancedRenderable.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/RenderElement.hpp> #include <Nazara/Graphics/SubmeshRenderer.hpp> #include <Nazara/Graphics/ViewerInstance.hpp> #include <Nazara/Graphics/WorldInstance.hpp> #include <Nazara/Renderer/CommandBufferBuilder.hpp> #include <Nazara/Renderer/Framebuffer.hpp> #include <Nazara/Renderer/RenderFrame.hpp> #include <Nazara/Renderer/RenderTarget.hpp> #include <Nazara/Renderer/UploadPool.hpp> #include <array> #include <Nazara/Graphics/Debug.hpp> namespace Nz { ForwardFramePipeline::ForwardFramePipeline() : m_rebuildFrameGraph(true), m_rebuildDepthPrepass(false), m_rebuildForwardPass(false) { auto& passRegistry = Graphics::Instance()->GetMaterialPassRegistry(); m_depthPassIndex = passRegistry.GetPassIndex("DepthPass"); m_forwardPassIndex = passRegistry.GetPassIndex("ForwardPass"); m_elementRenderers.resize(1); m_elementRenderers[UnderlyingCast(BasicRenderElement::Submesh)] = std::make_unique<SubmeshRenderer>(); } void ForwardFramePipeline::InvalidateViewer(AbstractViewer* viewerInstance) { m_invalidatedViewerInstances.insert(viewerInstance); } void ForwardFramePipeline::InvalidateWorldInstance(WorldInstance* worldInstance) { m_invalidatedWorldInstances.insert(worldInstance); } void ForwardFramePipeline::RegisterInstancedDrawable(WorldInstancePtr worldInstance, const InstancedRenderable* instancedRenderable) { m_removedWorldInstances.erase(worldInstance); auto& renderableMap = m_renderables[worldInstance]; if (renderableMap.empty()) InvalidateWorldInstance(worldInstance.get()); if (auto it = renderableMap.find(instancedRenderable); it == renderableMap.end()) { auto& renderableData = renderableMap.emplace(instancedRenderable, RenderableData{}).first->second; renderableData.onMaterialInvalidated.Connect(instancedRenderable->OnMaterialInvalidated, [this](InstancedRenderable* instancedRenderable, std::size_t materialIndex, const std::shared_ptr<Material>& newMaterial) { if (newMaterial) { if (MaterialPass* pass = newMaterial->GetPass(m_depthPassIndex)) RegisterMaterialPass(pass); if (MaterialPass* pass = newMaterial->GetPass(m_forwardPassIndex)) RegisterMaterialPass(pass); } const auto& prevMaterial = instancedRenderable->GetMaterial(materialIndex); if (prevMaterial) { if (MaterialPass* pass = prevMaterial->GetPass(m_depthPassIndex)) UnregisterMaterialPass(pass); if (MaterialPass* pass = prevMaterial->GetPass(m_forwardPassIndex)) UnregisterMaterialPass(pass); } m_rebuildDepthPrepass = true; m_rebuildForwardPass = true; }); std::size_t matCount = instancedRenderable->GetMaterialCount(); for (std::size_t i = 0; i < matCount; ++i) { if (Material* mat = instancedRenderable->GetMaterial(i).get()) { if (MaterialPass* pass = mat->GetPass(m_depthPassIndex)) RegisterMaterialPass(pass); if (MaterialPass* pass = mat->GetPass(m_forwardPassIndex)) RegisterMaterialPass(pass); } } m_rebuildDepthPrepass = true; m_rebuildForwardPass = true; } } void ForwardFramePipeline::RegisterViewer(AbstractViewer* viewerInstance) { m_viewers.emplace(viewerInstance, ViewerData{}); m_invalidatedViewerInstances.insert(viewerInstance); } void ForwardFramePipeline::Render(RenderFrame& renderFrame) { Graphics* graphics = Graphics::Instance(); renderFrame.PushForRelease(std::move(m_removedWorldInstances)); m_removedWorldInstances.clear(); if (m_rebuildFrameGraph) { renderFrame.PushForRelease(std::move(m_bakedFrameGraph)); m_bakedFrameGraph = BuildFrameGraph(); } // Update UBOs and materials UploadPool& uploadPool = renderFrame.GetUploadPool(); renderFrame.Execute([&](CommandBufferBuilder& builder) { builder.BeginDebugRegion("UBO Update", Color::Yellow); { builder.PreTransferBarrier(); for (AbstractViewer* viewer : m_invalidatedViewerInstances) viewer->GetViewerInstance().UpdateBuffers(uploadPool, builder); m_invalidatedViewerInstances.clear(); for (WorldInstance* worldInstance : m_invalidatedWorldInstances) worldInstance->UpdateBuffers(uploadPool, builder); m_invalidatedWorldInstances.clear(); for (MaterialPass* material : m_invalidatedMaterials) { if (material->Update(renderFrame, builder)) { m_rebuildDepthPrepass = true; m_rebuildForwardPass = true; } } m_invalidatedMaterials.clear(); builder.PostTransferBarrier(); } builder.EndDebugRegion(); }, QueueType::Transfer); if (m_rebuildDepthPrepass) { m_depthPrepassRenderElements.clear(); for (const auto& [worldInstance, renderables] : m_renderables) { for (const auto& [renderable, renderableData] : renderables) renderable->BuildElement(m_depthPassIndex, *worldInstance, m_depthPrepassRenderElements); } } if (m_rebuildForwardPass) { m_forwardRenderElements.clear(); for (const auto& [worldInstance, renderables] : m_renderables) { for (const auto& [renderable, renderableData] : renderables) renderable->BuildElement(m_forwardPassIndex, *worldInstance, m_forwardRenderElements); } } // RenderQueue handling m_depthPrepassRegistry.Clear(); m_depthPrepassRenderQueue.Clear(); for (const auto& renderElement : m_depthPrepassRenderElements) { renderElement->Register(m_depthPrepassRegistry); m_depthPrepassRenderQueue.Insert(renderElement.get()); } m_depthPrepassRenderQueue.Sort([&](const RenderElement* element) { return element->ComputeSortingScore(m_depthPrepassRegistry); }); m_forwardRegistry.Clear(); m_forwardRenderQueue.Clear(); for (const auto& renderElement : m_forwardRenderElements) { renderElement->Register(m_forwardRegistry); m_forwardRenderQueue.Insert(renderElement.get()); } m_forwardRenderQueue.Sort([&](const RenderElement* element) { return element->ComputeSortingScore(m_forwardRegistry); }); if (m_bakedFrameGraph.Resize(renderFrame)) { const std::shared_ptr<TextureSampler>& sampler = graphics->GetSamplerCache().Get({}); for (auto&& [_, viewerData] : m_viewers) { if (viewerData.blitShaderBinding) renderFrame.PushForRelease(std::move(viewerData.blitShaderBinding)); viewerData.blitShaderBinding = graphics->GetBlitPipelineLayout()->AllocateShaderBinding(0); viewerData.blitShaderBinding->Update({ { 0, ShaderBinding::TextureBinding { m_bakedFrameGraph.GetAttachmentTexture(viewerData.colorAttachment).get(), sampler.get() } } }); } } m_bakedFrameGraph.Execute(renderFrame); m_rebuildForwardPass = false; m_rebuildDepthPrepass = false; m_rebuildFrameGraph = false; const Vector2ui& frameSize = renderFrame.GetSize(); for (auto&& [viewer, viewerData] : m_viewers) { const RenderTarget& renderTarget = viewer->GetRenderTarget(); Recti renderRegion(0, 0, frameSize.x, frameSize.y); const ShaderBindingPtr& blitShaderBinding = viewerData.blitShaderBinding; const std::shared_ptr<Texture>& sourceTexture = m_bakedFrameGraph.GetAttachmentTexture(viewerData.colorAttachment); renderFrame.Execute([&](CommandBufferBuilder& builder) { builder.TextureBarrier(PipelineStage::ColorOutput, PipelineStage::FragmentShader, MemoryAccess::ColorWrite, MemoryAccess::ShaderRead, TextureLayout::ColorOutput, TextureLayout::ColorInput, *sourceTexture); std::array<CommandBufferBuilder::ClearValues, 2> clearValues; clearValues[0].color = Color::Black; clearValues[1].depth = 1.f; clearValues[1].stencil = 0; builder.BeginDebugRegion("Main window rendering", Color::Green); { builder.BeginRenderPass(renderTarget.GetFramebuffer(renderFrame.GetFramebufferIndex()), renderTarget.GetRenderPass(), renderRegion, { clearValues[0], clearValues[1] }); { builder.SetScissor(renderRegion); builder.SetViewport(renderRegion); builder.BindPipeline(*graphics->GetBlitPipeline()); builder.BindVertexBuffer(0, *graphics->GetFullscreenVertexBuffer()); builder.BindShaderBinding(0, *blitShaderBinding); builder.Draw(3); } builder.EndRenderPass(); } builder.EndDebugRegion(); }, QueueType::Graphics); } } void ForwardFramePipeline::UnregisterInstancedDrawable(const WorldInstancePtr& worldInstance, const InstancedRenderable* instancedRenderable) { auto instanceIt = m_renderables.find(worldInstance); if (instanceIt == m_renderables.end()) return; auto& instancedRenderables = instanceIt->second; auto renderableIt = instancedRenderables.find(instancedRenderable); if (renderableIt == instancedRenderables.end()) return; if (instancedRenderables.size() > 1) instancedRenderables.erase(renderableIt); else { m_removedWorldInstances.insert(worldInstance); m_renderables.erase(instanceIt);; } std::size_t matCount = instancedRenderable->GetMaterialCount(); for (std::size_t i = 0; i < matCount; ++i) { if (MaterialPass* pass = instancedRenderable->GetMaterial(i)->GetPass(m_depthPassIndex)) UnregisterMaterialPass(pass); if (MaterialPass* pass = instancedRenderable->GetMaterial(i)->GetPass(m_forwardPassIndex)) UnregisterMaterialPass(pass); } m_rebuildDepthPrepass = true; m_rebuildForwardPass = true; } void ForwardFramePipeline::UnregisterViewer(AbstractViewer* viewerInstance) { m_viewers.erase(viewerInstance); m_rebuildFrameGraph = true; } BakedFrameGraph ForwardFramePipeline::BuildFrameGraph() { FrameGraph frameGraph; for (auto&& [viewer, viewerData] : m_viewers) { viewerData.colorAttachment = frameGraph.AddAttachment({ "Color", PixelFormat::RGBA8 }); viewerData.depthStencilAttachment = frameGraph.AddAttachment({ "Depth-stencil buffer", Graphics::Instance()->GetPreferredDepthStencilFormat() }); } for (auto&& [viewer, viewerData] : m_viewers) { FramePass& depthPrepass = frameGraph.AddPass("Depth pre-pass"); depthPrepass.SetDepthStencilOutput(viewerData.depthStencilAttachment); depthPrepass.SetDepthStencilClear(1.f, 0); depthPrepass.SetExecutionCallback([this]() { if (m_rebuildForwardPass) return FramePassExecution::UpdateAndExecute; else return FramePassExecution::Execute; }); depthPrepass.SetCommandCallback([this, viewer = viewer](CommandBufferBuilder& builder, const Recti& /*renderRect*/) { Recti viewport = viewer->GetViewport(); builder.SetScissor(viewport); builder.SetViewport(viewport); builder.BindShaderBinding(Graphics::ViewerBindingSet, viewer->GetViewerInstance().GetShaderBinding()); ProcessRenderQueue(builder, m_depthPrepassRenderQueue); }); FramePass& forwardPass = frameGraph.AddPass("Forward pass"); forwardPass.AddOutput(viewerData.colorAttachment); forwardPass.SetDepthStencilInput(viewerData.depthStencilAttachment); //forwardPass.SetDepthStencilOutput(viewerData.depthStencilAttachment); forwardPass.SetClearColor(0, Color::Black); forwardPass.SetDepthStencilClear(1.f, 0); forwardPass.SetExecutionCallback([this]() { if (m_rebuildForwardPass) return FramePassExecution::UpdateAndExecute; else return FramePassExecution::Execute; }); forwardPass.SetCommandCallback([this, viewer = viewer](CommandBufferBuilder& builder, const Recti& /*renderRect*/) { Recti viewport = viewer->GetViewport(); builder.SetScissor(viewport); builder.SetViewport(viewport); builder.BindShaderBinding(Graphics::ViewerBindingSet, viewer->GetViewerInstance().GetShaderBinding()); ProcessRenderQueue(builder, m_forwardRenderQueue); }); } //FIXME: This doesn't handle multiple window viewers for (auto&& [viewer, viewerData] : m_viewers) frameGraph.SetBackbufferOutput(viewerData.colorAttachment); return frameGraph.Bake(); } void ForwardFramePipeline::RegisterMaterialPass(MaterialPass* material) { auto it = m_materials.find(material); if (it == m_materials.end()) { it = m_materials.emplace(material, MaterialData{}).first; it->second.onMaterialInvalided.Connect(material->OnMaterialInvalidated, [this, material](const MaterialPass* /*material*/) { m_invalidatedMaterials.insert(material); }); m_invalidatedMaterials.insert(material); } it->second.usedCount++; } void ForwardFramePipeline::ProcessRenderQueue(CommandBufferBuilder& builder, const RenderQueue<RenderElement*>& renderQueue) { if (renderQueue.empty()) return; auto it = renderQueue.begin(); auto itEnd = renderQueue.end(); while (it != itEnd) { const RenderElement* element = *it; UInt8 elementType = element->GetElementType(); const Pointer<const RenderElement>* first = it; ++it; while (it != itEnd && (*it)->GetElementType() == elementType) ++it; std::size_t count = it - first; if (elementType >= m_elementRenderers.size() || !m_elementRenderers[elementType]) continue; ElementRenderer& elementRenderer = *m_elementRenderers[elementType]; elementRenderer.Render(builder, first, count); } } void ForwardFramePipeline::UnregisterMaterialPass(MaterialPass* material) { auto it = m_materials.find(material); assert(it != m_materials.end()); MaterialData& materialData = it->second; assert(materialData.usedCount > 0); if (--materialData.usedCount == 0) m_materials.erase(material); } } <commit_msg>Fix compilation<commit_after>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/ForwardFramePipeline.hpp> #include <Nazara/Graphics/AbstractViewer.hpp> #include <Nazara/Graphics/FrameGraph.hpp> #include <Nazara/Graphics/Graphics.hpp> #include <Nazara/Graphics/InstancedRenderable.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/RenderElement.hpp> #include <Nazara/Graphics/SubmeshRenderer.hpp> #include <Nazara/Graphics/ViewerInstance.hpp> #include <Nazara/Graphics/WorldInstance.hpp> #include <Nazara/Renderer/CommandBufferBuilder.hpp> #include <Nazara/Renderer/Framebuffer.hpp> #include <Nazara/Renderer/RenderFrame.hpp> #include <Nazara/Renderer/RenderTarget.hpp> #include <Nazara/Renderer/UploadPool.hpp> #include <array> #include <Nazara/Graphics/Debug.hpp> namespace Nz { ForwardFramePipeline::ForwardFramePipeline() : m_rebuildFrameGraph(true), m_rebuildDepthPrepass(false), m_rebuildForwardPass(false) { auto& passRegistry = Graphics::Instance()->GetMaterialPassRegistry(); m_depthPassIndex = passRegistry.GetPassIndex("DepthPass"); m_forwardPassIndex = passRegistry.GetPassIndex("ForwardPass"); m_elementRenderers.resize(1); m_elementRenderers[UnderlyingCast(BasicRenderElement::Submesh)] = std::make_unique<SubmeshRenderer>(); } void ForwardFramePipeline::InvalidateViewer(AbstractViewer* viewerInstance) { m_invalidatedViewerInstances.insert(viewerInstance); } void ForwardFramePipeline::InvalidateWorldInstance(WorldInstance* worldInstance) { m_invalidatedWorldInstances.insert(worldInstance); } void ForwardFramePipeline::RegisterInstancedDrawable(WorldInstancePtr worldInstance, const InstancedRenderable* instancedRenderable) { m_removedWorldInstances.erase(worldInstance); auto& renderableMap = m_renderables[worldInstance]; if (renderableMap.empty()) InvalidateWorldInstance(worldInstance.get()); if (auto it = renderableMap.find(instancedRenderable); it == renderableMap.end()) { auto& renderableData = renderableMap.emplace(instancedRenderable, RenderableData{}).first->second; renderableData.onMaterialInvalidated.Connect(instancedRenderable->OnMaterialInvalidated, [this](InstancedRenderable* instancedRenderable, std::size_t materialIndex, const std::shared_ptr<Material>& newMaterial) { if (newMaterial) { if (MaterialPass* pass = newMaterial->GetPass(m_depthPassIndex)) RegisterMaterialPass(pass); if (MaterialPass* pass = newMaterial->GetPass(m_forwardPassIndex)) RegisterMaterialPass(pass); } const auto& prevMaterial = instancedRenderable->GetMaterial(materialIndex); if (prevMaterial) { if (MaterialPass* pass = prevMaterial->GetPass(m_depthPassIndex)) UnregisterMaterialPass(pass); if (MaterialPass* pass = prevMaterial->GetPass(m_forwardPassIndex)) UnregisterMaterialPass(pass); } m_rebuildDepthPrepass = true; m_rebuildForwardPass = true; }); std::size_t matCount = instancedRenderable->GetMaterialCount(); for (std::size_t i = 0; i < matCount; ++i) { if (Material* mat = instancedRenderable->GetMaterial(i).get()) { if (MaterialPass* pass = mat->GetPass(m_depthPassIndex)) RegisterMaterialPass(pass); if (MaterialPass* pass = mat->GetPass(m_forwardPassIndex)) RegisterMaterialPass(pass); } } m_rebuildDepthPrepass = true; m_rebuildForwardPass = true; } } void ForwardFramePipeline::RegisterViewer(AbstractViewer* viewerInstance) { m_viewers.emplace(viewerInstance, ViewerData{}); m_invalidatedViewerInstances.insert(viewerInstance); } void ForwardFramePipeline::Render(RenderFrame& renderFrame) { Graphics* graphics = Graphics::Instance(); renderFrame.PushForRelease(std::move(m_removedWorldInstances)); m_removedWorldInstances.clear(); if (m_rebuildFrameGraph) { renderFrame.PushForRelease(std::move(m_bakedFrameGraph)); m_bakedFrameGraph = BuildFrameGraph(); } // Update UBOs and materials UploadPool& uploadPool = renderFrame.GetUploadPool(); renderFrame.Execute([&](CommandBufferBuilder& builder) { builder.BeginDebugRegion("UBO Update", Color::Yellow); { builder.PreTransferBarrier(); for (AbstractViewer* viewer : m_invalidatedViewerInstances) viewer->GetViewerInstance().UpdateBuffers(uploadPool, builder); m_invalidatedViewerInstances.clear(); for (WorldInstance* worldInstance : m_invalidatedWorldInstances) worldInstance->UpdateBuffers(uploadPool, builder); m_invalidatedWorldInstances.clear(); for (MaterialPass* material : m_invalidatedMaterials) { if (material->Update(renderFrame, builder)) { m_rebuildDepthPrepass = true; m_rebuildForwardPass = true; } } m_invalidatedMaterials.clear(); builder.PostTransferBarrier(); } builder.EndDebugRegion(); }, QueueType::Transfer); if (m_rebuildDepthPrepass) { m_depthPrepassRenderElements.clear(); for (const auto& [worldInstance, renderables] : m_renderables) { for (const auto& [renderable, renderableData] : renderables) renderable->BuildElement(m_depthPassIndex, *worldInstance, m_depthPrepassRenderElements); } } if (m_rebuildForwardPass) { m_forwardRenderElements.clear(); for (const auto& [worldInstance, renderables] : m_renderables) { for (const auto& [renderable, renderableData] : renderables) renderable->BuildElement(m_forwardPassIndex, *worldInstance, m_forwardRenderElements); } } // RenderQueue handling m_depthPrepassRegistry.Clear(); m_depthPrepassRenderQueue.Clear(); for (const auto& renderElement : m_depthPrepassRenderElements) { renderElement->Register(m_depthPrepassRegistry); m_depthPrepassRenderQueue.Insert(renderElement.get()); } m_depthPrepassRenderQueue.Sort([&](const RenderElement* element) { return element->ComputeSortingScore(m_depthPrepassRegistry); }); m_forwardRegistry.Clear(); m_forwardRenderQueue.Clear(); for (const auto& renderElement : m_forwardRenderElements) { renderElement->Register(m_forwardRegistry); m_forwardRenderQueue.Insert(renderElement.get()); } m_forwardRenderQueue.Sort([&](const RenderElement* element) { return element->ComputeSortingScore(m_forwardRegistry); }); if (m_bakedFrameGraph.Resize(renderFrame)) { const std::shared_ptr<TextureSampler>& sampler = graphics->GetSamplerCache().Get({}); for (auto&& [_, viewerData] : m_viewers) { if (viewerData.blitShaderBinding) renderFrame.PushForRelease(std::move(viewerData.blitShaderBinding)); viewerData.blitShaderBinding = graphics->GetBlitPipelineLayout()->AllocateShaderBinding(0); viewerData.blitShaderBinding->Update({ { 0, ShaderBinding::TextureBinding { m_bakedFrameGraph.GetAttachmentTexture(viewerData.colorAttachment).get(), sampler.get() } } }); } } m_bakedFrameGraph.Execute(renderFrame); m_rebuildForwardPass = false; m_rebuildDepthPrepass = false; m_rebuildFrameGraph = false; const Vector2ui& frameSize = renderFrame.GetSize(); for (auto&& [viewer, viewerData] : m_viewers) { const RenderTarget& renderTarget = viewer->GetRenderTarget(); Recti renderRegion(0, 0, frameSize.x, frameSize.y); const ShaderBindingPtr& blitShaderBinding = viewerData.blitShaderBinding; const std::shared_ptr<Texture>& sourceTexture = m_bakedFrameGraph.GetAttachmentTexture(viewerData.colorAttachment); renderFrame.Execute([&](CommandBufferBuilder& builder) { builder.TextureBarrier(PipelineStage::ColorOutput, PipelineStage::FragmentShader, MemoryAccess::ColorWrite, MemoryAccess::ShaderRead, TextureLayout::ColorOutput, TextureLayout::ColorInput, *sourceTexture); std::array<CommandBufferBuilder::ClearValues, 2> clearValues; clearValues[0].color = Color::Black; clearValues[1].depth = 1.f; clearValues[1].stencil = 0; builder.BeginDebugRegion("Main window rendering", Color::Green); { builder.BeginRenderPass(renderTarget.GetFramebuffer(renderFrame.GetFramebufferIndex()), renderTarget.GetRenderPass(), renderRegion, { clearValues[0], clearValues[1] }); { builder.SetScissor(renderRegion); builder.SetViewport(renderRegion); builder.BindPipeline(*graphics->GetBlitPipeline()); builder.BindVertexBuffer(0, *graphics->GetFullscreenVertexBuffer()); builder.BindShaderBinding(0, *blitShaderBinding); builder.Draw(3); } builder.EndRenderPass(); } builder.EndDebugRegion(); }, QueueType::Graphics); } } void ForwardFramePipeline::UnregisterInstancedDrawable(const WorldInstancePtr& worldInstance, const InstancedRenderable* instancedRenderable) { auto instanceIt = m_renderables.find(worldInstance); if (instanceIt == m_renderables.end()) return; auto& instancedRenderables = instanceIt->second; auto renderableIt = instancedRenderables.find(instancedRenderable); if (renderableIt == instancedRenderables.end()) return; if (instancedRenderables.size() > 1) instancedRenderables.erase(renderableIt); else { m_removedWorldInstances.insert(worldInstance); m_renderables.erase(instanceIt);; } std::size_t matCount = instancedRenderable->GetMaterialCount(); for (std::size_t i = 0; i < matCount; ++i) { if (MaterialPass* pass = instancedRenderable->GetMaterial(i)->GetPass(m_depthPassIndex)) UnregisterMaterialPass(pass); if (MaterialPass* pass = instancedRenderable->GetMaterial(i)->GetPass(m_forwardPassIndex)) UnregisterMaterialPass(pass); } m_rebuildDepthPrepass = true; m_rebuildForwardPass = true; } void ForwardFramePipeline::UnregisterViewer(AbstractViewer* viewerInstance) { m_viewers.erase(viewerInstance); m_rebuildFrameGraph = true; } BakedFrameGraph ForwardFramePipeline::BuildFrameGraph() { FrameGraph frameGraph; for (auto&& [viewer, viewerData] : m_viewers) { viewerData.colorAttachment = frameGraph.AddAttachment({ "Color", PixelFormat::RGBA8 }); viewerData.depthStencilAttachment = frameGraph.AddAttachment({ "Depth-stencil buffer", Graphics::Instance()->GetPreferredDepthStencilFormat() }); } for (auto&& [viewer, viewerData] : m_viewers) { FramePass& depthPrepass = frameGraph.AddPass("Depth pre-pass"); depthPrepass.SetDepthStencilOutput(viewerData.depthStencilAttachment); depthPrepass.SetDepthStencilClear(1.f, 0); depthPrepass.SetExecutionCallback([this]() { if (m_rebuildForwardPass) return FramePassExecution::UpdateAndExecute; else return FramePassExecution::Execute; }); depthPrepass.SetCommandCallback([this, viewer = viewer](CommandBufferBuilder& builder, const Recti& /*renderRect*/) { Recti viewport = viewer->GetViewport(); builder.SetScissor(viewport); builder.SetViewport(viewport); builder.BindShaderBinding(Graphics::ViewerBindingSet, viewer->GetViewerInstance().GetShaderBinding()); ProcessRenderQueue(builder, m_depthPrepassRenderQueue); }); FramePass& forwardPass = frameGraph.AddPass("Forward pass"); forwardPass.AddOutput(viewerData.colorAttachment); forwardPass.SetDepthStencilInput(viewerData.depthStencilAttachment); //forwardPass.SetDepthStencilOutput(viewerData.depthStencilAttachment); forwardPass.SetClearColor(0, Color::Black); forwardPass.SetDepthStencilClear(1.f, 0); forwardPass.SetExecutionCallback([this]() { if (m_rebuildForwardPass) return FramePassExecution::UpdateAndExecute; else return FramePassExecution::Execute; }); forwardPass.SetCommandCallback([this, viewer = viewer](CommandBufferBuilder& builder, const Recti& /*renderRect*/) { Recti viewport = viewer->GetViewport(); builder.SetScissor(viewport); builder.SetViewport(viewport); builder.BindShaderBinding(Graphics::ViewerBindingSet, viewer->GetViewerInstance().GetShaderBinding()); ProcessRenderQueue(builder, m_forwardRenderQueue); }); } //FIXME: This doesn't handle multiple window viewers for (auto&& [viewer, viewerData] : m_viewers) frameGraph.SetBackbufferOutput(viewerData.colorAttachment); return frameGraph.Bake(); } void ForwardFramePipeline::RegisterMaterialPass(MaterialPass* material) { auto it = m_materials.find(material); if (it == m_materials.end()) { it = m_materials.emplace(material, MaterialData{}).first; it->second.onMaterialInvalided.Connect(material->OnMaterialInvalidated, [this, material](const MaterialPass* /*material*/) { m_invalidatedMaterials.insert(material); }); m_invalidatedMaterials.insert(material); } it->second.usedCount++; } void ForwardFramePipeline::ProcessRenderQueue(CommandBufferBuilder& builder, const RenderQueue<RenderElement*>& renderQueue) { if (renderQueue.empty()) return; auto it = renderQueue.begin(); auto itEnd = renderQueue.end(); while (it != itEnd) { const RenderElement* element = *it; UInt8 elementType = element->GetElementType(); const Pointer<RenderElement>* first = it; ++it; while (it != itEnd && (*it)->GetElementType() == elementType) ++it; std::size_t count = it - first; if (elementType >= m_elementRenderers.size() || !m_elementRenderers[elementType]) continue; ElementRenderer& elementRenderer = *m_elementRenderers[elementType]; elementRenderer.Render(builder, first, count); } } void ForwardFramePipeline::UnregisterMaterialPass(MaterialPass* material) { auto it = m_materials.find(material); assert(it != m_materials.end()); MaterialData& materialData = it->second; assert(materialData.usedCount > 0); if (--materialData.usedCount == 0) m_materials.erase(material); } } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> const int maxn = 110; const int MOD = (long long) 1e9 + 7L; typedef long long int64; int64 n, m; int64 dp[maxn][maxn][maxn]; inline int64 gcd(int64 a, int64 b) { if (a < b) a ^= b ^= a ^= b; return b == 0 ? a : gcd(b, a%b); } inline int64 min(int64 a,int64 b) { return a < b ? a : b; } inline int64 get(int64 i, int64 n, int64 r) { if (dp[i][n][r] != -1) return dp[i][n][r]; if (i>n) return 0L; int64 ans = 0; for (int64 y=1; y<=m; ++ y) { if (gcd(y*i, m) == r) { for (int64 x=min(i-1, n-i); x>0; --x) { ans += get(x, n-i, y); if (ans >= MOD) ans -= MOD; } } } return dp[i][n][r] = ans; } int main() { scanf("%lld %lld", &n, &m); memset(dp, -1, sizeof(dp)); /* dp[1][1][1] = 1; for (int r = 2; r <= m; ++ r) { dp[1][1][r] = 0; } */ for (int i = 1; i <= n; ++ i) { dp[i][i][gcd(i, m)] = 1; } int64 ans = 0; for (int i = 1; i <= n; ++ i) { ans += get(i, n, m); } printf("%lld\n", ans); return 0; } <commit_msg> add comment of dp<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> const int maxn = 110; const int MOD = (long long) 1e9 + 7L; typedef long long int64; int64 n, m; int64 dp[maxn][maxn][maxn]; inline int64 gcd(int64 a, int64 b) { if (a < b) a ^= b ^= a ^= b; return b == 0 ? a : gcd(b, a%b); } inline int64 min(int64 a,int64 b) { return a < b ? a : b; } /* 状态表示最后一个数为 i,和为 n, 所有的数的乘积与 m 的 最大公约数为 r 的个数。答案就是 n = n,r = m 的时候。 */ inline int64 get(int64 i, int64 n, int64 r) { if (dp[i][n][r] != -1) return dp[i][n][r]; if (i>n) return 0L; int64 ans = 0; for (int64 y=1; y<=m; ++ y) { if (gcd(y*i, m) == r) { for (int64 x=min(i-1, n-i); x>0; --x) { ans += get(x, n-i, y); if (ans >= MOD) ans -= MOD; } } } return dp[i][n][r] = ans; } int main() { scanf("%lld %lld", &n, &m); memset(dp, -1, sizeof(dp)); /* dp[1][1][1] = 1; for (int r = 2; r <= m; ++ r) { dp[1][1][r] = 0; } */ for (int i = 1; i <= n; ++ i) { dp[i][i][gcd(i, m)] = 1; } int64 ans = 0; for (int i = 1; i <= n; ++ i) { ans += get(i, n, m); } printf("%lld\n", ans); return 0; } <|endoftext|>
<commit_before>#include <ir/index_manager/index/RTPostingWriter.h> #include <ir/index_manager/index/OutputDescriptor.h> #include <ir/index_manager/index/InputDescriptor.h> #include <ir/index_manager/index/SkipListWriter.h> #include <ir/index_manager/index/SkipListReader.h> #include <ir/index_manager/store/IndexOutput.h> #include <ir/index_manager/store/IndexInput.h> #include <math.h> using namespace std; NS_IZENELIB_IR_BEGIN namespace indexmanager{ RTPostingWriter::RTPostingWriter(MemCache* pCache, int skipInterval, int maxSkipLevel) :pMemCache_(pCache) ,skipInterval_(skipInterval) ,maxSkipLevel_(maxSkipLevel) ,nDF_(0) ,nLastDocID_(BAD_DOCID) ,nLastLoc_(BAD_DOCID) ,nCurTermFreq_(0) ,nCTF_(0) ,pSkipListWriter_(0) ,dirty_(false) { pDocFreqList_ = new VariantDataPool(pCache); pLocList_ = new VariantDataPool(pCache); if(skipInterval_) pSkipListWriter_ = new SkipListWriter(skipInterval_,maxSkipLevel_,pMemCache_); } RTPostingWriter::~RTPostingWriter() { if (pDocFreqList_) { delete pDocFreqList_; pDocFreqList_ = NULL; } if (pLocList_) { delete pLocList_; pLocList_ = NULL; } pMemCache_ = NULL; if(pSkipListWriter_) { delete pSkipListWriter_; pSkipListWriter_ = 0; } } bool RTPostingWriter::isEmpty() { return (pDocFreqList_->pTailChunk_==NULL); } void RTPostingWriter::write(OutputDescriptor* pOutputDescriptor, TermInfo& termInfo) { ///flush last document flushLastDoc(true); termInfo.docFreq_ = nDF_; termInfo.ctf_ = nCTF_; termInfo.lastDocID_ = nLastDocID_; if(skipInterval_ && nDF_ > 0 && nDF_ % skipInterval_ == 0) { if(pSkipListWriter_) { pSkipListWriter_->addSkipPoint(nLastDocID_,pDocFreqList_->getLength(),pLocList_->getLength()); } } IndexOutput* pDOutput = pOutputDescriptor->getDPostingOutput(); if( pSkipListWriter_ && pSkipListWriter_->getNumLevels() > 0) ///nDF_ > SkipInterval { termInfo.skipLevel_ = pSkipListWriter_->getNumLevels(); termInfo.skipPointer_ = pDOutput->getFilePointer(); pSkipListWriter_->write(pDOutput); ///write skip list data } else { termInfo.skipPointer_ = -1; termInfo.skipLevel_ = 0; } ///save the offset of posting descriptor termInfo.docPointer_ = pDOutput->getFilePointer(); ///write doc posting data pDocFreqList_->write(pDOutput); termInfo.docPostingLen_ = pDOutput->getFilePointer() - termInfo.docPointer_; IndexOutput* pPOutput = pOutputDescriptor->getPPostingOutput(); termInfo.positionPointer_ = pPOutput->getFilePointer(); ///write position posting data pLocList_->write(pPOutput); termInfo.positionPostingLen_ = pPOutput->getFilePointer() - termInfo.positionPointer_; } void RTPostingWriter::reset() { pDocFreqList_->reset(); pLocList_->reset(); nCTF_ = 0; nLastDocID_ = BAD_DOCID; nLastLoc_ = 0; nDF_ = 0; nCurTermFreq_ = 0; if(pSkipListWriter_) pSkipListWriter_ ->reset(); } void RTPostingWriter::add(docid_t docid, loc_t location) { if (docid == nLastDocID_) { ///see it before,only position is needed pLocList_->addVData32(location - nLastLoc_); nCurTermFreq_++; nLastLoc_ = location; } else///first see it { if (nCurTermFreq_ > 0)///write previous document's term freq { pDocFreqList_->addVData32(nCurTermFreq_); } else if (nLastDocID_ == BAD_DOCID)///first see it { nLastDocID_ = 0; } if(skipInterval_ && nDF_ > 0 && nDF_ % skipInterval_ == 0) { pSkipListWriter_->addSkipPoint(nLastDocID_,pDocFreqList_->getLength(),pLocList_->getLength()); } pDocFreqList_->addVData32(docid - nLastDocID_); pLocList_->addVData32(location); nCTF_ += nCurTermFreq_; nCurTermFreq_ = 1; nLastDocID_ = docid; nLastLoc_ = location; nDF_++; } } int32_t RTPostingWriter::getSkipLevel() { if( pSkipListWriter_ && pSkipListWriter_->getNumLevels() > 0) return pSkipListWriter_->getNumLevels(); else return 0; } void RTPostingWriter::flushLastDoc(bool bTruncTail) { if(!pMemCache_) return; if (nCurTermFreq_ > 0) { pDocFreqList_->addVData32(nCurTermFreq_); if (bTruncTail) { pDocFreqList_->truncTailChunk();///update real size pLocList_->truncTailChunk();///update real size } nCTF_ += nCurTermFreq_; nCurTermFreq_ = 0; } else if (bTruncTail) { pDocFreqList_->truncTailChunk();///update real size pLocList_->truncTailChunk();///update real size } } PostingReader* RTPostingWriter::createPostingReader() { return new MemPostingReader(this); } } NS_IZENELIB_IR_END <commit_msg>similar to 459f7fd58033f49b594d45d3153df007434774a6, create RTPostingWriter::pSkipListWriter_ only when maxSkipLevel_ is a positive value.<commit_after>#include <ir/index_manager/index/RTPostingWriter.h> #include <ir/index_manager/index/OutputDescriptor.h> #include <ir/index_manager/index/InputDescriptor.h> #include <ir/index_manager/index/SkipListWriter.h> #include <ir/index_manager/index/SkipListReader.h> #include <ir/index_manager/store/IndexOutput.h> #include <ir/index_manager/store/IndexInput.h> #include <math.h> using namespace std; NS_IZENELIB_IR_BEGIN namespace indexmanager{ RTPostingWriter::RTPostingWriter(MemCache* pCache, int skipInterval, int maxSkipLevel) :pMemCache_(pCache) ,skipInterval_(skipInterval) ,maxSkipLevel_(maxSkipLevel) ,nDF_(0) ,nLastDocID_(BAD_DOCID) ,nLastLoc_(BAD_DOCID) ,nCurTermFreq_(0) ,nCTF_(0) ,pSkipListWriter_(0) ,dirty_(false) { pDocFreqList_ = new VariantDataPool(pCache); pLocList_ = new VariantDataPool(pCache); if(skipInterval_> 0 && maxSkipLevel_ > 0) pSkipListWriter_ = new SkipListWriter(skipInterval_,maxSkipLevel_,pMemCache_); } RTPostingWriter::~RTPostingWriter() { if (pDocFreqList_) { delete pDocFreqList_; pDocFreqList_ = NULL; } if (pLocList_) { delete pLocList_; pLocList_ = NULL; } pMemCache_ = NULL; if(pSkipListWriter_) { delete pSkipListWriter_; pSkipListWriter_ = 0; } } bool RTPostingWriter::isEmpty() { return (pDocFreqList_->pTailChunk_==NULL); } void RTPostingWriter::write(OutputDescriptor* pOutputDescriptor, TermInfo& termInfo) { ///flush last document flushLastDoc(true); termInfo.docFreq_ = nDF_; termInfo.ctf_ = nCTF_; termInfo.lastDocID_ = nLastDocID_; if(pSkipListWriter_ && nDF_ > 0 && nDF_ % skipInterval_ == 0) pSkipListWriter_->addSkipPoint(nLastDocID_,pDocFreqList_->getLength(),pLocList_->getLength()); IndexOutput* pDOutput = pOutputDescriptor->getDPostingOutput(); if( pSkipListWriter_ && pSkipListWriter_->getNumLevels() > 0) ///nDF_ > SkipInterval { termInfo.skipLevel_ = pSkipListWriter_->getNumLevels(); termInfo.skipPointer_ = pDOutput->getFilePointer(); pSkipListWriter_->write(pDOutput); ///write skip list data } else { termInfo.skipPointer_ = -1; termInfo.skipLevel_ = 0; } ///save the offset of posting descriptor termInfo.docPointer_ = pDOutput->getFilePointer(); ///write doc posting data pDocFreqList_->write(pDOutput); termInfo.docPostingLen_ = pDOutput->getFilePointer() - termInfo.docPointer_; IndexOutput* pPOutput = pOutputDescriptor->getPPostingOutput(); termInfo.positionPointer_ = pPOutput->getFilePointer(); ///write position posting data pLocList_->write(pPOutput); termInfo.positionPostingLen_ = pPOutput->getFilePointer() - termInfo.positionPointer_; } void RTPostingWriter::reset() { pDocFreqList_->reset(); pLocList_->reset(); nCTF_ = 0; nLastDocID_ = BAD_DOCID; nLastLoc_ = 0; nDF_ = 0; nCurTermFreq_ = 0; if(pSkipListWriter_) pSkipListWriter_ ->reset(); } void RTPostingWriter::add(docid_t docid, loc_t location) { if (docid == nLastDocID_) { ///see it before,only position is needed pLocList_->addVData32(location - nLastLoc_); nCurTermFreq_++; nLastLoc_ = location; } else///first see it { if (nCurTermFreq_ > 0)///write previous document's term freq { pDocFreqList_->addVData32(nCurTermFreq_); } else if (nLastDocID_ == BAD_DOCID)///first see it { nLastDocID_ = 0; } if(pSkipListWriter_ && nDF_ > 0 && nDF_ % skipInterval_ == 0) pSkipListWriter_->addSkipPoint(nLastDocID_,pDocFreqList_->getLength(),pLocList_->getLength()); pDocFreqList_->addVData32(docid - nLastDocID_); pLocList_->addVData32(location); nCTF_ += nCurTermFreq_; nCurTermFreq_ = 1; nLastDocID_ = docid; nLastLoc_ = location; nDF_++; } } int32_t RTPostingWriter::getSkipLevel() { if( pSkipListWriter_ && pSkipListWriter_->getNumLevels() > 0) return pSkipListWriter_->getNumLevels(); else return 0; } void RTPostingWriter::flushLastDoc(bool bTruncTail) { if(!pMemCache_) return; if (nCurTermFreq_ > 0) { pDocFreqList_->addVData32(nCurTermFreq_); if (bTruncTail) { pDocFreqList_->truncTailChunk();///update real size pLocList_->truncTailChunk();///update real size } nCTF_ += nCurTermFreq_; nCurTermFreq_ = 0; } else if (bTruncTail) { pDocFreqList_->truncTailChunk();///update real size pLocList_->truncTailChunk();///update real size } } PostingReader* RTPostingWriter::createPostingReader() { return new MemPostingReader(this); } } NS_IZENELIB_IR_END <|endoftext|>
<commit_before>#include <kernel.hpp> #include <os.hpp> #include <kernel/memory.hpp> #include <kprint> #define HIGHMEM_LOCATION (1ull << 45) #define LIVEUPDATE_AREA_SIZE 25 static_assert(LIVEUPDATE_AREA_SIZE > 0 && LIVEUPDATE_AREA_SIZE < 50, "LIVEUPDATE_AREA_SIZE must be a value between 1 and 50"); static uintptr_t temp_phys = 0; //#define LIU_DEBUG 1 #ifdef LIU_DEBUG #define PRATTLE(fmt, ...) kprintf(fmt, ##__VA_ARGS__) #else #define PRATTLE(fmt, ...) /* fmt */ #endif size_t kernel::liveupdate_phys_size(size_t phys_max) noexcept { return phys_max / (100 / size_t(LIVEUPDATE_AREA_SIZE)); }; uintptr_t kernel::liveupdate_phys_loc(size_t phys_max) noexcept { return (phys_max - liveupdate_phys_size(phys_max)) & ~(uintptr_t) 0xFFF; }; void kernel::setup_liveupdate(uintptr_t phys) { PRATTLE("Setting up LiveUpdate with phys at %p\n", (void*) phys); if (phys != 0) { PRATTLE("Deferring setup because too early\n"); temp_phys = phys; return; } if (kernel::state().liveupdate_loc != 0) return; PRATTLE("New virtual move heap_max: %p\n", (void*) OS::heap_max()); // highmem location kernel::state().liveupdate_loc = HIGHMEM_LOCATION; size_t size = 0; if (phys == 0) { size = kernel::liveupdate_phys_size(kernel::heap_max()); phys = kernel::liveupdate_phys_loc(kernel::heap_max()); } else { size = kernel::heap_max() - phys; } size &= ~(uintptr_t) 0xFFF; // page sized // move location to high memory const uintptr_t dst = (uintptr_t) kernel::liveupdate_storage_area(); PRATTLE("virtual_move %p to %p (%zu bytes)\n", (void*) phys, (void*) dst, size); os::mem::virtual_move(phys, size, dst, "LiveUpdate"); } <commit_msg>liu: Set update loc to temp phys if 0<commit_after>#include <kernel.hpp> #include <os.hpp> #include <kernel/memory.hpp> #include <kprint> #define HIGHMEM_LOCATION (1ull << 45) #define LIVEUPDATE_AREA_SIZE 25 static_assert(LIVEUPDATE_AREA_SIZE > 0 && LIVEUPDATE_AREA_SIZE < 50, "LIVEUPDATE_AREA_SIZE must be a value between 1 and 50"); static uintptr_t temp_phys = 0; //#define LIU_DEBUG 1 #ifdef LIU_DEBUG #define PRATTLE(fmt, ...) kprintf(fmt, ##__VA_ARGS__) #else #define PRATTLE(fmt, ...) /* fmt */ #endif size_t kernel::liveupdate_phys_size(size_t phys_max) noexcept { return phys_max / (100 / size_t(LIVEUPDATE_AREA_SIZE)); }; uintptr_t kernel::liveupdate_phys_loc(size_t phys_max) noexcept { return (phys_max - liveupdate_phys_size(phys_max)) & ~(uintptr_t) 0xFFF; }; void kernel::setup_liveupdate(uintptr_t phys) { PRATTLE("Setting up LiveUpdate with phys at %p\n", (void*) phys); if (phys != 0) { PRATTLE("Deferring setup because too early\n"); temp_phys = phys; return; } else { PRATTLE("Using temp at %p\n", (void*) temp_phys); phys = temp_phys; } if (kernel::state().liveupdate_loc != 0) return; PRATTLE("New virtual move heap_max: %p\n", (void*) OS::heap_max()); // highmem location kernel::state().liveupdate_loc = HIGHMEM_LOCATION; size_t size = 0; if (phys == 0) { size = kernel::liveupdate_phys_size(kernel::heap_max()); phys = kernel::liveupdate_phys_loc(kernel::heap_max()); } else { size = kernel::heap_max() - phys; } size &= ~(uintptr_t) 0xFFF; // page sized // move location to high memory const uintptr_t dst = (uintptr_t) kernel::liveupdate_storage_area(); PRATTLE("virtual_move %p to %p (%zu bytes)\n", (void*) phys, (void*) dst, size); os::mem::virtual_move(phys, size, dst, "LiveUpdate"); } <|endoftext|>
<commit_before>#include <boost/program_options.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/exceptions.hpp> #include <boost/utility/typed_in_place_factory.hpp> #include <boost/format.hpp> #include <fstream> #include <stdexcept> #include <mapnik/utils.hpp> #include <mapnik/load_map.hpp> #include <mapnik/font_engine_freetype.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/graphics.hpp> #include <mapnik/image_util.hpp> #include "avecado.hpp" #include "tilejson.hpp" #include "fetcher.hpp" #include "fetcher_io.hpp" #include "util.hpp" #include "config.h" namespace bpo = boost::program_options; namespace bpt = boost::property_tree; int make_vector(int argc, char *argv[]) { unsigned int path_multiplier; int buffer_size; double scale_factor; unsigned int offset_x; unsigned int offset_y; unsigned int tolerance; std::string image_format; mapnik::scaling_method_e scaling_method = mapnik::SCALING_NEAR; double scale_denominator; std::string output_file; std::string config_file; std::string map_file; int z, x, y; std::string fonts_dir, input_plugins_dir; bpo::options_description options( "Avecado " VERSION "\n" "\n" " Usage: avecado vector [options] <map-file> <tile-z> <tile-x> <tile-y>\n" "\n"); options.add_options() ("help,h", "Print this help message.") ("config-file,c", bpo::value<std::string>(&config_file), "JSON config file to specify post-processing for data layers.") ("output-file,o", bpo::value<std::string>(&output_file)->default_value("tile.pbf"), "File to serialise the vector tile to.") ("path-multiplier,p", bpo::value<unsigned int>(&path_multiplier)->default_value(16), "Create a tile with coordinates multiplied by this constant to get sub-pixel " "accuracy.") ("buffer-size,b", bpo::value<int>(&buffer_size)->default_value(0), "Number of pixels around the tile to buffer in order to allow for features " "whose rendering effects extend beyond the geometric extent.") ("scale_factor,s", bpo::value<double>(&scale_factor)->default_value(1.0), "Scale factor to multiply style values by.") ("offset-x", bpo::value<unsigned int>(&offset_x)->default_value(0), "Offset added to tile geometry x coordinates.") ("offset-y", bpo::value<unsigned int>(&offset_y)->default_value(0), "Offset added to tile geometry y coordinates.") ("tolerance,t", bpo::value<unsigned int>(&tolerance)->default_value(1), "Tolerance used to simplify output geometry.") ("image-format,f", bpo::value<std::string>(&image_format)->default_value("jpeg"), "Image file format used for embedding raster layers.") ("scaling-method,m", bpo::value<std::string>()->default_value("near"), "Method used to re-sample raster layers.") ("scale-denominator,d", bpo::value<double>(&scale_denominator)->default_value(0.0), "Override for scale denominator. A value of 0 means to use the sensible default " "which Mapnik will generate from the tile context.") ("fonts", bpo::value<std::string>(&fonts_dir)->default_value(MAPNIK_DEFAULT_FONT_DIR), "Directory to tell Mapnik to look in for fonts.") ("input-plugins", bpo::value<std::string>(&input_plugins_dir) ->default_value(MAPNIK_DEFAULT_INPUT_PLUGIN_DIR), "Directory to tell Mapnik to look in for input plugins.") // positional arguments ("map-file", bpo::value<std::string>(&map_file), "Mapnik XML input file.") ("tile-z", bpo::value<int>(&z), "Zoom level.") ("tile-x", bpo::value<int>(&x), "Tile x coordinate.") ("tile-y", bpo::value<int>(&y), "Tile x coordinate.") ; bpo::positional_options_description pos_options; pos_options .add("map-file", 1) .add("tile-z", 1) .add("tile-x", 1) .add("tile-y", 1) ; bpo::variables_map vm; try { bpo::store(bpo::command_line_parser(argc,argv) .options(options) .positional(pos_options) .run(), vm); bpo::notify(vm); } catch (std::exception & e) { std::cerr << "Unable to parse command line options because: " << e.what() << "\n" << "This is a bug, please report it at " PACKAGE_BUGREPORT << "\n"; return EXIT_FAILURE; } if (vm.count("help")) { std::cout << options << "\n"; return EXIT_SUCCESS; } // argument checking and verification for (auto arg : {"map-file", "tile-z", "tile-x", "tile-y"}) { if (vm.count(arg) == 0) { std::cerr << "The <" << arg << "> argument was not provided, but is mandatory\n\n"; std::cerr << options << "\n"; return EXIT_FAILURE; } } if (vm.count("scaling-method")) { std::string method_str(vm["scaling-method"].as<std::string>()); boost::optional<mapnik::scaling_method_e> method = mapnik::scaling_method_from_string(method_str); if (!method) { std::cerr << "The string \"" << method_str << "\" was not recognised as a " << "valid scaling method by Mapnik.\n"; return EXIT_FAILURE; } scaling_method = *method; } // load post processor config if it is provided avecado::post_processor post_processor; boost::optional<const avecado::post_processor &> pp; if (!config_file.empty()) { try { // parse json config bpt::ptree config; bpt::read_json(config_file, config); // init processor post_processor.load(config); pp = post_processor; } catch (bpt::ptree_error const& e) { std::cerr << "Error while parsing config: " << config_file << std::endl; std::cerr << e.what() << std::endl; return EXIT_FAILURE; } catch (std::exception const& e) { std::cerr << "Error while loading config: " << config_file << std::endl; std::cerr << e.what() << std::endl; return EXIT_FAILURE; } } try { mapnik::Map map; avecado::tile tile(z, x, y); // try to register fonts and input plugins mapnik::freetype_engine::register_fonts(fonts_dir); mapnik::datasource_cache::instance().register_datasources(input_plugins_dir); // load map config from disk mapnik::load_map(map, map_file); // setup map parameters map.resize(256, 256); map.zoom_to_box(avecado::util::box_for_tile(z, x, y)); // actually make the vector tile avecado::make_vector_tile(tile, path_multiplier, map, buffer_size, scale_factor, offset_x, offset_y, tolerance, image_format, scaling_method, scale_denominator, pp); // serialise to file std::ofstream output(output_file); output << tile; } catch (const std::exception &e) { std::cerr << "Unable to make vector tile: " << e.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } int make_raster(int argc, char *argv[]) { unsigned int z = 0, x = 0, y = 0; double scale_factor = 1.0; unsigned int buffer_size = 0; unsigned int width = 256, height = 256; std::string tilejson_uri, output_file, map_file; std::string fonts_dir, input_plugins_dir; bpo::options_description options( "Avecado " VERSION "\n" "\n" " Usage: avecado raster [options] <tilejson> <map-file> <tile-z> <tile-x> <tile-y>\n" "\n"); options.add_options() ("help,h", "Print this help message.") ("output-file,o", bpo::value<std::string>(&output_file)->default_value("tile.png"), "File to write PNG data to.") ("buffer-size,b", bpo::value<unsigned int>(&buffer_size)->default_value(0), "Number of pixels around the tile to buffer in order to allow for features " "whose rendering effects extend beyond the geometric extent.") ("scale_factor,s", bpo::value<double>(&scale_factor)->default_value(1.0), "Scale factor to multiply style values by.") ("fonts", bpo::value<std::string>(&fonts_dir)->default_value(MAPNIK_DEFAULT_FONT_DIR), "Directory to tell Mapnik to look in for fonts.") ("input-plugins", bpo::value<std::string>(&input_plugins_dir) ->default_value(MAPNIK_DEFAULT_INPUT_PLUGIN_DIR), "Directory to tell Mapnik to look in for input plugins.") ("width", bpo::value<unsigned int>(&width), "Width of output raster.") ("height", bpo::value<unsigned int>(&height), "Height of output raster.") // positional arguments ("tilejson", bpo::value<std::string>(&tilejson_uri), "TileJSON config file URI to specify where to get vector tiles from.") ("map-file", bpo::value<std::string>(&map_file), "Mapnik XML input file.") ("tile-z", bpo::value<unsigned int>(&z), "Zoom level.") ("tile-x", bpo::value<unsigned int>(&x), "Tile x coordinate.") ("tile-y", bpo::value<unsigned int>(&y), "Tile x coordinate.") ; bpo::positional_options_description pos_options; pos_options .add("tilejson", 1) .add("map-file", 1) .add("tile-z", 1) .add("tile-x", 1) .add("tile-y", 1) ; bpo::variables_map vm; try { bpo::store(bpo::command_line_parser(argc,argv) .options(options) .positional(pos_options) .run(), vm); bpo::notify(vm); } catch (std::exception & e) { std::cerr << "Unable to parse command line options because: " << e.what() << "\n" << "This is a bug, please report it at " PACKAGE_BUGREPORT << "\n"; return EXIT_FAILURE; } if (vm.count("help")) { std::cout << options << "\n"; return EXIT_SUCCESS; } // argument checking and verification for (auto arg : {"tilejson", "map-file", "tile-z", "tile-x", "tile-y"}) { if (vm.count(arg) == 0) { std::cerr << "The <" << arg << "> argument was not provided, but is mandatory\n\n"; std::cerr << options << "\n"; return EXIT_FAILURE; } } try { mapnik::Map map; // try to register fonts and input plugins mapnik::freetype_engine::register_fonts(fonts_dir); mapnik::datasource_cache::instance().register_datasources(input_plugins_dir); // load map config from disk mapnik::load_map(map, map_file); // setup map parameters map.resize(width, height); map.zoom_to_box(avecado::util::box_for_tile(z, x, y)); bpt::ptree conf = avecado::tilejson(tilejson_uri); std::unique_ptr<avecado::fetcher> fetcher = avecado::make_tilejson_fetcher(conf); avecado::fetch_response response = (*fetcher)(z, x, y).get(); if (response.is_left()) { mapnik::image_32 image(width, height); std::unique_ptr<avecado::tile> tile(std::move(response.left())); avecado::render_vector_tile(image, *tile, map, scale_factor, buffer_size); mapnik::save_to_file(image, output_file, "png"); } else { throw std::runtime_error((boost::format("Error while fetching tile: %1%") % response.right()).str()); } } catch (const std::exception &e) { std::cerr << "Unable to render raster tile: " << e.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } int main(int argc, char *argv[]) { if (argc > 1) { std::string command = argv[1]; // urgh, removing a value from argv is a bit of a pain... const int new_argc = argc - 1; char **new_argv = (char **)alloca(sizeof(*argv) * new_argc); new_argv[0] = argv[0]; for (int i = 1; i < new_argc; ++i) { new_argv[i] = argv[i+1]; } if (command == "vector") { return make_vector(new_argc, new_argv); } else if (command == "raster") { return make_raster(new_argc, new_argv); } else { std::cerr << "Unknown command \"" << command << "\".\n"; } } std::cerr << "avecado <command> [command-options]\n" "\n" "Where command is:\n" " vector: Avecado will make vector tiles from a Mapnik XML\n" " file and export them as PBFs.\n" " raster: Avecado will make raster tiles from vector tiles\n" " plus a style file.\n" "\n" "To get more information on the options available for a\n" "particular command, run `avecado <command> --help`.\n"; return EXIT_FAILURE; } <commit_msg>Extract common options.<commit_after>#include <boost/program_options.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/exceptions.hpp> #include <boost/utility/typed_in_place_factory.hpp> #include <boost/format.hpp> #include <fstream> #include <stdexcept> #include <mapnik/utils.hpp> #include <mapnik/load_map.hpp> #include <mapnik/font_engine_freetype.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/graphics.hpp> #include <mapnik/image_util.hpp> #include "avecado.hpp" #include "tilejson.hpp" #include "fetcher.hpp" #include "fetcher_io.hpp" #include "util.hpp" #include "config.h" namespace bpo = boost::program_options; namespace bpt = boost::property_tree; struct vector_options { unsigned int path_multiplier; int buffer_size; double scale_factor; unsigned int offset_x; unsigned int offset_y; unsigned int tolerance; std::string image_format; double scale_denominator; void add(bpo::options_description &options) { options.add_options() ("path-multiplier,p", bpo::value<unsigned int>(&path_multiplier)->default_value(16), "Create a tile with coordinates multiplied by this constant to get sub-pixel " "accuracy.") ("buffer-size,b", bpo::value<int>(&buffer_size)->default_value(0), "Number of pixels around the tile to buffer in order to allow for features " "whose rendering effects extend beyond the geometric extent.") ("scale_factor,s", bpo::value<double>(&scale_factor)->default_value(1.0), "Scale factor to multiply style values by.") ("offset-x", bpo::value<unsigned int>(&offset_x)->default_value(0), "Offset added to tile geometry x coordinates.") ("offset-y", bpo::value<unsigned int>(&offset_y)->default_value(0), "Offset added to tile geometry y coordinates.") ("tolerance,t", bpo::value<unsigned int>(&tolerance)->default_value(1), "Tolerance used to simplify output geometry.") ("image-format,f", bpo::value<std::string>(&image_format)->default_value("jpeg"), "Image file format used for embedding raster layers.") ("scale-denominator,d", bpo::value<double>(&scale_denominator)->default_value(0.0), "Override for scale denominator. A value of 0 means to use the sensible default " "which Mapnik will generate from the tile context.") ; } }; int make_vector(int argc, char *argv[]) { std::string output_file; std::string config_file; mapnik::scaling_method_e scaling_method = mapnik::SCALING_NEAR; vector_options vopt; std::string map_file; int z, x, y; std::string fonts_dir, input_plugins_dir; bpo::options_description options( "Avecado " VERSION "\n" "\n" " Usage: avecado vector [options] <map-file> <tile-z> <tile-x> <tile-y>\n" "\n"); vopt.add(options); options.add_options() ("help,h", "Print this help message.") ("config-file,c", bpo::value<std::string>(&config_file), "JSON config file to specify post-processing for data layers.") ("output-file,o", bpo::value<std::string>(&output_file)->default_value("tile.pbf"), "File to serialise the vector tile to.") ("fonts", bpo::value<std::string>(&fonts_dir)->default_value(MAPNIK_DEFAULT_FONT_DIR), "Directory to tell Mapnik to look in for fonts.") ("input-plugins", bpo::value<std::string>(&input_plugins_dir) ->default_value(MAPNIK_DEFAULT_INPUT_PLUGIN_DIR), "Directory to tell Mapnik to look in for input plugins.") ("scaling-method,m", bpo::value<std::string>()->default_value("near"), "Method used to re-sample raster layers.") // positional arguments ("map-file", bpo::value<std::string>(&map_file), "Mapnik XML input file.") ("tile-z", bpo::value<int>(&z), "Zoom level.") ("tile-x", bpo::value<int>(&x), "Tile x coordinate.") ("tile-y", bpo::value<int>(&y), "Tile x coordinate.") ; bpo::positional_options_description pos_options; pos_options .add("map-file", 1) .add("tile-z", 1) .add("tile-x", 1) .add("tile-y", 1) ; bpo::variables_map vm; try { bpo::store(bpo::command_line_parser(argc,argv) .options(options) .positional(pos_options) .run(), vm); bpo::notify(vm); } catch (std::exception & e) { std::cerr << "Unable to parse command line options because: " << e.what() << "\n" << "This is a bug, please report it at " PACKAGE_BUGREPORT << "\n"; return EXIT_FAILURE; } if (vm.count("help")) { std::cout << options << "\n"; return EXIT_SUCCESS; } // argument checking and verification for (auto arg : {"map-file", "tile-z", "tile-x", "tile-y"}) { if (vm.count(arg) == 0) { std::cerr << "The <" << arg << "> argument was not provided, but is mandatory\n\n"; std::cerr << options << "\n"; return EXIT_FAILURE; } } if (vm.count("scaling-method")) { std::string method_str(vm["scaling-method"].as<std::string>()); boost::optional<mapnik::scaling_method_e> method = mapnik::scaling_method_from_string(method_str); if (!method) { std::cerr << "The string \"" << method_str << "\" was not recognised as a " << "valid scaling method by Mapnik.\n"; return EXIT_FAILURE; } scaling_method = *method; } // load post processor config if it is provided avecado::post_processor post_processor; boost::optional<const avecado::post_processor &> pp; if (!config_file.empty()) { try { // parse json config bpt::ptree config; bpt::read_json(config_file, config); // init processor post_processor.load(config); pp = post_processor; } catch (bpt::ptree_error const& e) { std::cerr << "Error while parsing config: " << config_file << std::endl; std::cerr << e.what() << std::endl; return EXIT_FAILURE; } catch (std::exception const& e) { std::cerr << "Error while loading config: " << config_file << std::endl; std::cerr << e.what() << std::endl; return EXIT_FAILURE; } } try { mapnik::Map map; avecado::tile tile(z, x, y); // try to register fonts and input plugins mapnik::freetype_engine::register_fonts(fonts_dir); mapnik::datasource_cache::instance().register_datasources(input_plugins_dir); // load map config from disk mapnik::load_map(map, map_file); // setup map parameters map.resize(256, 256); map.zoom_to_box(avecado::util::box_for_tile(z, x, y)); // actually make the vector tile avecado::make_vector_tile(tile, vopt.path_multiplier, map, vopt.buffer_size, vopt.scale_factor, vopt.offset_x, vopt.offset_y, vopt.tolerance, vopt.image_format, scaling_method, vopt.scale_denominator, pp); // serialise to file std::ofstream output(output_file); output << tile; } catch (const std::exception &e) { std::cerr << "Unable to make vector tile: " << e.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } int make_raster(int argc, char *argv[]) { unsigned int z = 0, x = 0, y = 0; double scale_factor = 1.0; unsigned int buffer_size = 0; unsigned int width = 256, height = 256; std::string tilejson_uri, output_file, map_file; std::string fonts_dir, input_plugins_dir; bpo::options_description options( "Avecado " VERSION "\n" "\n" " Usage: avecado raster [options] <tilejson> <map-file> <tile-z> <tile-x> <tile-y>\n" "\n"); options.add_options() ("help,h", "Print this help message.") ("output-file,o", bpo::value<std::string>(&output_file)->default_value("tile.png"), "File to write PNG data to.") ("buffer-size,b", bpo::value<unsigned int>(&buffer_size)->default_value(0), "Number of pixels around the tile to buffer in order to allow for features " "whose rendering effects extend beyond the geometric extent.") ("scale_factor,s", bpo::value<double>(&scale_factor)->default_value(1.0), "Scale factor to multiply style values by.") ("fonts", bpo::value<std::string>(&fonts_dir)->default_value(MAPNIK_DEFAULT_FONT_DIR), "Directory to tell Mapnik to look in for fonts.") ("input-plugins", bpo::value<std::string>(&input_plugins_dir) ->default_value(MAPNIK_DEFAULT_INPUT_PLUGIN_DIR), "Directory to tell Mapnik to look in for input plugins.") ("width", bpo::value<unsigned int>(&width), "Width of output raster.") ("height", bpo::value<unsigned int>(&height), "Height of output raster.") // positional arguments ("tilejson", bpo::value<std::string>(&tilejson_uri), "TileJSON config file URI to specify where to get vector tiles from.") ("map-file", bpo::value<std::string>(&map_file), "Mapnik XML input file.") ("tile-z", bpo::value<unsigned int>(&z), "Zoom level.") ("tile-x", bpo::value<unsigned int>(&x), "Tile x coordinate.") ("tile-y", bpo::value<unsigned int>(&y), "Tile x coordinate.") ; bpo::positional_options_description pos_options; pos_options .add("tilejson", 1) .add("map-file", 1) .add("tile-z", 1) .add("tile-x", 1) .add("tile-y", 1) ; bpo::variables_map vm; try { bpo::store(bpo::command_line_parser(argc,argv) .options(options) .positional(pos_options) .run(), vm); bpo::notify(vm); } catch (std::exception & e) { std::cerr << "Unable to parse command line options because: " << e.what() << "\n" << "This is a bug, please report it at " PACKAGE_BUGREPORT << "\n"; return EXIT_FAILURE; } if (vm.count("help")) { std::cout << options << "\n"; return EXIT_SUCCESS; } // argument checking and verification for (auto arg : {"tilejson", "map-file", "tile-z", "tile-x", "tile-y"}) { if (vm.count(arg) == 0) { std::cerr << "The <" << arg << "> argument was not provided, but is mandatory\n\n"; std::cerr << options << "\n"; return EXIT_FAILURE; } } try { mapnik::Map map; // try to register fonts and input plugins mapnik::freetype_engine::register_fonts(fonts_dir); mapnik::datasource_cache::instance().register_datasources(input_plugins_dir); // load map config from disk mapnik::load_map(map, map_file); // setup map parameters map.resize(width, height); map.zoom_to_box(avecado::util::box_for_tile(z, x, y)); bpt::ptree conf = avecado::tilejson(tilejson_uri); std::unique_ptr<avecado::fetcher> fetcher = avecado::make_tilejson_fetcher(conf); avecado::fetch_response response = (*fetcher)(z, x, y).get(); if (response.is_left()) { mapnik::image_32 image(width, height); std::unique_ptr<avecado::tile> tile(std::move(response.left())); avecado::render_vector_tile(image, *tile, map, scale_factor, buffer_size); mapnik::save_to_file(image, output_file, "png"); } else { throw std::runtime_error((boost::format("Error while fetching tile: %1%") % response.right()).str()); } } catch (const std::exception &e) { std::cerr << "Unable to render raster tile: " << e.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } int main(int argc, char *argv[]) { if (argc > 1) { std::string command = argv[1]; // urgh, removing a value from argv is a bit of a pain... const int new_argc = argc - 1; char **new_argv = (char **)alloca(sizeof(*argv) * new_argc); new_argv[0] = argv[0]; for (int i = 1; i < new_argc; ++i) { new_argv[i] = argv[i+1]; } if (command == "vector") { return make_vector(new_argc, new_argv); } else if (command == "raster") { return make_raster(new_argc, new_argv); } else { std::cerr << "Unknown command \"" << command << "\".\n"; } } std::cerr << "avecado <command> [command-options]\n" "\n" "Where command is:\n" " vector: Avecado will make vector tiles from a Mapnik XML\n" " file and export them as PBFs.\n" " raster: Avecado will make raster tiles from vector tiles\n" " plus a style file.\n" "\n" "To get more information on the options available for a\n" "particular command, run `avecado <command> --help`.\n"; return EXIT_FAILURE; } <|endoftext|>
<commit_before>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org> * Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com> * * Hook-setup code provided by Ruslan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or( at your option ) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygenargbhelper.h" #include "oxygengtktypenames.h" #include "config.h" #include <gtk/gtk.h> #include <sys/stat.h> #include <cassert> #include <fstream> #include <iostream> #include <string> #include <vector> namespace Oxygen { //__________________________________________________________________ ArgbHelper::ArgbHelper( void ): _hooksInitialized( false ), _logId( 0 ) {} //_____________________________________________________ ArgbHelper::~ArgbHelper( void ) { std::cerr << "ArgbHelper::~ArgbHelper" << std::endl; // disconnect hooks _colormapHook.disconnect(); _styleHook.disconnect(); if( _logId > 0 ) { g_log_remove_handler( "GLib-GObject", _logId ); g_log_set_handler( "GLib-GObject", G_LOG_LEVEL_CRITICAL, g_log_default_handler, 0L ); } } //_____________________________________________________ void ArgbHelper::initializeHooks( void ) { if( _hooksInitialized ) return; // lookup relevant signal const guint signalId( g_signal_lookup("style-set", GTK_TYPE_WINDOW ) ); if( signalId <= 0 ) return; // install hooks _colormapHook.connect( "style-set", (GSignalEmissionHook)colormapHook, 0L ); _styleHook.connect( "parent-set", (GSignalEmissionHook)styleHook, 0L ); /* the installation of "parent-set" hook triggers some glib critical error when destructing ComboBoxEntry. a glib/gtk bug has been filed. In the meanwhile, and since the error is apparently harmless, we simply disable the corresponding log */ _logId = g_log_set_handler( "GLib-GObject", G_LOG_LEVEL_CRITICAL, logHandler, 0L ); _hooksInitialized = true; return; } //_____________________________________________________ gboolean ArgbHelper::colormapHook( GSignalInvocationHint*, guint, const GValue* params, gpointer ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; if( !GTK_IS_WINDOW( widget ) ) return TRUE; // make sure widget has not been realized already if( gtk_widget_get_realized( widget ) ) return TRUE; // cast to window GtkWindow* window( GTK_WINDOW( widget ) ); // check type hint GdkWindowTypeHint hint = gtk_window_get_type_hint( window ); // screen GdkScreen* screen = gdk_screen_get_default(); if( !screen ) return TRUE; if( hint == GDK_WINDOW_TYPE_HINT_DROPDOWN_MENU || hint == GDK_WINDOW_TYPE_HINT_POPUP_MENU || hint == GDK_WINDOW_TYPE_HINT_TOOLTIP || hint == GDK_WINDOW_TYPE_HINT_COMBO ) { #if OXYGEN_DEBUG std::cerr << "Oxygen::ArgbHelper::colormapHook - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << " hint: " << Gtk::TypeNames::windowTypeHint( hint ) << std::endl; #endif GdkColormap* cmap=gdk_screen_get_rgba_colormap( screen ); gtk_widget_set_colormap( widget, cmap ); } return TRUE; } //_____________________________________________________ gboolean ArgbHelper::styleHook( GSignalInvocationHint*, guint, const GValue* params, gpointer ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; // retrieve widget style and check GtkStyle* style( widget->style ); if( !( style && style->depth >= 0 ) ) return TRUE; // retrieve parent window and check GdkWindow* window( gtk_widget_get_parent_window( widget ) ); if( !window ) return TRUE; // adjust depth if( style->depth != gdk_drawable_get_depth( window ) ) { #if OXYGEN_DEBUG std::cerr << "Oxygen::ArgbHelper::styleHook -" << " widget: " << widget << " (" <<G_OBJECT_TYPE_NAME( widget ) << ")" << " style depth: " << style->depth << " window depth: " << gdk_drawable_get_depth( window ) << std::endl; #endif widget->style = gtk_style_attach( style, window ); } return TRUE; } //_________________________________________________________ void ArgbHelper::logHandler( const gchar* domain, GLogLevelFlags flags, const gchar* message, gpointer data ) { /* discard all messages containing "IA__gtk_box_reorder_child:" and fallback to default handler otherwise */ if( std::string( message ).find( "g_object_ref" ) == std::string::npos ) { g_log_default_handler( domain, flags, message, data ); } } } <commit_msg>removed printout in destructor.<commit_after>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org> * Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com> * * Hook-setup code provided by Ruslan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or( at your option ) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "oxygenargbhelper.h" #include "oxygengtktypenames.h" #include "config.h" #include <gtk/gtk.h> #include <sys/stat.h> #include <cassert> #include <fstream> #include <iostream> #include <string> #include <vector> namespace Oxygen { //__________________________________________________________________ ArgbHelper::ArgbHelper( void ): _hooksInitialized( false ), _logId( 0 ) {} //_____________________________________________________ ArgbHelper::~ArgbHelper( void ) { // disconnect hooks _colormapHook.disconnect(); _styleHook.disconnect(); if( _logId > 0 ) { g_log_remove_handler( "GLib-GObject", _logId ); g_log_set_handler( "GLib-GObject", G_LOG_LEVEL_CRITICAL, g_log_default_handler, 0L ); } } //_____________________________________________________ void ArgbHelper::initializeHooks( void ) { if( _hooksInitialized ) return; // lookup relevant signal const guint signalId( g_signal_lookup("style-set", GTK_TYPE_WINDOW ) ); if( signalId <= 0 ) return; // install hooks _colormapHook.connect( "style-set", (GSignalEmissionHook)colormapHook, 0L ); _styleHook.connect( "parent-set", (GSignalEmissionHook)styleHook, 0L ); /* the installation of "parent-set" hook triggers some glib critical error when destructing ComboBoxEntry. a glib/gtk bug has been filed. In the meanwhile, and since the error is apparently harmless, we simply disable the corresponding log */ _logId = g_log_set_handler( "GLib-GObject", G_LOG_LEVEL_CRITICAL, logHandler, 0L ); _hooksInitialized = true; return; } //_____________________________________________________ gboolean ArgbHelper::colormapHook( GSignalInvocationHint*, guint, const GValue* params, gpointer ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; if( !GTK_IS_WINDOW( widget ) ) return TRUE; // make sure widget has not been realized already if( gtk_widget_get_realized( widget ) ) return TRUE; // cast to window GtkWindow* window( GTK_WINDOW( widget ) ); // check type hint GdkWindowTypeHint hint = gtk_window_get_type_hint( window ); // screen GdkScreen* screen = gdk_screen_get_default(); if( !screen ) return TRUE; if( hint == GDK_WINDOW_TYPE_HINT_DROPDOWN_MENU || hint == GDK_WINDOW_TYPE_HINT_POPUP_MENU || hint == GDK_WINDOW_TYPE_HINT_TOOLTIP || hint == GDK_WINDOW_TYPE_HINT_COMBO ) { #if OXYGEN_DEBUG std::cerr << "Oxygen::ArgbHelper::colormapHook - " << widget << " (" << G_OBJECT_TYPE_NAME( widget ) << ")" << " hint: " << Gtk::TypeNames::windowTypeHint( hint ) << std::endl; #endif GdkColormap* cmap=gdk_screen_get_rgba_colormap( screen ); gtk_widget_set_colormap( widget, cmap ); } return TRUE; } //_____________________________________________________ gboolean ArgbHelper::styleHook( GSignalInvocationHint*, guint, const GValue* params, gpointer ) { // get widget from params GtkWidget* widget( GTK_WIDGET( g_value_get_object( params ) ) ); // check type if( !GTK_IS_WIDGET( widget ) ) return FALSE; // retrieve widget style and check GtkStyle* style( widget->style ); if( !( style && style->depth >= 0 ) ) return TRUE; // retrieve parent window and check GdkWindow* window( gtk_widget_get_parent_window( widget ) ); if( !window ) return TRUE; // adjust depth if( style->depth != gdk_drawable_get_depth( window ) ) { #if OXYGEN_DEBUG std::cerr << "Oxygen::ArgbHelper::styleHook -" << " widget: " << widget << " (" <<G_OBJECT_TYPE_NAME( widget ) << ")" << " style depth: " << style->depth << " window depth: " << gdk_drawable_get_depth( window ) << std::endl; #endif widget->style = gtk_style_attach( style, window ); } return TRUE; } //_________________________________________________________ void ArgbHelper::logHandler( const gchar* domain, GLogLevelFlags flags, const gchar* message, gpointer data ) { /* discard all messages containing "IA__gtk_box_reorder_child:" and fallback to default handler otherwise */ if( std::string( message ).find( "g_object_ref" ) == std::string::npos ) { g_log_default_handler( domain, flags, message, data ); } } } <|endoftext|>
<commit_before>#pragma once #include "pre_header.hpp" namespace tdc { namespace lz78u { template<typename string_coder_t> class BufferingStrategy: public Algorithm { public: using Algorithm::Algorithm; inline static Meta meta() { Meta m("lz78u_strategy", "buffering"); m.option("string_coder").templated<string_coder_t>(); return m; } template<typename ref_coder_t> class Compression: public Algorithm { Env m_ref_env; std::shared_ptr<BitOStream> m_out; std::vector<size_t> m_refs; std::vector<size_t> m_ref_ranges; std::vector<uliteral_t> m_strings; public: inline Compression(Env&& env, Env&& ref_env, std::shared_ptr<BitOStream> out): Algorithm(std::move(env)), m_ref_env(std::move(ref_env)), m_out(out) {} inline void encode(Factor fact, size_t ref_range) { m_refs.push_back(fact.ref); m_ref_ranges.push_back(ref_range); //std::cout << "encode: " << vec_to_debug_string(fact.string) << "\n"; for (auto c : fact.string) { m_strings.push_back(c); } m_strings.push_back(0); } inline void encode_ref(size_t ref, size_t ref_range) { } inline void encode_str(View str) { } inline void encode_sep(bool val) { } inline void encode_char(uliteral_t c) { } inline ~Compression() { typename ref_coder_t::Encoder ref_coder { std::move(m_ref_env), m_out, NoLiterals() }; typename string_coder_t::Encoder string_coder { std::move(this->env().env_for_option("string_coder")), m_out, ViewLiterals(m_strings) }; size_t strings_i = 0; for (size_t i = 0; i < m_refs.size(); i++) { ref_coder.encode(m_refs[i], Range(m_ref_ranges[i])); m_out->write_bit(!OVER_THRESHOLD_FLAG); while (true) { string_coder.encode(m_strings[strings_i], literal_r); if (m_strings[strings_i] == 0) { strings_i++; break; } strings_i++; } } } }; template<typename ref_coder_t> class Decompression: public Algorithm { typename ref_coder_t::Decoder m_ref_coder; typename string_coder_t::Decoder m_string_coder; std::vector<uliteral_t> m_buf; std::shared_ptr<BitIStream> m_in; public: inline Decompression(Env&& env, Env&& ref_env, std::shared_ptr<BitIStream> in): Algorithm(std::move(env)), m_ref_coder(std::move(ref_env), in), m_string_coder(std::move(this->env().env_for_option("string_coder")), in), m_in(in) {} inline size_t decode_ref(size_t ref_range) { return 0; } inline uliteral_t decode_char() { return 0; } inline View decode_str() { return ""; } inline bool decode_sep() { return false; } inline Factor decode(size_t ref_range) { auto ref = m_ref_coder.template decode<size_t>(Range(ref_range)); bool is_over_threshold = false; is_over_threshold = m_in->read_bit(); DCHECK(is_over_threshold); m_buf.clear(); while (true) { auto c = m_string_coder.template decode<uliteral_t>(literal_r); if (c == 0) { break; } m_buf.push_back(c); } return Factor { m_buf, ref }; } inline bool eof() { return m_ref_coder.eof(); } inline ~Decompression() { } }; }; } } <commit_msg>completed simplification<commit_after>#pragma once #include "pre_header.hpp" namespace tdc { namespace lz78u { template<typename string_coder_t> class BufferingStrategy: public Algorithm { public: using Algorithm::Algorithm; inline static Meta meta() { Meta m("lz78u_strategy", "buffering"); m.option("string_coder").templated<string_coder_t>(); return m; } template<typename ref_coder_t> class Compression: public Algorithm { Env m_ref_env; std::shared_ptr<BitOStream> m_out; // TODO Optimization: Replace with something that just stores the increment points std::vector<size_t> m_ref_ranges; // TODO Optimization: Replace with variable bit width std::vector<size_t> m_refs; // TODO Optimization: Replace with bitvector std::vector<bool> m_seps; std::vector<uliteral_t> m_chars; // TODO Optimization: Replace with 2-bit vector, or remove completely // by hardcoding the encoding scheme in the strategy // TODO Optimization: Encode "encode_str" case more compactly by using single code? std::vector<uint8_t> m_stream; public: inline Compression(Env&& env, Env&& ref_env, std::shared_ptr<BitOStream> out): Algorithm(std::move(env)), m_ref_env(std::move(ref_env)), m_out(out) {} inline void encode_ref(size_t ref, size_t ref_range) { m_refs.push_back(ref); m_ref_ranges.push_back(ref_range); m_stream.push_back(0); } inline void encode_sep(bool val) { m_seps.push_back(val); m_stream.push_back(1); } inline void encode_char(uliteral_t c) { m_chars.push_back(c); m_stream.push_back(2); } inline void encode_str(View str) { for (auto c : str) { encode_char(c); } encode_char(0); } inline ~Compression() { typename ref_coder_t::Encoder ref_coder { std::move(m_ref_env), m_out, NoLiterals() }; typename string_coder_t::Encoder string_coder { std::move(this->env().env_for_option("string_coder")), m_out, ViewLiterals(m_chars) }; auto refs_i = m_refs.begin(); auto ref_ranges_i = m_ref_ranges.begin(); auto seps_i = m_seps.begin(); auto chars_i = m_chars.begin(); for (auto kind : m_stream) { switch (kind) { case 0: { auto ref = *(refs_i++); auto ref_range = *(ref_ranges_i++); ref_coder.encode(ref, Range(ref_range)); break; } case 1: { auto sep = *(seps_i++); m_out->write_bit(sep); break; } case 2: { auto chr = *(chars_i++); string_coder.encode(chr, literal_r); break; } } } DCHECK(refs_i == m_refs.end()); DCHECK(ref_ranges_i == m_ref_ranges.end()); DCHECK(seps_i == m_seps.end()); DCHECK(chars_i == m_chars.end()); } }; template<typename ref_coder_t> class Decompression: public Algorithm { typename ref_coder_t::Decoder m_ref_coder; typename string_coder_t::Decoder m_string_coder; std::vector<uliteral_t> m_buf; std::shared_ptr<BitIStream> m_in; public: inline Decompression(Env&& env, Env&& ref_env, std::shared_ptr<BitIStream> in): Algorithm(std::move(env)), m_ref_coder(std::move(ref_env), in), m_string_coder(std::move(this->env().env_for_option("string_coder")), in), m_in(in) {} inline size_t decode_ref(size_t ref_range) { return m_ref_coder.template decode<size_t>(Range(ref_range)); } inline uliteral_t decode_char() { return m_string_coder.template decode<uliteral_t>(literal_r); } inline View decode_str() { m_buf.clear(); while (true) { auto c = decode_char(); if (c == 0) { break; } m_buf.push_back(c); } return m_buf; } inline bool decode_sep() { return m_in->read_bit(); } inline bool eof() { return m_ref_coder.eof(); } }; }; } } <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <Array.hpp> #include <diff.hpp> #include <stdexcept> #include <err_cpu.hpp> namespace cpu { unsigned getIdx(af::dim4 strides, af::dim4 offs, int i, int j = 0, int k = 0, int l = 0) { return (l * strides[3] + k * strides[2] + j * strides[1] + i); } template<typename T> Array<T> diff1(const Array<T> &in, const int dim) { // Bool for dimension bool is_dim0 = dim == 0; bool is_dim1 = dim == 1; bool is_dim2 = dim == 2; bool is_dim3 = dim == 3; // Decrement dimension of select dimension af::dim4 dims = in.dims(); dims[dim]--; // Create output placeholder Array<T> outArray = createValueArray(dims, (T)0); // Get pointers to raw data const T *inPtr = in.get(); T *outPtr = outArray.get(); // TODO: Improve this for(dim_t l = 0; l < dims[3]; l++) { for(dim_t k = 0; k < dims[2]; k++) { for(dim_t j = 0; j < dims[1]; j++) { for(dim_t i = 0; i < dims[0]; i++) { // Operation: out[index] = in[index + 1 * dim_size] - in[index] int idx = getIdx(in.strides(), in.offsets(), i, j, k, l); int jdx = getIdx(in.strides(), in.offsets(), i + is_dim0, j + is_dim1, k + is_dim2, l + is_dim3); int odx = getIdx(outArray.strides(), outArray.offsets(), i, j, k, l); outPtr[odx] = inPtr[jdx] - inPtr[idx]; } } } } return outArray; } template<typename T> Array<T> diff2(const Array<T> &in, const int dim) { // Bool for dimension bool is_dim0 = dim == 0; bool is_dim1 = dim == 1; bool is_dim2 = dim == 2; bool is_dim3 = dim == 3; // Decrement dimension of select dimension af::dim4 dims = in.dims(); dims[dim] -= 2; // Create output placeholder Array<T> outArray = createValueArray(dims, (T)0); // Get pointers to raw data const T *inPtr = in.get(); T *outPtr = outArray.get(); // TODO: Improve this for(dim_t l = 0; l < dims[3]; l++) { for(dim_t k = 0; k < dims[2]; k++) { for(dim_t j = 0; j < dims[1]; j++) { for(dim_t i = 0; i < dims[0]; i++) { // Operation: out[index] = in[index + 1 * dim_size] - in[index] int idx = getIdx(in.strides(), in.offsets(), i, j, k, l); int jdx = getIdx(in.strides(), in.offsets(), i + is_dim0, j + is_dim1, k + is_dim2, l + is_dim3); int kdx = getIdx(in.strides(), in.offsets(), i + 2 * is_dim0, j + 2 * is_dim1, k + 2 * is_dim2, l + 2 * is_dim3); int odx = getIdx(outArray.strides(), outArray.offsets(), i, j, k, l); outPtr[odx] = inPtr[kdx] + inPtr[idx] - inPtr[jdx] - inPtr[jdx]; } } } } return outArray; } #define INSTANTIATE(T) \ template Array<T> diff1<T> (const Array<T> &in, const int dim); \ template Array<T> diff2<T> (const Array<T> &in, const int dim); \ INSTANTIATE(float) INSTANTIATE(double) INSTANTIATE(cfloat) INSTANTIATE(cdouble) INSTANTIATE(int) INSTANTIATE(uint) INSTANTIATE(intl) INSTANTIATE(uintl) INSTANTIATE(uchar) INSTANTIATE(char) } <commit_msg>Async CPU diff1 and diff2<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <Array.hpp> #include <diff.hpp> #include <stdexcept> #include <err_cpu.hpp> #include <platform.hpp> #include <async_queue.hpp> namespace cpu { unsigned getIdx(af::dim4 strides, af::dim4 offs, int i, int j = 0, int k = 0, int l = 0) { return (l * strides[3] + k * strides[2] + j * strides[1] + i); } template<typename T> Array<T> diff1(const Array<T> &in, const int dim) { // Bool for dimension bool is_dim0 = dim == 0; bool is_dim1 = dim == 1; bool is_dim2 = dim == 2; bool is_dim3 = dim == 3; // Decrement dimension of select dimension af::dim4 dims = in.dims(); dims[dim]--; // Create output placeholder Array<T> outArray = createEmptyArray<T>(dims); auto func = [=] (Array<T> outArray, Array<T> in) { // Get pointers to raw data const T *inPtr = in.get(); T *outPtr = outArray.get(); // TODO: Improve this for(dim_t l = 0; l < dims[3]; l++) { for(dim_t k = 0; k < dims[2]; k++) { for(dim_t j = 0; j < dims[1]; j++) { for(dim_t i = 0; i < dims[0]; i++) { // Operation: out[index] = in[index + 1 * dim_size] - in[index] int idx = getIdx(in.strides(), in.offsets(), i, j, k, l); int jdx = getIdx(in.strides(), in.offsets(), i + is_dim0, j + is_dim1, k + is_dim2, l + is_dim3); int odx = getIdx(outArray.strides(), outArray.offsets(), i, j, k, l); outPtr[odx] = inPtr[jdx] - inPtr[idx]; } } } } }; getQueue().enqueue(func, outArray, in); return outArray; } template<typename T> Array<T> diff2(const Array<T> &in, const int dim) { // Bool for dimension bool is_dim0 = dim == 0; bool is_dim1 = dim == 1; bool is_dim2 = dim == 2; bool is_dim3 = dim == 3; // Decrement dimension of select dimension af::dim4 dims = in.dims(); dims[dim] -= 2; // Create output placeholder Array<T> outArray = createEmptyArray<T>(dims); auto func = [=] (Array<T> outArray, Array<T> in) { // Get pointers to raw data const T *inPtr = in.get(); T *outPtr = outArray.get(); // TODO: Improve this for(dim_t l = 0; l < dims[3]; l++) { for(dim_t k = 0; k < dims[2]; k++) { for(dim_t j = 0; j < dims[1]; j++) { for(dim_t i = 0; i < dims[0]; i++) { // Operation: out[index] = in[index + 1 * dim_size] - in[index] int idx = getIdx(in.strides(), in.offsets(), i, j, k, l); int jdx = getIdx(in.strides(), in.offsets(), i + is_dim0, j + is_dim1, k + is_dim2, l + is_dim3); int kdx = getIdx(in.strides(), in.offsets(), i + 2 * is_dim0, j + 2 * is_dim1, k + 2 * is_dim2, l + 2 * is_dim3); int odx = getIdx(outArray.strides(), outArray.offsets(), i, j, k, l); outPtr[odx] = inPtr[kdx] + inPtr[idx] - inPtr[jdx] - inPtr[jdx]; } } } } }; getQueue().enqueue(func, outArray, in); return outArray; } #define INSTANTIATE(T) \ template Array<T> diff1<T> (const Array<T> &in, const int dim); \ template Array<T> diff2<T> (const Array<T> &in, const int dim); \ INSTANTIATE(float) INSTANTIATE(double) INSTANTIATE(cfloat) INSTANTIATE(cdouble) INSTANTIATE(int) INSTANTIATE(uint) INSTANTIATE(intl) INSTANTIATE(uintl) INSTANTIATE(uchar) INSTANTIATE(char) } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: javatype.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-03-30 16:53:39 $ * * 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 _CPPUMAKER_CPPUTYPE_HXX_ #define _CPPUMAKER_CPPUTYPE_HXX_ #ifndef _CODEMAKER_TYPEMANAGER_HXX_ #include <codemaker/typemanager.hxx> #endif #ifndef _CODEMAKER_DEPENDENCY_HXX_ #include <codemaker/dependency.hxx> #endif #include "codemaker/options.hxx" #include "registry/reader.hxx" #include "registry/types.h" namespace codemaker { struct ExceptionTreeNode; } enum JavaTypeDecl { CPPUTYPEDECL_ALLTYPES, CPPUTYPEDECL_NOINTERFACES, CPPUTYPEDECL_ONLYINTERFACES }; static const sal_Int32 UIT_IN = 0x00000001; static const sal_Int32 UIT_OUT = 0x00000002; static const sal_Int32 UIT_UNSIGNED = 0x00000004; static const sal_Int32 UIT_READONLY = 0x00000008; static const sal_Int32 UIT_ONEWAY = 0x00000010; static const sal_Int32 UIT_CONST = 0x00000020; static const sal_Int32 UIT_ANY = 0x00000040; static const sal_Int32 UIT_INTERFACE = 0x00000080; static const sal_Int32 UIT_BOUND = 0x00000100; enum UnoTypeInfo { UNOTYPEINFO_INVALID, UNOTYPEINFO_METHOD, UNOTYPEINFO_PARAMETER, UNOTYPEINFO_ATTIRBUTE, UNOTYPEINFO_MEMBER }; struct UnoInfo { UnoInfo() : m_unoTypeInfo(UNOTYPEINFO_INVALID) , m_index(-1) , m_flags(0) {} UnoInfo(const ::rtl::OString& name, const ::rtl::OString& methodName, UnoTypeInfo unoTypeInfo, sal_Int32 index, sal_Int32 flags) : m_name(name) , m_methodName(methodName) , m_unoTypeInfo(unoTypeInfo) , m_index(index) , m_flags(flags) {} ::rtl::OString m_name; ::rtl::OString m_methodName; UnoTypeInfo m_unoTypeInfo; sal_Int32 m_index; sal_Int32 m_flags; }; inline int operator == (const UnoInfo& u1, const UnoInfo& u2) { return ((u1.m_name == u2.m_name) && (u1.m_methodName == u2.m_methodName)); } inline int operator < (const UnoInfo& u1, const UnoInfo& u2) { if (u1.m_name == u2.m_name) return (u1.m_methodName < u2.m_methodName); else return (u1.m_name < u2.m_name); } typedef ::std::list< UnoInfo > UnoInfoList; class JavaOptions; class FileStream; class JavaType { public: JavaType(typereg::Reader& typeReader, const ::rtl::OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies); virtual ~JavaType(); virtual sal_Bool dump(JavaOptions* pOptions) throw( CannotDumpException ); void dumpDependedTypes(JavaOptions * options); virtual sal_Bool dumpFile(FileStream& o) throw( CannotDumpException ) { return sal_True; } void dumpPackage(FileStream& o, sal_Bool bFullScope = sal_False); virtual void dumpType(FileStream& o, const ::rtl::OString& type) throw( CannotDumpException ); void dumpTypeInit(FileStream& o, const ::rtl::OString& name, const ::rtl::OString& type); sal_Bool isUnsigned(const ::rtl::OString& type); sal_Bool isAny(const ::rtl::OString& type); sal_Bool isInterface(const ::rtl::OString& type); void dumpConstantValue(FileStream& o, sal_uInt16 index); // only used for structs and exceptions sal_Bool dumpMemberConstructor(FileStream& o); sal_Bool dumpInheritedMembers( FileStream& o, const ::rtl::OString& type, sal_Bool first, sal_Bool withType= sal_True ); void dumpSeqStaticMember(FileStream& o, const ::rtl::OString& type, const ::rtl::OString& name); void inc(sal_uInt32 num=4); void dec(sal_uInt32 num=4); ::rtl::OString indent(); ::rtl::OString indent(sal_uInt32 num); protected: rtl::OString resolveTypedefs(rtl::OString const & unoType); rtl::OString unfoldType(rtl::OString const & unoType, sal_Int32 * rank = 0); ::rtl::OString checkRealBaseType(const ::rtl::OString& type); virtual rtl::OString translateTypeName() { return m_typeName; } protected: sal_uInt32 m_indentLength; ::rtl::OString m_typeName; ::rtl::OString m_name; typereg::Reader m_reader; TypeManager& m_typeMgr; TypeDependency m_dependencies; }; class InterfaceType : public JavaType { public: InterfaceType(typereg::Reader& typeReader, const ::rtl::OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies); virtual ~InterfaceType(); sal_Bool dumpFile(FileStream& o) throw( CannotDumpException ); void dumpAttributes(FileStream& o, UnoInfoList* pUnoInfos); void dumpMethods(FileStream& o, UnoInfoList* pUnoInfos); void dumpUnoInfo(FileStream& o, const UnoInfo& unoInfo, sal_Int32 * index); private: void dumpExceptionSpecification(FileStream & out, sal_uInt16 methodIndex); void dumpAttributeExceptionSpecification( FileStream & out, rtl::OUString const & name, RTMethodMode sort); }; class ModuleType : public JavaType { public: ModuleType(typereg::Reader& typeReader, const ::rtl::OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies); virtual ~ModuleType(); sal_Bool dump(JavaOptions* pOptions) throw( CannotDumpException ); sal_Bool hasConstants(); }; class ConstantsType : public JavaType { public: ConstantsType(typereg::Reader& typeReader, const ::rtl::OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies); virtual ~ConstantsType(); sal_Bool dumpFile(FileStream& o) throw( CannotDumpException ); }; class StructureType : public JavaType { public: StructureType(typereg::Reader& typeReader, const ::rtl::OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies); virtual ~StructureType(); sal_Bool dumpFile(FileStream& o) throw( CannotDumpException ); }; class ExceptionType : public JavaType { public: ExceptionType(typereg::Reader& typeReader, const ::rtl::OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies); virtual ~ExceptionType(); sal_Bool dumpFile(FileStream& o) throw( CannotDumpException ); sal_Bool dumpSimpleMemberConstructor(FileStream& o); }; class EnumType : public JavaType { public: EnumType(typereg::Reader& typeReader, const ::rtl::OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies); virtual ~EnumType(); sal_Bool dumpFile(FileStream& o) throw( CannotDumpException ); }; class TypeDefType : public JavaType { public: TypeDefType(typereg::Reader& typeReader, const ::rtl::OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies); virtual ~TypeDefType(); sal_Bool dump(JavaOptions* pOptions) throw( CannotDumpException ); }; class ServiceType: public JavaType { public: ServiceType( typereg::Reader & reader, rtl::OString const & name, TypeManager const & manager, TypeDependency const & dependencies): JavaType(reader, name, manager, dependencies) {} bool isSingleInterfaceBased(); virtual sal_Bool dumpFile(FileStream & out) throw (CannotDumpException); private: virtual rtl::OString translateTypeName(); void dumpCatchClauses( FileStream & out, codemaker::ExceptionTreeNode const * node); void dumpAny( FileStream & out, rtl::OString const & javaExpression, rtl::OString const & unoType); }; class SingletonType: public JavaType { public: SingletonType( typereg::Reader & reader, rtl::OString const & name, TypeManager const & manager, TypeDependency const & dependencies): JavaType(reader, name, manager, dependencies) {} bool isInterfaceBased(); virtual sal_Bool dumpFile(FileStream & out) throw (CannotDumpException); private: virtual rtl::OString translateTypeName(); }; sal_Bool produceType(const ::rtl::OString& typeName, TypeManager& typeMgr, TypeDependency& typeDependencies, JavaOptions* pOptions) throw( CannotDumpException ); /** * This function returns a Java scoped name, represents the package * scoping of this type, e.g. com.sun.star.uno.XInterface. If the scope of * the type is equal scope, the relativ name will be used. */ ::rtl::OString scopedName(const ::rtl::OString& scope, const ::rtl::OString& type, sal_Bool bNoNameSpace=sal_False); #endif // _CPPUMAKER_CPPUTYPE_HXX_ <commit_msg>INTEGRATION: CWS sb18 (1.3.4); FILE MERGED 2004/05/07 08:25:48 sb 1.3.4.3: #i21150# Complete rewrite of javamaker to generate .class files instead of .java files. 2004/04/28 08:59:43 sb 1.3.4.2: #i21150# Simplified TypeDependency to Dependencies. 2004/04/22 08:23:26 sb 1.3.4.1: #i21150# Refactord GeneratedTypeSet out of TypeDependency; expanded unotypesort.hxx to unotype.hxx.<commit_after>/************************************************************************* * * $RCSfile: javatype.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-06-04 03:14:13 $ * * 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 INCLUDED_codemaker_source_javamaker_javatype_hxx #define INCLUDED_codemaker_source_javamaker_javatype_hxx namespace codemaker { class GeneratedTypeSet; } namespace rtl { class OString; } class JavaOptions; class TypeManager; bool produceType( rtl::OString const & type, TypeManager & manager, codemaker::GeneratedTypeSet & generated, JavaOptions * options); #endif <|endoftext|>
<commit_before>#include <reflectionzeug/AbstractProperty.h> #include <utility> #include <reflectionzeug/AbstractValueProperty.h> #include <reflectionzeug/AbstractPropertyCollection.h> #include <reflectionzeug/PropertyGroup.h> #include <reflectionzeug/util.h> namespace reflectionzeug { const std::string AbstractProperty::s_nameRegexString("[a-zA-Z_]+\\w*"); AbstractProperty::AbstractProperty() { } AbstractProperty::AbstractProperty(const std::string & name) { setName(name); } AbstractProperty::~AbstractProperty() { } std::string AbstractProperty::name() const { return m_name; } bool AbstractProperty::setName(const std::string & name) { if (!util::matchesRegex(name, s_nameRegexString)) return false; m_name = name; return true; } bool AbstractProperty::hasName() const { return !m_name.empty(); } Variant AbstractProperty::option(const std::string & key) const { if (!this->hasOption(key)) return Variant(); return m_options.at(key); } void AbstractProperty::setOption(const std::string & key, const Variant & value) { m_options[key] = value; } void AbstractProperty::setOptions(const VariantMap & map) { for (const auto & pair : map) { m_options[pair.first] = pair.second; optionChanged(pair.first); } } bool AbstractProperty::removeOption(const std::string & key) { if (!this->hasOption(key)) return false; m_options.erase(key); return true; } bool AbstractProperty::hasOption(const std::string & key) const { return m_options.count(key) != 0; } const VariantMap & AbstractProperty::options() const { return m_options; } AbstractValueProperty * AbstractProperty::asValue() { return dynamic_cast<AbstractValueProperty *>(this); } const AbstractValueProperty * AbstractProperty::asValue() const { return dynamic_cast<const AbstractValueProperty *>(this); } AbstractPropertyCollection * AbstractProperty::asCollection() { return dynamic_cast<AbstractPropertyCollection *>(this); } const AbstractPropertyCollection * AbstractProperty::asCollection() const { return dynamic_cast<const AbstractPropertyCollection *>(this); } PropertyGroup * AbstractProperty::asGroup() { return dynamic_cast<PropertyGroup *>(this); } const PropertyGroup * AbstractProperty::asGroup() const { return dynamic_cast<const PropertyGroup *>(this); } bool AbstractProperty::isCollection() const { return false; } bool AbstractProperty::isValue() const { return false; } bool AbstractProperty::isGroup() const { return false; } } // namespace reflectionzeug <commit_msg>reapply changes which were lost while merging the last pullrequest<commit_after>#include <reflectionzeug/AbstractProperty.h> #include <utility> #include <reflectionzeug/AbstractValueProperty.h> #include <reflectionzeug/AbstractPropertyCollection.h> #include <reflectionzeug/PropertyGroup.h> #include <reflectionzeug/util.h> namespace reflectionzeug { const std::string AbstractProperty::s_nameRegexString("[a-zA-Z_]+\\w*"); AbstractProperty::AbstractProperty() { } AbstractProperty::AbstractProperty(const std::string & name) { setName(name); } AbstractProperty::~AbstractProperty() { } std::string AbstractProperty::name() const { return m_name; } bool AbstractProperty::setName(const std::string & name) { if (!util::matchesRegex(name, s_nameRegexString)) return false; m_name = name; return true; } bool AbstractProperty::hasName() const { return !m_name.empty(); } Variant AbstractProperty::option(const std::string & key) const { if (!this->hasOption(key)) return Variant(); return m_options.at(key); } void AbstractProperty::setOption(const std::string & key, const Variant & value) { m_options[key] = value; optionChanged(key); } void AbstractProperty::setOptions(const VariantMap & map) { for (const auto & pair : map) { m_options[pair.first] = pair.second; optionChanged(pair.first); } } bool AbstractProperty::removeOption(const std::string & key) { if (!this->hasOption(key)) return false; m_options.erase(key); optionChanged(key); return true; } bool AbstractProperty::hasOption(const std::string & key) const { return m_options.count(key) != 0; } const VariantMap & AbstractProperty::options() const { return m_options; } AbstractValueProperty * AbstractProperty::asValue() { return dynamic_cast<AbstractValueProperty *>(this); } const AbstractValueProperty * AbstractProperty::asValue() const { return dynamic_cast<const AbstractValueProperty *>(this); } AbstractPropertyCollection * AbstractProperty::asCollection() { return dynamic_cast<AbstractPropertyCollection *>(this); } const AbstractPropertyCollection * AbstractProperty::asCollection() const { return dynamic_cast<const AbstractPropertyCollection *>(this); } PropertyGroup * AbstractProperty::asGroup() { return dynamic_cast<PropertyGroup *>(this); } const PropertyGroup * AbstractProperty::asGroup() const { return dynamic_cast<const PropertyGroup *>(this); } bool AbstractProperty::isCollection() const { return false; } bool AbstractProperty::isValue() const { return false; } bool AbstractProperty::isGroup() const { return false; } } // namespace reflectionzeug <|endoftext|>
<commit_before>#include "vast/program.h" #include <cstdlib> #include <iostream> #include <boost/exception/diagnostic_information.hpp> #include "vast/exception.h" #include "vast/fs/path.h" #include "vast/fs/operations.h" #include "vast/meta/taxonomy.h" #include "vast/util/logger.h" #include "vast/util/make_unique.h" #include "vast/store/ingestor.h" #include "config.h" #ifdef USE_PERFTOOLS #include "google/profiler.h" #include "google/heap-profiler.h" #endif namespace vast { /// Declaration of global (extern) variables. namespace util { logger* LOGGER; } program::program() : terminating_(false) , return_(EXIT_SUCCESS) , ingestor_(io_) , profiler_(io_.service()) { } program::~program() { } bool program::init(std::string const& filename) { try { config_.load(filename); do_init(); return true; } catch (boost::program_options::unknown_option const& e) { std::cerr << e.what() << ", try -h or --help" << std::endl; } return false; } bool program::init(int argc, char *argv[]) { try { config_.load(argc, argv); if (argc < 2 || config_.check("help") || config_.check("advanced")) { config_.print(std::cerr, config_.check("advanced")); return false; } do_init(); return true; } catch (config_exception const& e) { std::cerr << e.what() << std::endl; } catch (boost::program_options::unknown_option const& e) { std::cerr << e.what() << ", try -h or --help" << std::endl; } catch (boost::exception const& e) { std::cerr << boost::diagnostic_information(e); } return false; } void program::start() { try { auto dir = config_.get<fs::path>("dir"); if (config_.check("profile")) { auto const& filename = config_.get<fs::path>("dir") / config_.get<fs::path>("log-dir") / "profiler.log"; typedef std::chrono::duration<unsigned, std::ratio<1>> seconds; seconds interval(config_.get<unsigned>("profiler-interval")); profiler_.init( filename, std::chrono::duration_cast<util::duration>(interval)); profiler_.start(); } #ifdef USE_PERFTOOLS if (config_.check("perftools-heap")) { LOG(info, core) << "starting perftools CPU profiler"; ::HeapProfilerStart((dir / "heap.profile").string().c_str()); } if (config_.check("perftools-cpu")) { LOG(info, core) << "starting perftools heap profiler"; ::ProfilerStart((dir / "cpu.profile").string().c_str()); } #endif if (config_.check("taxonomy")) { auto const& taxonomy = config_.get<fs::path>("taxonomy"); tax_manager_.init(taxonomy); if (config_.check("dump-taxonomy")) { std::cout << tax_manager_.get()->to_string(); return; } } if (config_.check("ingestor") || config_.check("all")) { ingestor_.init(config_.get<std::string>("ingest.ip"), config_.get<unsigned>("ingest.port")); } io_.start(errors_); std::exception_ptr error = errors_.pop(); if (error) std::rethrow_exception(error); } catch (...) { // FIXME: When streaming directly to the logger, the compiler complains // about "no match for 'operator<<'. std::stringstream ss; ss << "exception details:" << std::endl << boost::current_exception_diagnostic_information(); LOG(fatal, core) << ss.str(); return_ = EXIT_FAILURE; } if (! terminating_) stop(); } void program::stop() { if (! terminating_) { terminating_ = true; LOG(verbose, core) << "writing out in-memory state"; #ifdef USE_PERFTOOLS if (config_.check("perftools-cpu")) { LOG(info, core) << "stopping perftools CPU profiler"; ::ProfilerStop(); } if (config_.check("perftools-heap") && ::IsHeapProfilerRunning()) { LOG(info, core) << "stopping perftools heap profiler"; ::HeapProfilerDump("cleanup"); ::HeapProfilerStop(); } #endif io_.stop(); if (config_.check("profile")) profiler_.stop(); LOG(verbose, core) << "state saved"; // FIXME: this is not yet working correctly when stop is called from // the SIGINT handler. What should happen by pushing an empty // exception_ptr (meaning, no error) onto the error queue is that // start() resumes executing after having waited in errors_.pop(); if (errors_.empty()) errors_.push(std::exception_ptr()); } else { io_.terminate(); } } int program::end() { switch (return_) { case EXIT_SUCCESS: LOG(verbose, core) << "VAST terminated cleanly"; break; case EXIT_FAILURE: LOG(verbose, core) << "VAST terminated with errors"; break; default: assert(! "invalid return code"); } return return_; } void program::do_init() { auto dir = config_.get<fs::path>("dir"); if (! fs::exists(dir)) fs::mkdir(dir); util::LOGGER = new util::logger( config_.get<int>("console-verbosity"), config_.get<int>("log-verbosity"), dir / config_.get<fs::path>("log-dir")); LOG(info, core) << " _ _____ __________"; LOG(info, core) << "| | / / _ | / __/_ __/"; LOG(info, core) << "| |/ / __ |_\\ \\ / / "; LOG(info, core) << "|___/_/ |_/___/ /_/ " << VAST_VERSION; LOG(info, core) << ""; } } // namespace vast <commit_msg>Address FIXME.<commit_after>#include "vast/program.h" #include <cstdlib> #include <iostream> #include <boost/exception/diagnostic_information.hpp> #include "vast/exception.h" #include "vast/fs/path.h" #include "vast/fs/operations.h" #include "vast/meta/taxonomy.h" #include "vast/util/logger.h" #include "vast/util/make_unique.h" #include "vast/store/ingestor.h" #include "config.h" #ifdef USE_PERFTOOLS #include "google/profiler.h" #include "google/heap-profiler.h" #endif namespace vast { /// Declaration of global (extern) variables. namespace util { logger* LOGGER; } program::program() : terminating_(false) , return_(EXIT_SUCCESS) , ingestor_(io_) , profiler_(io_.service()) { } program::~program() { } bool program::init(std::string const& filename) { try { config_.load(filename); do_init(); return true; } catch (boost::program_options::unknown_option const& e) { std::cerr << e.what() << ", try -h or --help" << std::endl; } return false; } bool program::init(int argc, char *argv[]) { try { config_.load(argc, argv); if (argc < 2 || config_.check("help") || config_.check("advanced")) { config_.print(std::cerr, config_.check("advanced")); return false; } do_init(); return true; } catch (config_exception const& e) { std::cerr << e.what() << std::endl; } catch (boost::program_options::unknown_option const& e) { std::cerr << e.what() << ", try -h or --help" << std::endl; } catch (boost::exception const& e) { std::cerr << boost::diagnostic_information(e); } return false; } void program::start() { try { auto dir = config_.get<fs::path>("dir"); if (config_.check("profile")) { auto const& filename = config_.get<fs::path>("dir") / config_.get<fs::path>("log-dir") / "profiler.log"; typedef std::chrono::duration<unsigned, std::ratio<1>> seconds; seconds interval(config_.get<unsigned>("profiler-interval")); profiler_.init( filename, std::chrono::duration_cast<util::duration>(interval)); profiler_.start(); } #ifdef USE_PERFTOOLS if (config_.check("perftools-heap")) { LOG(info, core) << "starting perftools CPU profiler"; ::HeapProfilerStart((dir / "heap.profile").string().c_str()); } if (config_.check("perftools-cpu")) { LOG(info, core) << "starting perftools heap profiler"; ::ProfilerStart((dir / "cpu.profile").string().c_str()); } #endif if (config_.check("taxonomy")) { auto const& taxonomy = config_.get<fs::path>("taxonomy"); tax_manager_.init(taxonomy); if (config_.check("dump-taxonomy")) { std::cout << tax_manager_.get()->to_string(); return; } } if (config_.check("ingestor") || config_.check("all")) { ingestor_.init(config_.get<std::string>("ingest.ip"), config_.get<unsigned>("ingest.port")); } io_.start(errors_); std::exception_ptr error = errors_.pop(); if (error) std::rethrow_exception(error); } catch (...) { LOG(fatal, core) << "exception details:" << std::endl << boost::current_exception_diagnostic_information(); return_ = EXIT_FAILURE; } if (! terminating_) stop(); } void program::stop() { if (! terminating_) { terminating_ = true; LOG(verbose, core) << "writing out in-memory state"; #ifdef USE_PERFTOOLS if (config_.check("perftools-cpu")) { LOG(info, core) << "stopping perftools CPU profiler"; ::ProfilerStop(); } if (config_.check("perftools-heap") && ::IsHeapProfilerRunning()) { LOG(info, core) << "stopping perftools heap profiler"; ::HeapProfilerDump("cleanup"); ::HeapProfilerStop(); } #endif io_.stop(); if (config_.check("profile")) profiler_.stop(); LOG(verbose, core) << "state saved"; // FIXME: this is not yet working correctly when stop is called from // the SIGINT handler. What should happen by pushing an empty // exception_ptr (meaning, no error) onto the error queue is that // start() resumes executing after having waited in errors_.pop(); if (errors_.empty()) errors_.push(std::exception_ptr()); } else { io_.terminate(); } } int program::end() { switch (return_) { case EXIT_SUCCESS: LOG(verbose, core) << "VAST terminated cleanly"; break; case EXIT_FAILURE: LOG(verbose, core) << "VAST terminated with errors"; break; default: assert(! "invalid return code"); } return return_; } void program::do_init() { auto dir = config_.get<fs::path>("dir"); if (! fs::exists(dir)) fs::mkdir(dir); util::LOGGER = new util::logger( config_.get<int>("console-verbosity"), config_.get<int>("log-verbosity"), dir / config_.get<fs::path>("log-dir")); LOG(info, core) << " _ _____ __________"; LOG(info, core) << "| | / / _ | / __/_ __/"; LOG(info, core) << "| |/ / __ |_\\ \\ / / "; LOG(info, core) << "|___/_/ |_/___/ /_/ " << VAST_VERSION; LOG(info, core) << ""; } } // namespace vast <|endoftext|>
<commit_before>#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "pybind11_glm.hpp" #include <VFRendering/View.hxx> #include <VFRendering/Geometry.hxx> #include <VFRendering/RendererBase.hxx> #include <VFRendering/ArrowRenderer.hxx> #include <VFRendering/BoundingBoxRenderer.hxx> #include <VFRendering/CoordinateSystemRenderer.hxx> #include <VFRendering/Options.hxx> #include <memory> namespace py = pybind11; using namespace VFRendering; typedef unsigned int index_type; PYBIND11_MODULE(pyVFRendering, m) { py::class_<Geometry>(m, "Geometry") .def(py::init<>()) .def(py::init<const std::vector<glm::vec3>&, const std::vector<std::array<index_type, 3>>&, const std::vector<std::array<index_type, 4>>&, const bool&>()) .def("cartesianGeometry", &Geometry::cartesianGeometry) .def("rectilinearGeometry", &Geometry::rectilinearGeometry) .def("min", &Geometry::min) .def("max", &Geometry::max); py::class_<View>(m, "View") .def(py::init<>()) .def("update", &View::update) .def("draw", &View::draw) .def("renderers", &View::renderers) .def("setFramebufferSize", &View::setFramebufferSize) .def("updateOptions", &View::updateOptions) .def("mouseMove", &View::mouseMove) .def("mouseScroll", &View::mouseScroll); py::enum_<Utilities::Colormap>(m, "Colormap") .value("HSV", Utilities::Colormap::HSV) .value("BLUEWHITERED", Utilities::Colormap::BLUEWHITERED) .export_values(); py::enum_<CameraMovementModes>(m, "CameraMovementModes") .value("rotate_bounded", CameraMovementModes::ROTATE_BOUNDED) .value("rotate_free", CameraMovementModes::ROTATE_FREE) .value("translate", CameraMovementModes::TRANSLATE) .export_values(); m.def("getColormapImplementation", &Utilities::getColormapImplementation, "Get a CM implementation from the CM enum"); py::class_<RendererBase, std::shared_ptr<RendererBase>>(m, "RendererBase"); py::class_<ArrowRenderer, RendererBase, std::shared_ptr<ArrowRenderer>>(m, "ArrowRenderer") .def(py::init<View&>()); py::class_<BoundingBoxRenderer, RendererBase, std::shared_ptr<BoundingBoxRenderer>>(m, "BoundingBoxRenderer") .def("forCuboid", &BoundingBoxRenderer::forCuboid); py::class_<CoordinateSystemRenderer, RendererBase, std::shared_ptr<CoordinateSystemRenderer>>(m, "CoordinateSystemRenderer") .def(py::init<View&>()) .def("set_axis_length", &CoordinateSystemRenderer::setOption<CoordinateSystemRenderer::Option::AXIS_LENGTH>) .def("set_normalize", &CoordinateSystemRenderer::setOption<CoordinateSystemRenderer::Option::NORMALIZE>); py::class_<Options>(m, "Options") .def(py::init<>()) .def("set_system_center", &Options::set<View::Option::SYSTEM_CENTER>) .def("set_vertical_fov", &Options::set<View::Option::VERTICAL_FIELD_OF_VIEW>) .def("set_background_color", &Options::set<View::Option::BACKGROUND_COLOR>) .def("set_colormap_implementation", &Options::set<View::Option::COLORMAP_IMPLEMENTATION>) .def("set_is_visible_implementation", &Options::set<View::Option::IS_VISIBLE_IMPLEMENTATION>) .def("set_camera_position", &Options::set<View::Option::CAMERA_POSITION>) .def("set_center_position", &Options::set<View::Option::CENTER_POSITION>) .def("set_up_vector", &Options::set<View::Option::UP_VECTOR>); } <commit_msg>Added more useful options to python bindings.<commit_after>#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "pybind11_glm.hpp" #include <VFRendering/View.hxx> #include <VFRendering/Geometry.hxx> #include <VFRendering/RendererBase.hxx> #include <VFRendering/ArrowRenderer.hxx> #include <VFRendering/BoundingBoxRenderer.hxx> #include <VFRendering/CoordinateSystemRenderer.hxx> #include <VFRendering/Options.hxx> #include <memory> namespace py = pybind11; using namespace VFRendering; typedef unsigned int index_type; PYBIND11_MODULE(pyVFRendering, m) { py::class_<Geometry>(m, "Geometry") .def(py::init<>()) .def(py::init<const std::vector<glm::vec3>&, const std::vector<std::array<index_type, 3>>&, const std::vector<std::array<index_type, 4>>&, const bool&>()) .def("cartesianGeometry", &Geometry::cartesianGeometry) .def("rectilinearGeometry", &Geometry::rectilinearGeometry) .def("min", &Geometry::min) .def("max", &Geometry::max); py::class_<View>(m, "View") .def(py::init<>()) .def("update", &View::update) .def("draw", &View::draw) .def("renderers", &View::renderers) .def("setFramebufferSize", &View::setFramebufferSize) .def("updateOptions", &View::updateOptions) .def("mouseMove", &View::mouseMove) .def("mouseScroll", &View::mouseScroll) .def("getFramerate", &View::getFramerate); py::enum_<Utilities::Colormap>(m, "Colormap") .value("HSV", Utilities::Colormap::HSV) .value("BLUEWHITERED", Utilities::Colormap::BLUEWHITERED) .export_values(); py::enum_<CameraMovementModes>(m, "CameraMovementModes") .value("rotate_bounded", CameraMovementModes::ROTATE_BOUNDED) .value("rotate_free", CameraMovementModes::ROTATE_FREE) .value("translate", CameraMovementModes::TRANSLATE) .export_values(); m.def("getColormapImplementation", &Utilities::getColormapImplementation, "Get a CM implementation from the CM enum"); py::class_<RendererBase, std::shared_ptr<RendererBase>>(m, "RendererBase"); py::class_<ArrowRenderer, RendererBase, std::shared_ptr<ArrowRenderer>>(m, "ArrowRenderer") .def(py::init<View&>()); py::class_<BoundingBoxRenderer, RendererBase, std::shared_ptr<BoundingBoxRenderer>>(m, "BoundingBoxRenderer") .def("forCuboid", &BoundingBoxRenderer::forCuboid); py::class_<CoordinateSystemRenderer, RendererBase, std::shared_ptr<CoordinateSystemRenderer>>(m, "CoordinateSystemRenderer") .def(py::init<View&>()) .def("set_axis_length", &CoordinateSystemRenderer::setOption<CoordinateSystemRenderer::Option::AXIS_LENGTH>) .def("set_normalize", &CoordinateSystemRenderer::setOption<CoordinateSystemRenderer::Option::NORMALIZE>); py::class_<Options>(m, "Options") .def(py::init<>()) .def("set_system_center", &Options::set<View::Option::SYSTEM_CENTER>) .def("set_vertical_fov", &Options::set<View::Option::VERTICAL_FIELD_OF_VIEW>) .def("set_background_color", &Options::set<View::Option::BACKGROUND_COLOR>) .def("set_boundingbox_color", &Options::set<BoundingBoxRenderer::Option::COLOR>) .def("set_colormap_implementation", &Options::set<View::Option::COLORMAP_IMPLEMENTATION>) .def("set_is_visible_implementation", &Options::set<View::Option::IS_VISIBLE_IMPLEMENTATION>) .def("set_camera_position", &Options::set<View::Option::CAMERA_POSITION>) .def("set_center_position", &Options::set<View::Option::CENTER_POSITION>) .def("set_up_vector", &Options::set<View::Option::UP_VECTOR>) .def("get_system_center", &Options::get<View::Option::SYSTEM_CENTER>) .def("get_background_color", &Options::get<View::Option::BACKGROUND_COLOR>) .def("get_boundingbox_color", &Options::get<BoundingBoxRenderer::Option::COLOR>) .def("get_camera_position", &Options::get<View::Option::CAMERA_POSITION>) .def("get_center_position", &Options::get<View::Option::CENTER_POSITION>) .def("get_up_vector", &Options::get<View::Option::UP_VECTOR>); } <|endoftext|>
<commit_before>/* * $Id$ * * Copyright(C) 1998-2003 Satoshi Nakamura * All rights reserved. * */ #include <qmapplication.h> #include <qmmessage.h> #include <qsconv.h> #include <qsnew.h> #include <qsosutil.h> #include <qsstream.h> #include "externaleditor.h" #pragma warning(disable:4786) using namespace qm; using namespace qs; /**************************************************************************** * * ExternalEditorManager * */ qm::ExternalEditorManager::ExternalEditorManager(Document* pDocument, Profile* pProfile, HWND hwnd, FolderModel* pFolderModel, QSTATUS* pstatus) : composer_(false, pDocument, pProfile, hwnd, pFolderModel), pProfile_(pProfile), hwnd_(hwnd), pThread_(0), pEvent_(0) { } qm::ExternalEditorManager::~ExternalEditorManager() { if (pThread_) { pThread_->stop(); delete pThread_; } delete pEvent_; ItemList::iterator it = listItem_.begin(); while (it != listItem_.end()) { Item& item = *it; freeWString(item.wstrPath_); ::CloseHandle(item.hProcess_); ++it; } } QSTATUS qm::ExternalEditorManager::open(const WCHAR* pwszMessage) { DECLARE_QSTATUS(); string_ptr<WSTRING> wstrPath; status = prepareTemporaryFile(pwszMessage, &wstrPath); CHECK_QSTATUS(); W2T(wstrPath.get(), ptszPath); WIN32_FIND_DATA fd; AutoFindHandle hFind(::FindFirstFile(ptszPath, &fd)); if (!hFind.get()) return QSTATUS_FAIL; string_ptr<WSTRING> wstrEditor; status = pProfile_->getString(L"Global", L"ExternalEditor", L"", &wstrEditor); CHECK_QSTATUS(); if (!*wstrEditor.get()) { wstrEditor.reset(0); status = pProfile_->getString(L"Global", L"Editor", L"", &wstrEditor); CHECK_QSTATUS(); } const WCHAR* pFile = wstrEditor.get(); WCHAR* pParam = 0; if (*wstrEditor.get() == L'\"') { ++pFile; pParam = wcschr(wstrEditor.get() + 1, L'\"'); } else { pParam = wcschr(wstrEditor.get(), L' '); } if (pParam) { *pParam = L'\0'; ++pParam; } string_ptr<WSTRING> wstrParam; status = createParam(pParam, wstrPath.get(), &wstrParam); CHECK_QSTATUS(); W2T(pFile, ptszFile); W2T(wstrParam.get(), ptszParam); SHELLEXECUTEINFO sei = { sizeof(sei), SEE_MASK_NOCLOSEPROCESS, hwnd_, 0, ptszFile, ptszParam, 0, #ifdef _WIN32_WCE SW_SHOWNORMAL, #else SW_SHOWDEFAULT, #endif }; ::ShellExecuteEx(&sei); AutoHandle hProcess(sei.hProcess); Item item = { wstrPath.get(), { fd.ftLastWriteTime.dwLowDateTime, fd.ftLastWriteTime.dwHighDateTime }, hProcess.get() }; { Lock<CriticalSection> lock(cs_); status = STLWrapper<ItemList>(listItem_).push_back(item); CHECK_QSTATUS(); } wstrPath.release(); hProcess.release(); if (!pThread_) { status = newQsObject(&pEvent_); CHECK_QSTATUS(); status = newQsObject(this, &pThread_); CHECK_QSTATUS(); status = pThread_->start(); CHECK_QSTATUS(); } else { pEvent_->set(); } return QSTATUS_SUCCESS; } QSTATUS qm::ExternalEditorManager::prepareTemporaryFile( const WCHAR* pwszMessage, qs::WSTRING* pwstrPath) { assert(pwszMessage); assert(pwstrPath); DECLARE_QSTATUS(); Time time(Time::getCurrentTime()); WCHAR wszName[128]; swprintf(wszName, L"q3edit-%04d%02d%02d%02d%02d%02d%03d.txt", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds); string_ptr<WSTRING> wstrPath(concat( Application::getApplication().getTemporaryFolder(), wszName)); if (!wstrPath.get()) return QSTATUS_OUTOFMEMORY; FileOutputStream stream(wstrPath.get(), &status); CHECK_QSTATUS(); BufferedOutputStream bufferedStream(&stream, false, &status); CHECK_QSTATUS(); OutputStreamWriter writer(&bufferedStream, false, getSystemEncoding(), &status); CHECK_QSTATUS(); status = writer.write(pwszMessage, wcslen(pwszMessage)); CHECK_QSTATUS(); status = writer.close(); CHECK_QSTATUS(); *pwstrPath = wstrPath.release(); return QSTATUS_SUCCESS; } QSTATUS qm::ExternalEditorManager::createParam(const WCHAR* pwszTemplate, const WCHAR* pwszPath, WSTRING* pwstrParam) { assert(pwszPath); assert(pwstrParam); DECLARE_QSTATUS(); StringBuffer<WSTRING> bufParam(&status); CHECK_QSTATUS(); if (pwszTemplate) { const WCHAR* p = wcsstr(pwszTemplate, L"%f"); if (p) { status = bufParam.append(pwszTemplate, p - pwszTemplate); CHECK_QSTATUS(); status = bufParam.append(pwszPath); CHECK_QSTATUS(); status = bufParam.append(p + 2); CHECK_QSTATUS(); } else { status = bufParam.append(pwszTemplate); CHECK_QSTATUS(); status = bufParam.append(L' '); CHECK_QSTATUS(); status = bufParam.append(pwszPath); CHECK_QSTATUS(); } } else { status = bufParam.append(pwszPath); CHECK_QSTATUS(); } *pwstrParam = bufParam.getString(); return QSTATUS_SUCCESS; } QSTATUS qm::ExternalEditorManager::createMessage(const WCHAR* pwszPath) { assert(pwszPath); DECLARE_QSTATUS(); FileInputStream stream(pwszPath, &status); CHECK_QSTATUS(); BufferedInputStream bufferedStream(&stream, false, &status); CHECK_QSTATUS(); InputStreamReader reader(&bufferedStream, false, getSystemEncoding(), &status); CHECK_QSTATUS(); typedef std::vector<WCHAR> Buffer; Buffer buffer; size_t nSize = 0; while (true) { status = STLWrapper<Buffer>(buffer).resize(nSize + 1024); CHECK_QSTATUS(); size_t nRead = 0; status = reader.read(&buffer[nSize], 1024, &nRead); CHECK_QSTATUS(); if (nRead == -1) break; nSize += nRead; } status = reader.close(); CHECK_QSTATUS(); if (nSize != 0) { Message* p = 0; MessageCreator creator; status = creator.createMessage(&buffer[0], nSize, &p); CHECK_QSTATUS(); std::auto_ptr<Message> pMessage(p); unsigned int nFlags = 0; // TODO // Set flags status = composer_.compose(0, 0, pMessage.get(), nFlags); CHECK_QSTATUS(); } return QSTATUS_SUCCESS; } /**************************************************************************** * * ExternalEditorManager::WaitThread * */ qm::ExternalEditorManager::WaitThread::WaitThread( ExternalEditorManager* pManager, QSTATUS* pstatus) : Thread(pstatus), pManager_(pManager), bStop_(false) { } qm::ExternalEditorManager::WaitThread::~WaitThread() { } void qm::ExternalEditorManager::WaitThread::stop() { bStop_ = true; pManager_->pEvent_->set(); join(); } unsigned int qm::ExternalEditorManager::WaitThread::run() { DECLARE_QSTATUS(); while (true) { typedef std::vector<HANDLE> HandleList; HandleList listHandle; { Lock<CriticalSection> lock(pManager_->cs_); status = STLWrapper<HandleList>(listHandle).resize( pManager_->listItem_.size() + 1); listHandle[0] = pManager_->pEvent_->getHandle(); // TODO // Error std::transform(pManager_->listItem_.begin(), pManager_->listItem_.end(), listHandle.begin() + 1, mem_data_ref(&Item::hProcess_)); } DWORD dw = ::WaitForMultipleObjects( listHandle.size(), &listHandle[0], FALSE, INFINITE); HANDLE handle = 0; if (WAIT_OBJECT_0 <= dw && dw < WAIT_OBJECT_0 + listHandle.size()) { handle = listHandle[dw - WAIT_OBJECT_0]; } else if (WAIT_ABANDONED_0 <= dw && dw < WAIT_ABANDONED_0 + listHandle.size()) { handle = listHandle[dw - WAIT_ABANDONED_0]; } else { // TODO } if (handle == pManager_->pEvent_->getHandle()) { if (bStop_) return 0; } else { string_ptr<WSTRING> wstrPath; FILETIME ft; { Lock<CriticalSection> lock(pManager_->cs_); ItemList::iterator it = std::find_if( pManager_->listItem_.begin(), pManager_->listItem_.end(), std::bind2nd( binary_compose_f_gx_hy( std::equal_to<HANDLE>(), mem_data_ref(&Item::hProcess_), std::identity<HANDLE>()), handle)); assert(it != pManager_->listItem_.end()); Item& item = *it; ::CloseHandle(item.hProcess_); wstrPath.reset(item.wstrPath_); ft = item.ft_; pManager_->listItem_.erase(it); } W2T_STATUS(wstrPath.get(), ptszPath); // TODO // Error WIN32_FIND_DATA fd; AutoFindHandle hFind(::FindFirstFile(ptszPath, &fd)); if (hFind.get() && ::CompareFileTime(&ft, &fd.ftLastWriteTime) != 0) { status = pManager_->createMessage(wstrPath.get()); // TODO // Error ::DeleteFile(ptszPath); } } } return 0; } <commit_msg>Fix Content-Type etc is not generated while creating message using an external editor. <BTS:398><commit_after>/* * $Id$ * * Copyright(C) 1998-2003 Satoshi Nakamura * All rights reserved. * */ #include <qmapplication.h> #include <qmmessage.h> #include <qsconv.h> #include <qsnew.h> #include <qsosutil.h> #include <qsstream.h> #include "externaleditor.h" #pragma warning(disable:4786) using namespace qm; using namespace qs; /**************************************************************************** * * ExternalEditorManager * */ qm::ExternalEditorManager::ExternalEditorManager(Document* pDocument, Profile* pProfile, HWND hwnd, FolderModel* pFolderModel, QSTATUS* pstatus) : composer_(false, pDocument, pProfile, hwnd, pFolderModel), pProfile_(pProfile), hwnd_(hwnd), pThread_(0), pEvent_(0) { } qm::ExternalEditorManager::~ExternalEditorManager() { if (pThread_) { pThread_->stop(); delete pThread_; } delete pEvent_; ItemList::iterator it = listItem_.begin(); while (it != listItem_.end()) { Item& item = *it; freeWString(item.wstrPath_); ::CloseHandle(item.hProcess_); ++it; } } QSTATUS qm::ExternalEditorManager::open(const WCHAR* pwszMessage) { DECLARE_QSTATUS(); string_ptr<WSTRING> wstrPath; status = prepareTemporaryFile(pwszMessage, &wstrPath); CHECK_QSTATUS(); W2T(wstrPath.get(), ptszPath); WIN32_FIND_DATA fd; AutoFindHandle hFind(::FindFirstFile(ptszPath, &fd)); if (!hFind.get()) return QSTATUS_FAIL; string_ptr<WSTRING> wstrEditor; status = pProfile_->getString(L"Global", L"ExternalEditor", L"", &wstrEditor); CHECK_QSTATUS(); if (!*wstrEditor.get()) { wstrEditor.reset(0); status = pProfile_->getString(L"Global", L"Editor", L"", &wstrEditor); CHECK_QSTATUS(); } const WCHAR* pFile = wstrEditor.get(); WCHAR* pParam = 0; if (*wstrEditor.get() == L'\"') { ++pFile; pParam = wcschr(wstrEditor.get() + 1, L'\"'); } else { pParam = wcschr(wstrEditor.get(), L' '); } if (pParam) { *pParam = L'\0'; ++pParam; } string_ptr<WSTRING> wstrParam; status = createParam(pParam, wstrPath.get(), &wstrParam); CHECK_QSTATUS(); W2T(pFile, ptszFile); W2T(wstrParam.get(), ptszParam); SHELLEXECUTEINFO sei = { sizeof(sei), SEE_MASK_NOCLOSEPROCESS, hwnd_, 0, ptszFile, ptszParam, 0, #ifdef _WIN32_WCE SW_SHOWNORMAL, #else SW_SHOWDEFAULT, #endif }; ::ShellExecuteEx(&sei); AutoHandle hProcess(sei.hProcess); Item item = { wstrPath.get(), { fd.ftLastWriteTime.dwLowDateTime, fd.ftLastWriteTime.dwHighDateTime }, hProcess.get() }; { Lock<CriticalSection> lock(cs_); status = STLWrapper<ItemList>(listItem_).push_back(item); CHECK_QSTATUS(); } wstrPath.release(); hProcess.release(); if (!pThread_) { status = newQsObject(&pEvent_); CHECK_QSTATUS(); status = newQsObject(this, &pThread_); CHECK_QSTATUS(); status = pThread_->start(); CHECK_QSTATUS(); } else { pEvent_->set(); } return QSTATUS_SUCCESS; } QSTATUS qm::ExternalEditorManager::prepareTemporaryFile( const WCHAR* pwszMessage, qs::WSTRING* pwstrPath) { assert(pwszMessage); assert(pwstrPath); DECLARE_QSTATUS(); Time time(Time::getCurrentTime()); WCHAR wszName[128]; swprintf(wszName, L"q3edit-%04d%02d%02d%02d%02d%02d%03d.txt", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds); string_ptr<WSTRING> wstrPath(concat( Application::getApplication().getTemporaryFolder(), wszName)); if (!wstrPath.get()) return QSTATUS_OUTOFMEMORY; FileOutputStream stream(wstrPath.get(), &status); CHECK_QSTATUS(); BufferedOutputStream bufferedStream(&stream, false, &status); CHECK_QSTATUS(); OutputStreamWriter writer(&bufferedStream, false, getSystemEncoding(), &status); CHECK_QSTATUS(); status = writer.write(pwszMessage, wcslen(pwszMessage)); CHECK_QSTATUS(); status = writer.close(); CHECK_QSTATUS(); *pwstrPath = wstrPath.release(); return QSTATUS_SUCCESS; } QSTATUS qm::ExternalEditorManager::createParam(const WCHAR* pwszTemplate, const WCHAR* pwszPath, WSTRING* pwstrParam) { assert(pwszPath); assert(pwstrParam); DECLARE_QSTATUS(); StringBuffer<WSTRING> bufParam(&status); CHECK_QSTATUS(); if (pwszTemplate) { const WCHAR* p = wcsstr(pwszTemplate, L"%f"); if (p) { status = bufParam.append(pwszTemplate, p - pwszTemplate); CHECK_QSTATUS(); status = bufParam.append(pwszPath); CHECK_QSTATUS(); status = bufParam.append(p + 2); CHECK_QSTATUS(); } else { status = bufParam.append(pwszTemplate); CHECK_QSTATUS(); status = bufParam.append(L' '); CHECK_QSTATUS(); status = bufParam.append(pwszPath); CHECK_QSTATUS(); } } else { status = bufParam.append(pwszPath); CHECK_QSTATUS(); } *pwstrParam = bufParam.getString(); return QSTATUS_SUCCESS; } QSTATUS qm::ExternalEditorManager::createMessage(const WCHAR* pwszPath) { assert(pwszPath); DECLARE_QSTATUS(); FileInputStream stream(pwszPath, &status); CHECK_QSTATUS(); BufferedInputStream bufferedStream(&stream, false, &status); CHECK_QSTATUS(); InputStreamReader reader(&bufferedStream, false, getSystemEncoding(), &status); CHECK_QSTATUS(); typedef std::vector<WCHAR> Buffer; Buffer buffer; size_t nSize = 0; while (true) { status = STLWrapper<Buffer>(buffer).resize(nSize + 1024); CHECK_QSTATUS(); size_t nRead = 0; status = reader.read(&buffer[nSize], 1024, &nRead); CHECK_QSTATUS(); if (nRead == -1) break; nSize += nRead; } status = reader.close(); CHECK_QSTATUS(); if (nSize != 0) { Message* p = 0; MessageCreator creator(MessageCreator::FLAG_ADDCONTENTTYPE | MessageCreator::FLAG_EXPANDALIAS); status = creator.createMessage(&buffer[0], nSize, &p); CHECK_QSTATUS(); std::auto_ptr<Message> pMessage(p); unsigned int nFlags = 0; // TODO // Set flags status = composer_.compose(0, 0, pMessage.get(), nFlags); CHECK_QSTATUS(); } return QSTATUS_SUCCESS; } /**************************************************************************** * * ExternalEditorManager::WaitThread * */ qm::ExternalEditorManager::WaitThread::WaitThread( ExternalEditorManager* pManager, QSTATUS* pstatus) : Thread(pstatus), pManager_(pManager), bStop_(false) { } qm::ExternalEditorManager::WaitThread::~WaitThread() { } void qm::ExternalEditorManager::WaitThread::stop() { bStop_ = true; pManager_->pEvent_->set(); join(); } unsigned int qm::ExternalEditorManager::WaitThread::run() { DECLARE_QSTATUS(); while (true) { typedef std::vector<HANDLE> HandleList; HandleList listHandle; { Lock<CriticalSection> lock(pManager_->cs_); status = STLWrapper<HandleList>(listHandle).resize( pManager_->listItem_.size() + 1); listHandle[0] = pManager_->pEvent_->getHandle(); // TODO // Error std::transform(pManager_->listItem_.begin(), pManager_->listItem_.end(), listHandle.begin() + 1, mem_data_ref(&Item::hProcess_)); } DWORD dw = ::WaitForMultipleObjects( listHandle.size(), &listHandle[0], FALSE, INFINITE); HANDLE handle = 0; if (WAIT_OBJECT_0 <= dw && dw < WAIT_OBJECT_0 + listHandle.size()) { handle = listHandle[dw - WAIT_OBJECT_0]; } else if (WAIT_ABANDONED_0 <= dw && dw < WAIT_ABANDONED_0 + listHandle.size()) { handle = listHandle[dw - WAIT_ABANDONED_0]; } else { // TODO } if (handle == pManager_->pEvent_->getHandle()) { if (bStop_) return 0; } else { string_ptr<WSTRING> wstrPath; FILETIME ft; { Lock<CriticalSection> lock(pManager_->cs_); ItemList::iterator it = std::find_if( pManager_->listItem_.begin(), pManager_->listItem_.end(), std::bind2nd( binary_compose_f_gx_hy( std::equal_to<HANDLE>(), mem_data_ref(&Item::hProcess_), std::identity<HANDLE>()), handle)); assert(it != pManager_->listItem_.end()); Item& item = *it; ::CloseHandle(item.hProcess_); wstrPath.reset(item.wstrPath_); ft = item.ft_; pManager_->listItem_.erase(it); } W2T_STATUS(wstrPath.get(), ptszPath); // TODO // Error WIN32_FIND_DATA fd; AutoFindHandle hFind(::FindFirstFile(ptszPath, &fd)); if (hFind.get() && ::CompareFileTime(&ft, &fd.ftLastWriteTime) != 0) { status = pManager_->createMessage(wstrPath.get()); // TODO // Error ::DeleteFile(ptszPath); } } } return 0; } <|endoftext|>
<commit_before>#include "sqlite_blocking.h" #include <sqlite3.h> #include <unistd.h> #include "qdebug.h" #include "qthread.h" QString debugString() { return QString( "[QSQLITE3: " + QString::number( (quint64)( QThread::currentThreadId() ) ) + "] " ); } int sqlite3_blocking_step( sqlite3_stmt *pStmt ) { // NOTE: The example at http://www.sqlite.org/unlock_notify.html says to wait // for SQLITE_LOCK but for some reason I don't understand I get // SQLITE_BUSY. int rc = sqlite3_step( pStmt ); QThread::currentThreadId(); if ( rc == SQLITE_BUSY ) qDebug() << debugString() + "sqlite3_blocking_step: Entering while loop"; while( rc == SQLITE_BUSY ) { usleep(5000); sqlite3_reset( pStmt ); rc = sqlite3_step( pStmt ); if ( rc != SQLITE_BUSY ) { qDebug() << debugString() + "sqlite3_blocking_step: Leaving while loop"; } } return rc; } int sqlite3_blocking_prepare16_v2( sqlite3 *db, /* Database handle. */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nSql, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ) { int rc = sqlite3_prepare16_v2( db, zSql, nSql, ppStmt, pzTail ); if ( rc == SQLITE_BUSY ) qDebug() << debugString() + "sqlite3_blocking_prepare16_v2: Entering while loop"; while( rc == SQLITE_BUSY ) { usleep(500000); rc = sqlite3_prepare16_v2( db, zSql, nSql, ppStmt, pzTail ); if ( rc != SQLITE_BUSY ) { qDebug() << debugString() + "sqlite3_prepare16_v2: Leaving while loop"; } } return rc; } <commit_msg>A constructor-style cast also works and is slightly less ugly<commit_after>#include "sqlite_blocking.h" #include <sqlite3.h> #include <unistd.h> #include "qdebug.h" #include "qthread.h" QString debugString() { return QString( "[QSQLITE3: " + QString::number( quint64( QThread::currentThreadId() ) ) + "] " ); } int sqlite3_blocking_step( sqlite3_stmt *pStmt ) { // NOTE: The example at http://www.sqlite.org/unlock_notify.html says to wait // for SQLITE_LOCK but for some reason I don't understand I get // SQLITE_BUSY. int rc = sqlite3_step( pStmt ); QThread::currentThreadId(); if ( rc == SQLITE_BUSY ) qDebug() << debugString() + "sqlite3_blocking_step: Entering while loop"; while( rc == SQLITE_BUSY ) { usleep(5000); sqlite3_reset( pStmt ); rc = sqlite3_step( pStmt ); if ( rc != SQLITE_BUSY ) { qDebug() << debugString() + "sqlite3_blocking_step: Leaving while loop"; } } return rc; } int sqlite3_blocking_prepare16_v2( sqlite3 *db, /* Database handle. */ const void *zSql, /* SQL statement, UTF-16 encoded */ int nSql, /* Length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ) { int rc = sqlite3_prepare16_v2( db, zSql, nSql, ppStmt, pzTail ); if ( rc == SQLITE_BUSY ) qDebug() << debugString() + "sqlite3_blocking_prepare16_v2: Entering while loop"; while( rc == SQLITE_BUSY ) { usleep(500000); rc = sqlite3_prepare16_v2( db, zSql, nSql, ppStmt, pzTail ); if ( rc != SQLITE_BUSY ) { qDebug() << debugString() + "sqlite3_prepare16_v2: Leaving while loop"; } } return rc; } <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <string> #include <sstream> // GSL includes #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> // Boost includes #include <boost/math/constants/constants.hpp> #include <mpi.h> // LibMesh includes #include <libmesh/libmesh.h> #include <libmesh/mesh.h> #include <libmesh/mesh_generation.h> #include <libmesh/equation_systems.h> #include <libmesh/vector_value.h> #include <libmesh/exact_solution.h> #include <libmesh/exact_error_estimator.h> #include <libmesh/explicit_system.h> // QUESO includes #include <queso/FunctionOperatorBuilder.h> #include <queso/LibMeshFunction.h> #include <queso/LibMeshNegativeLaplacianOperator.h> #include <queso/InfiniteDimensionalGaussian.h> #include <queso/InfiniteDimensionalLikelihoodBase.h> #include <queso/InfiniteDimensionalMCMCSamplerOptions.h> #include <queso/InfiniteDimensionalMCMCSampler.h> // The likelihood object subclass class Likelihood : public QUESO::InfiniteDimensionalLikelihoodBase { public: Likelihood(double obs_stddev); ~Likelihood(); virtual double evaluate(QUESO::FunctionBase & state); gsl_rng *r; }; Likelihood::Likelihood(double obs_stddev) : QUESO::InfiniteDimensionalLikelihoodBase(obs_stddev) { this->r = gsl_rng_alloc(gsl_rng_default); } Likelihood::~Likelihood() { gsl_rng_free(this->r); } double Likelihood::evaluate(QUESO::FunctionBase & flow) { // This is where you call your forward problem, make observations and compute // the likelihood norm. Here we'll just pretend we observe a zero with // error. const double obs_stddev = this->obs_stddev(); const double obs = gsl_ran_gaussian(this->r, obs_stddev); return obs * obs / (2.0 * obs_stddev * obs_stddev); } int main(int argc, char **argv) { unsigned int num_pts = 100; unsigned int num_pairs = num_pts / 2.0; const double alpha = 3.0; const double beta = 10.0; const double obs_stddev = 1e-3; int ierr, my_rank, my_sub_rank; MPI_Init(&argc, &argv); QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL); #ifndef QUESO_HAVE_HDF5 std::cerr << "Cannot run infinite dimensional inverse problems\n" << "without HDF5 enabled." << std::endl; return 0; #else // When the number of processes passed to `mpirun` is different from the // number of subenvironments asked for in the input file, QUESO creates a // subcommunicator that 'does the right thing'. // // For example, let's say you execute `mpirun -np 6`, but only asked for 3 // QUESO subenvironments, QUESO creates a subcommunicator containing two // processes for each of the three subenvironments. This subcommunicator is // the one returned by env.subComm(). To get a raw MPI communicator, call // Comm() on a QUESO communicator. MPI_Comm libMeshComm = env.subComm().Comm(); // Get full rank ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); // Get subrank ierr = MPI_Comm_rank(libMeshComm, &my_sub_rank); std::stringstream ss; ss << "Hello from processor " << my_rank << " with sub rank " << my_sub_rank << " in subenvironment " << env.subIdString() << std::endl; std::cout << ss.str(); // Need an artifical block here because libMesh needs to call PetscFinalize // before we call MPI_Finalize { libMesh::LibMeshInit init(argc, argv, libMeshComm); // Generate the mesh on which the samples live. libMesh::Mesh mesh(init.comm()); libMesh::MeshTools::Generation::build_line(mesh, num_pts, 0.0, 1.0, libMeshEnums::EDGE2); // Use a helper object to define some of the properties of our samples QUESO::FunctionOperatorBuilder fobuilder; fobuilder.order = "FIRST"; fobuilder.family = "LAGRANGE"; fobuilder.num_req_eigenpairs = num_pairs; // Define the mean of the prior QUESO::LibMeshFunction mean(fobuilder, mesh); // Define the precision operator of the prior QUESO::LibMeshNegativeLaplacianOperator precision(fobuilder, mesh); // Define the prior measure QUESO::InfiniteDimensionalGaussian mu(env, mean, precision, alpha, beta); // Create likelihood object Likelihood llhd(obs_stddev); // Create the options helper object that determines what options to pass to // the sampler QUESO::InfiniteDimensionalMCMCSamplerOptions opts(env, ""); // Construct the sampler, and set the name of the output file (will only // write HDF5 files) QUESO::InfiniteDimensionalMCMCSampler s(env, mu, llhd, &opts); for (unsigned int i = 0; i < opts.m_num_iters; i++) { s.step(); if (i % 100 == 0) { std::cout << "sampler iteration: " << i << std::endl; std::cout << "avg acc prob is: " << s.avg_acc_prob() << std::endl; std::cout << "l2 norm is: " << s.llhd_val() << std::endl; } } } #endif // QUESO_HAVE_HDF5 MPI_Finalize(); return 0; } <commit_msg>Don't forget MPI_Finalize() if !QUESO_HAVE_HDF5<commit_after>#include <iostream> #include <cmath> #include <string> #include <sstream> // GSL includes #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> // Boost includes #include <boost/math/constants/constants.hpp> #include <mpi.h> // LibMesh includes #include <libmesh/libmesh.h> #include <libmesh/mesh.h> #include <libmesh/mesh_generation.h> #include <libmesh/equation_systems.h> #include <libmesh/vector_value.h> #include <libmesh/exact_solution.h> #include <libmesh/exact_error_estimator.h> #include <libmesh/explicit_system.h> // QUESO includes #include <queso/FunctionOperatorBuilder.h> #include <queso/LibMeshFunction.h> #include <queso/LibMeshNegativeLaplacianOperator.h> #include <queso/InfiniteDimensionalGaussian.h> #include <queso/InfiniteDimensionalLikelihoodBase.h> #include <queso/InfiniteDimensionalMCMCSamplerOptions.h> #include <queso/InfiniteDimensionalMCMCSampler.h> // The likelihood object subclass class Likelihood : public QUESO::InfiniteDimensionalLikelihoodBase { public: Likelihood(double obs_stddev); ~Likelihood(); virtual double evaluate(QUESO::FunctionBase & state); gsl_rng *r; }; Likelihood::Likelihood(double obs_stddev) : QUESO::InfiniteDimensionalLikelihoodBase(obs_stddev) { this->r = gsl_rng_alloc(gsl_rng_default); } Likelihood::~Likelihood() { gsl_rng_free(this->r); } double Likelihood::evaluate(QUESO::FunctionBase & flow) { // This is where you call your forward problem, make observations and compute // the likelihood norm. Here we'll just pretend we observe a zero with // error. const double obs_stddev = this->obs_stddev(); const double obs = gsl_ran_gaussian(this->r, obs_stddev); return obs * obs / (2.0 * obs_stddev * obs_stddev); } int main(int argc, char **argv) { unsigned int num_pts = 100; unsigned int num_pairs = num_pts / 2.0; const double alpha = 3.0; const double beta = 10.0; const double obs_stddev = 1e-3; int ierr, my_rank, my_sub_rank; MPI_Init(&argc, &argv); QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL); #ifndef QUESO_HAVE_HDF5 std::cerr << "Cannot run infinite dimensional inverse problems\n" << "without HDF5 enabled." << std::endl; MPI_Finalize(); return 0; #else // When the number of processes passed to `mpirun` is different from the // number of subenvironments asked for in the input file, QUESO creates a // subcommunicator that 'does the right thing'. // // For example, let's say you execute `mpirun -np 6`, but only asked for 3 // QUESO subenvironments, QUESO creates a subcommunicator containing two // processes for each of the three subenvironments. This subcommunicator is // the one returned by env.subComm(). To get a raw MPI communicator, call // Comm() on a QUESO communicator. MPI_Comm libMeshComm = env.subComm().Comm(); // Get full rank ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); // Get subrank ierr = MPI_Comm_rank(libMeshComm, &my_sub_rank); std::stringstream ss; ss << "Hello from processor " << my_rank << " with sub rank " << my_sub_rank << " in subenvironment " << env.subIdString() << std::endl; std::cout << ss.str(); // Need an artifical block here because libMesh needs to call PetscFinalize // before we call MPI_Finalize { libMesh::LibMeshInit init(argc, argv, libMeshComm); // Generate the mesh on which the samples live. libMesh::Mesh mesh(init.comm()); libMesh::MeshTools::Generation::build_line(mesh, num_pts, 0.0, 1.0, libMeshEnums::EDGE2); // Use a helper object to define some of the properties of our samples QUESO::FunctionOperatorBuilder fobuilder; fobuilder.order = "FIRST"; fobuilder.family = "LAGRANGE"; fobuilder.num_req_eigenpairs = num_pairs; // Define the mean of the prior QUESO::LibMeshFunction mean(fobuilder, mesh); // Define the precision operator of the prior QUESO::LibMeshNegativeLaplacianOperator precision(fobuilder, mesh); // Define the prior measure QUESO::InfiniteDimensionalGaussian mu(env, mean, precision, alpha, beta); // Create likelihood object Likelihood llhd(obs_stddev); // Create the options helper object that determines what options to pass to // the sampler QUESO::InfiniteDimensionalMCMCSamplerOptions opts(env, ""); // Construct the sampler, and set the name of the output file (will only // write HDF5 files) QUESO::InfiniteDimensionalMCMCSampler s(env, mu, llhd, &opts); for (unsigned int i = 0; i < opts.m_num_iters; i++) { s.step(); if (i % 100 == 0) { std::cout << "sampler iteration: " << i << std::endl; std::cout << "avg acc prob is: " << s.avg_acc_prob() << std::endl; std::cout << "l2 norm is: " << s.llhd_val() << std::endl; } } } #endif // QUESO_HAVE_HDF5 MPI_Finalize(); return 0; } <|endoftext|>
<commit_before>//===- Option.cpp - Abstract Driver Options -------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Config/llvm-config.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" #include "llvm/Option/OptTable.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstring> using namespace llvm; using namespace llvm::opt; Option::Option(const OptTable::Info *info, const OptTable *owner) : Info(info), Owner(owner) { // Multi-level aliases are not supported. This just simplifies option // tracking, it is not an inherent limitation. assert((!Info || !getAlias().isValid() || !getAlias().getAlias().isValid()) && "Multi-level aliases are not supported."); if (Info && getAliasArgs()) { assert(getAlias().isValid() && "Only alias options can have alias args."); assert(getKind() == FlagClass && "Only Flag aliases can have alias args."); assert(getAlias().getKind() != FlagClass && "Cannot provide alias args to a flag option."); } } void Option::print(raw_ostream &O) const { O << "<"; switch (getKind()) { #define P(N) case N: O << #N; break P(GroupClass); P(InputClass); P(UnknownClass); P(FlagClass); P(JoinedClass); P(ValuesClass); P(SeparateClass); P(CommaJoinedClass); P(MultiArgClass); P(JoinedOrSeparateClass); P(JoinedAndSeparateClass); P(RemainingArgsClass); P(RemainingArgsJoinedClass); #undef P } if (Info->Prefixes) { O << " Prefixes:["; for (const char *const *Pre = Info->Prefixes; *Pre != nullptr; ++Pre) { O << '"' << *Pre << (*(Pre + 1) == nullptr ? "\"" : "\", "); } O << ']'; } O << " Name:\"" << getName() << '"'; const Option Group = getGroup(); if (Group.isValid()) { O << " Group:"; Group.print(O); } const Option Alias = getAlias(); if (Alias.isValid()) { O << " Alias:"; Alias.print(O); } if (getKind() == MultiArgClass) O << " NumArgs:" << getNumArgs(); O << ">\n"; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void Option::dump() const { print(dbgs()); } #endif bool Option::matches(OptSpecifier Opt) const { // Aliases are never considered in matching, look through them. const Option Alias = getAlias(); if (Alias.isValid()) return Alias.matches(Opt); // Check exact match. if (getID() == Opt.getID()) return true; const Option Group = getGroup(); if (Group.isValid()) return Group.matches(Opt); return false; } Arg *Option::accept(const ArgList &Args, unsigned &Index, unsigned ArgSize) const { const Option &UnaliasedOption = getUnaliasedOption(); StringRef Spelling; // If the option was an alias, get the spelling from the unaliased one. if (getID() == UnaliasedOption.getID()) { Spelling = StringRef(Args.getArgString(Index), ArgSize); } else { Spelling = Args.MakeArgString(Twine(UnaliasedOption.getPrefix()) + Twine(UnaliasedOption.getName())); } switch (getKind()) { case FlagClass: { if (ArgSize != strlen(Args.getArgString(Index))) return nullptr; Arg *A = new Arg(UnaliasedOption, Spelling, Index++); if (getAliasArgs()) { const char *Val = getAliasArgs(); while (*Val != '\0') { A->getValues().push_back(Val); // Move past the '\0' to the next argument. Val += strlen(Val) + 1; } } if (UnaliasedOption.getKind() == JoinedClass && !getAliasArgs()) // A Flag alias for a Joined option must provide an argument. A->getValues().push_back(""); return A; } case JoinedClass: { const char *Value = Args.getArgString(Index) + ArgSize; return new Arg(UnaliasedOption, Spelling, Index++, Value); } case CommaJoinedClass: { // Always matches. const char *Str = Args.getArgString(Index) + ArgSize; Arg *A = new Arg(UnaliasedOption, Spelling, Index++); // Parse out the comma separated values. const char *Prev = Str; for (;; ++Str) { char c = *Str; if (!c || c == ',') { if (Prev != Str) { char *Value = new char[Str - Prev + 1]; memcpy(Value, Prev, Str - Prev); Value[Str - Prev] = '\0'; A->getValues().push_back(Value); } if (!c) break; Prev = Str + 1; } } A->setOwnsValues(true); return A; } case SeparateClass: // Matches iff this is an exact match. // FIXME: Avoid strlen. if (ArgSize != strlen(Args.getArgString(Index))) return nullptr; Index += 2; if (Index > Args.getNumInputArgStrings() || Args.getArgString(Index - 1) == nullptr) return nullptr; return new Arg(UnaliasedOption, Spelling, Index - 2, Args.getArgString(Index - 1)); case MultiArgClass: { // Matches iff this is an exact match. // FIXME: Avoid strlen. if (ArgSize != strlen(Args.getArgString(Index))) return nullptr; Index += 1 + getNumArgs(); if (Index > Args.getNumInputArgStrings()) return nullptr; Arg *A = new Arg(UnaliasedOption, Spelling, Index - 1 - getNumArgs(), Args.getArgString(Index - getNumArgs())); for (unsigned i = 1; i != getNumArgs(); ++i) A->getValues().push_back(Args.getArgString(Index - getNumArgs() + i)); return A; } case JoinedOrSeparateClass: { // If this is not an exact match, it is a joined arg. // FIXME: Avoid strlen. if (ArgSize != strlen(Args.getArgString(Index))) { const char *Value = Args.getArgString(Index) + ArgSize; return new Arg(*this, Spelling, Index++, Value); } // Otherwise it must be separate. Index += 2; if (Index > Args.getNumInputArgStrings() || Args.getArgString(Index - 1) == nullptr) return nullptr; return new Arg(UnaliasedOption, Spelling, Index - 2, Args.getArgString(Index - 1)); } case JoinedAndSeparateClass: // Always matches. Index += 2; if (Index > Args.getNumInputArgStrings() || Args.getArgString(Index - 1) == nullptr) return nullptr; return new Arg(UnaliasedOption, Spelling, Index - 2, Args.getArgString(Index - 2) + ArgSize, Args.getArgString(Index - 1)); case RemainingArgsClass: { // Matches iff this is an exact match. // FIXME: Avoid strlen. if (ArgSize != strlen(Args.getArgString(Index))) return nullptr; Arg *A = new Arg(UnaliasedOption, Spelling, Index++); while (Index < Args.getNumInputArgStrings() && Args.getArgString(Index) != nullptr) A->getValues().push_back(Args.getArgString(Index++)); return A; } case RemainingArgsJoinedClass: { Arg *A = new Arg(UnaliasedOption, Spelling, Index); if (ArgSize != strlen(Args.getArgString(Index))) { // An inexact match means there is a joined arg. A->getValues().push_back(Args.getArgString(Index) + ArgSize); } Index++; while (Index < Args.getNumInputArgStrings() && Args.getArgString(Index) != nullptr) A->getValues().push_back(Args.getArgString(Index++)); return A; } default: llvm_unreachable("Invalid option kind!"); } } <commit_msg>Make joined instances of JoinedOrSeparate flags point to the unaliased args, like all other arg types do<commit_after>//===- Option.cpp - Abstract Driver Options -------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Config/llvm-config.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" #include "llvm/Option/OptTable.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstring> using namespace llvm; using namespace llvm::opt; Option::Option(const OptTable::Info *info, const OptTable *owner) : Info(info), Owner(owner) { // Multi-level aliases are not supported. This just simplifies option // tracking, it is not an inherent limitation. assert((!Info || !getAlias().isValid() || !getAlias().getAlias().isValid()) && "Multi-level aliases are not supported."); if (Info && getAliasArgs()) { assert(getAlias().isValid() && "Only alias options can have alias args."); assert(getKind() == FlagClass && "Only Flag aliases can have alias args."); assert(getAlias().getKind() != FlagClass && "Cannot provide alias args to a flag option."); } } void Option::print(raw_ostream &O) const { O << "<"; switch (getKind()) { #define P(N) case N: O << #N; break P(GroupClass); P(InputClass); P(UnknownClass); P(FlagClass); P(JoinedClass); P(ValuesClass); P(SeparateClass); P(CommaJoinedClass); P(MultiArgClass); P(JoinedOrSeparateClass); P(JoinedAndSeparateClass); P(RemainingArgsClass); P(RemainingArgsJoinedClass); #undef P } if (Info->Prefixes) { O << " Prefixes:["; for (const char *const *Pre = Info->Prefixes; *Pre != nullptr; ++Pre) { O << '"' << *Pre << (*(Pre + 1) == nullptr ? "\"" : "\", "); } O << ']'; } O << " Name:\"" << getName() << '"'; const Option Group = getGroup(); if (Group.isValid()) { O << " Group:"; Group.print(O); } const Option Alias = getAlias(); if (Alias.isValid()) { O << " Alias:"; Alias.print(O); } if (getKind() == MultiArgClass) O << " NumArgs:" << getNumArgs(); O << ">\n"; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void Option::dump() const { print(dbgs()); } #endif bool Option::matches(OptSpecifier Opt) const { // Aliases are never considered in matching, look through them. const Option Alias = getAlias(); if (Alias.isValid()) return Alias.matches(Opt); // Check exact match. if (getID() == Opt.getID()) return true; const Option Group = getGroup(); if (Group.isValid()) return Group.matches(Opt); return false; } Arg *Option::accept(const ArgList &Args, unsigned &Index, unsigned ArgSize) const { const Option &UnaliasedOption = getUnaliasedOption(); StringRef Spelling; // If the option was an alias, get the spelling from the unaliased one. if (getID() == UnaliasedOption.getID()) { Spelling = StringRef(Args.getArgString(Index), ArgSize); } else { Spelling = Args.MakeArgString(Twine(UnaliasedOption.getPrefix()) + Twine(UnaliasedOption.getName())); } switch (getKind()) { case FlagClass: { if (ArgSize != strlen(Args.getArgString(Index))) return nullptr; Arg *A = new Arg(UnaliasedOption, Spelling, Index++); if (getAliasArgs()) { const char *Val = getAliasArgs(); while (*Val != '\0') { A->getValues().push_back(Val); // Move past the '\0' to the next argument. Val += strlen(Val) + 1; } } if (UnaliasedOption.getKind() == JoinedClass && !getAliasArgs()) // A Flag alias for a Joined option must provide an argument. A->getValues().push_back(""); return A; } case JoinedClass: { const char *Value = Args.getArgString(Index) + ArgSize; return new Arg(UnaliasedOption, Spelling, Index++, Value); } case CommaJoinedClass: { // Always matches. const char *Str = Args.getArgString(Index) + ArgSize; Arg *A = new Arg(UnaliasedOption, Spelling, Index++); // Parse out the comma separated values. const char *Prev = Str; for (;; ++Str) { char c = *Str; if (!c || c == ',') { if (Prev != Str) { char *Value = new char[Str - Prev + 1]; memcpy(Value, Prev, Str - Prev); Value[Str - Prev] = '\0'; A->getValues().push_back(Value); } if (!c) break; Prev = Str + 1; } } A->setOwnsValues(true); return A; } case SeparateClass: // Matches iff this is an exact match. // FIXME: Avoid strlen. if (ArgSize != strlen(Args.getArgString(Index))) return nullptr; Index += 2; if (Index > Args.getNumInputArgStrings() || Args.getArgString(Index - 1) == nullptr) return nullptr; return new Arg(UnaliasedOption, Spelling, Index - 2, Args.getArgString(Index - 1)); case MultiArgClass: { // Matches iff this is an exact match. // FIXME: Avoid strlen. if (ArgSize != strlen(Args.getArgString(Index))) return nullptr; Index += 1 + getNumArgs(); if (Index > Args.getNumInputArgStrings()) return nullptr; Arg *A = new Arg(UnaliasedOption, Spelling, Index - 1 - getNumArgs(), Args.getArgString(Index - getNumArgs())); for (unsigned i = 1; i != getNumArgs(); ++i) A->getValues().push_back(Args.getArgString(Index - getNumArgs() + i)); return A; } case JoinedOrSeparateClass: { // If this is not an exact match, it is a joined arg. // FIXME: Avoid strlen. if (ArgSize != strlen(Args.getArgString(Index))) { const char *Value = Args.getArgString(Index) + ArgSize; return new Arg(UnaliasedOption, Spelling, Index++, Value); } // Otherwise it must be separate. Index += 2; if (Index > Args.getNumInputArgStrings() || Args.getArgString(Index - 1) == nullptr) return nullptr; return new Arg(UnaliasedOption, Spelling, Index - 2, Args.getArgString(Index - 1)); } case JoinedAndSeparateClass: // Always matches. Index += 2; if (Index > Args.getNumInputArgStrings() || Args.getArgString(Index - 1) == nullptr) return nullptr; return new Arg(UnaliasedOption, Spelling, Index - 2, Args.getArgString(Index - 2) + ArgSize, Args.getArgString(Index - 1)); case RemainingArgsClass: { // Matches iff this is an exact match. // FIXME: Avoid strlen. if (ArgSize != strlen(Args.getArgString(Index))) return nullptr; Arg *A = new Arg(UnaliasedOption, Spelling, Index++); while (Index < Args.getNumInputArgStrings() && Args.getArgString(Index) != nullptr) A->getValues().push_back(Args.getArgString(Index++)); return A; } case RemainingArgsJoinedClass: { Arg *A = new Arg(UnaliasedOption, Spelling, Index); if (ArgSize != strlen(Args.getArgString(Index))) { // An inexact match means there is a joined arg. A->getValues().push_back(Args.getArgString(Index) + ArgSize); } Index++; while (Index < Args.getNumInputArgStrings() && Args.getArgString(Index) != nullptr) A->getValues().push_back(Args.getArgString(Index++)); return A; } default: llvm_unreachable("Invalid option kind!"); } } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Quanta Research Cambridge, Inc * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <semaphore.h> #include <ctime> #include <monkit.h> #include <mp.h> #include "StdDmaIndication.h" #include <sys/types.h> #include <sys/stat.h> #include "MaxcommonsubseqIndicationWrapper.h" #include "MaxcommonsubseqRequestProxy.h" #include "GeneratedTypes.h" #include "DmaConfigProxy.h" sem_t test_sem; sem_t setup_sem; int sw_match_cnt = 0; int hw_match_cnt = 0; class MaxcommonsubseqIndication : public MaxcommonsubseqIndicationWrapper { public: MaxcommonsubseqIndication(unsigned int id) : MaxcommonsubseqIndicationWrapper(id){}; virtual void setupAComplete() { fprintf(stderr, "setupAComplete\n"); sem_post(&setup_sem); } virtual void setupBComplete() { fprintf(stderr, "setupBComplete\n"); sem_post(&setup_sem); } virtual void fetchComplete() { fprintf(stderr, "fetchComplete\n"); sem_post(&setup_sem); } virtual void searchResult (int v){ fprintf(stderr, "searchResult = %d\n", v); sem_post(&test_sem); } }; int main(int argc, const char **argv) { MaxcommonsubseqRequestProxy *device = 0; DmaConfigProxy *dma = 0; MaxcommonsubseqIndication *deviceIndication = 0; DmaIndication *dmaIndication = 0; fprintf(stderr, "%s %s\n", __DATE__, __TIME__); device = new MaxcommonsubseqRequestProxy(IfcNames_MaxcommonsubseqRequest); dma = new DmaConfigProxy(IfcNames_DmaConfig); deviceIndication = new MaxcommonsubseqIndication(IfcNames_MaxcommonsubseqIndication); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication); if(sem_init(&test_sem, 1, 0)){ fprintf(stderr, "failed to init test_sem\n"); return -1; } if(sem_init(&setup_sem, 1, 0)){ fprintf(stderr, "failed to init setup_sem\n"); return -1; } pthread_t tid; fprintf(stderr, "creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "error creating exec thread\n"); exit(1); } fprintf(stderr, "simple tests\n"); PortalAlloc *strAAlloc; PortalAlloc *strBAlloc; PortalAlloc *fetchAlloc; unsigned int alloc_len = 128; unsigned int fetch_len = alloc_len * alloc_len; int rcA, rcB, rcFetch; struct stat statAbuf, statBbuf, statFetchbuf; dma->alloc(fetch_len*sizeof(uint16_t), &fetchAlloc); rcFetch = fstat(fetchAlloc->header.fd, &statFetchbuf); if (rcA < 0) perror("fstatFetch"); int *fetch = (int *)mmap(0, fetch_len * sizeof(uint16_t), PROT_READ|PROT_WRITE, MAP_SHARED, fetchAlloc->header.fd, 0); if (fetch == MAP_FAILED) perror("fetch mmap failed"); assert(fetch != MAP_FAILED); dma->alloc(alloc_len, &strAAlloc); rcA = fstat(strAAlloc->header.fd, &statAbuf); if (rcA < 0) perror("fstatA"); char *strA = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strAAlloc->header.fd, 0); if (strA == MAP_FAILED) perror("strA mmap failed"); assert(strA != MAP_FAILED); dma->alloc(alloc_len, &strBAlloc); rcB = fstat(strBAlloc->header.fd, &statBbuf); if (rcA < 0) perror("fstatB"); char *strB = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strBAlloc->header.fd, 0); if (strB == MAP_FAILED) perror("strB mmap failed"); assert(strB != MAP_FAILED); const char *strA_text = " a b c "; const char *strB_text = "..a........b.c...."; assert(strlen(strA_text) < alloc_len); assert(strlen(strB_text) < alloc_len); strncpy(strA, strA_text, alloc_len); strncpy(strB, strB_text, alloc_len); int strA_len = strlen(strA); int strB_len = strlen(strB); uint16_t swFetch[fetch_len]; init_timer(); start_timer(0); fprintf(stderr, "elapsed time (hw cycles): %zd\n", lap_timer(0)); dma->dCacheFlushInval(strAAlloc, strA); dma->dCacheFlushInval(strBAlloc, strB); dma->dCacheFlushInval(fetchAlloc, fetch); unsigned int ref_strAAlloc = dma->reference(strAAlloc); unsigned int ref_strBAlloc = dma->reference(strBAlloc); unsigned int ref_fetchAlloc = dma->reference(fetchAlloc); device->setupA(ref_strAAlloc, strA_len); sem_wait(&setup_sem); device->setupB(ref_strBAlloc, strB_len); sem_wait(&setup_sem); fprintf(stderr, "starting algorithm A\n"); init_timer(); start_timer(0); device->start(0); sem_wait(&test_sem); uint64_t cycles = lap_timer(0); uint64_t beats = dma->show_mem_stats(ChannelType_Read); fprintf(stderr, "hw cycles: %f\n", (float)cycles); device->fetch(ref_fetchAlloc, 0, 0, fetch_len / 2); sem_wait(&setup_sem); printf("fetch 1 finished \n"); device->fetch(ref_fetchAlloc, fetch_len, fetch_len / 2, fetch_len / 2); sem_wait(&setup_sem); printf("fetch 2 finished \n"); memcpy(swFetch, fetch, fetch_len * sizeof(uint16_t)); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", j); } printf("\n"); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4c", strB[j-1]); } printf("\n"); for (int i = 0; i <= strA_len; i += 1) { printf("%4c%4d", strA[i-1], i); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", swFetch[(i << 7) + j] & 0xff); } printf("\n"); } fprintf(stderr, "starting algorithm B\n"); init_timer(); start_timer(0); device->start(1); sem_wait(&test_sem); cycles = lap_timer(0); fprintf(stderr, "hw cycles: %f\n", (float)cycles); device->fetch(ref_fetchAlloc, 0, 0, fetch_len / 2); sem_wait(&setup_sem); memcpy(swFetch, fetch, fetch_len * sizeof(uint16_t)); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", j); } printf("\n"); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4c", strB[j-1]); } printf("\n"); for (int i = 0; i < 1; i += 1) { printf("%4c%4d", strA[i-1], i); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", swFetch[(i << 7) + j] & 0xff); } printf("\n"); } close(strAAlloc->header.fd); close(strBAlloc->header.fd); close(fetchAlloc->header.fd); } <commit_msg>line up HirschB printout<commit_after>/* Copyright (c) 2013 Quanta Research Cambridge, Inc * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <sys/mman.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <semaphore.h> #include <ctime> #include <monkit.h> #include <mp.h> #include "StdDmaIndication.h" #include <sys/types.h> #include <sys/stat.h> #include "MaxcommonsubseqIndicationWrapper.h" #include "MaxcommonsubseqRequestProxy.h" #include "GeneratedTypes.h" #include "DmaConfigProxy.h" sem_t test_sem; sem_t setup_sem; int sw_match_cnt = 0; int hw_match_cnt = 0; class MaxcommonsubseqIndication : public MaxcommonsubseqIndicationWrapper { public: MaxcommonsubseqIndication(unsigned int id) : MaxcommonsubseqIndicationWrapper(id){}; virtual void setupAComplete() { fprintf(stderr, "setupAComplete\n"); sem_post(&setup_sem); } virtual void setupBComplete() { fprintf(stderr, "setupBComplete\n"); sem_post(&setup_sem); } virtual void fetchComplete() { fprintf(stderr, "fetchComplete\n"); sem_post(&setup_sem); } virtual void searchResult (int v){ fprintf(stderr, "searchResult = %d\n", v); sem_post(&test_sem); } }; int main(int argc, const char **argv) { MaxcommonsubseqRequestProxy *device = 0; DmaConfigProxy *dma = 0; MaxcommonsubseqIndication *deviceIndication = 0; DmaIndication *dmaIndication = 0; fprintf(stderr, "%s %s\n", __DATE__, __TIME__); device = new MaxcommonsubseqRequestProxy(IfcNames_MaxcommonsubseqRequest); dma = new DmaConfigProxy(IfcNames_DmaConfig); deviceIndication = new MaxcommonsubseqIndication(IfcNames_MaxcommonsubseqIndication); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication); if(sem_init(&test_sem, 1, 0)){ fprintf(stderr, "failed to init test_sem\n"); return -1; } if(sem_init(&setup_sem, 1, 0)){ fprintf(stderr, "failed to init setup_sem\n"); return -1; } pthread_t tid; fprintf(stderr, "creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "error creating exec thread\n"); exit(1); } fprintf(stderr, "simple tests\n"); PortalAlloc *strAAlloc; PortalAlloc *strBAlloc; PortalAlloc *fetchAlloc; unsigned int alloc_len = 128; unsigned int fetch_len = alloc_len * alloc_len; int rcA, rcB, rcFetch; struct stat statAbuf, statBbuf, statFetchbuf; dma->alloc(fetch_len*sizeof(uint16_t), &fetchAlloc); rcFetch = fstat(fetchAlloc->header.fd, &statFetchbuf); if (rcA < 0) perror("fstatFetch"); int *fetch = (int *)mmap(0, fetch_len * sizeof(uint16_t), PROT_READ|PROT_WRITE, MAP_SHARED, fetchAlloc->header.fd, 0); if (fetch == MAP_FAILED) perror("fetch mmap failed"); assert(fetch != MAP_FAILED); dma->alloc(alloc_len, &strAAlloc); rcA = fstat(strAAlloc->header.fd, &statAbuf); if (rcA < 0) perror("fstatA"); char *strA = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strAAlloc->header.fd, 0); if (strA == MAP_FAILED) perror("strA mmap failed"); assert(strA != MAP_FAILED); dma->alloc(alloc_len, &strBAlloc); rcB = fstat(strBAlloc->header.fd, &statBbuf); if (rcA < 0) perror("fstatB"); char *strB = (char *)mmap(0, alloc_len, PROT_READ|PROT_WRITE, MAP_SHARED, strBAlloc->header.fd, 0); if (strB == MAP_FAILED) perror("strB mmap failed"); assert(strB != MAP_FAILED); const char *strA_text = " a b c "; const char *strB_text = "..a........b.c...."; assert(strlen(strA_text) < alloc_len); assert(strlen(strB_text) < alloc_len); strncpy(strA, strA_text, alloc_len); strncpy(strB, strB_text, alloc_len); int strA_len = strlen(strA); int strB_len = strlen(strB); uint16_t swFetch[fetch_len]; init_timer(); start_timer(0); fprintf(stderr, "elapsed time (hw cycles): %zd\n", lap_timer(0)); dma->dCacheFlushInval(strAAlloc, strA); dma->dCacheFlushInval(strBAlloc, strB); dma->dCacheFlushInval(fetchAlloc, fetch); unsigned int ref_strAAlloc = dma->reference(strAAlloc); unsigned int ref_strBAlloc = dma->reference(strBAlloc); unsigned int ref_fetchAlloc = dma->reference(fetchAlloc); device->setupA(ref_strAAlloc, strA_len); sem_wait(&setup_sem); device->setupB(ref_strBAlloc, strB_len); sem_wait(&setup_sem); fprintf(stderr, "starting algorithm A\n"); init_timer(); start_timer(0); device->start(0); sem_wait(&test_sem); uint64_t cycles = lap_timer(0); uint64_t beats = dma->show_mem_stats(ChannelType_Read); fprintf(stderr, "hw cycles: %f\n", (float)cycles); device->fetch(ref_fetchAlloc, 0, 0, fetch_len / 2); sem_wait(&setup_sem); printf("fetch 1 finished \n"); device->fetch(ref_fetchAlloc, fetch_len, fetch_len / 2, fetch_len / 2); sem_wait(&setup_sem); printf("fetch 2 finished \n"); memcpy(swFetch, fetch, fetch_len * sizeof(uint16_t)); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", j); } printf("\n"); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4c", strB[j-1]); } printf("\n"); for (int i = 0; i <= strA_len; i += 1) { printf("%4c%4d", strA[i-1], i); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", swFetch[(i << 7) + j] & 0xff); } printf("\n"); } fprintf(stderr, "starting algorithm B\n"); init_timer(); start_timer(0); device->start(1); sem_wait(&test_sem); cycles = lap_timer(0); fprintf(stderr, "hw cycles: %f\n", (float)cycles); device->fetch(ref_fetchAlloc, 0, 0, fetch_len / 2); sem_wait(&setup_sem); memcpy(swFetch, fetch, fetch_len * sizeof(uint16_t)); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", j); } printf("\n"); printf(" "); for (int j = 0; j <= strB_len; j += 1) { printf("%4c", strB[j-1]); } printf("\n"); for (int i = 0; i < 1; i += 1) { printf("%4c%4d", strA[i-1], i); for (int j = 0; j <= strB_len; j += 1) { printf("%4d", swFetch[(i << 7) + j] & 0xff); } printf("\n"); } close(strAAlloc->header.fd); close(strBAlloc->header.fd); close(fetchAlloc->header.fd); } <|endoftext|>
<commit_before> /** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <cinttypes> #include <common/Detector.h> #include <common/EFUArgs.h> #include <common/FBSerializer.h> #include <common/Producer.h> #include <common/RingBuffer.h> #include <common/Trace.h> #include <cstring> #include <fcntl.h> #include <iostream> #include <libs/include/SPSCFifo.h> #include <libs/include/Socket.h> #include <libs/include/TSCTimer.h> #include <libs/include/Timer.h> #include <memory> #include <sonde/ideas/Data.h> #include <stdio.h> #include <unistd.h> //#undef TRC_LEVEL //#define TRC_LEVEL TRC_L_DEB using namespace memory_sequential_consistent; // Lock free fifo const char *classname = "SoNDe detector using IDEA readout"; const int TSC_MHZ = 2900; // MJC's workstation - not reliable /** ----------------------------------------------------- */ class SONDEIDEA : public Detector { public: SONDEIDEA(BaseSettings settings); ~SONDEIDEA() { printf("sonde destructor called\n"); } void input_thread(); void processing_thread(); const char *detectorname(); /** @todo figure out the right size of the .._max_entries */ static const int eth_buffer_max_entries = 20000; static const int eth_buffer_size = 9000; static const int kafka_buffer_size = 124000; /**< events */ private: /** Shared between input_thread and processing_thread*/ CircularFifo<unsigned int, eth_buffer_max_entries> input2proc_fifo; RingBuffer<eth_buffer_size> *eth_ringbuf; NewStats ns{"efu.sonde."}; // struct { // Input Counters int64_t rx_packets; int64_t rx_bytes; int64_t fifo_push_errors; int64_t rx_pktlen_0; int64_t pad[4]; // Processing and Output counters int64_t rx_idle1; int64_t rx_events; int64_t rx_geometry_errors; int64_t tx_bytes; int64_t rx_seq_errors; int64_t fifo_synch_errors; } ALIGN(64) mystats; }; void SetCLIArguments(CLI::App __attribute__((unused)) & parser) {} PopulateCLIParser PopulateParser{SetCLIArguments}; SONDEIDEA::SONDEIDEA(BaseSettings settings) : Detector("SoNDe detector using IDEA readout", settings) { Stats.setPrefix("efu.sonde"); XTRACE(INIT, ALW, "Adding stats\n"); // clang-format off Stats.create("input.rx_packets", mystats.rx_packets); Stats.create("input.rx_bytes", mystats.rx_bytes); Stats.create("input.dropped", mystats.fifo_push_errors); Stats.create("input.rx_seq_errors", mystats.rx_seq_errors); Stats.create("processing.idle", mystats.rx_idle1); Stats.create("processing.rx_events", mystats.rx_events); Stats.create("processing.rx_geometry_errors", mystats.rx_geometry_errors); Stats.create("processing.rx_seq_errors", mystats.rx_seq_errors); Stats.create("output.tx_bytes", mystats.tx_bytes); // clang-format on std::function<void()> inputFunc = [this]() { SONDEIDEA::input_thread(); }; Detector::AddThreadFunction(inputFunc, "input"); std::function<void()> processingFunc = [this]() { SONDEIDEA::processing_thread(); }; Detector::AddThreadFunction(processingFunc, "processing"); XTRACE(INIT, ALW, "Creating %d SONDE Rx ringbuffers of size %d\n", eth_buffer_max_entries, eth_buffer_size); eth_ringbuf = new RingBuffer<eth_buffer_size>( eth_buffer_max_entries + 1); /** @todo testing workaround */ assert(eth_ringbuf != 0); } const char *SONDEIDEA::detectorname() { return classname; } void SONDEIDEA::input_thread() { /** Connection setup */ Socket::Endpoint local(EFUSettings.DetectorAddress.c_str(), EFUSettings.DetectorPort); UDPServer sondedata(local); sondedata.setbuffers(0, EFUSettings.DetectorRxBufferSize); sondedata.printbuffers(); sondedata.settimeout(0, 100000); // 1/10 second int rdsize; for (;;) { unsigned int eth_index = eth_ringbuf->getindex(); /** this is the processing step */ eth_ringbuf->setdatalength(eth_index, 0); if ((rdsize = sondedata.receive(eth_ringbuf->getdatabuffer(eth_index), eth_ringbuf->getmaxbufsize())) > 0) { mystats.rx_packets++; mystats.rx_bytes += rdsize; eth_ringbuf->setdatalength(eth_index, rdsize); if (input2proc_fifo.push(eth_index) == false) { mystats.fifo_push_errors++; } else { eth_ringbuf->nextbuffer(); } } // Checking for exit if (not runThreads) { XTRACE(INPUT, ALW, "Stopping input thread.\n"); return; } } } void SONDEIDEA::processing_thread() { SoNDeGeometry geometry; IDEASData ideasdata(&geometry); Producer eventprod(EFUSettings.KafkaBroker, "SKADI_detector"); FBSerializer flatbuffer(kafka_buffer_size, eventprod); unsigned int data_index; TSCTimer produce_timer; while (1) { if ((input2proc_fifo.pop(data_index)) == false) { mystats.rx_idle1++; usleep(10); } else { auto len = eth_ringbuf->getdatalength(data_index); if (len == 0) { mystats.fifo_synch_errors++; } else { int events = ideasdata.parse_buffer(eth_ringbuf->getdatabuffer(data_index), len); mystats.rx_geometry_errors += ideasdata.errors; mystats.rx_events += ideasdata.events; mystats.rx_seq_errors = ideasdata.ctr_outof_sequence; if (events > 0) { for (int i = 0; i < events; i++) { XTRACE(PROCESS, DEB, "flatbuffer.addevent[i: %d](t: %d, pix: %d)\n", i, ideasdata.data[i].time, ideasdata.data[i].pixel_id); mystats.tx_bytes += flatbuffer.addevent(ideasdata.data[i].time, ideasdata.data[i].pixel_id); } } if (produce_timer.timetsc() >= EFUSettings.UpdateIntervalSec * 1000000 * TSC_MHZ) { mystats.tx_bytes += flatbuffer.produce(); produce_timer.now(); } if (not runThreads) { XTRACE(INPUT, ALW, "Stopping input thread.\n"); return; } } } } } /** ----------------------------------------------------- */ class SONDEIDEAFactory : DetectorFactory { public: std::shared_ptr<Detector> create(BaseSettings settings) { return std::shared_ptr<Detector>(new SONDEIDEA(settings)); } }; SONDEIDEAFactory Factory; <commit_msg>Fix to sonde not exiting.<commit_after> /** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <cinttypes> #include <common/Detector.h> #include <common/EFUArgs.h> #include <common/FBSerializer.h> #include <common/Producer.h> #include <common/RingBuffer.h> #include <common/Trace.h> #include <cstring> #include <fcntl.h> #include <iostream> #include <libs/include/SPSCFifo.h> #include <libs/include/Socket.h> #include <libs/include/TSCTimer.h> #include <libs/include/Timer.h> #include <memory> #include <sonde/ideas/Data.h> #include <stdio.h> #include <unistd.h> //#undef TRC_LEVEL //#define TRC_LEVEL TRC_L_DEB using namespace memory_sequential_consistent; // Lock free fifo const char *classname = "SoNDe detector using IDEA readout"; const int TSC_MHZ = 2900; // MJC's workstation - not reliable /** ----------------------------------------------------- */ class SONDEIDEA : public Detector { public: SONDEIDEA(BaseSettings settings); ~SONDEIDEA() { printf("sonde destructor called\n"); } void input_thread(); void processing_thread(); const char *detectorname(); /** @todo figure out the right size of the .._max_entries */ static const int eth_buffer_max_entries = 20000; static const int eth_buffer_size = 9000; static const int kafka_buffer_size = 124000; /**< events */ private: /** Shared between input_thread and processing_thread*/ CircularFifo<unsigned int, eth_buffer_max_entries> input2proc_fifo; RingBuffer<eth_buffer_size> *eth_ringbuf; NewStats ns{"efu.sonde."}; // struct { // Input Counters int64_t rx_packets; int64_t rx_bytes; int64_t fifo_push_errors; int64_t rx_pktlen_0; int64_t pad[4]; // Processing and Output counters int64_t rx_idle1; int64_t rx_events; int64_t rx_geometry_errors; int64_t tx_bytes; int64_t rx_seq_errors; int64_t fifo_synch_errors; } ALIGN(64) mystats; }; void SetCLIArguments(CLI::App __attribute__((unused)) & parser) {} PopulateCLIParser PopulateParser{SetCLIArguments}; SONDEIDEA::SONDEIDEA(BaseSettings settings) : Detector("SoNDe detector using IDEA readout", settings) { Stats.setPrefix("efu.sonde"); XTRACE(INIT, ALW, "Adding stats\n"); // clang-format off Stats.create("input.rx_packets", mystats.rx_packets); Stats.create("input.rx_bytes", mystats.rx_bytes); Stats.create("input.dropped", mystats.fifo_push_errors); Stats.create("input.rx_seq_errors", mystats.rx_seq_errors); Stats.create("processing.idle", mystats.rx_idle1); Stats.create("processing.rx_events", mystats.rx_events); Stats.create("processing.rx_geometry_errors", mystats.rx_geometry_errors); Stats.create("processing.rx_seq_errors", mystats.rx_seq_errors); Stats.create("output.tx_bytes", mystats.tx_bytes); // clang-format on std::function<void()> inputFunc = [this]() { SONDEIDEA::input_thread(); }; Detector::AddThreadFunction(inputFunc, "input"); std::function<void()> processingFunc = [this]() { SONDEIDEA::processing_thread(); }; Detector::AddThreadFunction(processingFunc, "processing"); XTRACE(INIT, ALW, "Creating %d SONDE Rx ringbuffers of size %d\n", eth_buffer_max_entries, eth_buffer_size); eth_ringbuf = new RingBuffer<eth_buffer_size>( eth_buffer_max_entries + 1); /** @todo testing workaround */ assert(eth_ringbuf != 0); } const char *SONDEIDEA::detectorname() { return classname; } void SONDEIDEA::input_thread() { /** Connection setup */ Socket::Endpoint local(EFUSettings.DetectorAddress.c_str(), EFUSettings.DetectorPort); UDPServer sondedata(local); sondedata.setbuffers(0, EFUSettings.DetectorRxBufferSize); sondedata.printbuffers(); sondedata.settimeout(0, 100000); // 1/10 second int rdsize; for (;;) { unsigned int eth_index = eth_ringbuf->getindex(); /** this is the processing step */ eth_ringbuf->setdatalength(eth_index, 0); if ((rdsize = sondedata.receive(eth_ringbuf->getdatabuffer(eth_index), eth_ringbuf->getmaxbufsize())) > 0) { mystats.rx_packets++; mystats.rx_bytes += rdsize; eth_ringbuf->setdatalength(eth_index, rdsize); if (input2proc_fifo.push(eth_index) == false) { mystats.fifo_push_errors++; } else { eth_ringbuf->nextbuffer(); } } // Checking for exit if (not runThreads) { XTRACE(INPUT, ALW, "Stopping input thread.\n"); return; } } } void SONDEIDEA::processing_thread() { SoNDeGeometry geometry; IDEASData ideasdata(&geometry); Producer eventprod(EFUSettings.KafkaBroker, "SKADI_detector"); FBSerializer flatbuffer(kafka_buffer_size, eventprod); unsigned int data_index; TSCTimer produce_timer; while (1) { if ((input2proc_fifo.pop(data_index)) == false) { mystats.rx_idle1++; usleep(10); } else { auto len = eth_ringbuf->getdatalength(data_index); if (len == 0) { mystats.fifo_synch_errors++; } else { int events = ideasdata.parse_buffer(eth_ringbuf->getdatabuffer(data_index), len); mystats.rx_geometry_errors += ideasdata.errors; mystats.rx_events += ideasdata.events; mystats.rx_seq_errors = ideasdata.ctr_outof_sequence; if (events > 0) { for (int i = 0; i < events; i++) { XTRACE(PROCESS, DEB, "flatbuffer.addevent[i: %d](t: %d, pix: %d)\n", i, ideasdata.data[i].time, ideasdata.data[i].pixel_id); mystats.tx_bytes += flatbuffer.addevent(ideasdata.data[i].time, ideasdata.data[i].pixel_id); } } if (produce_timer.timetsc() >= EFUSettings.UpdateIntervalSec * 1000000 * TSC_MHZ) { mystats.tx_bytes += flatbuffer.produce(); produce_timer.now(); } } } if (not runThreads) { XTRACE(INPUT, ALW, "Stopping input thread.\n"); return; } } } /** ----------------------------------------------------- */ class SONDEIDEAFactory : DetectorFactory { public: std::shared_ptr<Detector> create(BaseSettings settings) { return std::shared_ptr<Detector>(new SONDEIDEA(settings)); } }; SONDEIDEAFactory Factory; <|endoftext|>
<commit_before>//===--- ParseAST.cpp - Provide the clang::ParseAST method ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the clang::ParseAST method. // //===----------------------------------------------------------------------===// #include "clang/Sema/ParseAST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/TranslationUnit.h" #include "Sema.h" #include "clang/Parse/Action.h" #include "clang/Parse/Parser.h" using namespace clang; //===----------------------------------------------------------------------===// // Public interface to the file //===----------------------------------------------------------------------===// /// ParseAST - Parse the entire file specified, notifying the ASTConsumer as /// the file is parsed. This takes ownership of the ASTConsumer and /// ultimately deletes it. void clang::ParseAST(Preprocessor &PP, ASTConsumer *Consumer, bool PrintStats) { // Collect global stats on Decls/Stmts (until we have a module streamer). if (PrintStats) { Decl::CollectingStats(true); Stmt::CollectingStats(true); } ASTContext Context(PP.getSourceManager(), PP.getTargetInfo(), PP.getIdentifierTable(), PP.getSelectorTable()); TranslationUnit TU(Context, PP.getLangOptions()); Parser P(PP, *new Sema(PP, Context, *Consumer)); PP.EnterMainSourceFile(); // Initialize the parser. P.Initialize(); Consumer->Initialize(Context); Parser::DeclTy *ADecl; while (!P.ParseTopLevelDecl(ADecl)) { // Not end of file. // If we got a null return and something *was* parsed, ignore it. This // is due to a top-level semicolon, an action override, or a parse error // skipping something. if (ADecl) { Decl* D = static_cast<Decl*>(ADecl); TU.AddTopLevelDecl(D); // TranslationUnit now owns the Decl. Consumer->HandleTopLevelDecl(D); } }; if (PrintStats) { fprintf(stderr, "\nSTATISTICS:\n"); P.getActions().PrintStats(); Context.PrintStats(); Decl::PrintStats(); Stmt::PrintStats(); Consumer->PrintStats(); Decl::CollectingStats(false); Stmt::CollectingStats(false); } delete Consumer; } <commit_msg>Stop leaking the main Sema object. (Leak found using valgrind.)<commit_after>//===--- ParseAST.cpp - Provide the clang::ParseAST method ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the clang::ParseAST method. // //===----------------------------------------------------------------------===// #include "clang/Sema/ParseAST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/TranslationUnit.h" #include "Sema.h" #include "clang/Parse/Action.h" #include "clang/Parse/Parser.h" using namespace clang; //===----------------------------------------------------------------------===// // Public interface to the file //===----------------------------------------------------------------------===// /// ParseAST - Parse the entire file specified, notifying the ASTConsumer as /// the file is parsed. This takes ownership of the ASTConsumer and /// ultimately deletes it. void clang::ParseAST(Preprocessor &PP, ASTConsumer *Consumer, bool PrintStats) { // Collect global stats on Decls/Stmts (until we have a module streamer). if (PrintStats) { Decl::CollectingStats(true); Stmt::CollectingStats(true); } ASTContext Context(PP.getSourceManager(), PP.getTargetInfo(), PP.getIdentifierTable(), PP.getSelectorTable()); TranslationUnit TU(Context, PP.getLangOptions()); Sema S(PP, Context, *Consumer); Parser P(PP, S); PP.EnterMainSourceFile(); // Initialize the parser. P.Initialize(); Consumer->Initialize(Context); Parser::DeclTy *ADecl; while (!P.ParseTopLevelDecl(ADecl)) { // Not end of file. // If we got a null return and something *was* parsed, ignore it. This // is due to a top-level semicolon, an action override, or a parse error // skipping something. if (ADecl) { Decl* D = static_cast<Decl*>(ADecl); TU.AddTopLevelDecl(D); // TranslationUnit now owns the Decl. Consumer->HandleTopLevelDecl(D); } }; if (PrintStats) { fprintf(stderr, "\nSTATISTICS:\n"); P.getActions().PrintStats(); Context.PrintStats(); Decl::PrintStats(); Stmt::PrintStats(); Consumer->PrintStats(); Decl::CollectingStats(false); Stmt::CollectingStats(false); } delete Consumer; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Execution/OperationNotSupportedException.h" #include "BinaryInputStreamFromIStreamAdapter.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Streams; using namespace Stroika::Foundation::Streams::iostream; /* ******************************************************************************** ********* Streams::iostream::BinaryInputStreamFromIStreamAdapter *************** ******************************************************************************** */ BinaryInputStreamFromIStreamAdapter::BinaryInputStreamFromIStreamAdapter (std::istream& originalStream) : fOriginalStream_ (originalStream) { } size_t BinaryInputStreamFromIStreamAdapter::_Read (Byte* intoStart, Byte* intoEnd) { RequireNotNull (intoStart); RequireNotNull (intoEnd); Require (intoStart < intoEnd); if (fOriginalStream_.eof ()) { return 0; } size_t maxToRead = intoEnd - intoStart; fOriginalStream_.read (reinterpret_cast<char*> (intoStart), maxToRead); size_t n = static_cast<size_t> (fOriginalStream_.gcount ()); // cast safe cuz amount asked to read was also size_t // apparently based on http://www.cplusplus.com/reference/iostream/istream/read/ EOF sets the EOF bit AND the fail bit if (not fOriginalStream_.eof () and fOriginalStream_.fail ()) { Execution::DoThrow (Execution::StringException (L"Failed to read from istream")); } return n; } Streams::SeekOffsetType BinaryInputStreamFromIStreamAdapter::_GetOffset () const override { return fOriginalStream_.tellg (); } bool BinaryInputStreamFromIStreamAdapter::_CanSeek (Streams::Whence whence) const override { return true; } void BinaryInputStreamFromIStreamAdapter::_Seek (Streams::Whence whence, Streams::SeekOffsetType offset) override { switch (whence) { case FromStart_W: fOriginalStream_.seekg (offset, ios::beg); break; case FromCurrent_W: fOriginalStream_.seekg (offset, ios::cur); break; case FromEnd_W: fOriginalStream_.seekg (offset, ios::end); break; } } <commit_msg>changed BinaryInputStreamFromIStreamAdapter::_GetOffset () to accomodate the fact that tellg () - at least on windows - fails if at EOF<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Execution/OperationNotSupportedException.h" #include "BinaryInputStreamFromIStreamAdapter.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Streams; using namespace Stroika::Foundation::Streams::iostream; /* ******************************************************************************** ********* Streams::iostream::BinaryInputStreamFromIStreamAdapter *************** ******************************************************************************** */ BinaryInputStreamFromIStreamAdapter::BinaryInputStreamFromIStreamAdapter (std::istream& originalStream) : fOriginalStream_ (originalStream) { } size_t BinaryInputStreamFromIStreamAdapter::_Read (Byte* intoStart, Byte* intoEnd) { RequireNotNull (intoStart); RequireNotNull (intoEnd); Require (intoStart < intoEnd); if (fOriginalStream_.eof ()) { return 0; } size_t maxToRead = intoEnd - intoStart; fOriginalStream_.read (reinterpret_cast<char*> (intoStart), maxToRead); size_t n = static_cast<size_t> (fOriginalStream_.gcount ()); // cast safe cuz amount asked to read was also size_t // apparently based on http://www.cplusplus.com/reference/iostream/istream/read/ EOF sets the EOF bit AND the fail bit if (not fOriginalStream_.eof () and fOriginalStream_.fail ()) { Execution::DoThrow (Execution::StringException (L"Failed to read from istream")); } return n; } Streams::SeekOffsetType BinaryInputStreamFromIStreamAdapter::_GetOffset () const override { // instead of tellg () - avoids issue with EOF where fail bit set??? return fOriginalStream_.rdbuf ()->pubseekoff (0, ios_base::cur, ios_base::in); } bool BinaryInputStreamFromIStreamAdapter::_CanSeek (Streams::Whence whence) const override { return true; } void BinaryInputStreamFromIStreamAdapter::_Seek (Streams::Whence whence, Streams::SeekOffsetType offset) override { switch (whence) { case FromStart_W: fOriginalStream_.seekg (offset, ios::beg); break; case FromCurrent_W: fOriginalStream_.seekg (offset, ios::cur); break; case FromEnd_W: fOriginalStream_.seekg (offset, ios::end); break; } } <|endoftext|>
<commit_before>#include "config.h" #include "cpptoml/include/cpptoml.h" #include "xenia/base/cvar.h" #include "xenia/base/filesystem.h" #include "xenia/base/logging.h" #include "xenia/base/string.h" CmdVar(config, "", "Specifies the target config to load."); namespace config { std::wstring config_name = L"xenia.config.toml"; std::wstring config_folder; std::wstring config_path; bool sortCvar(cvar::IConfigVar* a, cvar::IConfigVar* b) { if (a->category() < b->category()) return true; if (a->category() > b->category()) return false; if (a->name() < b->name()) return true; return false; } std::shared_ptr<cpptoml::table> ParseConfig(std::string config_path) { try { return cpptoml::parse_file(config_path); } catch (cpptoml::parse_exception e) { xe::FatalError("Failed to parse config file '%s':\n\n%s", config_path.c_str(), e.what()); return nullptr; } } void ReadConfig(const std::wstring& file_path) { const auto config = ParseConfig(xe::to_string(file_path)); for (auto& it : *cvar::ConfigVars) { auto configVar = static_cast<cvar::IConfigVar*>(it.second); auto configKey = configVar->category() + "." + configVar->name(); if (config->contains_qualified(configKey)) { configVar->LoadConfigValue(config->get_qualified(configKey)); } } XELOGI("Loaded config: %S", file_path.c_str()); } void ReadGameConfig(std::wstring file_path) { const auto config = ParseConfig(xe::to_string(file_path)); for (auto& it : *cvar::ConfigVars) { auto configVar = static_cast<cvar::IConfigVar*>(it.second); auto configKey = configVar->category() + "." + configVar->name(); if (config->contains_qualified(configKey)) { configVar->LoadGameConfigValue(config->get_qualified(configKey)); } } XELOGI("Loaded game config: %S", file_path.c_str()); } void SaveConfig() { std::vector<cvar::IConfigVar*> vars; for (const auto& s : *cvar::ConfigVars) vars.push_back(s.second); std::sort(vars.begin(), vars.end(), sortCvar); // we use our own write logic because cpptoml doesn't // allow us to specify comments :( std::ostringstream output; std::string lastCategory; for (auto configVar : vars) { if (configVar->is_transient()) { continue; } if (lastCategory != configVar->category()) { if (!lastCategory.empty()) { output << std::endl; } lastCategory = configVar->category(); output << xe::format_string("[%s]\n", lastCategory.c_str()); } output << std::left << std::setw(40) << std::setfill(' ') << xe::format_string("%s = %s", configVar->name().c_str(), configVar->config_value().c_str()); output << xe::format_string("\t# %s\n", configVar->description().c_str()); } if (xe::filesystem::PathExists(config_path)) { std::ifstream existingConfigStream(xe::to_string(config_path).c_str()); const std::string existingConfig( (std::istreambuf_iterator<char>(existingConfigStream)), std::istreambuf_iterator<char>()); // if the config didn't change, no need to modify the file if (existingConfig == output.str()) return; } // save the config file xe::filesystem::CreateParentFolder(config_path); std::ofstream file; file.open(xe::to_string(config_path), std::ios::out | std::ios::trunc); file << output.str(); file.close(); } void SetupConfig(const std::wstring& config_folder) { config::config_folder = config_folder; // check if the user specified a specific config to load if (!cvars::config.empty()) { config_path = xe::to_wstring(cvars::config); if (xe::filesystem::PathExists(config_path)) { ReadConfig(config_path); return; } } // if the user specified a --config argument, but the file doesn't exist, // let's also load the default config if (!config_folder.empty()) { config_path = xe::join_paths(config_folder, config_name); if (xe::filesystem::PathExists(config_path)) { ReadConfig(config_path); } // we only want to save the config if the user is using the default // config, we don't want to override a user created specific config SaveConfig(); } } void LoadGameConfig(const std::wstring& title_id) { const auto content_folder = xe::join_paths(config_folder, L"content"); const auto game_folder = xe::join_paths(content_folder, title_id); const auto game_config_path = xe::join_paths(game_folder, config_name); if (xe::filesystem::PathExists(game_config_path)) { ReadGameConfig(game_config_path); } } } // namespace config <commit_msg>[Core] Fix config load/save not using wide strings for path.<commit_after>#include "config.h" #include "cpptoml/include/cpptoml.h" #include "xenia/base/cvar.h" #include "xenia/base/filesystem.h" #include "xenia/base/logging.h" #include "xenia/base/string.h" namespace cpptoml { inline std::shared_ptr<table> parse_file(const std::wstring& filename) { std::ifstream file(filename); if (!file.is_open()) { throw parse_exception(xe::to_string(filename) + " could not be opened for parsing"); } parser p(file); return p.parse(); } } // namespace cpptoml CmdVar(config, "", "Specifies the target config to load."); namespace config { std::wstring config_name = L"xenia.config.toml"; std::wstring config_folder; std::wstring config_path; bool sortCvar(cvar::IConfigVar* a, cvar::IConfigVar* b) { if (a->category() < b->category()) return true; if (a->category() > b->category()) return false; if (a->name() < b->name()) return true; return false; } std::shared_ptr<cpptoml::table> ParseConfig(const std::wstring& config_path) { try { return cpptoml::parse_file(config_path); } catch (cpptoml::parse_exception e) { xe::FatalError(L"Failed to parse config file '%s':\n\n%s", config_path.c_str(), xe::to_wstring(e.what()).c_str()); return nullptr; } } void ReadConfig(const std::wstring& file_path) { const auto config = ParseConfig(file_path); for (auto& it : *cvar::ConfigVars) { auto configVar = static_cast<cvar::IConfigVar*>(it.second); auto configKey = configVar->category() + "." + configVar->name(); if (config->contains_qualified(configKey)) { configVar->LoadConfigValue(config->get_qualified(configKey)); } } XELOGI("Loaded config: %S", file_path.c_str()); } void ReadGameConfig(std::wstring file_path) { const auto config = ParseConfig(file_path); for (auto& it : *cvar::ConfigVars) { auto configVar = static_cast<cvar::IConfigVar*>(it.second); auto configKey = configVar->category() + "." + configVar->name(); if (config->contains_qualified(configKey)) { configVar->LoadGameConfigValue(config->get_qualified(configKey)); } } XELOGI("Loaded game config: %S", file_path.c_str()); } void SaveConfig() { std::vector<cvar::IConfigVar*> vars; for (const auto& s : *cvar::ConfigVars) vars.push_back(s.second); std::sort(vars.begin(), vars.end(), sortCvar); // we use our own write logic because cpptoml doesn't // allow us to specify comments :( std::ostringstream output; std::string lastCategory; for (auto configVar : vars) { if (configVar->is_transient()) { continue; } if (lastCategory != configVar->category()) { if (!lastCategory.empty()) { output << std::endl; } lastCategory = configVar->category(); output << xe::format_string("[%s]\n", lastCategory.c_str()); } output << std::left << std::setw(40) << std::setfill(' ') << xe::format_string("%s = %s", configVar->name().c_str(), configVar->config_value().c_str()); output << xe::format_string("\t# %s\n", configVar->description().c_str()); } if (xe::filesystem::PathExists(config_path)) { std::ifstream existingConfigStream(xe::to_string(config_path).c_str()); const std::string existingConfig( (std::istreambuf_iterator<char>(existingConfigStream)), std::istreambuf_iterator<char>()); // if the config didn't change, no need to modify the file if (existingConfig == output.str()) return; } // save the config file xe::filesystem::CreateParentFolder(config_path); std::ofstream file; file.open(config_path, std::ios::out | std::ios::trunc); file << output.str(); file.close(); } void SetupConfig(const std::wstring& config_folder) { config::config_folder = config_folder; // check if the user specified a specific config to load if (!cvars::config.empty()) { config_path = xe::to_wstring(cvars::config); if (xe::filesystem::PathExists(config_path)) { ReadConfig(config_path); return; } } // if the user specified a --config argument, but the file doesn't exist, // let's also load the default config if (!config_folder.empty()) { config_path = xe::join_paths(config_folder, config_name); if (xe::filesystem::PathExists(config_path)) { ReadConfig(config_path); } // we only want to save the config if the user is using the default // config, we don't want to override a user created specific config SaveConfig(); } } void LoadGameConfig(const std::wstring& title_id) { const auto content_folder = xe::join_paths(config_folder, L"content"); const auto game_folder = xe::join_paths(content_folder, title_id); const auto game_config_path = xe::join_paths(game_folder, config_name); if (xe::filesystem::PathExists(game_config_path)) { ReadGameConfig(game_config_path); } } } // namespace config <|endoftext|>
<commit_before>//===- Main.cpp - Top-Level TableGen implementation -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // TableGen is a tool which can be used to build up a description of something, // then invoke one or more "tablegen backends" to emit information about the // description in some predefined format. In practice, this is used by the LLVM // code generators to automate generation of a code generator through a // high-level description of the target. // //===----------------------------------------------------------------------===// #include "TGParser.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Main.h" #include "llvm/TableGen/Record.h" #include <algorithm> #include <cstdio> #include <system_error> using namespace llvm; namespace { cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-")); cl::opt<std::string> DependFilename("d", cl::desc("Dependency filename"), cl::value_desc("filename"), cl::init("")); cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); cl::list<std::string> IncludeDirs("I", cl::desc("Directory of include files"), cl::value_desc("directory"), cl::Prefix); } /// \brief Create a dependency file for `-d` option. /// /// This functionality is really only for the benefit of the build system. /// It is similar to GCC's `-M*` family of options. static int createDependencyFile(const TGParser &Parser, const char *argv0) { if (OutputFilename == "-") { errs() << argv0 << ": the option -d must be used together with -o\n"; return 1; } std::error_code EC; tool_output_file DepOut(DependFilename, EC, sys::fs::F_Text); if (EC) { errs() << argv0 << ": error opening " << DependFilename << ":" << EC.message() << "\n"; return 1; } DepOut.os() << OutputFilename << ":"; for (const auto &Dep : Parser.getDependencies()) { DepOut.os() << ' ' << Dep.first; } DepOut.os() << "\n"; DepOut.keep(); return 0; } namespace llvm { int TableGenMain(char *argv0, TableGenMainFn *MainFn) { RecordKeeper Records; // Parse the input file. ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = MemoryBuffer::getFileOrSTDIN(InputFilename); if (std::error_code EC = FileOrErr.getError()) { errs() << "Could not open input file '" << InputFilename << "': " << EC.message() << "\n"; return 1; } // Tell SrcMgr about this buffer, which is what TGParser will pick up. SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc()); // Record the location of the include directory so that the lexer can find // it later. SrcMgr.setIncludeDirs(IncludeDirs); TGParser Parser(SrcMgr, Records); if (Parser.ParseFile()) return 1; std::error_code EC; tool_output_file Out(OutputFilename, EC, sys::fs::F_Text); if (EC) { errs() << argv0 << ": error opening " << OutputFilename << ":" << EC.message() << "\n"; return 1; } if (!DependFilename.empty()) { if (int Ret = createDependencyFile(Parser, argv0)) return Ret; } if (MainFn(Out.os(), Records)) return 1; if (ErrorsPrinted > 0) { errs() << argv0 << ": " << ErrorsPrinted << " errors.\n"; return 1; } // Declare success. Out.keep(); return 0; } } <commit_msg>[TableGen] Use 'static' instead of an anonymous namespace.<commit_after>//===- Main.cpp - Top-Level TableGen implementation -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // TableGen is a tool which can be used to build up a description of something, // then invoke one or more "tablegen backends" to emit information about the // description in some predefined format. In practice, this is used by the LLVM // code generators to automate generation of a code generator through a // high-level description of the target. // //===----------------------------------------------------------------------===// #include "TGParser.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Main.h" #include "llvm/TableGen/Record.h" #include <algorithm> #include <cstdio> #include <system_error> using namespace llvm; static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-")); static cl::opt<std::string> DependFilename("d", cl::desc("Dependency filename"), cl::value_desc("filename"), cl::init("")); static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); static cl::list<std::string> IncludeDirs("I", cl::desc("Directory of include files"), cl::value_desc("directory"), cl::Prefix); /// \brief Create a dependency file for `-d` option. /// /// This functionality is really only for the benefit of the build system. /// It is similar to GCC's `-M*` family of options. static int createDependencyFile(const TGParser &Parser, const char *argv0) { if (OutputFilename == "-") { errs() << argv0 << ": the option -d must be used together with -o\n"; return 1; } std::error_code EC; tool_output_file DepOut(DependFilename, EC, sys::fs::F_Text); if (EC) { errs() << argv0 << ": error opening " << DependFilename << ":" << EC.message() << "\n"; return 1; } DepOut.os() << OutputFilename << ":"; for (const auto &Dep : Parser.getDependencies()) { DepOut.os() << ' ' << Dep.first; } DepOut.os() << "\n"; DepOut.keep(); return 0; } namespace llvm { int TableGenMain(char *argv0, TableGenMainFn *MainFn) { RecordKeeper Records; // Parse the input file. ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = MemoryBuffer::getFileOrSTDIN(InputFilename); if (std::error_code EC = FileOrErr.getError()) { errs() << "Could not open input file '" << InputFilename << "': " << EC.message() << "\n"; return 1; } // Tell SrcMgr about this buffer, which is what TGParser will pick up. SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc()); // Record the location of the include directory so that the lexer can find // it later. SrcMgr.setIncludeDirs(IncludeDirs); TGParser Parser(SrcMgr, Records); if (Parser.ParseFile()) return 1; std::error_code EC; tool_output_file Out(OutputFilename, EC, sys::fs::F_Text); if (EC) { errs() << argv0 << ": error opening " << OutputFilename << ":" << EC.message() << "\n"; return 1; } if (!DependFilename.empty()) { if (int Ret = createDependencyFile(Parser, argv0)) return Ret; } if (MainFn(Out.os(), Records)) return 1; if (ErrorsPrinted > 0) { errs() << argv0 << ": " << ErrorsPrinted << " errors.\n"; return 1; } // Declare success. Out.keep(); return 0; } } <|endoftext|>
<commit_before>//===-- Module.cpp - Implement the Module class ---------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Module class for the VMCore library. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/InstrTypes.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/LeakDetector.h" #include "SymbolTableListTraitsImpl.h" #include "llvm/TypeSymbolTable.h" #include <algorithm> #include <cstdarg> #include <cstdlib> #include <map> using namespace llvm; //===----------------------------------------------------------------------===// // Methods to implement the globals and functions lists. // Function *ilist_traits<Function>::createSentinel() { FunctionType *FTy = FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false, std::vector<FunctionType::ParameterAttributes>() ); Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage); // This should not be garbage monitored. LeakDetector::removeGarbageObject(Ret); return Ret; } GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() { GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false, GlobalValue::ExternalLinkage); // This should not be garbage monitored. LeakDetector::removeGarbageObject(Ret); return Ret; } iplist<Function> &ilist_traits<Function>::getList(Module *M) { return M->getFunctionList(); } iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) { return M->getGlobalList(); } // Explicit instantiations of SymbolTableListTraits since some of the methods // are not in the public header file. template class SymbolTableListTraits<GlobalVariable, Module, Module>; template class SymbolTableListTraits<Function, Module, Module>; //===----------------------------------------------------------------------===// // Primitive Module methods. // Module::Module(const std::string &MID) : ModuleID(MID), DataLayout("") { FunctionList.setItemParent(this); FunctionList.setParent(this); GlobalList.setItemParent(this); GlobalList.setParent(this); ValSymTab = new SymbolTable(); TypeSymTab = new TypeSymbolTable(); } Module::~Module() { dropAllReferences(); GlobalList.clear(); GlobalList.setParent(0); FunctionList.clear(); FunctionList.setParent(0); LibraryList.clear(); delete ValSymTab; delete TypeSymTab; } // Module::dump() - Allow printing from debugger void Module::dump() const { print(*cerr.stream()); } /// Target endian information... Module::Endianness Module::getEndianness() const { std::string temp = DataLayout; Module::Endianness ret = AnyEndianness; while (!temp.empty()) { std::string token = getToken(temp, "-"); if (token[0] == 'e') { ret = LittleEndian; } else if (token[0] == 'E') { ret = BigEndian; } } return ret; } void Module::setEndianness(Endianness E) { if (!DataLayout.empty() && E != AnyEndianness) DataLayout += "-"; if (E == LittleEndian) DataLayout += "e"; else if (E == BigEndian) DataLayout += "E"; } /// Target Pointer Size information... Module::PointerSize Module::getPointerSize() const { std::string temp = DataLayout; Module::PointerSize ret = AnyPointerSize; while (!temp.empty()) { std::string token = getToken(temp, "-"); char signal = getToken(token, ":")[0]; if (signal == 'p') { int size = atoi(getToken(token, ":").c_str()); if (size == 32) ret = Pointer32; else if (size == 64) ret = Pointer64; } } return ret; } void Module::setPointerSize(PointerSize PS) { if (!DataLayout.empty() && PS != AnyPointerSize) DataLayout += "-"; if (PS == Pointer32) DataLayout += "p:32:32"; else if (PS == Pointer64) DataLayout += "p:64:64"; } //===----------------------------------------------------------------------===// // Methods for easy access to the functions in the module. // Constant *Module::getOrInsertFunction(const std::string &Name, const FunctionType *Ty) { SymbolTable &SymTab = getValueSymbolTable(); // See if we have a definitions for the specified function already. Function *F = dyn_cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name)); if (F == 0) { // Nope, add it. Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name); FunctionList.push_back(New); return New; // Return the new prototype. } // Okay, the function exists. Does it have externally visible linkage? if (F->hasInternalLinkage()) { // Rename the function. F->setName(SymTab.getUniqueName(F->getType(), F->getName())); // Retry, now there won't be a conflict. return getOrInsertFunction(Name, Ty); } // If the function exists but has the wrong type, return a bitcast to the // right type. if (F->getFunctionType() != Ty) return ConstantExpr::getBitCast(F, PointerType::get(Ty)); // Otherwise, we just found the existing function or a prototype. return F; } // getOrInsertFunction - Look up the specified function in the module symbol // table. If it does not exist, add a prototype for the function and return it. // This version of the method takes a null terminated list of function // arguments, which makes it easier for clients to use. // Constant *Module::getOrInsertFunction(const std::string &Name, const Type *RetTy, ...) { va_list Args; va_start(Args, RetTy); // Build the list of argument types... std::vector<const Type*> ArgTys; while (const Type *ArgTy = va_arg(Args, const Type*)) ArgTys.push_back(ArgTy); va_end(Args); // Build the function type and chain to the other getOrInsertFunction... return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false)); } // getFunction - Look up the specified function in the module symbol table. // If it does not exist, return null. // Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) { SymbolTable &SymTab = getValueSymbolTable(); return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name)); } /// getMainFunction - This function looks up main efficiently. This is such a /// common case, that it is a method in Module. If main cannot be found, a /// null pointer is returned. /// Function *Module::getMainFunction() { std::vector<const Type*> Params; // int main(void)... if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty, Params, false))) return F; // void main(void)... if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy, Params, false))) return F; Params.push_back(Type::Int32Ty); // int main(int argc)... if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty, Params, false))) return F; // void main(int argc)... if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy, Params, false))) return F; for (unsigned i = 0; i != 2; ++i) { // Check argv and envp Params.push_back(PointerType::get(PointerType::get(Type::Int8Ty))); // int main(int argc, char **argv)... if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty, Params, false))) return F; // void main(int argc, char **argv)... if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy, Params, false))) return F; } // Ok, try to find main the hard way... return getNamedFunction("main"); } /// getNamedFunction - Return the first function in the module with the /// specified name, of arbitrary type. This method returns null if a function /// with the specified name is not found. /// Function *Module::getNamedFunction(const std::string &Name) const { // Loop over all of the functions, looking for the function desired const Function *Found = 0; for (const_iterator I = begin(), E = end(); I != E; ++I) if (I->getName() == Name) if (I->isExternal()) Found = I; else return const_cast<Function*>(&(*I)); return const_cast<Function*>(Found); // Non-external function not found... } //===----------------------------------------------------------------------===// // Methods for easy access to the global variables in the module. // /// getGlobalVariable - Look up the specified global variable in the module /// symbol table. If it does not exist, return null. The type argument /// should be the underlying type of the global, i.e., it should not have /// the top-level PointerType, which represents the address of the global. /// If AllowInternal is set to true, this function will return types that /// have InternalLinkage. By default, these types are not returned. /// GlobalVariable *Module::getGlobalVariable(const std::string &Name, const Type *Ty, bool AllowInternal) { if (Value *V = getValueSymbolTable().lookup(PointerType::get(Ty), Name)) { GlobalVariable *Result = cast<GlobalVariable>(V); if (AllowInternal || !Result->hasInternalLinkage()) return Result; } return 0; } /// getNamedGlobal - Return the first global variable in the module with the /// specified name, of arbitrary type. This method returns null if a global /// with the specified name is not found. /// GlobalVariable *Module::getNamedGlobal(const std::string &Name) const { // FIXME: This would be much faster with a symbol table that doesn't // discriminate based on type! for (const_global_iterator I = global_begin(), E = global_end(); I != E; ++I) if (I->getName() == Name) return const_cast<GlobalVariable*>(&(*I)); return 0; } //===----------------------------------------------------------------------===// // Methods for easy access to the types in the module. // // addTypeName - Insert an entry in the symbol table mapping Str to Type. If // there is already an entry for this name, true is returned and the symbol // table is not modified. // bool Module::addTypeName(const std::string &Name, const Type *Ty) { TypeSymbolTable &ST = getTypeSymbolTable(); if (ST.lookup(Name)) return true; // Already in symtab... // Not in symbol table? Set the name with the Symtab as an argument so the // type knows what to update... ST.insert(Name, Ty); return false; } /// getTypeByName - Return the type with the specified name in this module, or /// null if there is none by that name. const Type *Module::getTypeByName(const std::string &Name) const { const TypeSymbolTable &ST = getTypeSymbolTable(); return cast_or_null<Type>(ST.lookup(Name)); } // getTypeName - If there is at least one entry in the symbol table for the // specified type, return it. // std::string Module::getTypeName(const Type *Ty) const { const TypeSymbolTable &ST = getTypeSymbolTable(); TypeSymbolTable::const_iterator TI = ST.begin(); TypeSymbolTable::const_iterator TE = ST.end(); if ( TI == TE ) return ""; // No names for types while (TI != TE && TI->second != Ty) ++TI; if (TI != TE) // Must have found an entry! return TI->first; return ""; // Must not have found anything... } //===----------------------------------------------------------------------===// // Other module related stuff. // // dropAllReferences() - This function causes all the subelementss to "let go" // of all references that they are maintaining. This allows one to 'delete' a // whole module at a time, even though there may be circular references... first // all references are dropped, and all use counts go to zero. Then everything // is deleted for real. Note that no operations are valid on an object that // has "dropped all references", except operator delete. // void Module::dropAllReferences() { for(Module::iterator I = begin(), E = end(); I != E; ++I) I->dropAllReferences(); for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I) I->dropAllReferences(); } <commit_msg>For PR761: Remove the setEndianess and setPointerSize methods. These are now handled via the setDataLayout method.<commit_after>//===-- Module.cpp - Implement the Module class ---------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Module class for the VMCore library. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/InstrTypes.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/LeakDetector.h" #include "SymbolTableListTraitsImpl.h" #include "llvm/TypeSymbolTable.h" #include <algorithm> #include <cstdarg> #include <cstdlib> #include <map> using namespace llvm; //===----------------------------------------------------------------------===// // Methods to implement the globals and functions lists. // Function *ilist_traits<Function>::createSentinel() { FunctionType *FTy = FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false, std::vector<FunctionType::ParameterAttributes>() ); Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage); // This should not be garbage monitored. LeakDetector::removeGarbageObject(Ret); return Ret; } GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() { GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false, GlobalValue::ExternalLinkage); // This should not be garbage monitored. LeakDetector::removeGarbageObject(Ret); return Ret; } iplist<Function> &ilist_traits<Function>::getList(Module *M) { return M->getFunctionList(); } iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) { return M->getGlobalList(); } // Explicit instantiations of SymbolTableListTraits since some of the methods // are not in the public header file. template class SymbolTableListTraits<GlobalVariable, Module, Module>; template class SymbolTableListTraits<Function, Module, Module>; //===----------------------------------------------------------------------===// // Primitive Module methods. // Module::Module(const std::string &MID) : ModuleID(MID), DataLayout("") { FunctionList.setItemParent(this); FunctionList.setParent(this); GlobalList.setItemParent(this); GlobalList.setParent(this); ValSymTab = new SymbolTable(); TypeSymTab = new TypeSymbolTable(); } Module::~Module() { dropAllReferences(); GlobalList.clear(); GlobalList.setParent(0); FunctionList.clear(); FunctionList.setParent(0); LibraryList.clear(); delete ValSymTab; delete TypeSymTab; } // Module::dump() - Allow printing from debugger void Module::dump() const { print(*cerr.stream()); } /// Target endian information... Module::Endianness Module::getEndianness() const { std::string temp = DataLayout; Module::Endianness ret = AnyEndianness; while (!temp.empty()) { std::string token = getToken(temp, "-"); if (token[0] == 'e') { ret = LittleEndian; } else if (token[0] == 'E') { ret = BigEndian; } } return ret; } /// Target Pointer Size information... Module::PointerSize Module::getPointerSize() const { std::string temp = DataLayout; Module::PointerSize ret = AnyPointerSize; while (!temp.empty()) { std::string token = getToken(temp, "-"); char signal = getToken(token, ":")[0]; if (signal == 'p') { int size = atoi(getToken(token, ":").c_str()); if (size == 32) ret = Pointer32; else if (size == 64) ret = Pointer64; } } return ret; } //===----------------------------------------------------------------------===// // Methods for easy access to the functions in the module. // Constant *Module::getOrInsertFunction(const std::string &Name, const FunctionType *Ty) { SymbolTable &SymTab = getValueSymbolTable(); // See if we have a definitions for the specified function already. Function *F = dyn_cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name)); if (F == 0) { // Nope, add it. Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name); FunctionList.push_back(New); return New; // Return the new prototype. } // Okay, the function exists. Does it have externally visible linkage? if (F->hasInternalLinkage()) { // Rename the function. F->setName(SymTab.getUniqueName(F->getType(), F->getName())); // Retry, now there won't be a conflict. return getOrInsertFunction(Name, Ty); } // If the function exists but has the wrong type, return a bitcast to the // right type. if (F->getFunctionType() != Ty) return ConstantExpr::getBitCast(F, PointerType::get(Ty)); // Otherwise, we just found the existing function or a prototype. return F; } // getOrInsertFunction - Look up the specified function in the module symbol // table. If it does not exist, add a prototype for the function and return it. // This version of the method takes a null terminated list of function // arguments, which makes it easier for clients to use. // Constant *Module::getOrInsertFunction(const std::string &Name, const Type *RetTy, ...) { va_list Args; va_start(Args, RetTy); // Build the list of argument types... std::vector<const Type*> ArgTys; while (const Type *ArgTy = va_arg(Args, const Type*)) ArgTys.push_back(ArgTy); va_end(Args); // Build the function type and chain to the other getOrInsertFunction... return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false)); } // getFunction - Look up the specified function in the module symbol table. // If it does not exist, return null. // Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) { SymbolTable &SymTab = getValueSymbolTable(); return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name)); } /// getMainFunction - This function looks up main efficiently. This is such a /// common case, that it is a method in Module. If main cannot be found, a /// null pointer is returned. /// Function *Module::getMainFunction() { std::vector<const Type*> Params; // int main(void)... if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty, Params, false))) return F; // void main(void)... if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy, Params, false))) return F; Params.push_back(Type::Int32Ty); // int main(int argc)... if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty, Params, false))) return F; // void main(int argc)... if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy, Params, false))) return F; for (unsigned i = 0; i != 2; ++i) { // Check argv and envp Params.push_back(PointerType::get(PointerType::get(Type::Int8Ty))); // int main(int argc, char **argv)... if (Function *F = getFunction("main", FunctionType::get(Type::Int32Ty, Params, false))) return F; // void main(int argc, char **argv)... if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy, Params, false))) return F; } // Ok, try to find main the hard way... return getNamedFunction("main"); } /// getNamedFunction - Return the first function in the module with the /// specified name, of arbitrary type. This method returns null if a function /// with the specified name is not found. /// Function *Module::getNamedFunction(const std::string &Name) const { // Loop over all of the functions, looking for the function desired const Function *Found = 0; for (const_iterator I = begin(), E = end(); I != E; ++I) if (I->getName() == Name) if (I->isExternal()) Found = I; else return const_cast<Function*>(&(*I)); return const_cast<Function*>(Found); // Non-external function not found... } //===----------------------------------------------------------------------===// // Methods for easy access to the global variables in the module. // /// getGlobalVariable - Look up the specified global variable in the module /// symbol table. If it does not exist, return null. The type argument /// should be the underlying type of the global, i.e., it should not have /// the top-level PointerType, which represents the address of the global. /// If AllowInternal is set to true, this function will return types that /// have InternalLinkage. By default, these types are not returned. /// GlobalVariable *Module::getGlobalVariable(const std::string &Name, const Type *Ty, bool AllowInternal) { if (Value *V = getValueSymbolTable().lookup(PointerType::get(Ty), Name)) { GlobalVariable *Result = cast<GlobalVariable>(V); if (AllowInternal || !Result->hasInternalLinkage()) return Result; } return 0; } /// getNamedGlobal - Return the first global variable in the module with the /// specified name, of arbitrary type. This method returns null if a global /// with the specified name is not found. /// GlobalVariable *Module::getNamedGlobal(const std::string &Name) const { // FIXME: This would be much faster with a symbol table that doesn't // discriminate based on type! for (const_global_iterator I = global_begin(), E = global_end(); I != E; ++I) if (I->getName() == Name) return const_cast<GlobalVariable*>(&(*I)); return 0; } //===----------------------------------------------------------------------===// // Methods for easy access to the types in the module. // // addTypeName - Insert an entry in the symbol table mapping Str to Type. If // there is already an entry for this name, true is returned and the symbol // table is not modified. // bool Module::addTypeName(const std::string &Name, const Type *Ty) { TypeSymbolTable &ST = getTypeSymbolTable(); if (ST.lookup(Name)) return true; // Already in symtab... // Not in symbol table? Set the name with the Symtab as an argument so the // type knows what to update... ST.insert(Name, Ty); return false; } /// getTypeByName - Return the type with the specified name in this module, or /// null if there is none by that name. const Type *Module::getTypeByName(const std::string &Name) const { const TypeSymbolTable &ST = getTypeSymbolTable(); return cast_or_null<Type>(ST.lookup(Name)); } // getTypeName - If there is at least one entry in the symbol table for the // specified type, return it. // std::string Module::getTypeName(const Type *Ty) const { const TypeSymbolTable &ST = getTypeSymbolTable(); TypeSymbolTable::const_iterator TI = ST.begin(); TypeSymbolTable::const_iterator TE = ST.end(); if ( TI == TE ) return ""; // No names for types while (TI != TE && TI->second != Ty) ++TI; if (TI != TE) // Must have found an entry! return TI->first; return ""; // Must not have found anything... } //===----------------------------------------------------------------------===// // Other module related stuff. // // dropAllReferences() - This function causes all the subelementss to "let go" // of all references that they are maintaining. This allows one to 'delete' a // whole module at a time, even though there may be circular references... first // all references are dropped, and all use counts go to zero. Then everything // is deleted for real. Note that no operations are valid on an object that // has "dropped all references", except operator delete. // void Module::dropAllReferences() { for(Module::iterator I = begin(), E = end(); I != E; ++I) I->dropAllReferences(); for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I) I->dropAllReferences(); } <|endoftext|>
<commit_before>/*************************************************************************** begin : Wed Jun 16 2004 copyright : (C) 2004 by Richard Dale email : Richard_Dale@tipitina.demon.co.uk ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <stdlib.h> #include "qyotosmokebinding.h" #include "qyoto.h" #include "virtualmethodcall.h" #include <cstdlib> #include <qt_smoke.h> #if QT_VERSION >= 0x40200 #include <QVariant> #include <QGraphicsScene> #include <QGraphicsItem> #endif namespace Qyoto { Binding::Binding() : SmokeBinding(0) {} Binding::Binding(Smoke *s, QHash<int, char*> *classname) : SmokeBinding(s), _classname(classname) {} void Binding::deleted(Smoke::Index classId, void *ptr) { void * obj = (*GetInstance)(ptr, true); if (obj == 0) { return; } smokeqyoto_object *o = (smokeqyoto_object*) (*GetSmokeObject)(obj); if (do_debug & qtdb_gc) { printf("%p->~%s()\n", ptr, smoke->className(classId)); fflush(stdout); } (*TryDispose)(obj); if (o == 0 || o->ptr == 0) { (*FreeGCHandle)(obj); return; } unmapPointer(o, o->classId, 0); (*SetSmokeObject)(obj, 0); free_smokeqyoto_object(o); (*FreeGCHandle)(obj); } bool Binding::callMethod(Smoke::Index method, void *ptr, Smoke::Stack args, bool isAbstract) { // don't call anything if the application has already terminated if (application_terminated) return false; void * obj = (*GetInstance)(ptr, false); if (obj == 0 && !isAbstract) { return false; } Smoke::Method & meth = smoke->methods[method]; QByteArray signature(smoke->methodNames[meth.name]); signature += "("; for (int i = 0; i < meth.numArgs; i++) { if (i != 0) signature += ", "; signature += smoke->types[smoke->argumentList[meth.args + i]].name; } signature += ")"; if (meth.flags & Smoke::mf_const) { signature += " const"; } if (obj == 0) { printf( "Fatal error: C# instance has been wrongly GC'd for virtual %p->%s::%s call\n", ptr, smoke->classes[smoke->methods[method].classId].className, (const char *) signature ); std::exit(1); } if (do_debug & qtdb_virtual) { printf( "virtual %p->%s::%s called\n", ptr, smoke->classes[smoke->methods[method].classId].className, (const char *) signature ); fflush(stdout); } #if QT_VERSION >= 0x40200 static Smoke::Index qgraphicsitem_class = qt_Smoke->idClass("QGraphicsItem").index; #endif smokeqyoto_object *sqo = (smokeqyoto_object*) (*GetSmokeObject)(obj); if (strcmp(signature, "qt_metacall(QMetaObject::Call, int, void**)") == 0) { QMetaObject::Call _c = (QMetaObject::Call)args[1].s_int; int _id = args[2].s_int; void** _o = (void**)args[3].s_voidp; args[0].s_int = qt_metacall(obj, _c, _id, _o); (*FreeGCHandle)(obj); return true; #if QT_VERSION >= 0x40200 } else if (strcmp(signature, "itemChange(QGraphicsItem::GraphicsItemChange, const QVariant&)") == 0 && smoke->isDerivedFrom(smoke, sqo->classId, qt_Smoke, qgraphicsitem_class)) { int change = args[1].s_int; if (change == QGraphicsItem::ItemSceneChange) { QGraphicsScene *scene = ((QVariant*) args[2].s_voidp)->value<QGraphicsScene*>(); if (scene) { (*AddGlobalRef)(obj, ptr); } else { (*RemoveGlobalRef)(obj, ptr); } } #endif } void * overridenMethod = (*OverridenMethod)(obj, (const char *) signature); if (overridenMethod == 0) { (*FreeGCHandle)(obj); return false; } Qyoto::VirtualMethodCall c(smoke, method, args, obj, overridenMethod); c.next(); return true; } char* Binding::className(Smoke::Index classId) { return _classname->value((int) classId); } } <commit_msg>* Only remove the global ref if the item doesn't belong to a group. This could fix a bug reported by Eric Butler.<commit_after>/*************************************************************************** begin : Wed Jun 16 2004 copyright : (C) 2004 by Richard Dale email : Richard_Dale@tipitina.demon.co.uk ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <stdlib.h> #include "qyotosmokebinding.h" #include "qyoto.h" #include "virtualmethodcall.h" #include <cstdlib> #include <qt_smoke.h> #if QT_VERSION >= 0x40200 #include <QVariant> #include <QGraphicsScene> #include <QGraphicsItem> #endif namespace Qyoto { Binding::Binding() : SmokeBinding(0) {} Binding::Binding(Smoke *s, QHash<int, char*> *classname) : SmokeBinding(s), _classname(classname) {} void Binding::deleted(Smoke::Index classId, void *ptr) { void * obj = (*GetInstance)(ptr, true); if (obj == 0) { return; } smokeqyoto_object *o = (smokeqyoto_object*) (*GetSmokeObject)(obj); if (do_debug & qtdb_gc) { printf("%p->~%s()\n", ptr, smoke->className(classId)); fflush(stdout); } (*TryDispose)(obj); if (o == 0 || o->ptr == 0) { (*FreeGCHandle)(obj); return; } unmapPointer(o, o->classId, 0); (*SetSmokeObject)(obj, 0); free_smokeqyoto_object(o); (*FreeGCHandle)(obj); } bool Binding::callMethod(Smoke::Index method, void *ptr, Smoke::Stack args, bool isAbstract) { // don't call anything if the application has already terminated if (application_terminated) return false; void * obj = (*GetInstance)(ptr, false); if (obj == 0 && !isAbstract) { return false; } Smoke::Method & meth = smoke->methods[method]; QByteArray signature(smoke->methodNames[meth.name]); signature += "("; for (int i = 0; i < meth.numArgs; i++) { if (i != 0) signature += ", "; signature += smoke->types[smoke->argumentList[meth.args + i]].name; } signature += ")"; if (meth.flags & Smoke::mf_const) { signature += " const"; } if (obj == 0) { printf( "Fatal error: C# instance has been wrongly GC'd for virtual %p->%s::%s call\n", ptr, smoke->classes[smoke->methods[method].classId].className, (const char *) signature ); std::exit(1); } if (do_debug & qtdb_virtual) { printf( "virtual %p->%s::%s called\n", ptr, smoke->classes[smoke->methods[method].classId].className, (const char *) signature ); fflush(stdout); } #if QT_VERSION >= 0x40200 static Smoke::Index qgraphicsitem_class = qt_Smoke->idClass("QGraphicsItem").index; #endif smokeqyoto_object *sqo = (smokeqyoto_object*) (*GetSmokeObject)(obj); if (strcmp(signature, "qt_metacall(QMetaObject::Call, int, void**)") == 0) { QMetaObject::Call _c = (QMetaObject::Call)args[1].s_int; int _id = args[2].s_int; void** _o = (void**)args[3].s_voidp; args[0].s_int = qt_metacall(obj, _c, _id, _o); (*FreeGCHandle)(obj); return true; #if QT_VERSION >= 0x40200 } else if (strcmp(signature, "itemChange(QGraphicsItem::GraphicsItemChange, const QVariant&)") == 0 && smoke->isDerivedFrom(smoke, sqo->classId, qt_Smoke, qgraphicsitem_class)) { int change = args[1].s_int; if (change == QGraphicsItem::ItemSceneChange) { QGraphicsScene *scene = ((QVariant*) args[2].s_voidp)->value<QGraphicsScene*>(); if (scene) { (*AddGlobalRef)(obj, ptr); } else { QGraphicsItem *item = (QGraphicsItem*) sqo->smoke->cast(ptr, sqo->classId, qgraphicsitem_class); if (!item->group()) { // only remove the global ref if the item doesn't belong to a group (*RemoveGlobalRef)(obj, ptr); } } } #endif } void * overridenMethod = (*OverridenMethod)(obj, (const char *) signature); if (overridenMethod == 0) { (*FreeGCHandle)(obj); return false; } Qyoto::VirtualMethodCall c(smoke, method, args, obj, overridenMethod); c.next(); return true; } char* Binding::className(Smoke::Index classId) { return _classname->value((int) classId); } } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <cstdint> #include <limits> #include <string> #include "gtest/gtest.h" #include "arrow/test-util.h" #include "arrow/util/buffer.h" #include "arrow/util/status.h" using std::string; namespace arrow { class TestBuffer : public ::testing::Test {}; TEST_F(TestBuffer, Resize) { PoolBuffer buf; ASSERT_EQ(0, buf.size()); ASSERT_OK(buf.Resize(100)); ASSERT_EQ(100, buf.size()); ASSERT_OK(buf.Resize(200)); ASSERT_EQ(200, buf.size()); // Make it smaller, too ASSERT_OK(buf.Resize(50)); ASSERT_EQ(50, buf.size()); } TEST_F(TestBuffer, ResizeOOM) { // realloc fails, even though there may be no explicit limit PoolBuffer buf; ASSERT_OK(buf.Resize(100)); int64_t to_alloc = std::numeric_limits<int64_t>::max(); ASSERT_RAISES(OutOfMemory, buf.Resize(to_alloc)); } TEST_F(TestBuffer, EqualsWithSameContent) { MemoryPool* pool = default_memory_pool(); const int32_t bufferSize = 128 * 1024; uint8_t* rawBuffer1; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer1)); memset(rawBuffer1, 12, bufferSize); uint8_t* rawBuffer2; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer2)); memset(rawBuffer2, 12, bufferSize); uint8_t* rawBuffer3; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer3)); memset(rawBuffer3, 3, bufferSize); Buffer buffer1(rawBuffer1, bufferSize); Buffer buffer2(rawBuffer2, bufferSize); Buffer buffer3(rawBuffer3, bufferSize); ASSERT_TRUE(buffer1.Equals(buffer2)); ASSERT_FALSE(buffer1.Equals(buffer3)); } TEST_F(TestBuffer, EqualsWithSameBuffer) { MemoryPool* pool = default_memory_pool(); const int32_t bufferSize = 128 * 1024; uint8_t* rawBuffer; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer)); memset(rawBuffer, 111, bufferSize); Buffer buffer1(rawBuffer, bufferSize); Buffer buffer2(rawBuffer, bufferSize); ASSERT_TRUE(buffer1.Equals(buffer2)); const int64_t nbytes = bufferSize / 2; Buffer buffer3(rawBuffer, nbytes); ASSERT_TRUE(buffer1.Equals(buffer3, nbytes)); ASSERT_FALSE(buffer1.Equals(buffer3, nbytes + 1)); } } // namespace arrow <commit_msg>Free test buffers afterwards<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <cstdint> #include <limits> #include <string> #include "gtest/gtest.h" #include "arrow/test-util.h" #include "arrow/util/buffer.h" #include "arrow/util/status.h" using std::string; namespace arrow { class TestBuffer : public ::testing::Test {}; TEST_F(TestBuffer, Resize) { PoolBuffer buf; ASSERT_EQ(0, buf.size()); ASSERT_OK(buf.Resize(100)); ASSERT_EQ(100, buf.size()); ASSERT_OK(buf.Resize(200)); ASSERT_EQ(200, buf.size()); // Make it smaller, too ASSERT_OK(buf.Resize(50)); ASSERT_EQ(50, buf.size()); } TEST_F(TestBuffer, ResizeOOM) { // realloc fails, even though there may be no explicit limit PoolBuffer buf; ASSERT_OK(buf.Resize(100)); int64_t to_alloc = std::numeric_limits<int64_t>::max(); ASSERT_RAISES(OutOfMemory, buf.Resize(to_alloc)); } TEST_F(TestBuffer, EqualsWithSameContent) { MemoryPool* pool = default_memory_pool(); const int32_t bufferSize = 128 * 1024; uint8_t* rawBuffer1; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer1)); memset(rawBuffer1, 12, bufferSize); uint8_t* rawBuffer2; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer2)); memset(rawBuffer2, 12, bufferSize); uint8_t* rawBuffer3; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer3)); memset(rawBuffer3, 3, bufferSize); Buffer buffer1(rawBuffer1, bufferSize); Buffer buffer2(rawBuffer2, bufferSize); Buffer buffer3(rawBuffer3, bufferSize); ASSERT_TRUE(buffer1.Equals(buffer2)); ASSERT_FALSE(buffer1.Equals(buffer3)); pool->Free(rawBuffer1, bufferSize); pool->Free(rawBuffer2, bufferSize); pool->Free(rawBuffer3, bufferSize); } TEST_F(TestBuffer, EqualsWithSameBuffer) { MemoryPool* pool = default_memory_pool(); const int32_t bufferSize = 128 * 1024; uint8_t* rawBuffer; ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer)); memset(rawBuffer, 111, bufferSize); Buffer buffer1(rawBuffer, bufferSize); Buffer buffer2(rawBuffer, bufferSize); ASSERT_TRUE(buffer1.Equals(buffer2)); const int64_t nbytes = bufferSize / 2; Buffer buffer3(rawBuffer, nbytes); ASSERT_TRUE(buffer1.Equals(buffer3, nbytes)); ASSERT_FALSE(buffer1.Equals(buffer3, nbytes + 1)); pool->Free(rawBuffer, bufferSize); } } // namespace arrow <|endoftext|>
<commit_before>// // yas_delaying_caller.cpp // #include "yas_delaying_caller.h" using namespace yas; delaying_caller::delaying_caller() : _handler(std::nullopt), _push_count(0) { } void delaying_caller::request(handler_f handler) { if (!handler) { throw "argument is null."; } if (this->_push_count == 0) { if (this->_handler) { throw "_handler always exists."; } handler(); } else { this->_handler = std::move(handler); } } void delaying_caller::cancel() { this->_handler = std::nullopt; } void delaying_caller::push() { ++this->_push_count; } void delaying_caller::pop() { if (this->_push_count == 0) { throw "_push_count decrease failed"; } --this->_push_count; if (this->_push_count == 0 && this->_handler) { this->_handler.value()(); this->_handler = std::nullopt; } } <commit_msg>delaying caller throw<commit_after>// // yas_delaying_caller.cpp // #include "yas_delaying_caller.h" using namespace yas; delaying_caller::delaying_caller() : _handler(std::nullopt), _push_count(0) { } void delaying_caller::request(handler_f handler) { if (!handler) { throw std::invalid_argument("argument is null."); } if (this->_push_count == 0) { if (this->_handler) { throw std::runtime_error("_handler always exists."); } handler(); } else { this->_handler = std::move(handler); } } void delaying_caller::cancel() { this->_handler = std::nullopt; } void delaying_caller::push() { ++this->_push_count; } void delaying_caller::pop() { if (this->_push_count == 0) { throw std::runtime_error("_push_count decrease failed"); } --this->_push_count; if (this->_push_count == 0 && this->_handler) { this->_handler.value()(); this->_handler = std::nullopt; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: stdidlclass.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: dbo $ $Date: 2002-06-14 13:20:20 $ * * 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 <osl/mutex.hxx> #include <cppuhelper/weakref.hxx> #include <cppuhelper/weak.hxx> #include <cppuhelper/stdidlclass.hxx> #include <com/sun/star/reflection/XIdlClassProvider.hpp> #include <com/sun/star/reflection/XIdlReflection.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/uno/DeploymentException.hpp> #include <com/sun/star/beans/XPropertySet.hpp> using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::reflection; using namespace rtl; namespace cppu { /*--------------------------------------------------------- * This helper class implements XIdlClass. Is used by * createStdIdlClass() *---------------------------------------------------------*/ class OStdIdlClass : public OWeakObject, public XIdlClass, public XIdlClassProvider { public: OStdIdlClass( const Reference < XMultiServiceFactory > &rSMgr , const OUString & sImplementationName , const Reference < XIdlClass > & rSuperClass, const Sequence < OUString > &seq ) SAL_THROW( () ); // XInterface Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); void SAL_CALL acquire() throw() { OWeakObject::acquire(); } void SAL_CALL release() throw() { OWeakObject::release(); } // XIdlClassProvider Sequence< Reference < XIdlClass > > SAL_CALL getIdlClasses(void) throw (RuntimeException); // XIdlClass virtual Sequence< Reference< XIdlClass > > SAL_CALL getClasses( ) throw(RuntimeException) { return Sequence < Reference < XIdlClass > > (); } virtual Reference< XIdlClass > SAL_CALL getClass( const ::rtl::OUString& aName ) throw(RuntimeException) { return Reference < XIdlClass > (); } virtual sal_Bool SAL_CALL equals( const Reference< XIdlClass >& Type ) throw(RuntimeException) { return getName() == Type->getName(); } virtual sal_Bool SAL_CALL isAssignableFrom( const Reference< XIdlClass >& xType ) throw(RuntimeException) { return equals( xType ); } virtual TypeClass SAL_CALL getTypeClass( ) throw(RuntimeException) { return TypeClass_UNKNOWN; } virtual OUString SAL_CALL getName( ) throw(RuntimeException) { return m_sImplementationName; } virtual Uik SAL_CALL getUik( ) throw(RuntimeException) { return Uik(); } virtual Sequence< Reference< XIdlClass > > SAL_CALL getSuperclasses( ) throw(RuntimeException) { return m_seqSuperClasses; } virtual Sequence< Reference< XIdlClass > > SAL_CALL getInterfaces( ) throw(RuntimeException); virtual Reference< XIdlClass > SAL_CALL getComponentType( ) throw(RuntimeException) { return Reference < XIdlClass > (); } virtual Reference< XIdlField > SAL_CALL getField( const ::rtl::OUString& aName ) throw(RuntimeException) { return Reference < XIdlField > (); } virtual Sequence< Reference< XIdlField > > SAL_CALL getFields( ) throw(RuntimeException) { return Sequence< Reference < XIdlField > > (); } virtual Reference< XIdlMethod > SAL_CALL getMethod( const ::rtl::OUString& aName ) throw(RuntimeException) { return Reference < XIdlMethod > (); } virtual Sequence< Reference< XIdlMethod > > SAL_CALL getMethods( ) throw(RuntimeException) { return Sequence < Reference < XIdlMethod > > (); } virtual Reference< XIdlArray > SAL_CALL getArray( ) throw(RuntimeException) { return Reference < XIdlArray > (); } virtual void SAL_CALL createObject( Any& obj ) throw(RuntimeException) {} private: OUString m_sImplementationName; Sequence < OUString > m_seqSupportedInterface; Sequence < Reference < XIdlClass > > m_seqSuperClasses; Reference < XMultiServiceFactory > m_rSMgr; Reference< XIdlReflection > m_xCorefl; Reference< XIdlReflection > const & get_corefl() SAL_THROW( (RuntimeException) ); }; Reference< XIdlReflection > const & OStdIdlClass::get_corefl() SAL_THROW( (RuntimeException) ) { if (! m_xCorefl.is()) { if( m_rSMgr.is() ) { Reference< beans::XPropertySet > xProps( m_rSMgr, UNO_QUERY ); OSL_ASSERT( xProps.is() ); if (xProps.is()) { Reference< XComponentContext > xContext; xProps->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM("DefaultContext") ) ) >>= xContext; OSL_ASSERT( xContext.is() ); if (xContext.is()) { Reference < XIdlReflection > x; xContext->getValueByName( OUString( RTL_CONSTASCII_USTRINGPARAM("/singletons/com.sun.star.reflection.theCoreReflection") ) ) >>= x; OSL_ENSURE( x.is(), "### CoreReflection singleton not accessable!?" ); if (x.is()) { ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() ); if (! m_xCorefl.is()) { m_xCorefl = x; } } } } } if (! m_xCorefl.is()) { throw DeploymentException( OUString( RTL_CONSTASCII_USTRINGPARAM("/singletons/com.sun.star.reflection.theCoreReflection singleton not accessable") ), Reference< XInterface >() ); } } return m_xCorefl; } OStdIdlClass::OStdIdlClass( const Reference < XMultiServiceFactory > &rSMgr , const OUString & sImplementationName , const Reference < XIdlClass > & rSuperClass, const Sequence < OUString > &seq ) SAL_THROW( () ) : m_rSMgr( rSMgr ) , m_sImplementationName( sImplementationName ) , m_seqSupportedInterface( seq ) { if( rSuperClass.is() ) m_seqSuperClasses = Sequence< Reference < XIdlClass > >( &rSuperClass, 1 ); } Any SAL_CALL OStdIdlClass::queryInterface( const Type & rType ) throw(::com::sun::star::uno::RuntimeException) { Any aRet( ::cppu::queryInterface( rType, static_cast< XIdlClass * >( this ), static_cast< XIdlClassProvider * >( this ) ) ); return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType )); } Sequence< Reference< XIdlClass > > SAL_CALL OStdIdlClass::getInterfaces( ) throw(RuntimeException) { int nMax = m_seqSupportedInterface.getLength(); Reference< XIdlReflection > const & rCoreRefl = get_corefl(); if( rCoreRefl.is() ) { Sequence< Reference< XIdlClass > > seqClasses( nMax ); for( int n = 0 ; n < nMax ; n++ ) { seqClasses.getArray()[n] = rCoreRefl->forName( m_seqSupportedInterface.getArray()[n] ); } return seqClasses; } return Sequence< Reference< XIdlClass > > () ; } // XIdlClassProvider Sequence< Reference < XIdlClass > > SAL_CALL OStdIdlClass::getIdlClasses(void) throw (RuntimeException) { // weak reference to cache the standard class static WeakReference< XIdlClass > weakRef; // try to make weakref hard Reference < XIdlClass > r = weakRef; if( ! r.is() ) { // xidlclass has not been initialized before or has been destroyed already. r = ::cppu::createStandardClass( m_rSMgr , OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.cppuhelper.OStdIdlClass") ) , Reference < XIdlClass > () , SAL_STATIC_CAST( XIdlClassProvider * , this ) , SAL_STATIC_CAST( XIdlClass * , this ) ); // store reference for later use weakRef = r; } return Sequence < Reference < XIdlClass > > ( &r , 1 ); } // external constructor XIdlClass * SAL_CALL createStandardClassWithSequence( const Reference < XMultiServiceFactory > &rSMgr , const OUString & sImplementationName , const Reference < XIdlClass > & rSuperClass, const Sequence < OUString > &seqInterfaceNames ) SAL_THROW( () ) { return SAL_STATIC_CAST( XIdlClass * , new OStdIdlClass( rSMgr , sImplementationName, rSuperClass, seqInterfaceNames ) ); } } //end namespace cppu <commit_msg>INTEGRATION: CWS ooo20040329 (1.4.98); FILE MERGED 2004/03/17 11:49:16 waratah 1.4.98.1: #i1858# alter the order of some definitions to fix some -Wall warnings correct spelling mistake in code<commit_after>/************************************************************************* * * $RCSfile: stdidlclass.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: svesik $ $Date: 2004-04-21 14:08:04 $ * * 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 <osl/mutex.hxx> #include <cppuhelper/weakref.hxx> #include <cppuhelper/weak.hxx> #include <cppuhelper/stdidlclass.hxx> #include <com/sun/star/reflection/XIdlClassProvider.hpp> #include <com/sun/star/reflection/XIdlReflection.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/uno/DeploymentException.hpp> #include <com/sun/star/beans/XPropertySet.hpp> using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::reflection; using namespace rtl; namespace cppu { /*--------------------------------------------------------- * This helper class implements XIdlClass. Is used by * createStdIdlClass() *---------------------------------------------------------*/ class OStdIdlClass : public OWeakObject, public XIdlClass, public XIdlClassProvider { public: OStdIdlClass( const Reference < XMultiServiceFactory > &rSMgr , const OUString & sImplementationName , const Reference < XIdlClass > & rSuperClass, const Sequence < OUString > &seq ) SAL_THROW( () ); // XInterface Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); void SAL_CALL acquire() throw() { OWeakObject::acquire(); } void SAL_CALL release() throw() { OWeakObject::release(); } // XIdlClassProvider Sequence< Reference < XIdlClass > > SAL_CALL getIdlClasses(void) throw (RuntimeException); // XIdlClass virtual Sequence< Reference< XIdlClass > > SAL_CALL getClasses( ) throw(RuntimeException) { return Sequence < Reference < XIdlClass > > (); } virtual Reference< XIdlClass > SAL_CALL getClass( const ::rtl::OUString& aName ) throw(RuntimeException) { return Reference < XIdlClass > (); } virtual sal_Bool SAL_CALL equals( const Reference< XIdlClass >& Type ) throw(RuntimeException) { return getName() == Type->getName(); } virtual sal_Bool SAL_CALL isAssignableFrom( const Reference< XIdlClass >& xType ) throw(RuntimeException) { return equals( xType ); } virtual TypeClass SAL_CALL getTypeClass( ) throw(RuntimeException) { return TypeClass_UNKNOWN; } virtual OUString SAL_CALL getName( ) throw(RuntimeException) { return m_sImplementationName; } virtual Uik SAL_CALL getUik( ) throw(RuntimeException) { return Uik(); } virtual Sequence< Reference< XIdlClass > > SAL_CALL getSuperclasses( ) throw(RuntimeException) { return m_seqSuperClasses; } virtual Sequence< Reference< XIdlClass > > SAL_CALL getInterfaces( ) throw(RuntimeException); virtual Reference< XIdlClass > SAL_CALL getComponentType( ) throw(RuntimeException) { return Reference < XIdlClass > (); } virtual Reference< XIdlField > SAL_CALL getField( const ::rtl::OUString& aName ) throw(RuntimeException) { return Reference < XIdlField > (); } virtual Sequence< Reference< XIdlField > > SAL_CALL getFields( ) throw(RuntimeException) { return Sequence< Reference < XIdlField > > (); } virtual Reference< XIdlMethod > SAL_CALL getMethod( const ::rtl::OUString& aName ) throw(RuntimeException) { return Reference < XIdlMethod > (); } virtual Sequence< Reference< XIdlMethod > > SAL_CALL getMethods( ) throw(RuntimeException) { return Sequence < Reference < XIdlMethod > > (); } virtual Reference< XIdlArray > SAL_CALL getArray( ) throw(RuntimeException) { return Reference < XIdlArray > (); } virtual void SAL_CALL createObject( Any& obj ) throw(RuntimeException) {} private: OUString m_sImplementationName; Sequence < OUString > m_seqSupportedInterface; Sequence < Reference < XIdlClass > > m_seqSuperClasses; Reference < XMultiServiceFactory > m_rSMgr; Reference< XIdlReflection > m_xCorefl; Reference< XIdlReflection > const & get_corefl() SAL_THROW( (RuntimeException) ); }; Reference< XIdlReflection > const & OStdIdlClass::get_corefl() SAL_THROW( (RuntimeException) ) { if (! m_xCorefl.is()) { if( m_rSMgr.is() ) { Reference< beans::XPropertySet > xProps( m_rSMgr, UNO_QUERY ); OSL_ASSERT( xProps.is() ); if (xProps.is()) { Reference< XComponentContext > xContext; xProps->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM("DefaultContext") ) ) >>= xContext; OSL_ASSERT( xContext.is() ); if (xContext.is()) { Reference < XIdlReflection > x; xContext->getValueByName( OUString( RTL_CONSTASCII_USTRINGPARAM("/singletons/com.sun.star.reflection.theCoreReflection") ) ) >>= x; OSL_ENSURE( x.is(), "### CoreReflection singleton not accessible!?" ); if (x.is()) { ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() ); if (! m_xCorefl.is()) { m_xCorefl = x; } } } } } if (! m_xCorefl.is()) { throw DeploymentException( OUString( RTL_CONSTASCII_USTRINGPARAM("/singletons/com.sun.star.reflection.theCoreReflection singleton not accessible") ), Reference< XInterface >() ); } } return m_xCorefl; } OStdIdlClass::OStdIdlClass( const Reference < XMultiServiceFactory > &rSMgr , const OUString & sImplementationName , const Reference < XIdlClass > & rSuperClass, const Sequence < OUString > &seq ) SAL_THROW( () ) : m_sImplementationName( sImplementationName ) , m_seqSupportedInterface( seq ), m_rSMgr( rSMgr ) { if( rSuperClass.is() ) m_seqSuperClasses = Sequence< Reference < XIdlClass > >( &rSuperClass, 1 ); } Any SAL_CALL OStdIdlClass::queryInterface( const Type & rType ) throw(::com::sun::star::uno::RuntimeException) { Any aRet( ::cppu::queryInterface( rType, static_cast< XIdlClass * >( this ), static_cast< XIdlClassProvider * >( this ) ) ); return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType )); } Sequence< Reference< XIdlClass > > SAL_CALL OStdIdlClass::getInterfaces( ) throw(RuntimeException) { int nMax = m_seqSupportedInterface.getLength(); Reference< XIdlReflection > const & rCoreRefl = get_corefl(); if( rCoreRefl.is() ) { Sequence< Reference< XIdlClass > > seqClasses( nMax ); for( int n = 0 ; n < nMax ; n++ ) { seqClasses.getArray()[n] = rCoreRefl->forName( m_seqSupportedInterface.getArray()[n] ); } return seqClasses; } return Sequence< Reference< XIdlClass > > () ; } // XIdlClassProvider Sequence< Reference < XIdlClass > > SAL_CALL OStdIdlClass::getIdlClasses(void) throw (RuntimeException) { // weak reference to cache the standard class static WeakReference< XIdlClass > weakRef; // try to make weakref hard Reference < XIdlClass > r = weakRef; if( ! r.is() ) { // xidlclass has not been initialized before or has been destroyed already. r = ::cppu::createStandardClass( m_rSMgr , OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.cppuhelper.OStdIdlClass") ) , Reference < XIdlClass > () , SAL_STATIC_CAST( XIdlClassProvider * , this ) , SAL_STATIC_CAST( XIdlClass * , this ) ); // store reference for later use weakRef = r; } return Sequence < Reference < XIdlClass > > ( &r , 1 ); } // external constructor XIdlClass * SAL_CALL createStandardClassWithSequence( const Reference < XMultiServiceFactory > &rSMgr , const OUString & sImplementationName , const Reference < XIdlClass > & rSuperClass, const Sequence < OUString > &seqInterfaceNames ) SAL_THROW( () ) { return SAL_STATIC_CAST( XIdlClass * , new OStdIdlClass( rSMgr , sImplementationName, rSuperClass, seqInterfaceNames ) ); } } //end namespace cppu <|endoftext|>
<commit_before> #include "PointSetTopology.h" #include "PointSetTopology.inl" #include "Sofa/Components/Common/Vec3Types.h" #include "Sofa/Components/Common/ObjectFactory.h" namespace Sofa { namespace Components { using namespace Common; SOFA_DECL_CLASS(PointSetTopology) template class PointSetTopology<Vec3dTypes>; template class PointSetTopology<Vec3fTypes>; template class PointSetGeometryAlgorithms<Vec3fTypes>; template class PointSetGeometryAlgorithms<Vec3dTypes>; PointSetTopologyContainer::PointSetTopologyContainer(Core::BasicTopology *top) : Core::TopologyContainer(top) { } PointSetTopologyContainer::PointSetTopologyContainer(Core::BasicTopology *top, const std::vector<unsigned int>& DOFIndex) : Core::TopologyContainer(top), m_DOFIndex(DOFIndex) { } void PointSetTopologyContainer::createPointSetIndex() { // resizing m_PointSetIndex.resize( m_basicTopology->getDOFNumber() ); // initializing for (unsigned int i = 0; i < m_PointSetIndex.size(); ++i) m_PointSetIndex[i] = -1; // overwriting defined DOFs indices for (unsigned int i = 0; i < m_DOFIndex.size(); ++i) { m_PointSetIndex[ m_DOFIndex[i] ] = i; } } const std::vector<int> &PointSetTopologyContainer::getPointSetIndexArray() { if (!m_PointSetIndex.size()) createPointSetIndex(); return m_PointSetIndex; } int PointSetTopologyContainer::getPointSetIndex(const unsigned int i) { if (!m_PointSetIndex.size()) createPointSetIndex(); return m_PointSetIndex[i]; } unsigned int PointSetTopologyContainer::getNumberOfVertices() const { return m_DOFIndex.size(); } const std::vector<unsigned int> &PointSetTopologyContainer::getDOFIndexArray() const { return m_DOFIndex; } std::vector<unsigned int> &PointSetTopologyContainer::getDOFIndexArray() { return m_DOFIndex; } unsigned int PointSetTopologyContainer::getDOFIndex(const int i) const { return m_DOFIndex[i]; } template<class DataTypes> void create(PointSetTopology<DataTypes>*& obj, ObjectDescription* arg) { XML::createWithParent< PointSetTopology<DataTypes>, Core::MechanicalObject<DataTypes> >(obj, arg); if (obj!=NULL) { } } Creator<ObjectFactory, PointSetTopology<Vec3dTypes> > PointSetTopologyVec3dClass("PointSetTopology", true); Creator<ObjectFactory, PointSetTopology<Vec3fTypes> > PointSetTopologyVec3fClass("PointSetTopology", true); } // namespace Components } // namespace Sofa <commit_msg>r691/sofa-dev : Now PointSetTopology can be loaded from a file and updates the DOFs stored in MechanicalObject Debugged most of modifiers functions<commit_after> #include "PointSetTopology.h" #include "PointSetTopology.inl" #include "Sofa/Components/Common/Vec3Types.h" #include "Sofa/Components/Common/ObjectFactory.h" namespace Sofa { namespace Components { using namespace Common; SOFA_DECL_CLASS(PointSetTopology) template class PointSetTopology<Vec3dTypes>; template class PointSetTopology<Vec3fTypes>; template class PointSetGeometryAlgorithms<Vec3fTypes>; template class PointSetGeometryAlgorithms<Vec3dTypes>; PointSetTopologyContainer::PointSetTopologyContainer(Core::BasicTopology *top) : Core::TopologyContainer(top) { } PointSetTopologyContainer::PointSetTopologyContainer(Core::BasicTopology *top, const std::vector<unsigned int>& DOFIndex) : Core::TopologyContainer(top), m_DOFIndex(DOFIndex) { } void PointSetTopologyContainer::createPointSetIndex() { // resizing m_PointSetIndex.resize( m_basicTopology->getDOFNumber() ); // initializing for (unsigned int i = 0; i < m_PointSetIndex.size(); ++i) m_PointSetIndex[i] = -1; // overwriting defined DOFs indices for (unsigned int i = 0; i < m_DOFIndex.size(); ++i) { m_PointSetIndex[ m_DOFIndex[i] ] = i; } } const std::vector<int> &PointSetTopologyContainer::getPointSetIndexArray() { if (!m_PointSetIndex.size()) createPointSetIndex(); return m_PointSetIndex; } unsigned int PointSetTopologyContainer::getPointSetIndexSize() const { return m_PointSetIndex.size(); } std::vector<int> &PointSetTopologyContainer::getPointSetIndexArrayForModification() { if (!m_PointSetIndex.size()) createPointSetIndex(); return m_PointSetIndex; } int PointSetTopologyContainer::getPointSetIndex(const unsigned int i) { if (!m_PointSetIndex.size()) createPointSetIndex(); return m_PointSetIndex[i]; } unsigned int PointSetTopologyContainer::getNumberOfVertices() const { return m_DOFIndex.size(); } const std::vector<unsigned int> &PointSetTopologyContainer::getDOFIndexArray() const { return m_DOFIndex; } std::vector<unsigned int> &PointSetTopologyContainer::getDOFIndexArrayForModification() { return m_DOFIndex; } unsigned int PointSetTopologyContainer::getDOFIndex(const int i) const { return m_DOFIndex[i]; } template<class DataTypes> void create(PointSetTopology<DataTypes>*& obj, ObjectDescription* arg) { XML::createWithParent< PointSetTopology<DataTypes>, Core::MechanicalObject<DataTypes> >(obj, arg); if (obj!=NULL) { } } Creator<ObjectFactory, PointSetTopology<Vec3dTypes> > PointSetTopologyVec3dClass("PointSetTopology", true); Creator<ObjectFactory, PointSetTopology<Vec3fTypes> > PointSetTopologyVec3fClass("PointSetTopology", true); } // namespace Components } // namespace Sofa <|endoftext|>
<commit_before>/* Blink Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "sdkconfig.h" #include <cmath> #define ms(x) (x/portTICK_PERIOD_MS) #define DUMP_VAR_f(x) \ printf("%s:%d:%s=<%f>",__FILE__,__LINE__,#x,x) static const int iConstSampleRate = 50; static const int iConstSampleDelay = 1000/iConstSampleRate; static const double pi = std::acos(-1); static char signal(int counter) { double x = 2 * pi * (double)counter/(double)50; double y = sin(x); DUMP_VAR_f(x); DUMP_VAR_f(y); return y *127; } static int gSamplerCounter = 0; void signal_generator_task(void *pvParameter) { while(true) { auto sign = signal(gSamplerCounter++%iConstSampleRate); vTaskDelay(ms(iConstSampleDelay)); } } extern "C" void signal_generator_app_main() { xTaskCreate(&signal_generator_task, "signal_generator_task", 512, NULL, 5, NULL); } <commit_msg>Update signal.generator.cpp<commit_after>/* Blink Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "sdkconfig.h" #include <cmath> #define ms(x) (x/portTICK_PERIOD_MS) #define DUMP_VAR_f(x) \ printf("%s:%d:%s=<%f>",__FILE__,__LINE__,#x,x) static const int iConstSampleRate = 10; static const int iConstSampleDelay = 1000/iConstSampleRate; static const double pi = std::acos(-1); static char signal(int counter) { double x = 2 * pi * (double)counter/(double)50; double y = sin(x); DUMP_VAR_f(x); DUMP_VAR_f(y); return y *127; } static int gSamplerCounter = 0; void signal_generator_task(void *pvParameter) { while(true) { auto sign = signal(gSamplerCounter++%iConstSampleRate); vTaskDelay(ms(iConstSampleDelay)); } } extern "C" void signal_generator_app_main() { xTaskCreate(&signal_generator_task, "signal_generator_task", 512, NULL, 5, NULL); } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <sstream> #include <ios> #include <rang.hpp> #include "Tools/Exception/exception.hpp" #include "Tools/Noise/noise_utils.h" #include "Terminal_BFER.hpp" using namespace aff3ct; using namespace aff3ct::tools; template <typename B, typename R> Terminal_BFER<B,R> ::Terminal_BFER(const module::Monitor_BFER<B,R> &monitor, bool display_mutinfo) : Terminal ( ), monitor (monitor ), t_snr (std::chrono::steady_clock::now()), real_time_state(0 ), n (nullptr ), display_mutinfo(display_mutinfo ) { } template <typename B, typename R> void Terminal_BFER<B,R> ::set_noise(const Noise<float>& noise) { if (this->n != nullptr) delete this->n; this->n = tools::cast<float>(noise); } template <typename B, typename R> void Terminal_BFER<B,R> ::set_noise(const Noise<double>& noise) { if (this->n != nullptr) delete this->n; this->n = tools::cast<float>(noise); } template <typename B, typename R> void Terminal_BFER<B,R> ::legend(std::ostream &stream) { this->cols_groups.resize(2); auto& bfer_title = this->cols_groups[0].first; auto& bfer_cols = this->cols_groups[0].second; auto& throughput_title = this->cols_groups[1].first; auto& throughput_cols = this->cols_groups[1].second; bfer_title = std::make_pair("Bit Error Rate (BER) and Frame Error Rate (FER)", ""); if (this->n == nullptr) { std::stringstream message; message << "Undefined noise."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } switch (this->n->get_type()) { case Noise_type::SIGMA : bfer_title.second = "depending on the Signal Noise Ratio (SNR)"; bfer_cols.push_back(std::make_pair("Es/N0", "(dB)")); bfer_cols.push_back(std::make_pair("Eb/N0", "(dB)")); break; case Noise_type::ROP : bfer_title.second = "depending on the Received Optical Power (ROP)"; bfer_cols.push_back(std::make_pair("ROP", "(dB)")); break; case Noise_type::EP : bfer_title.second = "depending on the Erasure Probability (EP)"; bfer_cols.push_back(std::make_pair("EP", "")); break; } if (display_mutinfo) { bfer_title.first = "MutInfo (MI), " + bfer_title.first; bfer_cols.push_back(std::make_pair("MI", "")); } bfer_cols.push_back(std::make_pair("FRA", "")); bfer_cols.push_back(std::make_pair("BE", "")); bfer_cols.push_back(std::make_pair("FE", "")); bfer_cols.push_back(std::make_pair("BER", "")); bfer_cols.push_back(std::make_pair("FER", "")); throughput_title = std::make_pair("Global throughput", "and elapsed time"); throughput_cols.push_back(std::make_pair("SIM_THR", "(Mb/s)")); throughput_cols.push_back(std::make_pair("ET/RT", "(hhmmss)")); // stream << "# " << "---------------------------------------------------------------------||---------------------" << std::endl; // stream << "# " << " Bit Error Rate (BER) and Frame Error Rate (FER) depending || Global throughput " << std::endl; // stream << "# " << " on the Erasure Probability (EP) || and elapsed time " << std::endl; // stream << "# " << "---------------------------------------------------------------------||---------------------" << std::endl; // stream << "# " << "---------|-----------|-----------|-----------|-----------|-----------||----------|----------" << std::endl; // stream << "# " << " EP | FRA | BE | FE | BER | FER || SIM_THR | ET/RT " << std::endl; // stream << "# " << " | | | | | || (Mb/s) | (hhmmss) " << std::endl; // stream << "# " << "---------|-----------|-----------|-----------|-----------|-----------||----------|----------" << std::endl; Terminal::legend(stream); // print effectively the legend } template <typename B, typename R> void Terminal_BFER<B,R> ::_report(std::ostream &stream) { using namespace std::chrono; using namespace std; auto ber = monitor.get_ber(); auto fer = monitor.get_fer(); auto fra = monitor.get_n_analyzed_fra(); auto be = monitor.get_n_be(); auto fe = monitor.get_n_fe(); auto MI = monitor.get_MI (); auto simu_time = (float)duration_cast<nanoseconds>(steady_clock::now() - t_snr).count() * 0.000000001f; auto simu_cthr = ((float)monitor.get_K() * (float)monitor.get_n_analyzed_fra()) / simu_time ; // = bps simu_cthr /= 1000.f; // = kbps simu_cthr /= 1000.f; // = mbps if (module::Monitor::is_interrupt()) stream << "\r"; stream << data_tag; const auto report_style = rang::style::bold; if (this->n == nullptr) { std::stringstream message; message << "Undefined noise."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } switch (this->n->get_type()) { case Noise_type::SIGMA : { auto sig = dynamic_cast<const tools::Sigma<>*>(this->n); stream << setprecision(2) << fixed << setw(column_width - 1) << sig->get_esn0() << report_style << spaced_scol_separator << rang::style::reset; stream << setprecision(2) << fixed << setw(column_width - 1) << sig->get_ebn0() << report_style << spaced_scol_separator << rang::style::reset; break; } case Noise_type::ROP : { stream << setprecision(2) << fixed << setw(column_width - 1) << this->n->get_noise() << report_style << spaced_scol_separator << rang::style::reset; break; } case Noise_type::EP : { stream << setprecision(4) << fixed << setw(column_width - 1) << this->n->get_noise() << report_style << spaced_scol_separator << rang::style::reset; break; } } stringstream str_ber, str_fer, str_MI; str_ber << setprecision(2) << scientific << setw(column_width-1) << ber; str_fer << setprecision(2) << scientific << setw(column_width-1) << fer; str_MI << setprecision(2) << scientific << setw(column_width-1) << MI; const unsigned long long l = 99999999; // limit 0 if (display_mutinfo) stream << str_MI.str() << report_style << spaced_scol_separator << rang::style::reset; stream << setprecision((fra > l) ? 2 : 0) << ((fra > l) ? scientific : fixed) << setw(column_width-1) << ((fra > l) ? (float)fra : fra) << report_style << spaced_scol_separator << rang::style::reset; stream << setprecision(( be > l) ? 2 : 0) << ((be > l) ? scientific : fixed) << setw(column_width-1) << (( be > l) ? (float) be : be) << report_style << spaced_scol_separator << rang::style::reset; stream << setprecision(( fe > l) ? 2 : 0) << ((fe > l) ? scientific : fixed) << setw(column_width-1) << (( fe > l) ? (float) fe : fe) << report_style << spaced_scol_separator << rang::style::reset; stream << str_ber.str() << report_style << spaced_scol_separator << rang::style::reset; stream << str_fer.str() << report_style << spaced_dcol_separator << rang::style::reset; stream << setprecision( 2) << fixed << setw(column_width-1) << simu_cthr; } template <typename B, typename R> void Terminal_BFER<B,R> ::temp_report(std::ostream &stream) { using namespace std::chrono; std::ios::fmtflags f(stream.flags()); _report(stream); auto et = duration_cast<milliseconds>(steady_clock::now() - t_snr).count() / 1000.f; auto tr = et * ((float)monitor.get_fe_limit() / (float)monitor.get_n_fe()) - et; auto tr_format = get_time_format((monitor.get_n_fe() == 0) ? 0 : tr); stream << rang::style::bold << spaced_scol_separator << rang::style::reset << std::setprecision(0) << std::fixed << std::setw(column_width-1) << tr_format; stream << " "; switch (real_time_state) { case 0: stream << rang::style::bold << rang::fg::green << "*" << rang::style::reset; break; case 1: stream << rang::style::bold << rang::fg::green << "*" << rang::style::reset; break; case 2: stream << rang::style::bold << rang::fg::green << " " << rang::style::reset; break; case 3: stream << rang::style::bold << rang::fg::green << " " << rang::style::reset; break; default: break; } real_time_state = (real_time_state + (unsigned short)1) % (unsigned short)4; stream << "\r"; stream.flush(); stream.flags(f); } template <typename B, typename R> void Terminal_BFER<B,R> ::final_report(std::ostream &stream) { using namespace std::chrono; std::ios::fmtflags f(stream.flags()); Terminal::final_report(stream); this->_report(stream); auto et = duration_cast<milliseconds>(steady_clock::now() - t_snr).count() / 1000.f; auto et_format = get_time_format(et); stream << rang::style::bold << spaced_scol_separator << rang::style::reset << std::setprecision(0) << std::fixed << std::setw(column_width-1) << et_format; stream << (module::Monitor::is_interrupt() ? " x" : " ") << std::endl; t_snr = std::chrono::steady_clock::now(); stream.flags(f); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::tools::Terminal_BFER<B_8, Q_8>; template class aff3ct::tools::Terminal_BFER<B_16,Q_16>; template class aff3ct::tools::Terminal_BFER<B_32,Q_32>; template class aff3ct::tools::Terminal_BFER<B_64,Q_64>; #else template class aff3ct::tools::Terminal_BFER<B,Q>; #endif // ==================================================================================== explicit template instantiation <commit_msg>Do not display the last line when killing the simulation (Monisot::is_over)<commit_after>#include <iostream> #include <iomanip> #include <sstream> #include <ios> #include <rang.hpp> #include "Tools/Exception/exception.hpp" #include "Tools/Noise/noise_utils.h" #include "Terminal_BFER.hpp" using namespace aff3ct; using namespace aff3ct::tools; template <typename B, typename R> Terminal_BFER<B,R> ::Terminal_BFER(const module::Monitor_BFER<B,R> &monitor, bool display_mutinfo) : Terminal ( ), monitor (monitor ), t_snr (std::chrono::steady_clock::now()), real_time_state(0 ), n (nullptr ), display_mutinfo(display_mutinfo ) { } template <typename B, typename R> void Terminal_BFER<B,R> ::set_noise(const Noise<float>& noise) { if (this->n != nullptr) delete this->n; this->n = tools::cast<float>(noise); } template <typename B, typename R> void Terminal_BFER<B,R> ::set_noise(const Noise<double>& noise) { if (this->n != nullptr) delete this->n; this->n = tools::cast<float>(noise); } template <typename B, typename R> void Terminal_BFER<B,R> ::legend(std::ostream &stream) { this->cols_groups.resize(2); auto& bfer_title = this->cols_groups[0].first; auto& bfer_cols = this->cols_groups[0].second; auto& throughput_title = this->cols_groups[1].first; auto& throughput_cols = this->cols_groups[1].second; bfer_title = std::make_pair("Bit Error Rate (BER) and Frame Error Rate (FER)", ""); if (this->n == nullptr) { std::stringstream message; message << "Undefined noise."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } switch (this->n->get_type()) { case Noise_type::SIGMA : bfer_title.second = "depending on the Signal Noise Ratio (SNR)"; bfer_cols.push_back(std::make_pair("Es/N0", "(dB)")); bfer_cols.push_back(std::make_pair("Eb/N0", "(dB)")); break; case Noise_type::ROP : bfer_title.second = "depending on the Received Optical Power (ROP)"; bfer_cols.push_back(std::make_pair("ROP", "(dB)")); break; case Noise_type::EP : bfer_title.second = "depending on the Erasure Probability (EP)"; bfer_cols.push_back(std::make_pair("EP", "")); break; } if (display_mutinfo) { bfer_title.first = "MutInfo (MI), " + bfer_title.first; bfer_cols.push_back(std::make_pair("MI", "")); } bfer_cols.push_back(std::make_pair("FRA", "")); bfer_cols.push_back(std::make_pair("BE", "")); bfer_cols.push_back(std::make_pair("FE", "")); bfer_cols.push_back(std::make_pair("BER", "")); bfer_cols.push_back(std::make_pair("FER", "")); throughput_title = std::make_pair("Global throughput", "and elapsed time"); throughput_cols.push_back(std::make_pair("SIM_THR", "(Mb/s)")); throughput_cols.push_back(std::make_pair("ET/RT", "(hhmmss)")); // stream << "# " << "---------------------------------------------------------------------||---------------------" << std::endl; // stream << "# " << " Bit Error Rate (BER) and Frame Error Rate (FER) depending || Global throughput " << std::endl; // stream << "# " << " on the Erasure Probability (EP) || and elapsed time " << std::endl; // stream << "# " << "---------------------------------------------------------------------||---------------------" << std::endl; // stream << "# " << "---------|-----------|-----------|-----------|-----------|-----------||----------|----------" << std::endl; // stream << "# " << " EP | FRA | BE | FE | BER | FER || SIM_THR | ET/RT " << std::endl; // stream << "# " << " | | | | | || (Mb/s) | (hhmmss) " << std::endl; // stream << "# " << "---------|-----------|-----------|-----------|-----------|-----------||----------|----------" << std::endl; Terminal::legend(stream); // print effectively the legend } template <typename B, typename R> void Terminal_BFER<B,R> ::_report(std::ostream &stream) { using namespace std::chrono; using namespace std; auto ber = monitor.get_ber(); auto fer = monitor.get_fer(); auto fra = monitor.get_n_analyzed_fra(); auto be = monitor.get_n_be(); auto fe = monitor.get_n_fe(); auto MI = monitor.get_MI (); auto simu_time = (float)duration_cast<nanoseconds>(steady_clock::now() - t_snr).count() * 0.000000001f; auto simu_cthr = ((float)monitor.get_K() * (float)monitor.get_n_analyzed_fra()) / simu_time ; // = bps simu_cthr /= 1000.f; // = kbps simu_cthr /= 1000.f; // = mbps if (module::Monitor::is_interrupt()) stream << "\r"; stream << data_tag; const auto report_style = rang::style::bold; if (this->n == nullptr) { std::stringstream message; message << "Undefined noise."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } switch (this->n->get_type()) { case Noise_type::SIGMA : { auto sig = dynamic_cast<const tools::Sigma<>*>(this->n); stream << setprecision(2) << fixed << setw(column_width - 1) << sig->get_esn0() << report_style << spaced_scol_separator << rang::style::reset; stream << setprecision(2) << fixed << setw(column_width - 1) << sig->get_ebn0() << report_style << spaced_scol_separator << rang::style::reset; break; } case Noise_type::ROP : { stream << setprecision(2) << fixed << setw(column_width - 1) << this->n->get_noise() << report_style << spaced_scol_separator << rang::style::reset; break; } case Noise_type::EP : { stream << setprecision(4) << fixed << setw(column_width - 1) << this->n->get_noise() << report_style << spaced_scol_separator << rang::style::reset; break; } } stringstream str_ber, str_fer, str_MI; str_ber << setprecision(2) << scientific << setw(column_width-1) << ber; str_fer << setprecision(2) << scientific << setw(column_width-1) << fer; str_MI << setprecision(2) << scientific << setw(column_width-1) << MI; const unsigned long long l = 99999999; // limit 0 if (display_mutinfo) stream << str_MI.str() << report_style << spaced_scol_separator << rang::style::reset; stream << setprecision((fra > l) ? 2 : 0) << ((fra > l) ? scientific : fixed) << setw(column_width-1) << ((fra > l) ? (float)fra : fra) << report_style << spaced_scol_separator << rang::style::reset; stream << setprecision(( be > l) ? 2 : 0) << ((be > l) ? scientific : fixed) << setw(column_width-1) << (( be > l) ? (float) be : be) << report_style << spaced_scol_separator << rang::style::reset; stream << setprecision(( fe > l) ? 2 : 0) << ((fe > l) ? scientific : fixed) << setw(column_width-1) << (( fe > l) ? (float) fe : fe) << report_style << spaced_scol_separator << rang::style::reset; stream << str_ber.str() << report_style << spaced_scol_separator << rang::style::reset; stream << str_fer.str() << report_style << spaced_dcol_separator << rang::style::reset; stream << setprecision( 2) << fixed << setw(column_width-1) << simu_cthr; } template <typename B, typename R> void Terminal_BFER<B,R> ::temp_report(std::ostream &stream) { using namespace std::chrono; std::ios::fmtflags f(stream.flags()); _report(stream); auto et = duration_cast<milliseconds>(steady_clock::now() - t_snr).count() / 1000.f; auto tr = et * ((float)monitor.get_fe_limit() / (float)monitor.get_n_fe()) - et; auto tr_format = get_time_format((monitor.get_n_fe() == 0) ? 0 : tr); stream << rang::style::bold << spaced_scol_separator << rang::style::reset << std::setprecision(0) << std::fixed << std::setw(column_width-1) << tr_format; stream << " "; switch (real_time_state) { case 0: stream << rang::style::bold << rang::fg::green << "*" << rang::style::reset; break; case 1: stream << rang::style::bold << rang::fg::green << "*" << rang::style::reset; break; case 2: stream << rang::style::bold << rang::fg::green << " " << rang::style::reset; break; case 3: stream << rang::style::bold << rang::fg::green << " " << rang::style::reset; break; default: break; } real_time_state = (real_time_state + (unsigned short)1) % (unsigned short)4; stream << "\r"; stream.flush(); stream.flags(f); } template <typename B, typename R> void Terminal_BFER<B,R> ::final_report(std::ostream &stream) { using namespace std::chrono; std::ios::fmtflags f(stream.flags()); Terminal::final_report(stream); auto et = duration_cast<milliseconds>(steady_clock::now() - t_snr).count() / 1000.f; if (!module::Monitor::is_over() || et >= 1.f) { this->_report(stream); auto et_format = get_time_format(et); stream << rang::style::bold << spaced_scol_separator << rang::style::reset << std::setprecision(0) << std::fixed << std::setw(column_width - 1) << et_format; stream << (module::Monitor::is_interrupt() ? " x" : " ") << std::endl; } t_snr = std::chrono::steady_clock::now(); stream.flags(f); } // ==================================================================================== explicit template instantiation #include "Tools/types.h" #ifdef MULTI_PREC template class aff3ct::tools::Terminal_BFER<B_8, Q_8>; template class aff3ct::tools::Terminal_BFER<B_16,Q_16>; template class aff3ct::tools::Terminal_BFER<B_32,Q_32>; template class aff3ct::tools::Terminal_BFER<B_64,Q_64>; #else template class aff3ct::tools::Terminal_BFER<B,Q>; #endif // ==================================================================================== explicit template instantiation <|endoftext|>
<commit_before>#pragma once #include <string> #include <unordered_map> #include <Utility/Timer/Include/Measure/MeasureInfo.hpp> namespace Utility { namespace Timer { class MeasureTimer { public: /** Gets an instance of this object, if no instance exists, it creates one. */ static MeasureTimer& GetInstance(); /** Gets a timer with a given name */ MeasureInfo& GetTimer(const std::string& p_name); /** */ void MeasureTimer::AddChildToParent(const std::string& p_parent, const std::string& p_child); /** TODORT docs */ void DumpData(const std::string& p_origin); protected: MeasureTimer(); MeasureTimer(MeasureTimer const&) = delete; void operator=(MeasureTimer const&) = delete; void DumpChildrenData(const std::string& p_origin, const MeasureInfo& p_parent, const size_t& p_index); std::unordered_map<std::string, MeasureInfo> m_timers; }; } } <commit_msg>Added macros for measuring functions<commit_after>#pragma once #include <string> #include <unordered_map> #include <Utility/Timer/Include/Measure/MeasureInfo.hpp> #define FILE_AND_FUNC std::string(__FILE__) + ":" + std::string(__func__) #define TIMING #ifdef TIMING #define TIME_FUNCTION_START Utility::Timer::MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Start(); #define TIME_FUNCTION_STOP Utility::Timer::MeasureTimer::GetInstance().GetTimer(FILE_AND_FUNC).Stop(); #else #define TIME_FUNCTION_START ; #define TIME_FUNCTION_STOP ; #endif namespace Utility { namespace Timer { class MeasureTimer { public: /** Gets an instance of this object, if no instance exists, it creates one. */ static MeasureTimer& GetInstance(); /** Gets a timer with a given name */ MeasureInfo& GetTimer(const std::string& p_name); /** */ void MeasureTimer::AddChildToParent(const std::string& p_parent, const std::string& p_child); /** TODORT docs */ void DumpData(const std::string& p_origin); protected: MeasureTimer(); MeasureTimer(MeasureTimer const&) = delete; void operator=(MeasureTimer const&) = delete; void DumpChildrenData(const std::string& p_origin, const MeasureInfo& p_parent, const size_t& p_index); std::unordered_map<std::string, MeasureInfo> m_timers; }; } } <|endoftext|>
<commit_before>/* Copyright (c) 2015 Diego Ongaro * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <unistd.h> #include "build/Protocol/ServerControl.pb.h" #include "Core/Debug.h" #include "RPC/ServerRPC.h" #include "Server/ControlService.h" #include "Server/Globals.h" #include "Server/RaftConsensus.h" #include "Server/StateMachine.h" namespace LogCabin { namespace Server { ControlService::ControlService(Globals& globals) : globals(globals) { } ControlService::~ControlService() { } void ControlService::handleRPC(RPC::ServerRPC rpc) { using Protocol::ServerControl::OpCode; // Call the appropriate RPC handler based on the request's opCode. switch (rpc.getOpCode()) { case OpCode::DEBUG_FILENAME_GET: debugFilenameGet(std::move(rpc)); break; case OpCode::DEBUG_FILENAME_SET: debugFilenameSet(std::move(rpc)); break; case OpCode::DEBUG_POLICY_GET: debugPolicyGet(std::move(rpc)); break; case OpCode::DEBUG_POLICY_SET: debugPolicySet(std::move(rpc)); break; case OpCode::DEBUG_ROTATE: debugRotate(std::move(rpc)); break; case OpCode::SERVER_INFO_GET: serverInfoGet(std::move(rpc)); break; case OpCode::SERVER_STATS_DUMP: serverStatsDump(std::move(rpc)); break; case OpCode::SERVER_STATS_GET: serverStatsGet(std::move(rpc)); break; case OpCode::SNAPSHOT_CONTROL: snapshotControl(std::move(rpc)); break; case OpCode::SNAPSHOT_INHIBIT_GET: snapshotInhibitGet(std::move(rpc)); break; case OpCode::SNAPSHOT_INHIBIT_SET: snapshotInhibitSet(std::move(rpc)); break; default: WARNING("Client sent request with bad op code (%u) to " "ControlService", rpc.getOpCode()); rpc.rejectInvalidRequest(); } } std::string ControlService::getName() const { return "ControlService"; } /** * Place this at the top of each RPC handler. Afterwards, 'request' will refer * to the protocol buffer for the request with all required fields set. * 'response' will be an empty protocol buffer for you to fill in the response. */ #define PRELUDE(rpcClass) \ Protocol::ServerControl::rpcClass::Request request; \ Protocol::ServerControl::rpcClass::Response response; \ if (!rpc.getRequest(request)) \ return; ////////// RPC handlers ////////// void ControlService::debugFilenameGet(RPC::ServerRPC rpc) { PRELUDE(DebugFilenameGet); response.set_filename(Core::Debug::getLogFilename()); rpc.reply(response); } void ControlService::debugFilenameSet(RPC::ServerRPC rpc) { PRELUDE(DebugFilenameSet); std::string prev = Core::Debug::getLogFilename(); NOTICE("Switching to log file %s", request.filename().c_str()); std::string error = Core::Debug::setLogFilename(request.filename()); if (error.empty()) { NOTICE("Switched from log file %s", prev.c_str()); } else { ERROR("Failed to switch to log file %s: %s", request.filename().c_str(), error.c_str()); response.set_error(error); } rpc.reply(response); } void ControlService::debugPolicyGet(RPC::ServerRPC rpc) { PRELUDE(DebugPolicyGet); response.set_policy( Core::Debug::logPolicyToString( Core::Debug::getLogPolicy())); rpc.reply(response); } void ControlService::debugPolicySet(RPC::ServerRPC rpc) { PRELUDE(DebugPolicySet); NOTICE("Switching to log policy %s", request.policy().c_str()); Core::Debug::setLogPolicy( Core::Debug::logPolicyFromString( request.policy())); rpc.reply(response); } void ControlService::debugRotate(RPC::ServerRPC rpc) { PRELUDE(DebugRotate); NOTICE("Rotating logs"); std::string error = Core::Debug::reopenLogFromFilename(); if (error.empty()) { NOTICE("Done rotating logs"); } else { ERROR("Failed to rotate log file: %s", error.c_str()); response.set_error(error); } rpc.reply(response); } void ControlService::serverInfoGet(RPC::ServerRPC rpc) { PRELUDE(ServerInfoGet); response.set_server_id(globals.raft->serverId); response.set_addresses(globals.raft->serverAddresses); response.set_process_id(uint64_t(getpid())); rpc.reply(response); } void ControlService::serverStatsDump(RPC::ServerRPC rpc) { PRELUDE(ServerStatsDump); NOTICE("Requested dump of ServerStats through ServerControl RPC"); globals.serverStats.dumpToDebugLog(); rpc.reply(response); } void ControlService::serverStatsGet(RPC::ServerRPC rpc) { PRELUDE(ServerStatsGet); *response.mutable_server_stats() = globals.serverStats.getCurrent(); rpc.reply(response); } void ControlService::snapshotControl(RPC::ServerRPC rpc) { PRELUDE(SnapshotControl); using Protocol::ServerControl::SnapshotCommand; switch (request.command()) { case SnapshotCommand::START_SNAPSHOT: globals.stateMachine->startTakingSnapshot(); break; case SnapshotCommand::STOP_SNAPSHOT: globals.stateMachine->stopTakingSnapshot(); break; case SnapshotCommand::RESTART_SNAPSHOT: globals.stateMachine->stopTakingSnapshot(); globals.stateMachine->startTakingSnapshot(); break; case SnapshotCommand::UNKNOWN_SNAPSHOT_COMMAND: // fallthrough default: response.set_error("Unknown SnapshotControl command"); } rpc.reply(response); } void ControlService::snapshotInhibitGet(RPC::ServerRPC rpc) { PRELUDE(SnapshotInhibitGet); std::chrono::nanoseconds duration = globals.stateMachine->getInhibit(); assert(duration >= std::chrono::nanoseconds::zero()); response.set_nanoseconds(uint64_t(duration.count())); rpc.reply(response); } void ControlService::snapshotInhibitSet(RPC::ServerRPC rpc) { PRELUDE(SnapshotInhibitSet); bool abort = false; std::chrono::nanoseconds duration; if (request.has_nanoseconds()) { duration = std::chrono::nanoseconds(request.nanoseconds()); if (request.nanoseconds() > 0 && duration < std::chrono::nanoseconds::zero()) { // overflow duration = std::chrono::nanoseconds::max(); } if (request.nanoseconds() == 0) abort = false; } else { duration = std::chrono::nanoseconds::max(); } globals.stateMachine->setInhibit(duration); if (abort) { globals.stateMachine->stopTakingSnapshot(); } rpc.reply(response); } } // namespace LogCabin::Server } // namespace LogCabin <commit_msg>Fix aborting snapshots<commit_after>/* Copyright (c) 2015 Diego Ongaro * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <unistd.h> #include "build/Protocol/ServerControl.pb.h" #include "Core/Debug.h" #include "RPC/ServerRPC.h" #include "Server/ControlService.h" #include "Server/Globals.h" #include "Server/RaftConsensus.h" #include "Server/StateMachine.h" namespace LogCabin { namespace Server { ControlService::ControlService(Globals& globals) : globals(globals) { } ControlService::~ControlService() { } void ControlService::handleRPC(RPC::ServerRPC rpc) { using Protocol::ServerControl::OpCode; // Call the appropriate RPC handler based on the request's opCode. switch (rpc.getOpCode()) { case OpCode::DEBUG_FILENAME_GET: debugFilenameGet(std::move(rpc)); break; case OpCode::DEBUG_FILENAME_SET: debugFilenameSet(std::move(rpc)); break; case OpCode::DEBUG_POLICY_GET: debugPolicyGet(std::move(rpc)); break; case OpCode::DEBUG_POLICY_SET: debugPolicySet(std::move(rpc)); break; case OpCode::DEBUG_ROTATE: debugRotate(std::move(rpc)); break; case OpCode::SERVER_INFO_GET: serverInfoGet(std::move(rpc)); break; case OpCode::SERVER_STATS_DUMP: serverStatsDump(std::move(rpc)); break; case OpCode::SERVER_STATS_GET: serverStatsGet(std::move(rpc)); break; case OpCode::SNAPSHOT_CONTROL: snapshotControl(std::move(rpc)); break; case OpCode::SNAPSHOT_INHIBIT_GET: snapshotInhibitGet(std::move(rpc)); break; case OpCode::SNAPSHOT_INHIBIT_SET: snapshotInhibitSet(std::move(rpc)); break; default: WARNING("Client sent request with bad op code (%u) to " "ControlService", rpc.getOpCode()); rpc.rejectInvalidRequest(); } } std::string ControlService::getName() const { return "ControlService"; } /** * Place this at the top of each RPC handler. Afterwards, 'request' will refer * to the protocol buffer for the request with all required fields set. * 'response' will be an empty protocol buffer for you to fill in the response. */ #define PRELUDE(rpcClass) \ Protocol::ServerControl::rpcClass::Request request; \ Protocol::ServerControl::rpcClass::Response response; \ if (!rpc.getRequest(request)) \ return; ////////// RPC handlers ////////// void ControlService::debugFilenameGet(RPC::ServerRPC rpc) { PRELUDE(DebugFilenameGet); response.set_filename(Core::Debug::getLogFilename()); rpc.reply(response); } void ControlService::debugFilenameSet(RPC::ServerRPC rpc) { PRELUDE(DebugFilenameSet); std::string prev = Core::Debug::getLogFilename(); NOTICE("Switching to log file %s", request.filename().c_str()); std::string error = Core::Debug::setLogFilename(request.filename()); if (error.empty()) { NOTICE("Switched from log file %s", prev.c_str()); } else { ERROR("Failed to switch to log file %s: %s", request.filename().c_str(), error.c_str()); response.set_error(error); } rpc.reply(response); } void ControlService::debugPolicyGet(RPC::ServerRPC rpc) { PRELUDE(DebugPolicyGet); response.set_policy( Core::Debug::logPolicyToString( Core::Debug::getLogPolicy())); rpc.reply(response); } void ControlService::debugPolicySet(RPC::ServerRPC rpc) { PRELUDE(DebugPolicySet); NOTICE("Switching to log policy %s", request.policy().c_str()); Core::Debug::setLogPolicy( Core::Debug::logPolicyFromString( request.policy())); rpc.reply(response); } void ControlService::debugRotate(RPC::ServerRPC rpc) { PRELUDE(DebugRotate); NOTICE("Rotating logs"); std::string error = Core::Debug::reopenLogFromFilename(); if (error.empty()) { NOTICE("Done rotating logs"); } else { ERROR("Failed to rotate log file: %s", error.c_str()); response.set_error(error); } rpc.reply(response); } void ControlService::serverInfoGet(RPC::ServerRPC rpc) { PRELUDE(ServerInfoGet); response.set_server_id(globals.raft->serverId); response.set_addresses(globals.raft->serverAddresses); response.set_process_id(uint64_t(getpid())); rpc.reply(response); } void ControlService::serverStatsDump(RPC::ServerRPC rpc) { PRELUDE(ServerStatsDump); NOTICE("Requested dump of ServerStats through ServerControl RPC"); globals.serverStats.dumpToDebugLog(); rpc.reply(response); } void ControlService::serverStatsGet(RPC::ServerRPC rpc) { PRELUDE(ServerStatsGet); *response.mutable_server_stats() = globals.serverStats.getCurrent(); rpc.reply(response); } void ControlService::snapshotControl(RPC::ServerRPC rpc) { PRELUDE(SnapshotControl); using Protocol::ServerControl::SnapshotCommand; switch (request.command()) { case SnapshotCommand::START_SNAPSHOT: globals.stateMachine->startTakingSnapshot(); break; case SnapshotCommand::STOP_SNAPSHOT: globals.stateMachine->stopTakingSnapshot(); break; case SnapshotCommand::RESTART_SNAPSHOT: globals.stateMachine->stopTakingSnapshot(); globals.stateMachine->startTakingSnapshot(); break; case SnapshotCommand::UNKNOWN_SNAPSHOT_COMMAND: // fallthrough default: response.set_error("Unknown SnapshotControl command"); } rpc.reply(response); } void ControlService::snapshotInhibitGet(RPC::ServerRPC rpc) { PRELUDE(SnapshotInhibitGet); std::chrono::nanoseconds duration = globals.stateMachine->getInhibit(); assert(duration >= std::chrono::nanoseconds::zero()); response.set_nanoseconds(uint64_t(duration.count())); rpc.reply(response); } void ControlService::snapshotInhibitSet(RPC::ServerRPC rpc) { PRELUDE(SnapshotInhibitSet); bool abort = true; std::chrono::nanoseconds duration; if (request.has_nanoseconds()) { duration = std::chrono::nanoseconds(request.nanoseconds()); if (request.nanoseconds() > 0 && duration < std::chrono::nanoseconds::zero()) { // overflow duration = std::chrono::nanoseconds::max(); } if (request.nanoseconds() == 0) abort = false; } else { duration = std::chrono::nanoseconds::max(); } globals.stateMachine->setInhibit(duration); if (abort) { globals.stateMachine->stopTakingSnapshot(); } rpc.reply(response); } } // namespace LogCabin::Server } // namespace LogCabin <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited // // 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. // // Has to be first, to avoid redefinition warnings. #include "boost/python/detail/wrap_python.hpp" // appleseed.python headers. #include "gil_locks.h" // appleseed.renderer headers. #include "renderer/kernel/rendering/defaultrenderercontroller.h" #include "renderer/kernel/rendering/irenderercontroller.h" // appleseed.foundation headers. #include "foundation/platform/python.h" namespace bpy = boost::python; using namespace foundation; using namespace renderer; namespace detail { class IRendererControllerWrapper : public IRendererController , public bpy::wrapper<IRendererController> { public: virtual void on_rendering_begin() { // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_rendering_begin")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual void on_rendering_success() { // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_rendering_success")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual void on_rendering_abort() { // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_rendering_abort")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual void on_frame_begin() { // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_frame_begin")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual void on_frame_end() { // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_frame_end")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual Status on_progress() { // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { return get_override("on_progress")(); } catch (bpy::error_already_set) { PyErr_Print(); return AbortRendering; } } }; } void bind_renderer_controller() { bpy::enum_<IRendererController::Status>("IRenderControllerStatus") .value("ContinueRendering", IRendererController::ContinueRendering) .value("TerminateRendering", IRendererController::TerminateRendering) .value("AbortRendering", IRendererController::AbortRendering) .value("RestartRendering", IRendererController::RestartRendering) .value("ReinitializeRendering", IRendererController::ReinitializeRendering) ; bpy::class_<detail::IRendererControllerWrapper, boost::noncopyable>("IRendererController") .def("on_rendering_begin", bpy::pure_virtual(&IRendererController::on_rendering_begin)) .def("on_rendering_success", bpy::pure_virtual(&IRendererController::on_rendering_success)) .def("on_rendering_abort", bpy::pure_virtual(&IRendererController::on_rendering_abort)) .def("on_frame_begin", bpy::pure_virtual(&IRendererController::on_frame_begin)) .def("on_frame_end", bpy::pure_virtual(&IRendererController::on_frame_end)) .def("on_progress", bpy::pure_virtual(&IRendererController::on_progress)) ; bpy::class_<DefaultRendererController, boost::noncopyable>("DefaultRendererController") ; } <commit_msg>All python render controllers now inherit the functionality of DefaultRenderController<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited // // 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. // // Has to be first, to avoid redefinition warnings. #include "boost/python/detail/wrap_python.hpp" // appleseed.python headers. #include "gil_locks.h" // appleseed.renderer headers. #include "renderer/kernel/rendering/defaultrenderercontroller.h" #include "renderer/kernel/rendering/irenderercontroller.h" // appleseed.foundation headers. #include "foundation/platform/python.h" namespace bpy = boost::python; using namespace foundation; using namespace renderer; namespace detail { class IRendererControllerWrapper : public IRendererController , public bpy::wrapper<IRendererController> { public: virtual void on_rendering_begin() { m_base_controller.on_rendering_begin(); // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_rendering_begin")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual void on_rendering_success() { m_base_controller.on_rendering_success(); // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_rendering_success")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual void on_rendering_abort() { m_base_controller.on_rendering_abort(); // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_rendering_abort")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual void on_frame_begin() { m_base_controller.on_frame_begin(); // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_frame_begin")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual void on_frame_end() { m_base_controller.on_frame_end(); // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { get_override("on_frame_end")(); } catch (bpy::error_already_set) { PyErr_Print(); } } virtual Status on_progress() { m_base_controller.on_progress(); // Lock Python's global interpreter lock (GIL), // was released in MasterRenderer.render. ScopedGILLock lock; try { return get_override("on_progress")(); } catch (bpy::error_already_set) { PyErr_Print(); return AbortRendering; } } private: renderer::DefaultRendererController m_base_controller; }; } void bind_renderer_controller() { bpy::enum_<IRendererController::Status>("IRenderControllerStatus") .value("ContinueRendering", IRendererController::ContinueRendering) .value("TerminateRendering", IRendererController::TerminateRendering) .value("AbortRendering", IRendererController::AbortRendering) .value("RestartRendering", IRendererController::RestartRendering) .value("ReinitializeRendering", IRendererController::ReinitializeRendering) ; bpy::class_<detail::IRendererControllerWrapper, boost::noncopyable>("IRendererController") .def("on_rendering_begin", bpy::pure_virtual(&IRendererController::on_rendering_begin)) .def("on_rendering_success", bpy::pure_virtual(&IRendererController::on_rendering_success)) .def("on_rendering_abort", bpy::pure_virtual(&IRendererController::on_rendering_abort)) .def("on_frame_begin", bpy::pure_virtual(&IRendererController::on_frame_begin)) .def("on_frame_end", bpy::pure_virtual(&IRendererController::on_frame_end)) .def("on_progress", bpy::pure_virtual(&IRendererController::on_progress)) ; bpy::class_<DefaultRendererController, boost::noncopyable>("DefaultRendererController") ; } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // 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. // // appleseed.renderer headers. #include "renderer/global/globaltypes.h" #include "renderer/kernel/intersection/intersector.h" #include "renderer/kernel/intersection/tracecontext.h" #include "renderer/kernel/lighting/tracer.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/texturing/texturecache.h" #include "renderer/modeling/color/colorentity.h" #include "renderer/modeling/input/inputbinder.h" #include "renderer/modeling/material/material.h" #include "renderer/modeling/object/meshobject.h" #include "renderer/modeling/object/triangle.h" #include "renderer/modeling/scene/assembly.h" #include "renderer/modeling/scene/assemblyinstance.h" #include "renderer/modeling/scene/objectinstance.h" #include "renderer/modeling/scene/scene.h" #include "renderer/modeling/surfaceshader/constantsurfaceshader.h" #include "renderer/modeling/surfaceshader/surfaceshader.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/image/color.h" #include "foundation/math/matrix.h" #include "foundation/math/rng.h" #include "foundation/math/transform.h" #include "foundation/math/vector.h" #include "foundation/utility/containers/specializedarrays.h" #include "foundation/utility/autoreleaseptr.h" #include "foundation/utility/test.h" // Standard headers. #include <cstddef> #include <string> using namespace foundation; using namespace renderer; using namespace std; TEST_SUITE(Renderer_Kernel_Lighting_Tracer) { struct SceneBase { auto_release_ptr<Scene> m_scene; SceneBase() : m_scene(SceneFactory::create()) { create_assembly(); create_assembly_instance(); create_plane_object(); create_opaque_material(); create_transparent_material(); } void create_assembly() { m_scene->assemblies().insert( AssemblyFactory::create("assembly", ParamArray())); } void create_assembly_instance() { const Assembly* assembly = m_scene->assemblies().get_by_name("assembly"); m_scene->assembly_instances().insert( AssemblyInstanceFactory::create( "assembly_inst", *assembly, Transformd(Matrix4d::identity()))); } void create_plane_object() { auto_release_ptr<MeshObject> mesh_object = MeshObjectFactory::create("plane", ParamArray()); mesh_object->push_vertex(GVector3(0.0f, -0.5f, -0.5f)); mesh_object->push_vertex(GVector3(0.0f, +0.5f, -0.5f)); mesh_object->push_vertex(GVector3(0.0f, +0.5f, +0.5f)); mesh_object->push_vertex(GVector3(0.0f, -0.5f, +0.5f)); mesh_object->push_vertex_normal(GVector3(1.0f, 0.0f, 0.0f)); mesh_object->push_triangle(Triangle(0, 1, 2, 0, 0, 0, 0)); mesh_object->push_triangle(Triangle(2, 3, 0, 0, 0, 0, 0)); auto_release_ptr<Object> object(mesh_object.release()); m_scene->assemblies().get_by_name("assembly")->objects().insert(object); } void create_plane_object_instance(const char* name, const Vector3d& position, const char* material_name) { const Assembly* assembly = m_scene->assemblies().get_by_name("assembly"); Object* object = assembly->objects().get_by_name("plane"); StringArray material_names; material_names.push_back(material_name); assembly->object_instances().insert( ObjectInstanceFactory::create( name, ParamArray(), *object, Transformd(Matrix4d::translation(position)), material_names)); } void create_color(const char* name, const Color4f& color) { ParamArray params; params.insert("color_space", "linear_rgb"); const ColorValueArray color_values(3, &color[0]); const ColorValueArray alpha_values(1, &color[3]); m_scene->assemblies().get_by_name("assembly")->colors().insert( ColorEntityFactory::create(name, params, color_values, alpha_values)); } void create_constant_surface_shader(const char* surface_shader_name, const char* color_name) { ParamArray params; params.insert("color", color_name); ConstantSurfaceShaderFactory factory; auto_release_ptr<SurfaceShader> surface_shader(factory.create(surface_shader_name, params)); m_scene->assemblies().get_by_name("assembly")->surface_shaders().insert(surface_shader); } void create_material(const char* material_name, const char* surface_shader_name) { ParamArray params; params.insert("surface_shader", surface_shader_name); m_scene->assemblies().get_by_name("assembly")->materials().insert( MaterialFactory::create(material_name, params)); } void create_opaque_material() { create_color("opaque_color", Color4f(1.0f, 1.0f, 1.0f, 1.0f)); create_constant_surface_shader("opaque_surface_shader", "opaque_color"); create_material("opaque_material", "opaque_surface_shader"); } void create_transparent_material() { create_color("transparent_color", Color4f(1.0f, 1.0f, 1.0f, 0.5f)); create_constant_surface_shader("transparent_surface_shader", "transparent_color"); create_material("transparent_material", "transparent_surface_shader"); } }; template <typename Base> struct Fixture : public Base { TraceContext m_trace_context; Intersector m_intersector; TextureCache m_texture_cache; MersenneTwister m_rng; SamplingContext m_sampling_context; Tracer m_tracer; Fixture() : m_trace_context(Base::m_scene.ref()) , m_intersector(m_trace_context) , m_texture_cache(Base::m_scene.ref(), 1024 * 16) , m_sampling_context(m_rng, 0, 0, 0) , m_tracer(m_intersector, m_texture_cache) { InputBinder input_binder; input_binder.bind(Base::m_scene.ref()); } }; struct EmptyScene : public SceneBase { }; TEST_CASE_F(Trace_GivenOriginAndDirection_NoOccluder, Fixture<EmptyScene>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace( m_sampling_context, Vector3d(0.0), Vector3d(1.0, 0.0, 0.0), transmission); EXPECT_FALSE(shading_point.hit()); EXPECT_EQ(1.0, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_NoOccluder, Fixture<EmptyScene>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(5.0, 0.0, 0.0), transmission); EXPECT_FALSE(shading_point.hit()); EXPECT_EQ(1.0, transmission); } struct SceneWithSingleOpaqueOccluder : public SceneBase { SceneWithSingleOpaqueOccluder() { create_plane_object_instance("plane_inst", Vector3d(2.0, 0.0, 0.0), "opaque_material"); } }; TEST_CASE_F(Trace_GivenOriginAndDirection_SingleOpaqueOccluder, Fixture<SceneWithSingleOpaqueOccluder>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 0.0, 0.0), transmission); ASSERT_TRUE(shading_point.hit()); EXPECT_FEQ(Vector3d(2.0, 0.0, 0.0), shading_point.get_point()); EXPECT_EQ(1.0, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_SingleOpaqueOccluder, Fixture<SceneWithSingleOpaqueOccluder>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(5.0, 0.0, 0.0), transmission); ASSERT_TRUE(shading_point.hit()); EXPECT_FEQ(Vector3d(2.0, 0.0, 0.0), shading_point.get_point()); EXPECT_EQ(1.0, transmission); } struct SceneWithSingleTransparentOccluder : public SceneBase { SceneWithSingleTransparentOccluder() { create_plane_object_instance("plane_inst", Vector3d(2.0, 0.0, 0.0), "transparent_material"); } }; TEST_CASE_F(Trace_GivenOriginAndDirection_SingleTransparentOccluder, Fixture<SceneWithSingleTransparentOccluder>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 0.0, 0.0), transmission); ASSERT_FALSE(shading_point.hit()); EXPECT_FEQ(0.5, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_SingleTransparentOccluder, Fixture<SceneWithSingleTransparentOccluder>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(5.0, 0.0, 0.0), transmission); ASSERT_FALSE(shading_point.hit()); EXPECT_FEQ(0.5, transmission); } struct SceneWithTransparentThenOpaqueOccluders : public SceneBase { SceneWithTransparentThenOpaqueOccluders() { create_plane_object_instance("plane_inst1", Vector3d(2.0, 0.0, 0.0), "transparent_material"); create_plane_object_instance("plane_inst2", Vector3d(4.0, 0.0, 0.0), "opaque_material"); } }; TEST_CASE_F(Trace_GivenOriginAndDirection_TransparentThenOpaqueOccluders, Fixture<SceneWithTransparentThenOpaqueOccluders>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 0.0, 0.0), transmission); ASSERT_TRUE(shading_point.hit()); EXPECT_FEQ(Vector3d(4.0, 0.0, 0.0), shading_point.get_point()); EXPECT_FEQ(0.5, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_TransparentThenOpaqueOccluders_TargetPastOpaqueOccluder, Fixture<SceneWithTransparentThenOpaqueOccluders>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(5.0, 0.0, 0.0), transmission); ASSERT_TRUE(shading_point.hit()); EXPECT_FEQ(Vector3d(4.0, 0.0, 0.0), shading_point.get_point()); EXPECT_FEQ(0.5, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_TransparentThenOpaqueOccluders_TargetOnOpaqueOccluder, Fixture<SceneWithTransparentThenOpaqueOccluders>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(4.0, 0.0, 0.0), transmission); ASSERT_FALSE(shading_point.hit()); EXPECT_FEQ(0.5, transmission); } } <commit_msg>fixed renderer::Tracer unit tests: now that surfaces can have different materials on the front and back sides, make sure we hit the front side of the occluders.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // 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. // // appleseed.renderer headers. #include "renderer/global/globaltypes.h" #include "renderer/kernel/intersection/intersector.h" #include "renderer/kernel/intersection/tracecontext.h" #include "renderer/kernel/lighting/tracer.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/texturing/texturecache.h" #include "renderer/modeling/color/colorentity.h" #include "renderer/modeling/input/inputbinder.h" #include "renderer/modeling/material/material.h" #include "renderer/modeling/object/meshobject.h" #include "renderer/modeling/object/triangle.h" #include "renderer/modeling/scene/assembly.h" #include "renderer/modeling/scene/assemblyinstance.h" #include "renderer/modeling/scene/objectinstance.h" #include "renderer/modeling/scene/scene.h" #include "renderer/modeling/surfaceshader/constantsurfaceshader.h" #include "renderer/modeling/surfaceshader/surfaceshader.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/image/color.h" #include "foundation/math/matrix.h" #include "foundation/math/rng.h" #include "foundation/math/transform.h" #include "foundation/math/vector.h" #include "foundation/utility/containers/specializedarrays.h" #include "foundation/utility/autoreleaseptr.h" #include "foundation/utility/test.h" // Standard headers. #include <cstddef> #include <string> using namespace foundation; using namespace renderer; using namespace std; TEST_SUITE(Renderer_Kernel_Lighting_Tracer) { struct SceneBase { auto_release_ptr<Scene> m_scene; SceneBase() : m_scene(SceneFactory::create()) { create_assembly(); create_assembly_instance(); create_plane_object(); create_opaque_material(); create_transparent_material(); } void create_assembly() { m_scene->assemblies().insert( AssemblyFactory::create("assembly", ParamArray())); } void create_assembly_instance() { const Assembly* assembly = m_scene->assemblies().get_by_name("assembly"); m_scene->assembly_instances().insert( AssemblyInstanceFactory::create( "assembly_inst", *assembly, Transformd(Matrix4d::identity()))); } void create_plane_object() { auto_release_ptr<MeshObject> mesh_object = MeshObjectFactory::create("plane", ParamArray()); mesh_object->push_vertex(GVector3(0.0f, -0.5f, -0.5f)); mesh_object->push_vertex(GVector3(0.0f, +0.5f, -0.5f)); mesh_object->push_vertex(GVector3(0.0f, +0.5f, +0.5f)); mesh_object->push_vertex(GVector3(0.0f, -0.5f, +0.5f)); mesh_object->push_vertex_normal(GVector3(-1.0f, 0.0f, 0.0f)); mesh_object->push_triangle(Triangle(0, 1, 2, 0, 0, 0, 0)); mesh_object->push_triangle(Triangle(2, 3, 0, 0, 0, 0, 0)); auto_release_ptr<Object> object(mesh_object.release()); m_scene->assemblies().get_by_name("assembly")->objects().insert(object); } void create_plane_object_instance(const char* name, const Vector3d& position, const char* material_name) { const Assembly* assembly = m_scene->assemblies().get_by_name("assembly"); Object* object = assembly->objects().get_by_name("plane"); StringArray material_names; material_names.push_back(material_name); assembly->object_instances().insert( ObjectInstanceFactory::create( name, ParamArray(), *object, Transformd(Matrix4d::translation(position)), material_names)); } void create_color(const char* name, const Color4f& color) { ParamArray params; params.insert("color_space", "linear_rgb"); const ColorValueArray color_values(3, &color[0]); const ColorValueArray alpha_values(1, &color[3]); m_scene->assemblies().get_by_name("assembly")->colors().insert( ColorEntityFactory::create(name, params, color_values, alpha_values)); } void create_constant_surface_shader(const char* surface_shader_name, const char* color_name) { ParamArray params; params.insert("color", color_name); ConstantSurfaceShaderFactory factory; auto_release_ptr<SurfaceShader> surface_shader(factory.create(surface_shader_name, params)); m_scene->assemblies().get_by_name("assembly")->surface_shaders().insert(surface_shader); } void create_material(const char* material_name, const char* surface_shader_name) { ParamArray params; params.insert("surface_shader", surface_shader_name); m_scene->assemblies().get_by_name("assembly")->materials().insert( MaterialFactory::create(material_name, params)); } void create_opaque_material() { create_color("opaque_color", Color4f(1.0f, 1.0f, 1.0f, 1.0f)); create_constant_surface_shader("opaque_surface_shader", "opaque_color"); create_material("opaque_material", "opaque_surface_shader"); } void create_transparent_material() { create_color("transparent_color", Color4f(1.0f, 1.0f, 1.0f, 0.5f)); create_constant_surface_shader("transparent_surface_shader", "transparent_color"); create_material("transparent_material", "transparent_surface_shader"); } }; template <typename Base> struct Fixture : public Base { TraceContext m_trace_context; Intersector m_intersector; TextureCache m_texture_cache; MersenneTwister m_rng; SamplingContext m_sampling_context; Tracer m_tracer; Fixture() : m_trace_context(Base::m_scene.ref()) , m_intersector(m_trace_context) , m_texture_cache(Base::m_scene.ref(), 1024 * 16) , m_sampling_context(m_rng, 0, 0, 0) , m_tracer(m_intersector, m_texture_cache) { InputBinder input_binder; input_binder.bind(Base::m_scene.ref()); } }; struct EmptyScene : public SceneBase { }; TEST_CASE_F(Trace_GivenOriginAndDirection_NoOccluder, Fixture<EmptyScene>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace( m_sampling_context, Vector3d(0.0), Vector3d(1.0, 0.0, 0.0), transmission); EXPECT_FALSE(shading_point.hit()); EXPECT_EQ(1.0, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_NoOccluder, Fixture<EmptyScene>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(5.0, 0.0, 0.0), transmission); EXPECT_FALSE(shading_point.hit()); EXPECT_EQ(1.0, transmission); } struct SceneWithSingleOpaqueOccluder : public SceneBase { SceneWithSingleOpaqueOccluder() { create_plane_object_instance("plane_inst", Vector3d(2.0, 0.0, 0.0), "opaque_material"); } }; TEST_CASE_F(Trace_GivenOriginAndDirection_SingleOpaqueOccluder, Fixture<SceneWithSingleOpaqueOccluder>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 0.0, 0.0), transmission); ASSERT_TRUE(shading_point.hit()); EXPECT_FEQ(Vector3d(2.0, 0.0, 0.0), shading_point.get_point()); EXPECT_EQ(1.0, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_SingleOpaqueOccluder, Fixture<SceneWithSingleOpaqueOccluder>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(5.0, 0.0, 0.0), transmission); ASSERT_TRUE(shading_point.hit()); EXPECT_FEQ(Vector3d(2.0, 0.0, 0.0), shading_point.get_point()); EXPECT_EQ(1.0, transmission); } struct SceneWithSingleTransparentOccluder : public SceneBase { SceneWithSingleTransparentOccluder() { create_plane_object_instance("plane_inst", Vector3d(2.0, 0.0, 0.0), "transparent_material"); } }; TEST_CASE_F(Trace_GivenOriginAndDirection_SingleTransparentOccluder, Fixture<SceneWithSingleTransparentOccluder>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 0.0, 0.0), transmission); ASSERT_FALSE(shading_point.hit()); EXPECT_FEQ(0.5, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_SingleTransparentOccluder, Fixture<SceneWithSingleTransparentOccluder>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(5.0, 0.0, 0.0), transmission); ASSERT_FALSE(shading_point.hit()); EXPECT_FEQ(0.5, transmission); } struct SceneWithTransparentThenOpaqueOccluders : public SceneBase { SceneWithTransparentThenOpaqueOccluders() { create_plane_object_instance("plane_inst1", Vector3d(2.0, 0.0, 0.0), "transparent_material"); create_plane_object_instance("plane_inst2", Vector3d(4.0, 0.0, 0.0), "opaque_material"); } }; TEST_CASE_F(Trace_GivenOriginAndDirection_TransparentThenOpaqueOccluders, Fixture<SceneWithTransparentThenOpaqueOccluders>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 0.0, 0.0), transmission); ASSERT_TRUE(shading_point.hit()); EXPECT_FEQ(Vector3d(4.0, 0.0, 0.0), shading_point.get_point()); EXPECT_FEQ(0.5, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_TransparentThenOpaqueOccluders_TargetPastOpaqueOccluder, Fixture<SceneWithTransparentThenOpaqueOccluders>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(5.0, 0.0, 0.0), transmission); ASSERT_TRUE(shading_point.hit()); EXPECT_FEQ(Vector3d(4.0, 0.0, 0.0), shading_point.get_point()); EXPECT_FEQ(0.5, transmission); } TEST_CASE_F(TraceBetween_GivenOriginAndTarget_TransparentThenOpaqueOccluders_TargetOnOpaqueOccluder, Fixture<SceneWithTransparentThenOpaqueOccluders>) { double transmission; const ShadingPoint& shading_point = m_tracer.trace_between( m_sampling_context, Vector3d(0.0, 0.0, 0.0), Vector3d(4.0, 0.0, 0.0), transmission); ASSERT_FALSE(shading_point.hit()); EXPECT_FEQ(0.5, transmission); } } <|endoftext|>
<commit_before>#include "chrono_parallel/solver/ChSolverParallel.h" #include <blaze/math/SparseRow.h> #include <blaze/math/CompressedVector.h> using namespace chrono; uint ChSolverParallelGS::Solve(ChShurProduct& ShurProduct, ChProjectConstraints& Project, const uint max_iter, const uint size, const DynamicVector<real>& r, DynamicVector<real>& gamma) { real& residual = data_manager->measures.solver.residual; real& objective_value = data_manager->measures.solver.objective_value; ml = gamma; Project(ml.data()); CompressedMatrix<real> Nshur = data_manager->host_data.D_T * data_manager->host_data.M_invD; for (current_iteration = 0; current_iteration < max_iter; current_iteration++) { real omega = 1.0; for (int i = 0; i < data_manager->num_constraints; ++i) { ml[i] = ml[i] - omega * 1.0 / Nshur(i, i) * ((row(Nshur, i * 1 + 0), blaze::subvector(ml, 0, 1 * data_manager->num_constraints)) + data_manager->host_data.E[i] * ml[i] - r[i]); } Project(ml.data()); gamma = ml; residual = 0; // Res4Blaze(ml, mb); objective_value = 0; // GetObjective(ml, mb); } return current_iteration; } <commit_msg>gauss seidel solver working<commit_after>#include "chrono_parallel/solver/ChSolverParallel.h" #include <blaze/math/SparseRow.h> #include <blaze/math/CompressedVector.h> using namespace chrono; uint ChSolverParallelGS::Solve(ChShurProduct& ShurProduct, ChProjectConstraints& Project, const uint max_iter, const uint size, const DynamicVector<real>& r, DynamicVector<real>& gamma) { real& residual = data_manager->measures.solver.residual; real& objective_value = data_manager->measures.solver.objective_value; ml = gamma; Project(ml.data()); uint num_contacts = data_manager->num_constraints; CompressedMatrix<real> Nshur = data_manager->host_data.D_T * data_manager->host_data.M_invD; DynamicVector<real> D; D.resize(num_contacts, false); for (size_t i = 0; i < num_contacts; ++i) { Nshur(i, i) += data_manager->host_data.E[i]; D[i] = 1.0 / (Nshur(i, i)); } for (current_iteration = 0; current_iteration < max_iter; current_iteration++) { real omega = 1.0; for (int i = 0; i < data_manager->num_constraints; ++i) { ml[i] = ml[i] - omega * D[i] * ((row(Nshur, i * 1 + 0), blaze::subvector(ml, 0, 1 * data_manager->num_constraints)) - r[i]); } Project(ml.data()); gamma = ml; real gdiff = 1.0 / pow(data_manager->num_constraints, 2.0); ShurProduct(gamma, ml_old); objective_value = (ml, (0.5*ml_old - r)); ml_old = ml_old - r; ml_old = gamma - gdiff * (ml_old); Project(ml_old.data()); ml_old = (1.0 / gdiff) * (gamma - ml_old); residual = Sqrt((double)(ml_old, ml_old)); AtIterationEnd(residual, objective_value); } return current_iteration; } <|endoftext|>
<commit_before>#include "WMSTimeDimension.h" #include <boost/algorithm/string/join.hpp> #include <macgyver/StringConversion.h> #include <macgyver/TimeParser.h> namespace SmartMet { namespace Plugin { namespace WMS { namespace { boost::posix_time::ptime parse_time(const std::string& time_string) { if (time_string == "now") return boost::posix_time::second_clock::universal_time(); return Fmi::TimeParser::parse(time_string); } } // namespace void WMSTimeDimension::addTimestep(const boost::posix_time::ptime& timestep) { try { itsTimesteps.insert(timestep); } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to add time step!"); } } void WMSTimeDimension::removeTimestep(const boost::posix_time::ptime& timestep) { try { itsTimesteps.erase(timestep); } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to remove time step!"); } } bool WMSTimeDimension::isValidTime(const boost::posix_time::ptime& theTime) const { // Allow any time within the range if (itsTimesteps.empty()) return false; return (theTime >= *itsTimesteps.cbegin() && theTime <= *itsTimesteps.crbegin()); #if 0 // Allow only listed times try { auto res = itsTimesteps.find(theTime); if (res == itsTimesteps.end()) { return false; } else { return true; } } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to validate time!"); } #endif } std::set<boost::posix_time::ptime> WMSTimeDimension::getTimeSteps() const { return itsTimesteps; } boost::posix_time::ptime WMSTimeDimension::mostCurrentTime() const { try { if (itsTimesteps.size() == 0) return boost::posix_time::not_a_date_time; boost::posix_time::ptime current_time = boost::posix_time::second_clock::universal_time(); // if current time is earlier than first timestep -> return first timestep if (current_time <= *(itsTimesteps.begin())) return *(itsTimesteps.begin()); auto itLastTimestep = itsTimesteps.end(); itLastTimestep--; // if current time is later than last timestep -> return last timestep if (current_time >= *itLastTimestep) return *itLastTimestep; // otherwise iterate timesteps ans find the closest one auto itPrevious = itsTimesteps.begin(); for (auto it = itsTimesteps.begin(); it != itsTimesteps.end(); ++it) { if (*it >= current_time) { // perfect match: current timestep is equal to current time if (*it == current_time) return *it; // check which is closer to current time: current timestep or previous timestep boost::posix_time::time_duration duration_tonext(*it - current_time); boost::posix_time::time_duration duration_toprevious(current_time - *itPrevious); if (duration_toprevious.total_seconds() <= duration_tonext.total_seconds()) return *itPrevious; else return *it; } itPrevious = it; } return boost::posix_time::not_a_date_time; } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to establish most current time!"); } } std::string StepTimeDimension::getCapabilities(const boost::optional<std::string>& starttime, const boost::optional<std::string>& endtime) const { try { std::vector<std::string> ret; ret.reserve(itsTimesteps.size()); boost::posix_time::ptime startt = (starttime ? parse_time(*starttime) : boost::posix_time::min_date_time); boost::posix_time::ptime endt = (endtime ? parse_time(*endtime) : boost::posix_time::max_date_time); for (auto& step : itsTimesteps) { if (step >= startt && step <= endt) ret.push_back(Fmi::to_iso_extended_string(step) + "Z"); if (step > endt) break; } return boost::algorithm::join(ret, ","); } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to extract time dimension capabilities!"); } } IntervalTimeDimension::IntervalTimeDimension(const boost::posix_time::ptime& begin, const boost::posix_time::ptime& end, const boost::posix_time::time_duration& step) : itsInterval(begin, end, step) { } boost::posix_time::ptime IntervalTimeDimension::mostCurrentTime() const { return itsInterval.endTime; } bool IntervalTimeDimension::isValidTime(const boost::posix_time::ptime& theTime) const { return (theTime >= itsInterval.startTime && theTime <= itsInterval.endTime); } IntervalTimeDimension::tag_interval IntervalTimeDimension::getInterval() const { return itsInterval; } std::string IntervalTimeDimension::getCapabilities( const boost::optional<std::string>& starttime, const boost::optional<std::string>& endtime) const { try { if ((starttime && endtime) && parse_time(*starttime) > parse_time(*endtime)) throw Spine::Exception::Trace(BCP, "Requested starttime must be earlier than requested endtime!"); boost::posix_time::ptime startt = itsInterval.startTime; boost::posix_time::ptime endt = itsInterval.endTime; boost::posix_time::ptime requested_startt = (starttime ? parse_time(*starttime) : itsInterval.startTime); boost::posix_time::ptime requested_endt = (endtime ? parse_time(*endtime) : itsInterval.endTime); if (requested_startt > endt || requested_endt < startt) return ""; if (startt < requested_startt) { startt = boost::posix_time::ptime(requested_startt.date(), startt.time_of_day()); boost::posix_time::time_duration resolution = (itsInterval.resolution.total_seconds() == 0 ? boost::posix_time::minutes(1) : itsInterval.resolution); if (startt < requested_startt) { while (startt < requested_startt) startt += resolution; } else if (startt > requested_startt) { while (startt - resolution >= requested_startt) startt -= resolution; } } if (requested_endt < endt) { endt = requested_endt; } std::string ret = Fmi::to_iso_extended_string(startt) + "Z/" + Fmi::to_iso_extended_string(endt) + "Z/PT"; if (itsInterval.resolution.hours() == 0 && itsInterval.resolution.minutes() <= 60) ret += Fmi::to_string(itsInterval.resolution.minutes()) + "M"; else { ret += Fmi::to_string(itsInterval.resolution.hours()) + "H"; if (itsInterval.resolution.minutes() > 0) ret += Fmi::to_string(itsInterval.resolution.minutes()) + "M"; } return ret; } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to generate time dimension capabilities!"); } } std::ostream& operator<<(std::ostream& ost, const StepTimeDimension& timeDimension) { try { auto timesteps = timeDimension.getTimeSteps(); for (auto& step : timesteps) { ost << step << " "; } ost << std::endl; return ost; } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to print step time dimension data!"); } } std::ostream& operator<<(std::ostream& ost, const IntervalTimeDimension& timeDimension) { try { auto interval = timeDimension.getInterval(); ost << interval.startTime << " - " << interval.endTime << " : " << interval.resolution << " "; ost << std::endl; return ost; } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to print time dimension data!"); } } } // namespace WMS } // namespace Plugin } // namespace SmartMet <commit_msg>Use auto to simplify code<commit_after>#include "WMSTimeDimension.h" #include <boost/algorithm/string/join.hpp> #include <macgyver/StringConversion.h> #include <macgyver/TimeParser.h> namespace SmartMet { namespace Plugin { namespace WMS { namespace { boost::posix_time::ptime parse_time(const std::string& time_string) { if (time_string == "now") return boost::posix_time::second_clock::universal_time(); return Fmi::TimeParser::parse(time_string); } } // namespace void WMSTimeDimension::addTimestep(const boost::posix_time::ptime& timestep) { try { itsTimesteps.insert(timestep); } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to add time step!"); } } void WMSTimeDimension::removeTimestep(const boost::posix_time::ptime& timestep) { try { itsTimesteps.erase(timestep); } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to remove time step!"); } } bool WMSTimeDimension::isValidTime(const boost::posix_time::ptime& theTime) const { // Allow any time within the range if (itsTimesteps.empty()) return false; return (theTime >= *itsTimesteps.cbegin() && theTime <= *itsTimesteps.crbegin()); #if 0 // Allow only listed times try { auto res = itsTimesteps.find(theTime); if (res == itsTimesteps.end()) { return false; } else { return true; } } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to validate time!"); } #endif } std::set<boost::posix_time::ptime> WMSTimeDimension::getTimeSteps() const { return itsTimesteps; } boost::posix_time::ptime WMSTimeDimension::mostCurrentTime() const { try { if (itsTimesteps.size() == 0) return boost::posix_time::not_a_date_time; auto current_time = boost::posix_time::second_clock::universal_time(); // if current time is earlier than first timestep -> return first timestep if (current_time <= *(itsTimesteps.begin())) return *(itsTimesteps.begin()); auto itLastTimestep = itsTimesteps.end(); itLastTimestep--; // if current time is later than last timestep -> return last timestep if (current_time >= *itLastTimestep) return *itLastTimestep; // otherwise iterate timesteps ans find the closest one auto itPrevious = itsTimesteps.begin(); for (auto it = itsTimesteps.begin(); it != itsTimesteps.end(); ++it) { if (*it >= current_time) { // perfect match: current timestep is equal to current time if (*it == current_time) return *it; // check which is closer to current time: current timestep or previous timestep auto duration_tonext(*it - current_time); auto duration_toprevious(current_time - *itPrevious); if (duration_toprevious.total_seconds() <= duration_tonext.total_seconds()) return *itPrevious; else return *it; } itPrevious = it; } return boost::posix_time::not_a_date_time; } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to establish most current time!"); } } std::string StepTimeDimension::getCapabilities(const boost::optional<std::string>& starttime, const boost::optional<std::string>& endtime) const { try { std::vector<std::string> ret; ret.reserve(itsTimesteps.size()); auto startt = (starttime ? parse_time(*starttime) : boost::posix_time::min_date_time); auto endt = (endtime ? parse_time(*endtime) : boost::posix_time::max_date_time); for (auto& step : itsTimesteps) { if (step >= startt && step <= endt) ret.push_back(Fmi::to_iso_extended_string(step) + "Z"); if (step > endt) break; } return boost::algorithm::join(ret, ","); } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to extract time dimension capabilities!"); } } IntervalTimeDimension::IntervalTimeDimension(const boost::posix_time::ptime& begin, const boost::posix_time::ptime& end, const boost::posix_time::time_duration& step) : itsInterval(begin, end, step) { } boost::posix_time::ptime IntervalTimeDimension::mostCurrentTime() const { return itsInterval.endTime; } bool IntervalTimeDimension::isValidTime(const boost::posix_time::ptime& theTime) const { return (theTime >= itsInterval.startTime && theTime <= itsInterval.endTime); } IntervalTimeDimension::tag_interval IntervalTimeDimension::getInterval() const { return itsInterval; } std::string IntervalTimeDimension::getCapabilities( const boost::optional<std::string>& starttime, const boost::optional<std::string>& endtime) const { try { if ((starttime && endtime) && parse_time(*starttime) > parse_time(*endtime)) throw Spine::Exception::Trace(BCP, "Requested starttime must be earlier than requested endtime!"); auto startt = itsInterval.startTime; auto endt = itsInterval.endTime; auto requested_startt = (starttime ? parse_time(*starttime) : itsInterval.startTime); auto requested_endt = (endtime ? parse_time(*endtime) : itsInterval.endTime); if (requested_startt > endt || requested_endt < startt) return ""; if (startt < requested_startt) { startt = boost::posix_time::ptime(requested_startt.date(), startt.time_of_day()); auto resolution = (itsInterval.resolution.total_seconds() == 0 ? boost::posix_time::minutes(1) : itsInterval.resolution); if (startt < requested_startt) { while (startt < requested_startt) startt += resolution; } else if (startt > requested_startt) { while (startt - resolution >= requested_startt) startt -= resolution; } } if (requested_endt < endt) { endt = requested_endt; } std::string ret = Fmi::to_iso_extended_string(startt) + "Z/" + Fmi::to_iso_extended_string(endt) + "Z/PT"; if (itsInterval.resolution.hours() == 0 && itsInterval.resolution.minutes() <= 60) ret += Fmi::to_string(itsInterval.resolution.minutes()) + "M"; else { ret += Fmi::to_string(itsInterval.resolution.hours()) + "H"; if (itsInterval.resolution.minutes() > 0) ret += Fmi::to_string(itsInterval.resolution.minutes()) + "M"; } return ret; } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to generate time dimension capabilities!"); } } std::ostream& operator<<(std::ostream& ost, const StepTimeDimension& timeDimension) { try { auto timesteps = timeDimension.getTimeSteps(); for (auto& step : timesteps) { ost << step << " "; } ost << std::endl; return ost; } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to print step time dimension data!"); } } std::ostream& operator<<(std::ostream& ost, const IntervalTimeDimension& timeDimension) { try { auto interval = timeDimension.getInterval(); ost << interval.startTime << " - " << interval.endTime << " : " << interval.resolution << " "; ost << std::endl; return ost; } catch (...) { throw Spine::Exception::Trace(BCP, "Failed to print time dimension data!"); } } } // namespace WMS } // namespace Plugin } // namespace SmartMet <|endoftext|>
<commit_before>#include"myWindow.h" #include <glm/gtc/matrix_transform.hpp> #include<iostream> #define MOUSE_MOVE_HORIZON_ANGLE 90.0f #define MOUSE_MOVE_VERTICAL_ANGLE 60.0f #define KEY_MOVE_PACE 0.1f #define MOUSEWHEEL_MOVE_PACE 0.1f LRESULT CALLBACK defaultCallback(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { myWindow* window = (myWindow*)GetWindowLongPtr(hWnd, 0); switch (msg) { case WM_SIZE: window->width = LOWORD(lParam); window->height = HIWORD(lParam); window->changeSize = true; break; case WM_LBUTTONDOWN: window->bottonClickDown(LOWORD(lParam), HIWORD(lParam)); break; case WM_LBUTTONUP: window->bottonClickUp(); break; case WM_MOUSEMOVE: { int x, y; if (window->getClickedPosition(x, y)) { int position_x = LOWORD(lParam); int position_y = HIWORD(lParam); float vertical = y - position_y; float horizen = x - position_x; float angle_horizen = horizen / ((float)window->width / 2) * MOUSE_MOVE_HORIZON_ANGLE; float angle_vertical = vertical / ((float)window->height / 2) * MOUSE_MOVE_VERTICAL_ANGLE; window->getCamera()->rotate(glm::vec3(glm::radians(angle_vertical), glm::radians(angle_horizen), 0.0)); window->setClickedPosition(position_x, position_y); } break; } case WM_CHAR: switch (wParam) { case 'w': { glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); glm::vec3 forward = glm::normalize(glm::cross(up, right)); window->getCamera()->translate(KEY_MOVE_PACE * forward); break; } case 's': { glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); glm::vec3 forward = glm::normalize(glm::cross(up, right)); window->getCamera()->translate(-KEY_MOVE_PACE * forward); break; } case 'a': { glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); window->getCamera()->translate(-KEY_MOVE_PACE * right); break; } case 'd': { glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); window->getCamera()->translate(KEY_MOVE_PACE * right); break; } default: std::cout << wParam << std::endl; break; } break; case WM_MOUSEWHEEL: { int zDelta = (short)HIWORD(wParam); glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); glm::vec3 forward = glm::normalize(glm::cross(up, right)); window->getCamera()->translate(MOUSEWHEEL_MOVE_PACE * (zDelta / 120) * forward); break; } case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } myWindow::myWindow(const char* WindowName, int Width, int Height) { width = Width; height = Height; if (strlen(WindowName) >= 64) { MessageBox(NULL, TEXT("WindowName is too long, set it to 'Simple Demo' "), NULL, MB_OK); strcpy_s(winName, "Simple Demo"); } else strcpy_s(winName, WindowName); wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = defaultCallback; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = sizeof(void*); wndClass.hInstance = NULL; wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = WindowName; if (!RegisterClass(&wndClass)) { MessageBox(NULL, TEXT("Failed to create!"), WindowName, MB_ICONERROR); return; } hwnd = CreateWindow(WindowName, WindowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, NULL, NULL); SetWindowLongPtr(hwnd, 0, (long)this); camera.setPosition(glm::vec3(1.0, 1.0, 3.0)); botton_click_x = 0; botton_click_y = 0; button_clicked = false; } void myWindow::show() { ShowWindow(hwnd, SW_SHOW); } myWindow::~myWindow() { DestroyWindow(hwnd); UnregisterClass(winName, NULL); } void myWindow::bottonClickDown(int x, int y) { botton_click_x = x; botton_click_y = y; button_clicked = true; } void myWindow::bottonClickUp() { button_clicked = false; } bool myWindow::getClickedPosition(int& x, int& y) { if (!button_clicked) { x = -1; y = -1; } else { x = botton_click_x; y = botton_click_y; } return button_clicked; } bool myWindow::setClickedPosition(int x, int y) { if (!button_clicked) { botton_click_x = -1; botton_click_y = -1; } else { botton_click_y = y; botton_click_x = x; } return button_clicked; } HWND myWindow::getMyWindow() { return this->hwnd; } Camera* myWindow::getCamera() { return &this->camera; }<commit_msg>use LONG_PTR to replace long so that make it works on x64 platform<commit_after>#include"myWindow.h" #include <glm/gtc/matrix_transform.hpp> #include<iostream> #define MOUSE_MOVE_HORIZON_ANGLE 90.0f #define MOUSE_MOVE_VERTICAL_ANGLE 60.0f #define KEY_MOVE_PACE 0.1f #define MOUSEWHEEL_MOVE_PACE 0.1f LRESULT CALLBACK defaultCallback(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { myWindow* window = (myWindow*)GetWindowLongPtr(hWnd, 0); switch (msg) { case WM_SIZE: window->width = LOWORD(lParam); window->height = HIWORD(lParam); window->changeSize = true; break; case WM_LBUTTONDOWN: window->bottonClickDown(LOWORD(lParam), HIWORD(lParam)); break; case WM_LBUTTONUP: window->bottonClickUp(); break; case WM_MOUSEMOVE: { int x, y; if (window->getClickedPosition(x, y)) { int position_x = LOWORD(lParam); int position_y = HIWORD(lParam); float vertical = y - position_y; float horizen = x - position_x; float angle_horizen = horizen / ((float)window->width / 2) * MOUSE_MOVE_HORIZON_ANGLE; float angle_vertical = vertical / ((float)window->height / 2) * MOUSE_MOVE_VERTICAL_ANGLE; window->getCamera()->rotate(glm::vec3(glm::radians(angle_vertical), glm::radians(angle_horizen), 0.0)); window->setClickedPosition(position_x, position_y); } break; } case WM_CHAR: switch (wParam) { case 'w': { glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); glm::vec3 forward = glm::normalize(glm::cross(up, right)); window->getCamera()->translate(KEY_MOVE_PACE * forward); break; } case 's': { glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); glm::vec3 forward = glm::normalize(glm::cross(up, right)); window->getCamera()->translate(-KEY_MOVE_PACE * forward); break; } case 'a': { glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); window->getCamera()->translate(-KEY_MOVE_PACE * right); break; } case 'd': { glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); window->getCamera()->translate(KEY_MOVE_PACE * right); break; } default: std::cout << wParam << std::endl; break; } break; case WM_MOUSEWHEEL: { int zDelta = (short)HIWORD(wParam); glm::vec3 direction = window->getCamera()->getDirection(); glm::vec3 up = glm::vec3(0.0, 1.0, 0.0); glm::vec3 right = glm::cross(direction, up); glm::vec3 forward = glm::normalize(glm::cross(up, right)); window->getCamera()->translate(MOUSEWHEEL_MOVE_PACE * (zDelta / 120) * forward); break; } case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } myWindow::myWindow(const char* WindowName, int Width, int Height) { width = Width; height = Height; if (strlen(WindowName) >= 64) { MessageBox(NULL, TEXT("WindowName is too long, set it to 'Simple Demo' "), NULL, MB_OK); strcpy_s(winName, "Simple Demo"); } else strcpy_s(winName, WindowName); wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = defaultCallback; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = sizeof(void*); wndClass.hInstance = NULL; wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = WindowName; if (!RegisterClass(&wndClass)) { MessageBox(NULL, TEXT("Failed to create!"), WindowName, MB_ICONERROR); return; } hwnd = CreateWindow(WindowName, WindowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, NULL, NULL); SetWindowLongPtr(hwnd, 0, (LONG_PTR)this); camera.setPosition(glm::vec3(1.0, 1.0, 3.0)); botton_click_x = 0; botton_click_y = 0; button_clicked = false; } void myWindow::show() { ShowWindow(hwnd, SW_SHOW); } myWindow::~myWindow() { DestroyWindow(hwnd); UnregisterClass(winName, NULL); } void myWindow::bottonClickDown(int x, int y) { botton_click_x = x; botton_click_y = y; button_clicked = true; } void myWindow::bottonClickUp() { button_clicked = false; } bool myWindow::getClickedPosition(int& x, int& y) { if (!button_clicked) { x = -1; y = -1; } else { x = botton_click_x; y = botton_click_y; } return button_clicked; } bool myWindow::setClickedPosition(int x, int y) { if (!button_clicked) { botton_click_x = -1; botton_click_y = -1; } else { botton_click_y = y; botton_click_x = x; } return button_clicked; } HWND myWindow::getMyWindow() { return this->hwnd; } Camera* myWindow::getCamera() { return &this->camera; }<|endoftext|>
<commit_before>/// HEADER #include "rqt_evaluation.h" /// PROJECT #include <csapex/manager/connection_type_manager.h> #include <csapex/view/designer.h> #include <csapex/model/graph.h> #include <csapex/core/graphio.h> #include <csapex/view/designer_view.h> #include <csapex/view/designer.h> #include <csapex/core/settings.h> #include <csapex/manager/box_manager.h> #include <csapex/view/widget_controller.h> #include <csapex/view/overlay.h> /// SYSTEM #include <pluginlib/class_list_macros.h> #include <QStringList> #include <QMenuBar> #include <QBoxLayout> PLUGINLIB_DECLARE_CLASS(csapex_rqt, CsApex, csapex_rqt::CsApex, rqt_gui_cpp::Plugin) using namespace csapex_rqt; using namespace csapex; CsApex::CsApex() : graph_(new Graph(settings_)), widget_controller_(new csapex::WidgetController(graph_)), dispatcher_(new CommandDispatcher(graph_, widget_controller_)), core_(settings_, graph_, dispatcher_.get()), drag_io_(graph_.get(), dispatcher_.get(), widget_controller_), view_ (new DesignerView(graph_, dispatcher_.get(), widget_controller_, drag_io_)), designer_(new Designer(settings_, graph_, dispatcher_.get(), widget_controller_, view_)) { BoxManager::instance().settings_ = &settings_; widget_controller_->setDesigner(designer_); } CsApex::~CsApex() { delete eva_; } void CsApex::initPlugin(qt_gui_cpp::PluginContext& context) { context_ = &context; eva_ = new CsApexWindow(core_, dispatcher_.get(), widget_controller_, graph_, designer_); // eva_->showMenu(); context_->addWidget(eva_); } void CsApex::shutdownPlugin() { } void CsApex::saveSettings(qt_gui_cpp::Settings& plugin_settings, qt_gui_cpp::Settings& instance_settings) const { instance_settings.setValue("file", core_.getSettings().getConfig().c_str()); } void CsApex::restoreSettings(const qt_gui_cpp::Settings& plugin_settings, const qt_gui_cpp::Settings& instance_settings) { QString file = instance_settings.value("file").toString(); if(!file.isEmpty()) { core_.getSettings().setCurrentConfig(file.toStdString()); eva_->reload(); } } <commit_msg>new view<commit_after>/// HEADER #include "rqt_evaluation.h" /// PROJECT #include <csapex/manager/connection_type_manager.h> #include <csapex/view/designer.h> #include <csapex/model/graph.h> #include <csapex/core/graphio.h> #include <csapex/view/designer_view.h> #include <csapex/view/designer.h> #include <csapex/core/settings.h> #include <csapex/manager/box_manager.h> #include <csapex/view/widget_controller.h> /// SYSTEM #include <pluginlib/class_list_macros.h> #include <QStringList> #include <QMenuBar> #include <QBoxLayout> PLUGINLIB_DECLARE_CLASS(csapex_rqt, CsApex, csapex_rqt::CsApex, rqt_gui_cpp::Plugin) using namespace csapex_rqt; using namespace csapex; CsApex::CsApex() : graph_(new Graph(settings_)), widget_controller_(new csapex::WidgetController(graph_)), dispatcher_(new CommandDispatcher(graph_, widget_controller_)), core_(settings_, graph_, dispatcher_.get()), drag_io_(graph_.get(), dispatcher_.get(), widget_controller_), view_ (new DesignerView(graph_, dispatcher_.get(), widget_controller_, drag_io_)), designer_(new Designer(settings_, graph_, dispatcher_.get(), widget_controller_, view_)) { BoxManager::instance().settings_ = &settings_; widget_controller_->setDesigner(designer_); } CsApex::~CsApex() { delete eva_; } void CsApex::initPlugin(qt_gui_cpp::PluginContext& context) { context_ = &context; eva_ = new CsApexWindow(core_, dispatcher_.get(), widget_controller_, graph_, designer_); // eva_->showMenu(); context_->addWidget(eva_); } void CsApex::shutdownPlugin() { } void CsApex::saveSettings(qt_gui_cpp::Settings& plugin_settings, qt_gui_cpp::Settings& instance_settings) const { instance_settings.setValue("file", core_.getSettings().getConfig().c_str()); } void CsApex::restoreSettings(const qt_gui_cpp::Settings& plugin_settings, const qt_gui_cpp::Settings& instance_settings) { QString file = instance_settings.value("file").toString(); if(!file.isEmpty()) { core_.getSettings().setCurrentConfig(file.toStdString()); eva_->reload(); } } <|endoftext|>
<commit_before>// ---------------------------------------------------------------------------- // Copyright (C) 2002-2005 Marcin Kalicinski // // 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) // // For more information, see www.boost.org // ---------------------------------------------------------------------------- #ifndef BOOST_PROPERTY_TREE_DETAIL_XML_PARSER_READ_TINYXML_HPP_INCLUDED #define BOOST_PROPERTY_TREE_DETAIL_XML_PARSER_READ_TINYXML_HPP_INCLUDED #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/detail/xml_parser_error.hpp> #include <boost/property_tree/detail/xml_parser_flags.hpp> #include <boost/property_tree/detail/xml_parser_utils.hpp> #define TIXML_USE_STL #include <tinyxml.h> namespace boost { namespace property_tree { namespace xml_parser { template<class Ptree> void read_xml_node(TiXmlNode *node, Ptree &pt, int flags) { typedef typename Ptree::char_type Ch; if (TiXmlElement *elem = node->ToElement()) { Ptree &tmp = pt.push_back(std::make_pair(elem->Value(), Ptree()))->second; for (TiXmlAttribute *attr = elem->FirstAttribute(); attr; attr = attr->Next()) tmp.put(Ch('/'), xmlattr<Ch>() + "/" + attr->Name(), attr->Value()); for (TiXmlNode *child = node->FirstChild(); child; child = child->NextSibling()) read_xml_node(child, tmp, flags); } else if (TiXmlText *text = node->ToText()) { if (flags & no_concat_text) pt.push_back(std::make_pair(xmltext<Ch>(), Ptree(text->Value()))); else pt.data() += text->Value(); } else if (TiXmlComment *comment = node->ToComment()) { if (!(flags & no_comments)) pt.push_back(std::make_pair(xmlcomment<Ch>(), Ptree(comment->Value()))); } } template<class Ptree> void read_xml_internal(std::basic_istream<typename Ptree::char_type> &stream, Ptree &pt, int flags, const std::string &filename) { // Create and load document from stream TiXmlDocument doc; stream >> doc; if (!stream.good()) throw xml_parser_error("read error", filename, 0); if (doc.Error()) throw xml_parser_error(doc.ErrorDesc(), filename, doc.ErrorRow()); // Create ptree from nodes Ptree local; for (TiXmlNode *child = doc.FirstChild(); child; child = child->NextSibling()) read_xml_node(child, local, flags); // Swap local and result ptrees pt.swap(local); } } } } #endif <commit_msg>resolved multiple #defines<commit_after>// ---------------------------------------------------------------------------- // Copyright (C) 2002-2005 Marcin Kalicinski // // 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) // // For more information, see www.boost.org // ---------------------------------------------------------------------------- #ifndef BOOST_PROPERTY_TREE_DETAIL_XML_PARSER_READ_TINYXML_HPP_INCLUDED #define BOOST_PROPERTY_TREE_DETAIL_XML_PARSER_READ_TINYXML_HPP_INCLUDED #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/detail/xml_parser_error.hpp> #include <boost/property_tree/detail/xml_parser_flags.hpp> #include <boost/property_tree/detail/xml_parser_utils.hpp> #ifndef TIXML_USE_STL #define TIXML_USE_STL #endif #include <tinyxml.h> namespace boost { namespace property_tree { namespace xml_parser { template<class Ptree> void read_xml_node(TiXmlNode *node, Ptree &pt, int flags) { typedef typename Ptree::char_type Ch; if (TiXmlElement *elem = node->ToElement()) { Ptree &tmp = pt.push_back(std::make_pair(elem->Value(), Ptree()))->second; for (TiXmlAttribute *attr = elem->FirstAttribute(); attr; attr = attr->Next()) tmp.put(Ch('/'), xmlattr<Ch>() + "/" + attr->Name(), attr->Value()); for (TiXmlNode *child = node->FirstChild(); child; child = child->NextSibling()) read_xml_node(child, tmp, flags); } else if (TiXmlText *text = node->ToText()) { if (flags & no_concat_text) pt.push_back(std::make_pair(xmltext<Ch>(), Ptree(text->Value()))); else pt.data() += text->Value(); } else if (TiXmlComment *comment = node->ToComment()) { if (!(flags & no_comments)) pt.push_back(std::make_pair(xmlcomment<Ch>(), Ptree(comment->Value()))); } } template<class Ptree> void read_xml_internal(std::basic_istream<typename Ptree::char_type> &stream, Ptree &pt, int flags, const std::string &filename) { // Create and load document from stream TiXmlDocument doc; stream >> doc; if (!stream.good()) throw xml_parser_error("read error", filename, 0); if (doc.Error()) throw xml_parser_error(doc.ErrorDesc(), filename, doc.ErrorRow()); // Create ptree from nodes Ptree local; for (TiXmlNode *child = doc.FirstChild(); child; child = child->NextSibling()) read_xml_node(child, local, flags); // Swap local and result ptrees pt.swap(local); } } } } #endif <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * * Copyright: * Guido Tack, 2004 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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 <gecode/int.hh> namespace Gecode { namespace Set { namespace Channel { template<class View> template<class A> forceinline ChannelBool<View>::IndexAdvisor::IndexAdvisor(Space& home, ChannelBool<View>& p, Council<A>& c, int index) : Advisor(home,p,c), idx(index) { if (idx == -1) p.y.subscribe(home,*this); else { p.x[idx].subscribe(home,*this); } } template<class View> forceinline ChannelBool<View>::IndexAdvisor::IndexAdvisor(Space& home, bool share, IndexAdvisor& a) : Advisor(home,share,a), idx(a.idx) {} template<class View> forceinline int ChannelBool<View>::IndexAdvisor::index(void) const { return idx; } template<class View> template<class A> forceinline void ChannelBool<View>::IndexAdvisor::dispose(Space& home, Council<A>& c) { ChannelBool<View>& p = static_cast<ChannelBool<View>&>(propagator()); if (idx == -1) p.y.cancel(home,*this); else { p.x[idx].cancel(home,*this); } Advisor::dispose(home,c); } template<class View> forceinline ChannelBool<View>::ChannelBool(Home home, ViewArray<Gecode::Int::BoolView>& x0, View y0) : Super(home,x0,y0), co(home), running(false) { bool assigned = false; for (int i=x.size(); i--;) { if (x[i].zero()) { assigned = true; SetDelta d; zeros.include(home, i, i, d); } else if (x[i].one()) { assigned = true; SetDelta d; ones.include(home, i, i, d); } else { (void) new (home) IndexAdvisor(home,*this,co,i); } } if (assigned) Gecode::Int::BoolView::schedule(home, *this, Gecode::Int::ME_BOOL_VAL); View::schedule(home, *this, y.assigned() ? ME_SET_VAL : ME_SET_BB); if (y.assigned()) new (&delta) SetDelta(y.glbMin(),y.glbMax(),1,0); (void) new (home) IndexAdvisor(home,*this,co,-1); } template<class View> forceinline ChannelBool<View>::ChannelBool(Space& home, bool share, ChannelBool& p) : Super(home,share,p), running(false) { co.update(home, share, p.co); } template<class View> forceinline ExecStatus ChannelBool<View>::post(Home home, ViewArray<Gecode::Int::BoolView>& x, View y) { GECODE_ME_CHECK(y.intersect(home, 0, x.size()-1)); (void) new (home) ChannelBool(home,x,y); return ES_OK; } template<class View> PropCost ChannelBool<View>::cost(const Space&, const ModEventDelta&) const { return PropCost::quadratic(PropCost::LO, x.size()+1); } template<class View> forceinline size_t ChannelBool<View>::dispose(Space& home) { co.dispose(home); (void) Super::dispose(home); return sizeof(*this); } template<class View> Actor* ChannelBool<View>::copy(Space& home, bool share) { return new (home) ChannelBool(home,share,*this); } template<class View> ExecStatus ChannelBool<View>::propagate(Space& home, const ModEventDelta&) { running = true; if (zeros.size() > 0) { BndSetRanges zi(zeros); GECODE_ME_CHECK(y.excludeI(home, zi)); zeros.init(home); } if (ones.size() > 0) { BndSetRanges oi(ones); GECODE_ME_CHECK(y.includeI(home, oi)); ones.init(home); } running = false; if (delta.glbMin() != 1 || delta.glbMax() != 0) { if (!delta.glbAny()) { for (int i=delta.glbMin(); i<=delta.glbMax(); i++) GECODE_ME_CHECK(x[i].one(home)); } else { GlbRanges<View> glb(y); for (Iter::Ranges::ToValues<GlbRanges<View> > gv(glb); gv(); ++gv) { GECODE_ME_CHECK(x[gv.val()].one(home)); } } } if (delta.lubMin() != 1 || delta.lubMax() != 0) { if (!delta.lubAny()) { for (int i=delta.lubMin(); i<=delta.lubMax(); i++) GECODE_ME_CHECK(x[i].zero(home)); } else { int cur = 0; for (LubRanges<View> lub(y); lub(); ++lub) { for (; cur < lub.min(); cur++) { GECODE_ME_CHECK(x[cur].zero(home)); } cur = lub.max() + 1; } for (; cur < x.size(); cur++) { GECODE_ME_CHECK(x[cur].zero(home)); } } } new (&delta) SetDelta(); return y.assigned() ? home.ES_SUBSUMED(*this) : ES_FIX; } template<class View> ExecStatus ChannelBool<View>::advise(Space& home, Advisor& _a, const Delta& _d) { IndexAdvisor& a = static_cast<IndexAdvisor&>(_a); const SetDelta& d = static_cast<const SetDelta&>(_d); ModEvent me = View::modevent(d); int index = a.index(); if ( (running && index == -1 && me != ME_SET_VAL) || (index == -1 && me == ME_SET_CARD) ) { return ES_OK; } if (index >= 0) { if (x[index].zero()) { SetDelta dummy; zeros.include(home, index, index, dummy); } else { assert(x[index].one()); SetDelta dummy; ones.include(home, index, index, dummy); } return home.ES_NOFIX_DISPOSE( co, a); } if ((a.index() == -1) && Rel::testSetEventLB(me)) { if (d.glbAny()) { new (&delta) SetDelta(2,0, delta.lubMin(), delta.lubMax()); } else { if (delta.glbMin() == 1 && delta.glbMax() == 0) { new (&delta) SetDelta(d.glbMin(), d.glbMax(), delta.lubMin(), delta.lubMax()); } else { if (delta.glbMin() != 2 || delta.glbMax() != 0) { if ((delta.glbMin() <= d.glbMin() && delta.glbMax() >= d.glbMin()) || (delta.glbMin() <= d.glbMax() && delta.glbMax() >= d.glbMax()) ) { new (&delta) SetDelta(std::min(delta.glbMin(), d.glbMin()), std::max(delta.glbMax(), d.glbMax()), delta.lubMin(), delta.lubMax()); } else { new (&delta) SetDelta(2, 0, delta.lubMin(), delta.lubMax()); } } } } } if ((a.index() == -1) && Rel::testSetEventUB(me)) { if (d.lubAny()) { new (&delta) SetDelta(delta.glbMin(), delta.glbMax(), 2,0); } else { if (delta.lubMin() == 1 && delta.lubMax() == 0) { new (&delta) SetDelta(delta.glbMin(), delta.glbMax(), d.lubMin(), d.lubMax()); } else { if (delta.lubMin() != 2 || delta.lubMax() != 0) { if ((delta.lubMin() <= d.lubMin() && delta.lubMax() >= d.lubMin()) || (delta.lubMin() <= d.lubMax() && delta.lubMax() >= d.lubMax()) ) { new (&delta) SetDelta(delta.lubMin(), delta.lubMax(), std::min(delta.lubMin(), d.lubMin()), std::max(delta.lubMax(), d.lubMax()) ); } else { new (&delta) SetDelta(delta.glbMin(), delta.glbMax(), 2, 0); } } } } } if (y.assigned()) return home.ES_NOFIX_DISPOSE( co, a); else return ES_NOFIX; } }}} // STATISTICS: set-prop <commit_msg>Fix post function for set/bool channel<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * * Copyright: * Guido Tack, 2004 * * Last modified: * $Date$ by $Author$ * $Revision$ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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 <gecode/int.hh> namespace Gecode { namespace Set { namespace Channel { template<class View> template<class A> forceinline ChannelBool<View>::IndexAdvisor::IndexAdvisor(Space& home, ChannelBool<View>& p, Council<A>& c, int index) : Advisor(home,p,c), idx(index) { if (idx == -1) p.y.subscribe(home,*this); else { p.x[idx].subscribe(home,*this); } } template<class View> forceinline ChannelBool<View>::IndexAdvisor::IndexAdvisor(Space& home, bool share, IndexAdvisor& a) : Advisor(home,share,a), idx(a.idx) {} template<class View> forceinline int ChannelBool<View>::IndexAdvisor::index(void) const { return idx; } template<class View> template<class A> forceinline void ChannelBool<View>::IndexAdvisor::dispose(Space& home, Council<A>& c) { ChannelBool<View>& p = static_cast<ChannelBool<View>&>(propagator()); if (idx == -1) p.y.cancel(home,*this); else { p.x[idx].cancel(home,*this); } Advisor::dispose(home,c); } template<class View> forceinline ChannelBool<View>::ChannelBool(Home home, ViewArray<Gecode::Int::BoolView>& x0, View y0) : Super(home,x0,y0), co(home), running(false) { bool assigned = false; for (int i=x.size(); i--;) { if (x[i].zero()) { assigned = true; SetDelta d; zeros.include(home, i, i, d); } else if (x[i].one()) { assigned = true; SetDelta d; ones.include(home, i, i, d); } else { (void) new (home) IndexAdvisor(home,*this,co,i); } } if (assigned) Gecode::Int::BoolView::schedule(home, *this, Gecode::Int::ME_BOOL_VAL); View::schedule(home, *this, y.assigned() ? ME_SET_VAL : ME_SET_BB); if (y.assigned()) { if (y.glbSize() == y.glbMax()-y.glbMin()+1) { new (&delta) SetDelta(y.glbMin(),y.glbMax(),1,0); } else { new (&delta) SetDelta(2,0,1,0); } } (void) new (home) IndexAdvisor(home,*this,co,-1); } template<class View> forceinline ChannelBool<View>::ChannelBool(Space& home, bool share, ChannelBool& p) : Super(home,share,p), running(false) { co.update(home, share, p.co); } template<class View> forceinline ExecStatus ChannelBool<View>::post(Home home, ViewArray<Gecode::Int::BoolView>& x, View y) { GECODE_ME_CHECK(y.intersect(home, 0, x.size()-1)); (void) new (home) ChannelBool(home,x,y); return ES_OK; } template<class View> PropCost ChannelBool<View>::cost(const Space&, const ModEventDelta&) const { return PropCost::quadratic(PropCost::LO, x.size()+1); } template<class View> forceinline size_t ChannelBool<View>::dispose(Space& home) { co.dispose(home); (void) Super::dispose(home); return sizeof(*this); } template<class View> Actor* ChannelBool<View>::copy(Space& home, bool share) { return new (home) ChannelBool(home,share,*this); } template<class View> ExecStatus ChannelBool<View>::propagate(Space& home, const ModEventDelta&) { running = true; if (zeros.size() > 0) { BndSetRanges zi(zeros); GECODE_ME_CHECK(y.excludeI(home, zi)); zeros.init(home); } if (ones.size() > 0) { BndSetRanges oi(ones); GECODE_ME_CHECK(y.includeI(home, oi)); ones.init(home); } running = false; if (delta.glbMin() != 1 || delta.glbMax() != 0) { if (!delta.glbAny()) { for (int i=delta.glbMin(); i<=delta.glbMax(); i++) GECODE_ME_CHECK(x[i].one(home)); } else { GlbRanges<View> glb(y); for (Iter::Ranges::ToValues<GlbRanges<View> > gv(glb); gv(); ++gv) { GECODE_ME_CHECK(x[gv.val()].one(home)); } } } if (delta.lubMin() != 1 || delta.lubMax() != 0) { if (!delta.lubAny()) { for (int i=delta.lubMin(); i<=delta.lubMax(); i++) GECODE_ME_CHECK(x[i].zero(home)); } else { int cur = 0; for (LubRanges<View> lub(y); lub(); ++lub) { for (; cur < lub.min(); cur++) { GECODE_ME_CHECK(x[cur].zero(home)); } cur = lub.max() + 1; } for (; cur < x.size(); cur++) { GECODE_ME_CHECK(x[cur].zero(home)); } } } new (&delta) SetDelta(); return y.assigned() ? home.ES_SUBSUMED(*this) : ES_FIX; } template<class View> ExecStatus ChannelBool<View>::advise(Space& home, Advisor& _a, const Delta& _d) { IndexAdvisor& a = static_cast<IndexAdvisor&>(_a); const SetDelta& d = static_cast<const SetDelta&>(_d); ModEvent me = View::modevent(d); int index = a.index(); if ( (running && index == -1 && me != ME_SET_VAL) || (index == -1 && me == ME_SET_CARD) ) { return ES_OK; } if (index >= 0) { if (x[index].zero()) { SetDelta dummy; zeros.include(home, index, index, dummy); } else { assert(x[index].one()); SetDelta dummy; ones.include(home, index, index, dummy); } return home.ES_NOFIX_DISPOSE( co, a); } if ((a.index() == -1) && Rel::testSetEventLB(me)) { if (d.glbAny()) { new (&delta) SetDelta(2,0, delta.lubMin(), delta.lubMax()); } else { if (delta.glbMin() == 1 && delta.glbMax() == 0) { new (&delta) SetDelta(d.glbMin(), d.glbMax(), delta.lubMin(), delta.lubMax()); } else { if (delta.glbMin() != 2 || delta.glbMax() != 0) { if ((delta.glbMin() <= d.glbMin() && delta.glbMax() >= d.glbMin()) || (delta.glbMin() <= d.glbMax() && delta.glbMax() >= d.glbMax()) ) { new (&delta) SetDelta(std::min(delta.glbMin(), d.glbMin()), std::max(delta.glbMax(), d.glbMax()), delta.lubMin(), delta.lubMax()); } else { new (&delta) SetDelta(2, 0, delta.lubMin(), delta.lubMax()); } } } } } if ((a.index() == -1) && Rel::testSetEventUB(me)) { if (d.lubAny()) { new (&delta) SetDelta(delta.glbMin(), delta.glbMax(), 2,0); } else { if (delta.lubMin() == 1 && delta.lubMax() == 0) { new (&delta) SetDelta(delta.glbMin(), delta.glbMax(), d.lubMin(), d.lubMax()); } else { if (delta.lubMin() != 2 || delta.lubMax() != 0) { if ((delta.lubMin() <= d.lubMin() && delta.lubMax() >= d.lubMin()) || (delta.lubMin() <= d.lubMax() && delta.lubMax() >= d.lubMax()) ) { new (&delta) SetDelta(delta.lubMin(), delta.lubMax(), std::min(delta.lubMin(), d.lubMin()), std::max(delta.lubMax(), d.lubMax()) ); } else { new (&delta) SetDelta(delta.glbMin(), delta.glbMax(), 2, 0); } } } } } if (y.assigned()) return home.ES_NOFIX_DISPOSE( co, a); else return ES_NOFIX; } }}} // STATISTICS: set-prop <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2003 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _WIN32 #pragma warning(4:4786) #endif #include <string> #include <fstream> #include <stdlib.h> #include "Permissions.h" #include "md5.h" std::map<std::string, PlayerAccessInfo> groupAccess; std::map<std::string, PlayerAccessInfo> userDatabase; std::map<std::string, std::string> passwordDatabase; bool hasGroup(PlayerAccessInfo& info, const std::string &group) { std::string str = group; makeupper(str); std::vector<std::string>::iterator itr = info.groups.begin(); while (itr != info.groups.end()) { if ((*itr) == str) return true; itr++; } return false; } bool addGroup(PlayerAccessInfo& info, const std::string &group) { if (hasGroup(info, group)) return false; std::string str = group; makeupper(str); info.groups.push_back(str); return true; } bool removeGroup(PlayerAccessInfo& info, const std::string &group) { if (!hasGroup(info, group)) return false; std::string str = group; makeupper(str); std::vector<std::string>::iterator itr = info.groups.begin(); while (itr != info.groups.end()) { if ((*itr) == str) { itr = info.groups.erase(itr); return true; } else itr++; } return false; } bool hasPerm(PlayerAccessInfo& info, AccessPerm right) { if (!info.verified) return false; if (info.explicitDenys.test(right)) return false; if (info.explicitAllows.test(right)) return true; std::vector<std::string>::iterator itr = info.groups.begin(); std::map<std::string, PlayerAccessInfo>::iterator group; while (itr != info.groups.end()) { group = groupAccess.find(*itr); if (group != groupAccess.end()) if (group->second.explicitAllows.test(right)) return true; itr++; } return false; } bool userExists(const std::string &nick) { std::string str = nick; makeupper(str); std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.find(str); if (itr == userDatabase.end()) return false; return true; } //FIXME - check for non-existing user (throw?) PlayerAccessInfo& getUserInfo(const std::string &nick) { // if (!userExists(nick)) // return false; std::string str = nick; makeupper(str); std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.find(str); // if (itr == userDatabase.end()) // return false; return itr->second; } bool setUserInfo(const std::string &nick, PlayerAccessInfo& info) { std::string str = nick; makeupper(str); userDatabase[str] = info; return true; } bool verifyUserPassword(const std::string &nick, const std::string &pass) { std::string str1 = nick; makeupper(str1); std::map<std::string, std::string>::iterator itr = passwordDatabase.find(str1); if (itr == passwordDatabase.end()) return false; return itr->second == MD5(pass).hexdigest(); } void setUserPassword(const std::string &nick, const std::string &pass) { std::string str1 = nick; makeupper(str1); // assume it's already a hash when length is 32 (FIXME?) passwordDatabase[str1] = pass.size()==32 ? pass : MD5(pass).hexdigest(); } std::string nameFromPerm(AccessPerm perm) { switch (perm) { case idleStats: return "idleStats"; case lagStats: return "lagStats"; case flagMod: return "flagMod"; case flagHistory: return "flagHistory"; case lagwarn: return "lagwarn"; case kick: return "kick"; case ban: return "ban"; case banlist: return "banlist"; case unban: return "unban"; case countdown: return "countdown"; case endGame: return "endGame"; case shutdownServer: return "shutdownServer"; case superKill: return "superKill"; case playerList: return "playerList"; case info: return "info"; case listPerms: return "listPerms"; case showOthers: return "showOthers"; case removePerms: return "removePerms"; case setPassword: return "setPassword"; case setPerms: return "setPerms"; case setAll: return "setAll"; case setVar: return "setVar"; case poll: return "poll"; case vote: return "vote"; case veto: return "veto"; default: return NULL; }; } AccessPerm permFromName(const std::string &name) { if (name == "IDLESTATS") return idleStats; if (name == "LAGSTATS") return lagStats; if (name == "FLAGMOD") return flagMod; if (name == "FLAGHISTORY") return flagHistory; if (name == "LAGWARN") return lagwarn; if (name == "KICK") return kick; if (name == "BAN") return ban; if (name == "BANLIST") return banlist; if (name == "UNBAN") return unban; if (name == "COUNTDOWN") return countdown; if (name == "ENDGAME") return endGame; if (name == "SHUTDOWNSERVER") return shutdownServer; if (name == "SUPERKILL") return superKill; if (name == "PLAYERLIST") return playerList; if (name == "INFO") return info; if (name == "LISTPERMS") return listPerms; if (name == "SHOWOTHERS") return showOthers; if (name == "REMOVEPERMS") return removePerms; if (name == "SETPASSWORD") return setPassword; if (name == "SETPERMS") return setPerms; if (name == "SETVAR") return setVar; if (name == "SETALL") return setAll; if (name == "POLL") return poll; if (name == "VOTE") return vote; if (name == "VETO") return veto; return lastPerm; } void parsePermissionString(const std::string &permissionString, std::bitset<lastPerm> &perms) { if (permissionString.length() < 1) return; perms.reset(); std::istringstream permStream(permissionString); std::string word; while (permStream >> word) { makeupper(word); AccessPerm perm = permFromName(word); if (perm != lastPerm) perms.set(perm); } } bool readPassFile(const std::string &filename) { std::ifstream in(filename.c_str()); if (!in) return false; std::string line; while (std::getline(in, line)) { std::string::size_type colonpos = line.find(':'); if (colonpos != std::string::npos) { std::string name = line.substr(0, colonpos); std::string pass = line.substr(colonpos + 1); makeupper(name); setUserPassword(name.c_str(), pass.c_str()); } } return (passwordDatabase.size() > 0); } bool writePassFile(const std::string &filename) { std::ofstream out(filename.c_str()); if (!out) return false; std::map<std::string, std::string>::iterator itr = passwordDatabase.begin(); while (itr != passwordDatabase.end()) { out << itr->first << ':' << itr->second << std::endl; itr++; } out.close(); return true; } bool readGroupsFile(const std::string &filename) { std::ifstream in(filename.c_str()); if (!in) return false; std::string line; while (std::getline(in, line)) { std::string::size_type colonpos = line.find(':'); if (colonpos != std::string::npos) { std::string name = line.substr(0, colonpos); std::string perm = line.substr(colonpos + 1); makeupper(name); PlayerAccessInfo info; parsePermissionString(perm, info.explicitAllows); info.verified = true; groupAccess[name] = info; } } return true; } bool readPermsFile(const std::string &filename) { std::ifstream in(filename.c_str()); if (!in) return false; for (;;) { // 1st line - name std::string name; if (!std::getline(in, name)) break; PlayerAccessInfo info; // 2nd line - groups std::string groupline; std::getline(in, groupline); // FIXME -it's an error when line cannot be read std::istringstream groupstream(groupline); std::string group; while (groupstream >> group) { info.groups.push_back(group); } // 3rd line - allows std::string perms; std::getline(in, perms); parsePermissionString(perms, info.explicitAllows); std::getline(in, perms); parsePermissionString(perms, info.explicitDenys); userDatabase[name] = info; } return true; } bool writePermsFile(const std::string &filename) { int i; std::ofstream out(filename.c_str()); if (!out) return false; std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.begin(); std::vector<std::string>::iterator group; while (itr != userDatabase.end()) { out << itr->first << std::endl; group = itr->second.groups.begin(); while (group != itr->second.groups.end()) { out << (*group) << ' '; group++; } out << std::endl; // allows for (i = 0; i < lastPerm; i++) if (itr->second.explicitAllows.test(i)) out << nameFromPerm((AccessPerm) i); out << std::endl; // denys for (i = 0; i < lastPerm; i++) if (itr->second.explicitDenys.test(i)) out << nameFromPerm((AccessPerm) i); out << std::endl; itr++; } out.close(); return true; } std::string groupsFile; std::string passFile; std::string userDatabaseFile; void updateDatabases() { if(passFile.size()) writePassFile(passFile); if(userDatabaseFile.size()) writePermsFile(userDatabaseFile); } // ex: shiftwidth=2 tabstop=8 <commit_msg>Put the candle back, let default users have a go at ait.<commit_after>/* bzflag * Copyright (c) 1993 - 2003 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _WIN32 #pragma warning(4:4786) #endif #include <string> #include <fstream> #include <stdlib.h> #include "Permissions.h" #include "md5.h" std::map<std::string, PlayerAccessInfo> groupAccess; std::map<std::string, PlayerAccessInfo> userDatabase; std::map<std::string, std::string> passwordDatabase; bool hasGroup(PlayerAccessInfo& info, const std::string &group) { std::string str = group; makeupper(str); std::vector<std::string>::iterator itr = info.groups.begin(); while (itr != info.groups.end()) { if ((*itr) == str) return true; itr++; } return false; } bool addGroup(PlayerAccessInfo& info, const std::string &group) { if (hasGroup(info, group)) return false; std::string str = group; makeupper(str); info.groups.push_back(str); return true; } bool removeGroup(PlayerAccessInfo& info, const std::string &group) { if (!hasGroup(info, group)) return false; std::string str = group; makeupper(str); std::vector<std::string>::iterator itr = info.groups.begin(); while (itr != info.groups.end()) { if ((*itr) == str) { itr = info.groups.erase(itr); return true; } else itr++; } return false; } bool hasPerm(PlayerAccessInfo& info, AccessPerm right) { if (info.explicitDenys.test(right)) return false; if (info.explicitAllows.test(right)) return true; std::vector<std::string>::iterator itr = info.groups.begin(); std::map<std::string, PlayerAccessInfo>::iterator group; while (itr != info.groups.end()) { group = groupAccess.find(*itr); if (group != groupAccess.end()) if (group->second.explicitAllows.test(right)) return true; itr++; } return false; } bool userExists(const std::string &nick) { std::string str = nick; makeupper(str); std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.find(str); if (itr == userDatabase.end()) return false; return true; } //FIXME - check for non-existing user (throw?) PlayerAccessInfo& getUserInfo(const std::string &nick) { // if (!userExists(nick)) // return false; std::string str = nick; makeupper(str); std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.find(str); // if (itr == userDatabase.end()) // return false; return itr->second; } bool setUserInfo(const std::string &nick, PlayerAccessInfo& info) { std::string str = nick; makeupper(str); userDatabase[str] = info; return true; } bool verifyUserPassword(const std::string &nick, const std::string &pass) { std::string str1 = nick; makeupper(str1); std::map<std::string, std::string>::iterator itr = passwordDatabase.find(str1); if (itr == passwordDatabase.end()) return false; return itr->second == MD5(pass).hexdigest(); } void setUserPassword(const std::string &nick, const std::string &pass) { std::string str1 = nick; makeupper(str1); // assume it's already a hash when length is 32 (FIXME?) passwordDatabase[str1] = pass.size()==32 ? pass : MD5(pass).hexdigest(); } std::string nameFromPerm(AccessPerm perm) { switch (perm) { case idleStats: return "idleStats"; case lagStats: return "lagStats"; case flagMod: return "flagMod"; case flagHistory: return "flagHistory"; case lagwarn: return "lagwarn"; case kick: return "kick"; case ban: return "ban"; case banlist: return "banlist"; case unban: return "unban"; case countdown: return "countdown"; case endGame: return "endGame"; case shutdownServer: return "shutdownServer"; case superKill: return "superKill"; case playerList: return "playerList"; case info: return "info"; case listPerms: return "listPerms"; case showOthers: return "showOthers"; case removePerms: return "removePerms"; case setPassword: return "setPassword"; case setPerms: return "setPerms"; case setAll: return "setAll"; case setVar: return "setVar"; case poll: return "poll"; case vote: return "vote"; case veto: return "veto"; default: return NULL; }; } AccessPerm permFromName(const std::string &name) { if (name == "IDLESTATS") return idleStats; if (name == "LAGSTATS") return lagStats; if (name == "FLAGMOD") return flagMod; if (name == "FLAGHISTORY") return flagHistory; if (name == "LAGWARN") return lagwarn; if (name == "KICK") return kick; if (name == "BAN") return ban; if (name == "BANLIST") return banlist; if (name == "UNBAN") return unban; if (name == "COUNTDOWN") return countdown; if (name == "ENDGAME") return endGame; if (name == "SHUTDOWNSERVER") return shutdownServer; if (name == "SUPERKILL") return superKill; if (name == "PLAYERLIST") return playerList; if (name == "INFO") return info; if (name == "LISTPERMS") return listPerms; if (name == "SHOWOTHERS") return showOthers; if (name == "REMOVEPERMS") return removePerms; if (name == "SETPASSWORD") return setPassword; if (name == "SETPERMS") return setPerms; if (name == "SETVAR") return setVar; if (name == "SETALL") return setAll; if (name == "POLL") return poll; if (name == "VOTE") return vote; if (name == "VETO") return veto; return lastPerm; } void parsePermissionString(const std::string &permissionString, std::bitset<lastPerm> &perms) { if (permissionString.length() < 1) return; perms.reset(); std::istringstream permStream(permissionString); std::string word; while (permStream >> word) { makeupper(word); AccessPerm perm = permFromName(word); if (perm != lastPerm) perms.set(perm); } } bool readPassFile(const std::string &filename) { std::ifstream in(filename.c_str()); if (!in) return false; std::string line; while (std::getline(in, line)) { std::string::size_type colonpos = line.find(':'); if (colonpos != std::string::npos) { std::string name = line.substr(0, colonpos); std::string pass = line.substr(colonpos + 1); makeupper(name); setUserPassword(name.c_str(), pass.c_str()); } } return (passwordDatabase.size() > 0); } bool writePassFile(const std::string &filename) { std::ofstream out(filename.c_str()); if (!out) return false; std::map<std::string, std::string>::iterator itr = passwordDatabase.begin(); while (itr != passwordDatabase.end()) { out << itr->first << ':' << itr->second << std::endl; itr++; } out.close(); return true; } bool readGroupsFile(const std::string &filename) { std::ifstream in(filename.c_str()); if (!in) return false; std::string line; while (std::getline(in, line)) { std::string::size_type colonpos = line.find(':'); if (colonpos != std::string::npos) { std::string name = line.substr(0, colonpos); std::string perm = line.substr(colonpos + 1); makeupper(name); PlayerAccessInfo info; parsePermissionString(perm, info.explicitAllows); info.verified = true; groupAccess[name] = info; } } return true; } bool readPermsFile(const std::string &filename) { std::ifstream in(filename.c_str()); if (!in) return false; for (;;) { // 1st line - name std::string name; if (!std::getline(in, name)) break; PlayerAccessInfo info; // 2nd line - groups std::string groupline; std::getline(in, groupline); // FIXME -it's an error when line cannot be read std::istringstream groupstream(groupline); std::string group; while (groupstream >> group) { info.groups.push_back(group); } // 3rd line - allows std::string perms; std::getline(in, perms); parsePermissionString(perms, info.explicitAllows); std::getline(in, perms); parsePermissionString(perms, info.explicitDenys); userDatabase[name] = info; } return true; } bool writePermsFile(const std::string &filename) { int i; std::ofstream out(filename.c_str()); if (!out) return false; std::map<std::string, PlayerAccessInfo>::iterator itr = userDatabase.begin(); std::vector<std::string>::iterator group; while (itr != userDatabase.end()) { out << itr->first << std::endl; group = itr->second.groups.begin(); while (group != itr->second.groups.end()) { out << (*group) << ' '; group++; } out << std::endl; // allows for (i = 0; i < lastPerm; i++) if (itr->second.explicitAllows.test(i)) out << nameFromPerm((AccessPerm) i); out << std::endl; // denys for (i = 0; i < lastPerm; i++) if (itr->second.explicitDenys.test(i)) out << nameFromPerm((AccessPerm) i); out << std::endl; itr++; } out.close(); return true; } std::string groupsFile; std::string passFile; std::string userDatabaseFile; void updateDatabases() { if(passFile.size()) writePassFile(passFile); if(userDatabaseFile.size()) writePermsFile(userDatabaseFile); } // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2019, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "HTTP.h" #include "Base.h" #include "Request.h" #include "Event.h" #include "Connection.h" #include <cbang/config.h> #include <cbang/Exception.h> #include <cbang/Catch.h> #include <cbang/log/Logger.h> #include <cbang/time/Timer.h> #include <cbang/socket/Socket.h> #ifdef HAVE_OPENSSL #include <cbang/openssl/SSLContext.h> #else namespace cb {class SSLContext {};} #endif using namespace std; using namespace cb::Event; HTTP::HTTP(cb::Event::Base &base, const cb::SmartPointer<HTTPHandler> &handler, const cb::SmartPointer<cb::SSLContext> &sslCtx) : base(base), handler(handler), sslCtx(sslCtx) { #ifndef HAVE_OPENSSL if (!sslCtx.isNull()) THROW("C! was not built with openssl support"); #endif } HTTP::~HTTP() {} void HTTP::setMaxConnectionTTL(unsigned x) { maxConnectionTTL = x; if (maxConnectionTTL) { if (expireEvent.isNull()) expireEvent = base.newEvent(this, &HTTP::expireCB); expireEvent->add(60); // Check once per minute } else if (expireEvent->isPending()) expireEvent->del(); } void HTTP::remove(Connection &con) {connections.remove(&con);} void HTTP::bind(const cb::IPAddress &addr) { // TODO Support binding multiple listener sockets if (this->socket.isSet()) THROW("Already bound"); SmartPointer<Socket> socket = new Socket; socket->setReuseAddr(true); socket->bind(addr); socket->listen(128); socket_t fd = socket->get(); // This event will be destroyed with the HTTP acceptEvent = base.newEvent(fd, this, &HTTP::acceptCB, EVENT_READ | EVENT_PERSIST | EVENT_NO_SELF_REF); acceptEvent->add(); this->socket = socket; boundAddr = addr; } cb::SmartPointer<Request> HTTP::createRequest (Connection &con, RequestMethod method, const cb::URI &uri, const cb::Version &version) { return handler->createRequest(con, method, uri, version); } void HTTP::handleRequest(Request &req) { LOG_DEBUG(5, "New request on " << boundAddr << ", connection count = " << getConnectionCount()); TRY_CATCH_ERROR(dispatch(*handler, req)); } bool HTTP::dispatch(HTTPHandler &handler, Request &req) { try { if (handler.handleRequest(req)) { handler.endRequest(req); return true; } req.sendError(HTTPStatus::HTTP_NOT_FOUND); } catch (cb::Exception &e) { if (400 <= e.getCode() && e.getCode() < 600) { LOG_WARNING("REQ" << req.getID() << ':' << req.getClientIP() << ':' << e.getMessages()); req.reply((HTTPStatus::enum_t)e.getCode()); } else { if (!CBANG_LOG_DEBUG_ENABLED(3)) LOG_WARNING(e.getMessages()); LOG_DEBUG(3, e); req.sendError(e); } } catch (std::exception &e) { LOG_ERROR(e.what()); req.sendError(e); } catch (...) { LOG_ERROR(HTTPStatus(HTTPStatus::HTTP_INTERNAL_SERVER_ERROR) .getDescription()); req.sendError(HTTPStatus::HTTP_INTERNAL_SERVER_ERROR); } handler.endRequest(req); return false; } void HTTP::expireCB() { double now = Timer::now(); unsigned count; for (auto it = connections.begin(); it != connections.end();) if (maxConnectionTTL < now - (*it)->getStartTime()) { it = connections.erase(it); count++; } else it++; LOG_DEBUG(4, "Dropped " << count << " expired connections"); } void HTTP::acceptCB() { IPAddress peer; auto newSocket = socket->accept(&peer); LOG_DEBUG(4, "New connection from " << peer); // Create new Connection SmartPointer<Connection> con = new Connection(base, true, peer, newSocket, sslCtx); con->setHTTP(this); con->setMaxHeaderSize(maxHeaderSize); con->setMaxBodySize(maxBodySize); if (0 <= priority) con->setPriority(priority); con->setReadTimeout(readTimeout); con->setWriteTimeout(writeTimeout); connections.push_back(con); // Send "service unavailable" at connection limit if (maxConnections && maxConnections < connections.size()) con->sendServiceUnavailable(); else con->acceptRequest(); } <commit_msg>Uninitialized variable<commit_after>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2019, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "HTTP.h" #include "Base.h" #include "Request.h" #include "Event.h" #include "Connection.h" #include <cbang/config.h> #include <cbang/Exception.h> #include <cbang/Catch.h> #include <cbang/log/Logger.h> #include <cbang/time/Timer.h> #include <cbang/socket/Socket.h> #ifdef HAVE_OPENSSL #include <cbang/openssl/SSLContext.h> #else namespace cb {class SSLContext {};} #endif using namespace std; using namespace cb::Event; HTTP::HTTP(cb::Event::Base &base, const cb::SmartPointer<HTTPHandler> &handler, const cb::SmartPointer<cb::SSLContext> &sslCtx) : base(base), handler(handler), sslCtx(sslCtx) { #ifndef HAVE_OPENSSL if (!sslCtx.isNull()) THROW("C! was not built with openssl support"); #endif } HTTP::~HTTP() {} void HTTP::setMaxConnectionTTL(unsigned x) { maxConnectionTTL = x; if (maxConnectionTTL) { if (expireEvent.isNull()) expireEvent = base.newEvent(this, &HTTP::expireCB); expireEvent->add(60); // Check once per minute } else if (expireEvent->isPending()) expireEvent->del(); } void HTTP::remove(Connection &con) {connections.remove(&con);} void HTTP::bind(const cb::IPAddress &addr) { // TODO Support binding multiple listener sockets if (this->socket.isSet()) THROW("Already bound"); SmartPointer<Socket> socket = new Socket; socket->setReuseAddr(true); socket->bind(addr); socket->listen(128); socket_t fd = socket->get(); // This event will be destroyed with the HTTP acceptEvent = base.newEvent(fd, this, &HTTP::acceptCB, EVENT_READ | EVENT_PERSIST | EVENT_NO_SELF_REF); acceptEvent->add(); this->socket = socket; boundAddr = addr; } cb::SmartPointer<Request> HTTP::createRequest (Connection &con, RequestMethod method, const cb::URI &uri, const cb::Version &version) { return handler->createRequest(con, method, uri, version); } void HTTP::handleRequest(Request &req) { LOG_DEBUG(5, "New request on " << boundAddr << ", connection count = " << getConnectionCount()); TRY_CATCH_ERROR(dispatch(*handler, req)); } bool HTTP::dispatch(HTTPHandler &handler, Request &req) { try { if (handler.handleRequest(req)) { handler.endRequest(req); return true; } req.sendError(HTTPStatus::HTTP_NOT_FOUND); } catch (cb::Exception &e) { if (400 <= e.getCode() && e.getCode() < 600) { LOG_WARNING("REQ" << req.getID() << ':' << req.getClientIP() << ':' << e.getMessages()); req.reply((HTTPStatus::enum_t)e.getCode()); } else { if (!CBANG_LOG_DEBUG_ENABLED(3)) LOG_WARNING(e.getMessages()); LOG_DEBUG(3, e); req.sendError(e); } } catch (std::exception &e) { LOG_ERROR(e.what()); req.sendError(e); } catch (...) { LOG_ERROR(HTTPStatus(HTTPStatus::HTTP_INTERNAL_SERVER_ERROR) .getDescription()); req.sendError(HTTPStatus::HTTP_INTERNAL_SERVER_ERROR); } handler.endRequest(req); return false; } void HTTP::expireCB() { double now = Timer::now(); unsigned count = 0; for (auto it = connections.begin(); it != connections.end();) if (maxConnectionTTL < now - (*it)->getStartTime()) { it = connections.erase(it); count++; } else it++; LOG_DEBUG(4, "Dropped " << count << " expired connections"); } void HTTP::acceptCB() { IPAddress peer; auto newSocket = socket->accept(&peer); LOG_DEBUG(4, "New connection from " << peer); // Create new Connection SmartPointer<Connection> con = new Connection(base, true, peer, newSocket, sslCtx); con->setHTTP(this); con->setMaxHeaderSize(maxHeaderSize); con->setMaxBodySize(maxBodySize); if (0 <= priority) con->setPriority(priority); con->setReadTimeout(readTimeout); con->setWriteTimeout(writeTimeout); connections.push_back(con); // Send "service unavailable" at connection limit if (maxConnections && maxConnections < connections.size()) con->sendServiceUnavailable(); else con->acceptRequest(); } <|endoftext|>
<commit_before>/// @file mobile.cpp /// @brief Implements mobile methods. /// @author Enrico Fraccaroli /// @date Aug 23 2014 /// @copyright /// Copyright (c) 2016 Enrico Fraccaroli <enrico.fraccaroli@gmail.com> /// Permission is hereby granted, free of charge, to any person obtaining a /// copy of this software and associated documentation files (the "Software"), /// to deal in the Software without restriction, including without limitation /// the rights to use, copy, modify, merge, publish, distribute, sublicense, /// and/or sell copies of the Software, and to permit persons to whom the /// Software is furnished to do so, subject to the following conditions: /// The above copyright notice and this permission notice shall be included /// in all copies or substantial portions of the Software. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL /// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER /// DEALINGS IN THE SOFTWARE. #include "mobile.hpp" #include "generalBehaviour.hpp" #include "lua_script.hpp" #include "logger.hpp" #include "mud.hpp" Mobile::Mobile() : id(), respawnRoom(), keys(), shortdesc(), staticdesc(), actions(), message_buffer(), nextRespawn(), controller(), lua_script(), managedItem(), behaviourQueue(), behaviourTimer(std::chrono::system_clock::now()), behaviourDelay(500000) { // Nothing to do. } Mobile::~Mobile() { // Delete only the temporary items. for (auto item : equipment) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } for (auto item : inventory) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } if (this->isAlive()) { room->removeCharacter(this); } Logger::log(LogLevel::Debug, "Deleted mobile\t\t\t\t(%s)", this->getNameCapital()); } bool Mobile::setAbilities(const std::string & source) { if (source.empty()) return false; std::vector<std::string> charList = SplitString(source, ";"); if (charList.size() != 5) return false; if (!this->setAbility(Ability::Strength, ToNumber<unsigned int>(charList[0]))) { return false; } if (!this->setAbility(Ability::Agility, ToNumber<unsigned int>(charList[1]))) { return false; } if (!this->setAbility(Ability::Perception, ToNumber<unsigned int>(charList[2]))) { return false; } if (!this->setAbility(Ability::Constitution, ToNumber<unsigned int>(charList[3]))) { return false; } if (!this->setAbility(Ability::Intelligence, ToNumber<unsigned int>(charList[4]))) { return false; } return true; } void Mobile::respawn() { // Delete the models loaded as equipment. for (auto item : equipment) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } equipment.clear(); // Delete the models loaded in the inventory. for (auto item : inventory) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } inventory.clear(); // Intialize the lua state. L = luaL_newstate(); // Load the lua environment. LoadLuaEnvironmet(L, lua_script); // Set the mobile to Alive. this->setHealth(this->getMaxHealth(), true); this->setStamina(this->getMaxStamina(), true); // Trigger the init lua function. this->triggerEventInit(); // Add the mobile to the respawn room. this->respawnRoom->addCharacter(this); // Set the list of exceptions. std::vector<Character *> exceptions; exceptions.push_back(this); // Send the message inside the room. this->room->sendToAll("%s apear from somewhere.\n", exceptions, this->getNameCapital()); // Set the next action time. behaviourTimer = std::chrono::system_clock::now() + std::chrono::seconds(level); // Log to the mud. //Logger::log(LogLevel::Debug, "Respawning " + this->id); } bool Mobile::isAlive() const { return (this->room != nullptr); } bool Mobile::check() const { bool safe = Character::check(); safe &= CorrectAssert(!id.empty()); safe &= CorrectAssert(respawnRoom != nullptr); safe &= CorrectAssert(!keys.empty()); safe &= CorrectAssert(!shortdesc.empty()); safe &= CorrectAssert(!staticdesc.empty()); safe &= CorrectAssert(!actions.empty()); safe &= CorrectAssert(!lua_script.empty()); return safe; } bool Mobile::isMobile() const { return true; } void Mobile::getSheet(Table & sheet) const { // Call the function of the father class. Character::getSheet(sheet); // Add a divider. sheet.addDivider(); // Set the values. sheet.addRow({"Id", this->id}); sheet.addRow({"Respawn Room", ToString(this->respawnRoom->vnum)}); std::string keyGroup; for (auto it : this->keys) { keyGroup += " " + it; } sheet.addRow({"Keys", keyGroup}); sheet.addRow({"Short Desc.", this->shortdesc}); sheet.addRow({"Static Desc.", this->staticdesc}); std::string actionGroup; for (auto it : this->actions) { actionGroup += " " + it; } sheet.addRow({"Actions", actionGroup}); sheet.addRow({"Is Alive", ToString(this->isAlive())}); if (!this->isAlive()) { sheet.addRow({"Respawn Time", ToString(this->getRespawnTime())}); } if (this->controller != nullptr) { sheet.addRow({"Controller", this->controller->getName()}); } sheet.addRow({"Lua Script", this->lua_script}); } std::string Mobile::getName() const { return ToLower(staticdesc); } bool Mobile::hasKey(const std::string & key) const { bool found = false; for (auto iterator : keys) { if (BeginWith(iterator, key)) { found = true; } } return found; } bool Mobile::hasAction(const std::string & _action) const { bool found = false; for (auto iterator : actions) { if (BeginWith(iterator, _action)) { found = true; } } return found; } void Mobile::kill() { auto generateItem = [&](Item * item) { // Set the item vnum. item->vnum = Mud::instance().getMaxVnumItem() + 1; // Add the item to the mud. Mud::instance().addItem(item); // Evaluate the minimum and maximum condition. auto min = (item->maxCondition / 100) * 10; auto max = (item->maxCondition / 100) * 50; // Set a random condition for the new item. item->condition = TRandReal<double>(min, max); }; // Before calling the character kill function, set the vnum for the new // items, and set the item condition to a random value from 10% to 50%. for (auto item : this->inventory) generateItem(item); for (auto item : this->equipment) generateItem(item); // Call the method of the father class. Character::kill(); // Set to 0 the cycle that this mobile has passed dead. nextRespawn = std::chrono::system_clock::now() + std::chrono::seconds(10 * this->level); // Call the LUA function: Event_Death. this->triggerEventDeath(); } int64_t Mobile::getRespawnTime() const { // Return the check if the mobile can be respawned. return std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now() - nextRespawn).count(); } bool Mobile::canRespawn() { // Return the check if the mobile can be respawned. return (this->getRespawnTime() >= 0); } void Mobile::reloadLua() { // Delete the models loaded as equipment. for (auto item : equipment) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } equipment.clear(); // Delete the models loaded in the inventory. for (auto item : inventory) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } inventory.clear(); // Reset the lua state. L = luaL_newstate(); // Load the lua environment. LoadLuaEnvironmet(L, lua_script); // Call the LUA function: Event_Init in order to prepare the mobile. this->triggerEventInit(); } void Mobile::sendMsg(const std::string & msg) { if (controller != NULL) { controller->sendMsg(msg); } else { message_buffer += msg; } } void Mobile::performBehaviour() { if (behaviourQueue.empty()) { this->triggerEventMain(); } if (this->checkBehaviourTimer()) { auto status = behaviourQueue.front()->perform(); if ((status == BehaviourStatus::Finished) || (status == BehaviourStatus::Error)) { behaviourQueue.pop_front(); } } } bool Mobile::checkBehaviourTimer() { // Check if the tic is passed. if (std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now() - behaviourTimer) >= behaviourDelay) { behaviourTimer = std::chrono::system_clock::now(); return true; } return false; } void Mobile::triggerEventInit() { this->mobileThread("EventInit", nullptr, ""); } void Mobile::triggerEventFight(Character * character) { this->mobileThread("EventFight", character, ""); } void Mobile::triggerEventEnter(Character * character) { Logger::log(LogLevel::Trace, "Activating EventEnter."); this->mobileThread("EventEnter", character, ""); behaviourTimer = std::chrono::system_clock::now() - std::chrono::seconds(1); } void Mobile::triggerEventExit(Character * character) { this->mobileThread("EventExit", character, ""); } void Mobile::triggerEventMessage(Character * character, std::string message) { this->mobileThread("EventMessage", character, message); } void Mobile::triggerEventRandom() { this->mobileThread("EventRandom", nullptr, ""); } void Mobile::triggerEventMorning() { this->mobileThread("EventMorning", nullptr, ""); } void Mobile::triggerEventDay() { this->mobileThread("EventDay", nullptr, ""); } void Mobile::triggerEventDusk() { this->mobileThread("EventDusk", nullptr, ""); } void Mobile::triggerEventNight() { this->mobileThread("EventNight", nullptr, ""); } void Mobile::triggerEventDeath() { this->mobileThread("EventDeath", nullptr, ""); } void Mobile::triggerEventMain() { this->mobileThread("EventMain", nullptr, ""); } bool Mobile::mobileThread(std::string event, Character * character, std::string message) { if (!event.empty()) { try { luabridge::LuaRef func = luabridge::getGlobal(L, event.c_str()); if (func.isFunction()) { if (character != nullptr) { if (!message.empty()) { behaviourQueue.emplace_back( std::make_shared<BehaviourP3< Character *, Character *, std::string>>(event, func, this, character, message)); } else { behaviourQueue.emplace_back( std::make_shared< BehaviourP2< Character *, Character *>>(event, func, this, character)); } } else { behaviourQueue.emplace_back( std::make_shared< BehaviourP1<Character *>>(event, func, this)); } } } catch (luabridge::LuaException const & e) { Logger::log(LogLevel::Error, e.what()); } } return true; } void Mobile::updateTicImpl() { // Check if the mobile is alive. if (this->isAlive()) { Character::updateTicImpl(); } else { // Check if the mobile can be respawned. if (this->canRespawn()) { // Respawn the mobile. this->respawn(); } } } void Mobile::updateHourImpl() { if (this->isAlive()) { auto mudHour = MudUpdater::instance().getMudHour(); if (mudHour == 6) { this->triggerEventMorning(); } else if (mudHour == 12) { this->triggerEventDay(); } else if (mudHour == 18) { this->triggerEventDusk(); } else if (mudHour == 24) { this->triggerEventNight(); } else { this->triggerEventRandom(); } } } <commit_msg>Fix reset of Lua environment<commit_after>/// @file mobile.cpp /// @brief Implements mobile methods. /// @author Enrico Fraccaroli /// @date Aug 23 2014 /// @copyright /// Copyright (c) 2016 Enrico Fraccaroli <enrico.fraccaroli@gmail.com> /// Permission is hereby granted, free of charge, to any person obtaining a /// copy of this software and associated documentation files (the "Software"), /// to deal in the Software without restriction, including without limitation /// the rights to use, copy, modify, merge, publish, distribute, sublicense, /// and/or sell copies of the Software, and to permit persons to whom the /// Software is furnished to do so, subject to the following conditions: /// The above copyright notice and this permission notice shall be included /// in all copies or substantial portions of the Software. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL /// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER /// DEALINGS IN THE SOFTWARE. #include "mobile.hpp" #include "generalBehaviour.hpp" #include "lua_script.hpp" #include "logger.hpp" #include "mud.hpp" Mobile::Mobile() : id(), respawnRoom(), keys(), shortdesc(), staticdesc(), actions(), message_buffer(), nextRespawn(), controller(), lua_script(), managedItem(), behaviourQueue(), behaviourTimer(std::chrono::system_clock::now()), behaviourDelay(500000) { // Nothing to do. } Mobile::~Mobile() { // Delete only the temporary items. for (auto item : equipment) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } for (auto item : inventory) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } if (this->isAlive()) { room->removeCharacter(this); } Logger::log(LogLevel::Debug, "Deleted mobile\t\t\t\t(%s)", this->getNameCapital()); } bool Mobile::setAbilities(const std::string & source) { if (source.empty()) return false; std::vector<std::string> charList = SplitString(source, ";"); if (charList.size() != 5) return false; if (!this->setAbility(Ability::Strength, ToNumber<unsigned int>(charList[0]))) { return false; } if (!this->setAbility(Ability::Agility, ToNumber<unsigned int>(charList[1]))) { return false; } if (!this->setAbility(Ability::Perception, ToNumber<unsigned int>(charList[2]))) { return false; } if (!this->setAbility(Ability::Constitution, ToNumber<unsigned int>(charList[3]))) { return false; } if (!this->setAbility(Ability::Intelligence, ToNumber<unsigned int>(charList[4]))) { return false; } return true; } void Mobile::respawn() { // Delete the models loaded as equipment. for (auto item : equipment) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } equipment.clear(); // Delete the models loaded in the inventory. for (auto item : inventory) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } inventory.clear(); // Intialize the lua state. L = luaL_newstate(); // Load the lua environment. LoadLuaEnvironmet(L, lua_script); // Set the mobile to Alive. this->setHealth(this->getMaxHealth(), true); this->setStamina(this->getMaxStamina(), true); // Trigger the init lua function. this->triggerEventInit(); // Add the mobile to the respawn room. this->respawnRoom->addCharacter(this); // Set the list of exceptions. std::vector<Character *> exceptions; exceptions.push_back(this); // Send the message inside the room. this->room->sendToAll("%s apear from somewhere.\n", exceptions, this->getNameCapital()); // Set the next action time. behaviourTimer = std::chrono::system_clock::now() + std::chrono::seconds(level); // Log to the mud. //Logger::log(LogLevel::Debug, "Respawning " + this->id); } bool Mobile::isAlive() const { return (this->room != nullptr); } bool Mobile::check() const { bool safe = Character::check(); safe &= CorrectAssert(!id.empty()); safe &= CorrectAssert(respawnRoom != nullptr); safe &= CorrectAssert(!keys.empty()); safe &= CorrectAssert(!shortdesc.empty()); safe &= CorrectAssert(!staticdesc.empty()); safe &= CorrectAssert(!actions.empty()); safe &= CorrectAssert(!lua_script.empty()); return safe; } bool Mobile::isMobile() const { return true; } void Mobile::getSheet(Table & sheet) const { // Call the function of the father class. Character::getSheet(sheet); // Add a divider. sheet.addDivider(); // Set the values. sheet.addRow({"Id", this->id}); sheet.addRow({"Respawn Room", ToString(this->respawnRoom->vnum)}); std::string keyGroup; for (auto it : this->keys) { keyGroup += " " + it; } sheet.addRow({"Keys", keyGroup}); sheet.addRow({"Short Desc.", this->shortdesc}); sheet.addRow({"Static Desc.", this->staticdesc}); std::string actionGroup; for (auto it : this->actions) { actionGroup += " " + it; } sheet.addRow({"Actions", actionGroup}); sheet.addRow({"Is Alive", ToString(this->isAlive())}); if (!this->isAlive()) { sheet.addRow({"Respawn Time", ToString(this->getRespawnTime())}); } if (this->controller != nullptr) { sheet.addRow({"Controller", this->controller->getName()}); } sheet.addRow({"Lua Script", this->lua_script}); } std::string Mobile::getName() const { return ToLower(staticdesc); } bool Mobile::hasKey(const std::string & key) const { bool found = false; for (auto iterator : keys) { if (BeginWith(iterator, key)) { found = true; } } return found; } bool Mobile::hasAction(const std::string & _action) const { bool found = false; for (auto iterator : actions) { if (BeginWith(iterator, _action)) { found = true; } } return found; } void Mobile::kill() { auto generateItem = [&](Item * item) { // Set the item vnum. item->vnum = Mud::instance().getMaxVnumItem() + 1; // Add the item to the mud. Mud::instance().addItem(item); // Evaluate the minimum and maximum condition. auto min = (item->maxCondition / 100) * 10; auto max = (item->maxCondition / 100) * 50; // Set a random condition for the new item. item->condition = TRandReal<double>(min, max); }; // Before calling the character kill function, set the vnum for the new // items, and set the item condition to a random value from 10% to 50%. for (auto item : this->inventory) generateItem(item); for (auto item : this->equipment) generateItem(item); // Call the method of the father class. Character::kill(); // Set to 0 the cycle that this mobile has passed dead. nextRespawn = std::chrono::system_clock::now() + std::chrono::seconds(10 * this->level); // Call the LUA function: Event_Death. this->triggerEventDeath(); } int64_t Mobile::getRespawnTime() const { // Return the check if the mobile can be respawned. return std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now() - nextRespawn).count(); } bool Mobile::canRespawn() { // Return the check if the mobile can be respawned. return (this->getRespawnTime() >= 0); } void Mobile::reloadLua() { // Delete the models loaded as equipment. for (auto item : equipment) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } equipment.clear(); // Delete the models loaded in the inventory. for (auto item : inventory) { if (HasFlag(item->flags, ItemFlag::Temporary)) { delete (item); } } inventory.clear(); // Completely clear the stack. lua_settop(L, 0); // Reset the lua state. L = luaL_newstate(); // Load the lua environment. LoadLuaEnvironmet(L, lua_script); // Call the LUA function: Event_Init in order to prepare the mobile. this->triggerEventInit(); } void Mobile::sendMsg(const std::string & msg) { if (controller != NULL) { controller->sendMsg(msg); } else { message_buffer += msg; } } void Mobile::performBehaviour() { if (behaviourQueue.empty()) { this->triggerEventMain(); } if (this->checkBehaviourTimer()) { auto status = behaviourQueue.front()->perform(); if ((status == BehaviourStatus::Finished) || (status == BehaviourStatus::Error)) { behaviourQueue.pop_front(); } } } bool Mobile::checkBehaviourTimer() { // Check if the tic is passed. if (std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now() - behaviourTimer) >= behaviourDelay) { behaviourTimer = std::chrono::system_clock::now(); return true; } return false; } void Mobile::triggerEventInit() { this->mobileThread("EventInit", nullptr, ""); } void Mobile::triggerEventFight(Character * character) { this->mobileThread("EventFight", character, ""); } void Mobile::triggerEventEnter(Character * character) { Logger::log(LogLevel::Trace, "Activating EventEnter."); this->mobileThread("EventEnter", character, ""); behaviourTimer = std::chrono::system_clock::now() - std::chrono::seconds(1); } void Mobile::triggerEventExit(Character * character) { this->mobileThread("EventExit", character, ""); } void Mobile::triggerEventMessage(Character * character, std::string message) { this->mobileThread("EventMessage", character, message); } void Mobile::triggerEventRandom() { this->mobileThread("EventRandom", nullptr, ""); } void Mobile::triggerEventMorning() { this->mobileThread("EventMorning", nullptr, ""); } void Mobile::triggerEventDay() { this->mobileThread("EventDay", nullptr, ""); } void Mobile::triggerEventDusk() { this->mobileThread("EventDusk", nullptr, ""); } void Mobile::triggerEventNight() { this->mobileThread("EventNight", nullptr, ""); } void Mobile::triggerEventDeath() { this->mobileThread("EventDeath", nullptr, ""); } void Mobile::triggerEventMain() { this->mobileThread("EventMain", nullptr, ""); } bool Mobile::mobileThread(std::string event, Character * character, std::string message) { if (!event.empty()) { try { luabridge::LuaRef func = luabridge::getGlobal(L, event.c_str()); if (func.isFunction()) { if (character != nullptr) { if (!message.empty()) { behaviourQueue.emplace_back( std::make_shared<BehaviourP3< Character *, Character *, std::string>>(event, func, this, character, message)); } else { behaviourQueue.emplace_back( std::make_shared< BehaviourP2< Character *, Character *>>(event, func, this, character)); } } else { behaviourQueue.emplace_back( std::make_shared< BehaviourP1<Character *>>(event, func, this)); } } } catch (luabridge::LuaException const & e) { Logger::log(LogLevel::Error, e.what()); } } return true; } void Mobile::updateTicImpl() { // Check if the mobile is alive. if (this->isAlive()) { Character::updateTicImpl(); } else { // Check if the mobile can be respawned. if (this->canRespawn()) { // Respawn the mobile. this->respawn(); } } } void Mobile::updateHourImpl() { if (this->isAlive()) { auto mudHour = MudUpdater::instance().getMudHour(); if (mudHour == 6) { this->triggerEventMorning(); } else if (mudHour == 12) { this->triggerEventDay(); } else if (mudHour == 18) { this->triggerEventDusk(); } else if (mudHour == 24) { this->triggerEventNight(); } else { this->triggerEventRandom(); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: main.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 03:14:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include <rtl/ustring.hxx> #include <stdio.h> #include <com/sun/star/io/IOException.hpp> #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif using namespace rtl; #include <map> #include <list> struct ini_NameValue { rtl::OUString sName; rtl::OUString sValue; inline ini_NameValue() SAL_THROW( () ) {} inline ini_NameValue( OUString const & name, OUString const & value ) SAL_THROW( () ) : sName( name ), sValue( value ) {} }; typedef std::list< ini_NameValue > NameValueList; struct ini_Section { rtl::OUString sName; NameValueList lList; }; typedef std::map<rtl::OUString, ini_Section >IniSectionMap; class IniParser { IniSectionMap mAllSection; public: IniSectionMap * getAllSection(){return &mAllSection;}; ini_Section * getSection(OUString const & secName) { if (mAllSection.find(secName) != mAllSection.end()) return &mAllSection[secName]; return NULL; } IniParser(OUString const & rIniName) throw(com::sun::star::io::IOException ) { OUString curDirPth; OUString iniUrl; osl_getProcessWorkingDir( &curDirPth.pData ); if (osl_getAbsoluteFileURL( curDirPth.pData, rIniName.pData, &iniUrl.pData )) throw ::com::sun::star::io::IOException(); #if OSL_DEBUG_LEVEL > 1 OString sFile = OUStringToOString(iniUrl, RTL_TEXTENCODING_ASCII_US); OSL_TRACE(__FILE__" -- parser() - %s\n", sFile.getStr()); #endif oslFileHandle handle=NULL; if (iniUrl.getLength() && osl_File_E_None == osl_openFile(iniUrl.pData, &handle, osl_File_OpenFlag_Read)) { rtl::ByteSequence seq; sal_uInt64 nSize = 0; osl_getFileSize(handle, &nSize); OUString sectionName = OUString::createFromAscii("no name section"); while (true) { sal_uInt64 nPos; if (osl_File_E_None != osl_getFilePos(handle, &nPos) || nPos >= nSize) break; if (osl_File_E_None != osl_readLine(handle , (sal_Sequence **) &seq)) break; OString line( (const sal_Char *) seq.getConstArray(), seq.getLength() ); sal_Int32 nIndex = line.indexOf('='); if (nIndex >= 1) { ini_Section *aSection = &mAllSection[sectionName]; struct ini_NameValue nameValue; nameValue.sName = OStringToOUString( line.copy(0,nIndex).trim(), RTL_TEXTENCODING_ASCII_US ); nameValue.sValue = OStringToOUString( line.copy(nIndex+1).trim(), RTL_TEXTENCODING_UTF8 ); aSection->lList.push_back(nameValue); } else { sal_Int32 nIndexStart = line.indexOf('['); sal_Int32 nIndexEnd = line.indexOf(']'); if ( nIndexEnd > nIndexStart && nIndexStart >=0) { sectionName = OStringToOUString( line.copy(nIndexStart + 1,nIndexEnd - nIndexStart -1).trim(), RTL_TEXTENCODING_ASCII_US ); if (!sectionName.getLength()) sectionName = OUString::createFromAscii("no name section"); ini_Section *aSection = &mAllSection[sectionName]; aSection->sName = sectionName; } } } osl_closeFile(handle); } #if OSL_DEBUG_LEVEL > 1 else { OString file_tmp = OUStringToOString(iniUrl, RTL_TEXTENCODING_ASCII_US); OSL_TRACE( __FILE__" -- couldn't open file: %s", file_tmp.getStr() ); throw ::com::sun::star::io::IOException(); } #endif } #if OSL_DEBUG_LEVEL > 1 void Dump() { IniSectionMap::iterator iBegin = mAllSection.begin(); IniSectionMap::iterator iEnd = mAllSection.end(); for(;iBegin != iEnd;iBegin++) { ini_Section *aSection = &(*iBegin).second; OString sec_name_tmp = OUStringToOString(aSection->sName, RTL_TEXTENCODING_ASCII_US); for(NameValueList::iterator itor=aSection->lList.begin(); itor != aSection->lList.end(); itor++) { struct ini_NameValue * aValue = &(*itor); OString name_tmp = OUStringToOString(aValue->sName, RTL_TEXTENCODING_ASCII_US); OString value_tmp = OUStringToOString(aValue->sValue, RTL_TEXTENCODING_UTF8); OSL_TRACE( " section=%s name=%s value=%s\n", sec_name_tmp.getStr(), name_tmp.getStr(), value_tmp.getStr() ); } } } #endif }; #if (defined UNX) || (defined OS2) int main( int argc, char * argv[] ) #else int _cdecl main( int argc, char * argv[] ) #endif { IniParser parser(OUString::createFromAscii("test.ini")); parser.Dump(); return 0; } <commit_msg>INTEGRATION: CWS changefileheader (1.5.216); FILE MERGED 2008/04/01 15:09:33 thb 1.5.216.2: #i85898# Stripping all external header guards 2008/03/28 15:24:42 rt 1.5.216.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: main.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include <rtl/ustring.hxx> #include <stdio.h> #include <com/sun/star/io/IOException.hpp> #include <osl/process.h> using namespace rtl; #include <map> #include <list> struct ini_NameValue { rtl::OUString sName; rtl::OUString sValue; inline ini_NameValue() SAL_THROW( () ) {} inline ini_NameValue( OUString const & name, OUString const & value ) SAL_THROW( () ) : sName( name ), sValue( value ) {} }; typedef std::list< ini_NameValue > NameValueList; struct ini_Section { rtl::OUString sName; NameValueList lList; }; typedef std::map<rtl::OUString, ini_Section >IniSectionMap; class IniParser { IniSectionMap mAllSection; public: IniSectionMap * getAllSection(){return &mAllSection;}; ini_Section * getSection(OUString const & secName) { if (mAllSection.find(secName) != mAllSection.end()) return &mAllSection[secName]; return NULL; } IniParser(OUString const & rIniName) throw(com::sun::star::io::IOException ) { OUString curDirPth; OUString iniUrl; osl_getProcessWorkingDir( &curDirPth.pData ); if (osl_getAbsoluteFileURL( curDirPth.pData, rIniName.pData, &iniUrl.pData )) throw ::com::sun::star::io::IOException(); #if OSL_DEBUG_LEVEL > 1 OString sFile = OUStringToOString(iniUrl, RTL_TEXTENCODING_ASCII_US); OSL_TRACE(__FILE__" -- parser() - %s\n", sFile.getStr()); #endif oslFileHandle handle=NULL; if (iniUrl.getLength() && osl_File_E_None == osl_openFile(iniUrl.pData, &handle, osl_File_OpenFlag_Read)) { rtl::ByteSequence seq; sal_uInt64 nSize = 0; osl_getFileSize(handle, &nSize); OUString sectionName = OUString::createFromAscii("no name section"); while (true) { sal_uInt64 nPos; if (osl_File_E_None != osl_getFilePos(handle, &nPos) || nPos >= nSize) break; if (osl_File_E_None != osl_readLine(handle , (sal_Sequence **) &seq)) break; OString line( (const sal_Char *) seq.getConstArray(), seq.getLength() ); sal_Int32 nIndex = line.indexOf('='); if (nIndex >= 1) { ini_Section *aSection = &mAllSection[sectionName]; struct ini_NameValue nameValue; nameValue.sName = OStringToOUString( line.copy(0,nIndex).trim(), RTL_TEXTENCODING_ASCII_US ); nameValue.sValue = OStringToOUString( line.copy(nIndex+1).trim(), RTL_TEXTENCODING_UTF8 ); aSection->lList.push_back(nameValue); } else { sal_Int32 nIndexStart = line.indexOf('['); sal_Int32 nIndexEnd = line.indexOf(']'); if ( nIndexEnd > nIndexStart && nIndexStart >=0) { sectionName = OStringToOUString( line.copy(nIndexStart + 1,nIndexEnd - nIndexStart -1).trim(), RTL_TEXTENCODING_ASCII_US ); if (!sectionName.getLength()) sectionName = OUString::createFromAscii("no name section"); ini_Section *aSection = &mAllSection[sectionName]; aSection->sName = sectionName; } } } osl_closeFile(handle); } #if OSL_DEBUG_LEVEL > 1 else { OString file_tmp = OUStringToOString(iniUrl, RTL_TEXTENCODING_ASCII_US); OSL_TRACE( __FILE__" -- couldn't open file: %s", file_tmp.getStr() ); throw ::com::sun::star::io::IOException(); } #endif } #if OSL_DEBUG_LEVEL > 1 void Dump() { IniSectionMap::iterator iBegin = mAllSection.begin(); IniSectionMap::iterator iEnd = mAllSection.end(); for(;iBegin != iEnd;iBegin++) { ini_Section *aSection = &(*iBegin).second; OString sec_name_tmp = OUStringToOString(aSection->sName, RTL_TEXTENCODING_ASCII_US); for(NameValueList::iterator itor=aSection->lList.begin(); itor != aSection->lList.end(); itor++) { struct ini_NameValue * aValue = &(*itor); OString name_tmp = OUStringToOString(aValue->sName, RTL_TEXTENCODING_ASCII_US); OString value_tmp = OUStringToOString(aValue->sValue, RTL_TEXTENCODING_UTF8); OSL_TRACE( " section=%s name=%s value=%s\n", sec_name_tmp.getStr(), name_tmp.getStr(), value_tmp.getStr() ); } } } #endif }; #if (defined UNX) || (defined OS2) int main( int argc, char * argv[] ) #else int _cdecl main( int argc, char * argv[] ) #endif { IniParser parser(OUString::createFromAscii("test.ini")); parser.Dump(); return 0; } <|endoftext|>
<commit_before>/* <x0/mod_sendfile.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * * (c) 2009 Chrisitan Parpart <trapni@gentoo.org> */ #include <x0/server.hpp> #include <x0/request.hpp> #include <x0/response.hpp> #include <x0/range_def.hpp> #include <x0/strutils.hpp> #include <x0/types.hpp> #include <x0/io/file_source.hpp> #include <x0/io/buffer_source.hpp> #include <x0/io/composite_source.hpp> #include <x0/io/file.hpp> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <sstream> #include <sys/sendfile.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <time.h> /* feature to detect origin mime types of backup files. */ #define X0_SENDFILE_MIME_TYPES_BELOW_BACKUP 1 /** * \ingroup plugins * \brief serves static files from server's local filesystem to client. */ class sendfile_plugin : public x0::plugin { private: x0::request_handler::connection c; public: sendfile_plugin(x0::server& srv, const std::string& name) : x0::plugin(srv, name), c() { c = server_.generate_content.connect(&sendfile_plugin::sendfile, this); } ~sendfile_plugin() { c.disconnect(); } virtual void configure() { } private: /** * verifies wether the client may use its cache or not. * * \param in request object * \param out response object. this will be modified in case of cache reusability. * * \throw response::not_modified, in case the client may use its cache. */ void verify_client_cache(x0::request& in, x0::response& out) // {{{ { // If-None-Match, If-Modified-Since std::string value; if ((value = in.header("If-None-Match")) != "") { if (value == in.fileinfo->etag()) { if ((value = in.header("If-Modified-Since")) != "") // ETag + If-Modified-Since { x0::datetime date(value); if (date.valid()) { if (in.fileinfo->mtime() <= date.unixtime()) { throw x0::response::not_modified; } } } else // ETag-only { throw x0::response::not_modified; } } } else if ((value = in.header("If-Modified-Since")) != "") { x0::datetime date(value); if (date.valid()) { if (in.fileinfo->mtime() <= date.unixtime()) { throw x0::response::not_modified; } } } } // }}} enum method_type { HEAD, GET }; void sendfile(x0::request_handler::invokation_iterator next, x0::request *in, x0::response *out) // {{{ { std::string path(in->fileinfo->filename()); if (!in->fileinfo->exists()) return next(); if (!in->fileinfo->is_regular()) return next(); verify_client_cache(*in, *out); out->headers.push_back("Last-Modified", in->fileinfo->last_modified()); out->headers.push_back("ETag", in->fileinfo->etag()); x0::file_ptr f; if (equals(in->method, "GET")) { f.reset(new x0::file(in->fileinfo)); if (f->handle() == -1) { server_.log(x0::severity::error, "Could not open file '%s': %s", path.c_str(), strerror(errno)); return next(); } } else if (!equals(in->method, "HEAD")) return next(); if (!process_range_request(*in, *out, f)) { out->status = x0::response::ok; out->headers.push_back("Accept-Ranges", "bytes"); out->headers.push_back("Content-Type", in->fileinfo->mimetype()); out->headers.push_back("Content-Length", boost::lexical_cast<std::string>(in->fileinfo->size())); if (!f) return next.done(); posix_fadvise(f->handle(), 0, in->fileinfo->size(), POSIX_FADV_SEQUENTIAL); out->write( std::make_shared<x0::file_source>(f, 0, in->fileinfo->size()), std::bind(&sendfile_plugin::done, this, next) ); } } // }}} void done(x0::request_handler::invokation_iterator next) { next.done(); } inline bool process_range_request(x0::request& in, x0::response& out, x0::file_ptr& f) //{{{ { #if 1 return false; #else x0::buffer_ref range_value(in.header("Range")); x0::range_def range; // if no range request or range request was invalid (by syntax) we fall back to a full response if (range_value.empty() || !range.parse(range_value)) return false; out.status = x0::response::partial_content; if (range.size() > 1) { // generate a multipart/byteranged response, as we've more than one range to serve x0::buffer buf; x0::source_ptr content(new x0::composite_source); x0::composite_source& cc = *static_cast<x0::composite_source *>(content.get()); std::string boundary(boundary_generate()); std::size_t content_length = 0; for (int i = 0, e = range.size(); i != e; ) { std::pair<std::size_t, std::size_t> offsets(make_offsets(range[i], in.fileinfo->size())); std::size_t length = 1 + offsets.second - offsets.first; buf.clear(); buf.push_back("\r\n--"); buf.push_back(boundary); buf.push_back("\r\nContent-Type: "); buf.push_back(in.fileinfo->mimetype()); buf.push_back("\r\nContent-Range: bytes "); buf.push_back(boost::lexical_cast<std::string>(offsets.first)); buf.push_back("-"); buf.push_back(boost::lexical_cast<std::string>(offsets.second)); buf.push_back("/"); buf.push_back(boost::lexical_cast<std::string>(in.fileinfo->size())); buf.push_back("\r\n\r\n"); cc.push_back(x0::source_ptr(new x0::buffer_source(buf))); cc.push_back(x0::source_ptr(new x0::file_source(f, offsets.first, length))); content_length += buf.size() + length; } buf.clear(); buf.push_back("\r\n--"); buf.push_back(boundary); buf.push_back("--\r\n"); cc.push_back(x0::source_ptr(new x0::buffer_source(buf))); content_length += buf.size(); out.header("Content-Type", "multipart/byteranges; boundary=" + boundary); out.header("Content-Length", boost::lexical_cast<std::string>(content_length)); if (f) { // TODO it sould wrap finish to check error_code of the write result out.write(content, std::bind(&x0::response::finish, this)); } } else { // generate a simple partial response std::pair<std::size_t, std::size_t> offsets(make_offsets(range[0], in.fileinfo->size())); std::size_t length = 1 + offsets.second - offsets.first; out.header("Content-Type", in.fileinfo->mimetype()); out.header("Content-Length", boost::lexical_cast<std::string>(length)); std::stringstream cr; cr << "bytes " << offsets.first << '-' << offsets.second << '/' << in.fileinfo->size(); out.header("Content-Range", cr.str()); if (f) { out.write( std::make_shared<x0::file_source>(f, offsets.first, length), std::bind(response::finish, &out, asio::placeholders::error) ); } } return true; #endif }//}}} std::pair<std::size_t, std::size_t> make_offsets(const std::pair<std::size_t, std::size_t>& p, std::size_t actual_size) { std::pair<std::size_t, std::size_t> q; if (p.first == x0::range_def::npos) // suffix-range-spec { q.first = actual_size - p.second; q.second = actual_size - 1; } else { q.first = p.first; q.second = p.second == x0::range_def::npos && p.second > actual_size ? actual_size - 1 : p.second; } if (q.second < q.first) throw x0::response::requested_range_not_satisfiable; return q; } /** * generates a boundary tag. * * \return a value usable as boundary tag. */ inline std::string boundary_generate() const { static const char *map = "0123456789abcdef"; char buf[16 + 1]; for (std::size_t i = 0; i < sizeof(buf) - 1; ++i) buf[i] = map[random() % (sizeof(buf) - 1)]; buf[sizeof(buf) - 1] = '\0'; return std::string(buf); } }; X0_EXPORT_PLUGIN(sendfile); <commit_msg>sendfile: resurrected HTTP Range support<commit_after>/* <x0/mod_sendfile.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * * (c) 2009 Chrisitan Parpart <trapni@gentoo.org> */ #include <x0/server.hpp> #include <x0/request.hpp> #include <x0/response.hpp> #include <x0/range_def.hpp> #include <x0/strutils.hpp> #include <x0/types.hpp> #include <x0/io/file_source.hpp> #include <x0/io/buffer_source.hpp> #include <x0/io/composite_source.hpp> #include <x0/io/file.hpp> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <sstream> #include <sys/sendfile.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <time.h> /* feature to detect origin mime types of backup files. */ #define X0_SENDFILE_MIME_TYPES_BELOW_BACKUP 1 /** * \ingroup plugins * \brief serves static files from server's local filesystem to client. */ class sendfile_plugin : public x0::plugin { private: x0::request_handler::connection c; public: sendfile_plugin(x0::server& srv, const std::string& name) : x0::plugin(srv, name), c() { c = server_.generate_content.connect(&sendfile_plugin::sendfile, this); } ~sendfile_plugin() { c.disconnect(); } virtual void configure() { } private: /** * verifies wether the client may use its cache or not. * * \param in request object * \param out response object. this will be modified in case of cache reusability. * * \throw response::not_modified, in case the client may use its cache. */ void verify_client_cache(x0::request *in, x0::response *out) // {{{ { // If-None-Match, If-Modified-Since std::string value; if ((value = in->header("If-None-Match")) != "") { if (value == in->fileinfo->etag()) { if ((value = in->header("If-Modified-Since")) != "") // ETag + If-Modified-Since { x0::datetime date(value); if (date.valid()) { if (in->fileinfo->mtime() <= date.unixtime()) { throw x0::response::not_modified; } } } else // ETag-only { throw x0::response::not_modified; } } } else if ((value = in->header("If-Modified-Since")) != "") { x0::datetime date(value); if (date.valid()) { if (in->fileinfo->mtime() <= date.unixtime()) { throw x0::response::not_modified; } } } } // }}} enum method_type { HEAD, GET }; void sendfile(x0::request_handler::invokation_iterator next, x0::request *in, x0::response *out) // {{{ { std::string path(in->fileinfo->filename()); if (!in->fileinfo->exists()) return next(); if (!in->fileinfo->is_regular()) return next(); verify_client_cache(in, out); out->headers.push_back("Last-Modified", in->fileinfo->last_modified()); out->headers.push_back("ETag", in->fileinfo->etag()); x0::file_ptr f; if (equals(in->method, "GET")) { f.reset(new x0::file(in->fileinfo)); if (f->handle() == -1) { server_.log(x0::severity::error, "Could not open file '%s': %s", path.c_str(), strerror(errno)); return next(); } } else if (!equals(in->method, "HEAD")) return next(); if (!process_range_request(next, in, out, f)) { out->status = x0::response::ok; out->headers.push_back("Accept-Ranges", "bytes"); out->headers.push_back("Content-Type", in->fileinfo->mimetype()); out->headers.push_back("Content-Length", boost::lexical_cast<std::string>(in->fileinfo->size())); if (!f) return next.done(); posix_fadvise(f->handle(), 0, in->fileinfo->size(), POSIX_FADV_SEQUENTIAL); out->write( std::make_shared<x0::file_source>(f, 0, in->fileinfo->size()), std::bind(&sendfile_plugin::done, this, next) ); } } // }}} void done(x0::request_handler::invokation_iterator next) { next.done(); } inline bool process_range_request(x0::request_handler::invokation_iterator next, x0::request *in, x0::response *out, x0::file_ptr& f) //{{{ { x0::buffer_ref range_value(in->header("Range")); x0::range_def range; // if no range request or range request was invalid (by syntax) we fall back to a full response if (range_value.empty() || !range.parse(range_value)) return false; out->status = x0::response::partial_content; if (range.size() > 1) { // generate a multipart/byteranged response, as we've more than one range to serve auto content = std::make_shared<x0::composite_source>(); x0::buffer buf; std::string boundary(boundary_generate()); std::size_t content_length = 0; for (int i = 0, e = range.size(); i != e; ++i) { std::pair<std::size_t, std::size_t> offsets(make_offsets(range[i], in->fileinfo->size())); std::size_t length = 1 + offsets.second - offsets.first; buf.clear(); buf.push_back("\r\n--"); buf.push_back(boundary); buf.push_back("\r\nContent-Type: "); buf.push_back(in->fileinfo->mimetype()); buf.push_back("\r\nContent-Range: bytes "); buf.push_back(boost::lexical_cast<std::string>(offsets.first)); buf.push_back("-"); buf.push_back(boost::lexical_cast<std::string>(offsets.second)); buf.push_back("/"); buf.push_back(boost::lexical_cast<std::string>(in->fileinfo->size())); buf.push_back("\r\n\r\n"); content->push_back(std::make_shared<x0::buffer_source>(buf)); content->push_back(std::make_shared<x0::file_source>(f, offsets.first, length)); content_length += buf.size() + length; } buf.clear(); buf.push_back("\r\n--"); buf.push_back(boundary); buf.push_back("--\r\n"); content->push_back(std::make_shared<x0::buffer_source>(buf)); content_length += buf.size(); out->headers.push_back("Content-Type", "multipart/byteranges; boundary=" + boundary); out->headers.push_back("Content-Length", boost::lexical_cast<std::string>(content_length)); if (f) { out->write(content, std::bind(&sendfile_plugin::done, this, next)); } } else { // generate a simple partial response std::pair<std::size_t, std::size_t> offsets(make_offsets(range[0], in->fileinfo->size())); std::size_t length = 1 + offsets.second - offsets.first; out->headers.push_back("Content-Type", in->fileinfo->mimetype()); out->headers.push_back("Content-Length", boost::lexical_cast<std::string>(length)); std::stringstream cr; cr << "bytes " << offsets.first << '-' << offsets.second << '/' << in->fileinfo->size(); out->headers.push_back("Content-Range", cr.str()); if (f) { out->write( std::make_shared<x0::file_source>(f, offsets.first, length), std::bind(&sendfile_plugin::done, this, next) ); } } return true; }//}}} std::pair<std::size_t, std::size_t> make_offsets(const std::pair<std::size_t, std::size_t>& p, std::size_t actual_size) { std::pair<std::size_t, std::size_t> q; if (p.first == x0::range_def::npos) // suffix-range-spec { q.first = actual_size - p.second; q.second = actual_size - 1; } else { q.first = p.first; q.second = p.second == x0::range_def::npos && p.second > actual_size ? actual_size - 1 : p.second; } if (q.second < q.first) throw x0::response::requested_range_not_satisfiable; return q; } /** * generates a boundary tag. * * \return a value usable as boundary tag. */ inline std::string boundary_generate() const { static const char *map = "0123456789abcdef"; char buf[16 + 1]; for (std::size_t i = 0; i < sizeof(buf) - 1; ++i) buf[i] = map[random() % (sizeof(buf) - 1)]; buf[sizeof(buf) - 1] = '\0'; return std::string(buf); } }; X0_EXPORT_PLUGIN(sendfile); <|endoftext|>
<commit_before>#include "consts.h" #include "circuits/element.h" #include "matrix/matrix.h" #include <sstream> #include <cstdlib> #include <set> #include <math.h> //TODO: not to use cout inside Element class #include <iostream> // Element::Element() { } Element::Element(string netlistLine, int &numNodes, vector<string> &variablesList): polynomial(false) { stringstream sstream(netlistLine); char na[MAX_NAME], nb[MAX_NAME], nc[MAX_NAME], nd[MAX_NAME]; vector<double> _params(MAX_PARAMS); for (int i=0; i<MAX_PARAMS; i++){ _params[i] = 0; } sstream >> name; cout << name << " "; type = getType(); sstream.str( string(netlistLine, name.size(), string::npos) ); if (type=='R' || type=='I' || type=='V') { sstream >> na >> nb; cout << na << " " << nb << " "; for (int i = 0; i < MAX_PARAMS; i++){ sstream >> _params[i]; if (i>=1 && _params[i]!=0) polynomial = true; } if (!polynomial){ value = _params[0]; cout << value << endl; } else { params = _params; for (int i = 0; i < MAX_PARAMS; i++){ cout << params[i] << " "; } cout << endl; } a = getNodeNumber(na, numNodes, variablesList); b = getNodeNumber(nb, numNodes, variablesList); } else if (type=='G' || type=='E' || type=='F' || type=='H') { sstream >> na >> nb >> nc >> nd >> value; cout << name << " " << na << " " << nb << " " << nc << " " << nd << " "<< value << endl; a = getNodeNumber(na, numNodes, variablesList); b = getNodeNumber(nb, numNodes, variablesList); c = getNodeNumber(nc, numNodes, variablesList); d = getNodeNumber(nd, numNodes, variablesList); } else if (type=='O') { sstream >> na >> nb >> nc >> nd; cout << name << " " << na << " " << nb << " " << nc << " " << nd << " " << endl; a = getNodeNumber(na, numNodes, variablesList); b = getNodeNumber(nb, numNodes, variablesList); c = getNodeNumber(nc, numNodes, variablesList); d = getNodeNumber(nd, numNodes, variablesList); } } void Element::addCurrentVariables(int &numVariables, vector<string> &variablesList){ if (type=='V' || type=='E' || type=='F' || type=='O') { numVariables++; if (numVariables>MAX_NODES) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NODES << ")" << endl; exit(EXIT_FAILURE); } x=numVariables; variablesList[numVariables] = "j" + name; } else if (type=='H') { numVariables=numVariables+2; x=numVariables-1; y=numVariables; variablesList[numVariables-1] = "jx" + name; variablesList[numVariables] = "jy" + name; } } Element::Element(string name, double value, int a, int b, int c, int d, int x, int y): name(name), value(value), a(a), b(b), c(c), d(d), x(x), y(y), polynomial(false) { type = getType(); } Element::Element(string name, vector<double> &params, int a, int b, int c, int d): name(name), params(params), a(a), b(b), c(c), d(d), polynomial(true) { type = getType(); } void Element::calcNewtonRaphsonParameters(const double &Xn){ dFx = params[1]; FxMinusdFxTimesXn = params[0]; for (int i = 2; i < MAX_PARAMS; i++){ dFx += params[i]*(i)*pow(Xn, i-1); FxMinusdFxTimesXn -= params[i]*(i-1)*pow(Xn, i); } } void Element::applyStamp(double Yn[MAX_NODES+1][MAX_NODES+2], const int &numVariables, double previousSolution[MAX_NODES+1]) { double g; if (type=='R') { double G; if (!polynomial){ G=1/value; } else { double Vab = previousSolution[a]-previousSolution[b]; calcNewtonRaphsonParameters(Vab); G = dFx; double I0; I0 = FxMinusdFxTimesXn; Yn[a][numVariables+1]-=I0; Yn[b][numVariables+1]+=I0; } Yn[a][a]+=G; Yn[b][b]+=G; Yn[a][b]-=G; Yn[b][a]-=G; } else if (type=='G') { double G; if (!polynomial){ G=value; } else { double Vcd = previousSolution[c]-previousSolution[d]; calcNewtonRaphsonParameters(Vcd); G = dFx; double I0; I0 = FxMinusdFxTimesXn; Yn[a][numVariables+1]-=I0; Yn[b][numVariables+1]+=I0; } Yn[a][c]+=G; Yn[b][d]+=G; Yn[a][d]-=G; Yn[b][c]-=G; } else if (type=='I') { g=value; Yn[a][numVariables+1]-=g; Yn[b][numVariables+1]+=g; } else if (type=='V') { Yn[a][x]+=1; Yn[b][x]-=1; Yn[x][a]-=1; Yn[x][b]+=1; Yn[x][numVariables+1]-=value; } else if (type=='E') { // Voltage Amplifier double A; double k; if (!polynomial){ A=value; k=1; } else { double Vcd = previousSolution[c]-previousSolution[d]; calcNewtonRaphsonParameters(Vcd); A = dFx; double V0; V0 = FxMinusdFxTimesXn; Yn[x][numVariables+1]-=V0; k=2; } Yn[a][x]+=k*1; Yn[b][x]-=k*1; Yn[x][a]-=k*1; Yn[x][b]+=k*1; Yn[x][c]+=A; Yn[x][d]-=A; } else if (type=='F') { g=value; Yn[a][x]+=g; Yn[b][x]-=g; Yn[c][x]+=1; Yn[d][x]-=1; Yn[x][c]-=1; Yn[x][d]+=1; } else if (type=='H') { g=value; Yn[a][y]+=1; Yn[b][y]-=1; Yn[c][x]+=1; Yn[d][x]-=1; Yn[y][a]-=1; Yn[y][b]+=1; Yn[x][c]-=1; Yn[x][d]+=1; Yn[y][x]+=g; } else if (type=='O') { Yn[a][x]+=1; Yn[b][x]-=1; Yn[x][c]+=1; Yn[x][d]-=1; } } int Element::getNodeNumber(const char *name, int &numNodes, vector<string> &variablesList) { int i=0, achou=0; while (!achou && i<=numNodes) if (!(achou=!variablesList[i].compare(name))) i++; if (!achou) { if (numNodes==MAX_NODES) { cout << "Maximum number of nodes reached: " << MAX_NODES << endl; #if defined (WIN32) || defined(_WIN32) cin.get(); #endif exit(EXIT_FAILURE); } numNodes++; variablesList[numNodes] = name; return numNodes; /* new node */ } else { return i; /* known node */ } } bool Element::isValidElement(const char &netlistLinePrefix){ // Initializing set with tmpElementPrefixes char tmpElementPrefixes[] = { 'R', 'I', 'V', 'G', 'E', 'F', 'H', 'O' }; set<char> elementPrefixes( tmpElementPrefixes, tmpElementPrefixes + sizeof(tmpElementPrefixes) / sizeof(tmpElementPrefixes[0]) ); // Returns whether or not line prefix corresponds to valid Element // verifying if netlistLinePrefix is in elementPrefixes return elementPrefixes.find(netlistLinePrefix) != elementPrefixes.end(); } string Element::getName() const { return name; } char Element::getType() const { return name[0]; } <commit_msg>Refactors simple variables names on test<commit_after>#include "consts.h" #include "circuits/element.h" #include "matrix/matrix.h" #include <sstream> #include <cstdlib> #include <set> #include <math.h> //TODO: not to use cout inside Element class #include <iostream> // Element::Element() { } Element::Element(string netlistLine, int &numNodes, vector<string> &variablesList): polynomial(false) { stringstream sstream(netlistLine); char na[MAX_NAME], nb[MAX_NAME], nc[MAX_NAME], nd[MAX_NAME]; vector<double> _params(MAX_PARAMS); for (int i=0; i<MAX_PARAMS; i++){ _params[i] = 0; } sstream >> name; cout << name << " "; type = getType(); sstream.str( string(netlistLine, name.size(), string::npos) ); if (type=='R' || type=='I' || type=='V') { sstream >> na >> nb; cout << na << " " << nb << " "; for (int i = 0; i < MAX_PARAMS; i++){ sstream >> _params[i]; if (i>=1 && _params[i]!=0) polynomial = true; } if (!polynomial){ value = _params[0]; cout << value << endl; } else { params = _params; for (int i = 0; i < MAX_PARAMS; i++){ cout << params[i] << " "; } cout << endl; } a = getNodeNumber(na, numNodes, variablesList); b = getNodeNumber(nb, numNodes, variablesList); } else if (type=='G' || type=='E' || type=='F' || type=='H') { sstream >> na >> nb >> nc >> nd >> value; cout << name << " " << na << " " << nb << " " << nc << " " << nd << " "<< value << endl; a = getNodeNumber(na, numNodes, variablesList); b = getNodeNumber(nb, numNodes, variablesList); c = getNodeNumber(nc, numNodes, variablesList); d = getNodeNumber(nd, numNodes, variablesList); } else if (type=='O') { sstream >> na >> nb >> nc >> nd; cout << name << " " << na << " " << nb << " " << nc << " " << nd << " " << endl; a = getNodeNumber(na, numNodes, variablesList); b = getNodeNumber(nb, numNodes, variablesList); c = getNodeNumber(nc, numNodes, variablesList); d = getNodeNumber(nd, numNodes, variablesList); } } void Element::addCurrentVariables(int &numVariables, vector<string> &variablesList){ if (type=='V' || type=='E' || type=='F' || type=='O') { numVariables++; if (numVariables>MAX_NODES) { cout << "As correntes extra excederam o numero de variaveis permitido (" << MAX_NODES << ")" << endl; exit(EXIT_FAILURE); } x=numVariables; variablesList[numVariables] = "j" + name; } else if (type=='H') { numVariables=numVariables+2; x=numVariables-1; y=numVariables; variablesList[numVariables-1] = "jx" + name; variablesList[numVariables] = "jy" + name; } } Element::Element(string name, double value, int a, int b, int c, int d, int x, int y): name(name), value(value), a(a), b(b), c(c), d(d), x(x), y(y), polynomial(false) { type = getType(); } Element::Element(string name, vector<double> &params, int a, int b, int c, int d): name(name), params(params), a(a), b(b), c(c), d(d), polynomial(true) { type = getType(); } void Element::calcNewtonRaphsonParameters(const double &Xn){ dFx = params[1]; FxMinusdFxTimesXn = params[0]; for (int i = 2; i < MAX_PARAMS; i++){ dFx += params[i]*(i)*pow(Xn, i-1); FxMinusdFxTimesXn -= params[i]*(i-1)*pow(Xn, i); } } void Element::applyStamp(double Yn[MAX_NODES+1][MAX_NODES+2], const int &numVariables, double previousSolution[MAX_NODES+1]) { double g; if (type=='R') { double G; if (!polynomial){ G=1/value; } else { double Vab = previousSolution[a]-previousSolution[b]; calcNewtonRaphsonParameters(Vab); G = dFx; double I0; I0 = FxMinusdFxTimesXn; Yn[a][numVariables+1]-=I0; Yn[b][numVariables+1]+=I0; } Yn[a][a]+=G; Yn[b][b]+=G; Yn[a][b]-=G; Yn[b][a]-=G; } else if (type=='G') { double G; if (!polynomial){ G=value; } else { double Vcd = previousSolution[c]-previousSolution[d]; calcNewtonRaphsonParameters(Vcd); G = dFx; double I0 = FxMinusdFxTimesXn; Yn[a][numVariables+1]-=I0; Yn[b][numVariables+1]+=I0; } Yn[a][c]+=G; Yn[b][d]+=G; Yn[a][d]-=G; Yn[b][c]-=G; } else if (type=='I') { double I=value; Yn[a][numVariables+1]-=I; Yn[b][numVariables+1]+=I; } else if (type=='V') { Yn[a][x]+=1; Yn[b][x]-=1; Yn[x][a]-=1; Yn[x][b]+=1; Yn[x][numVariables+1]-=value; } else if (type=='E') { // Voltage Amplifier double A; double k; if (!polynomial){ A=value; k=1; } else { double Vcd = previousSolution[c]-previousSolution[d]; calcNewtonRaphsonParameters(Vcd); A = dFx; double V0 = FxMinusdFxTimesXn; Yn[x][numVariables+1]-=V0; k=2; } Yn[a][x]+=k*1; Yn[b][x]-=k*1; Yn[x][a]-=k*1; Yn[x][b]+=k*1; Yn[x][c]+=A; Yn[x][d]-=A; } else if (type=='F') { g=value; Yn[a][x]+=g; Yn[b][x]-=g; Yn[c][x]+=1; Yn[d][x]-=1; Yn[x][c]-=1; Yn[x][d]+=1; } else if (type=='H') { g=value; Yn[a][y]+=1; Yn[b][y]-=1; Yn[c][x]+=1; Yn[d][x]-=1; Yn[y][a]-=1; Yn[y][b]+=1; Yn[x][c]-=1; Yn[x][d]+=1; Yn[y][x]+=g; } else if (type=='O') { Yn[a][x]+=1; Yn[b][x]-=1; Yn[x][c]+=1; Yn[x][d]-=1; } } int Element::getNodeNumber(const char *name, int &numNodes, vector<string> &variablesList) { int i=0, achou=0; while (!achou && i<=numNodes) if (!(achou=!variablesList[i].compare(name))) i++; if (!achou) { if (numNodes==MAX_NODES) { cout << "Maximum number of nodes reached: " << MAX_NODES << endl; #if defined (WIN32) || defined(_WIN32) cin.get(); #endif exit(EXIT_FAILURE); } numNodes++; variablesList[numNodes] = name; return numNodes; /* new node */ } else { return i; /* known node */ } } bool Element::isValidElement(const char &netlistLinePrefix){ // Initializing set with tmpElementPrefixes char tmpElementPrefixes[] = { 'R', 'I', 'V', 'G', 'E', 'F', 'H', 'O' }; set<char> elementPrefixes( tmpElementPrefixes, tmpElementPrefixes + sizeof(tmpElementPrefixes) / sizeof(tmpElementPrefixes[0]) ); // Returns whether or not line prefix corresponds to valid Element // verifying if netlistLinePrefix is in elementPrefixes return elementPrefixes.find(netlistLinePrefix) != elementPrefixes.end(); } string Element::getName() const { return name; } char Element::getType() const { return name[0]; } <|endoftext|>
<commit_before>#include "AbstractRenderer.h" #include "util.h" AbstractRenderer::AbstractRenderer(ty::WorldContext *_ctx, ty::User* _user) : ctx(_ctx), user(_user) { XnMapOutputMode outputMode; ctx->imageGenerator()->GetMapOutputMode(outputMode); camera = ::cvCreateImage(cvSize(outputMode.nXRes, outputMode.nYRes), IPL_DEPTH_8U, 3); if (!camera) { throw std::runtime_error( "error : cvCreateImage" ); } } AbstractRenderer::~AbstractRenderer(void) { } void AbstractRenderer::draw(void) { ctx->updateImage(); ctx->updateDepth(); xn::ImageMetaData imageMD; ctx->imageGenerator()->GetMetaData(imageMD); char* dest = camera->imageData; const xn::RGB24Map& rgb = ctx->imageRGB24Map(); const XnLabel* label = user->scene()->Data(); for (int y = 0; y < ctx->imageHeight(); ++y) { for (int x = 0; x < ctx->imageWidth(); ++x) { XnRGB24Pixel pixel = rgb(x, y); if (label[y*ctx->imageWidth() + x]) { dest[0] = 0; dest[1] = 255; dest[2] = 0; } else { dest[0] = pixel.nRed; dest[1] = pixel.nGreen; dest[2] = pixel.nBlue; } dest += 3; } } ::cvCvtColor(camera, camera, CV_BGR2RGB); ::cvShowImage("KinectImage", camera); } <commit_msg>color blue to red<commit_after>#include "AbstractRenderer.h" #include "util.h" AbstractRenderer::AbstractRenderer(ty::WorldContext *_ctx, ty::User* _user) : ctx(_ctx), user(_user) { XnMapOutputMode outputMode; ctx->imageGenerator()->GetMapOutputMode(outputMode); camera = ::cvCreateImage(cvSize(outputMode.nXRes, outputMode.nYRes), IPL_DEPTH_8U, 3); if (!camera) { throw std::runtime_error( "error : cvCreateImage" ); } } AbstractRenderer::~AbstractRenderer(void) { } void AbstractRenderer::draw(void) { ctx->updateImage(); ctx->updateDepth(); xn::ImageMetaData imageMD; ctx->imageGenerator()->GetMetaData(imageMD); char* dest = camera->imageData; const xn::RGB24Map& rgb = ctx->imageRGB24Map(); const XnLabel* label = user->scene()->Data(); for (int y = 0; y < ctx->imageHeight(); ++y) { for (int x = 0; x < ctx->imageWidth(); ++x) { XnRGB24Pixel pixel = rgb(x, y); if (label[y*ctx->imageWidth() + x]) { dest[0] = 255; dest[1] = 0; dest[2] = 0; } else { dest[0] = pixel.nRed; dest[1] = pixel.nGreen; dest[2] = pixel.nBlue; } dest += 3; } } ::cvCvtColor(camera, camera, CV_BGR2RGB); ::cvShowImage("KinectImage", camera); } <|endoftext|>
<commit_before>#pragma once #include <unordered_map> #include <mutex> #include "base/common_util.hpp" #include "base/table/threadsafe_unordered_map.hpp" #include "client_base.hpp" using namespace czrpc::base::table; namespace czrpc { namespace client { class async_rpc_client : public client_base { public: async_rpc_client(const async_rpc_client&) = delete; async_rpc_client& operator=(const async_rpc_client&) = delete; async_rpc_client() { client_type_ = client_type::async_rpc_client; } virtual void run() override final { client_base::run(); sync_connect(); } using task_t = std::function<void(const response_content&)>; class rpc_task { public: rpc_task(const client_flag& flag, const request_content& content, async_rpc_client* client) : flag_(flag), content_(content), client_(client) {} void result(const std::function<void(const message_ptr&)>& func) { task_ = [&func, this](const response_content& content) { try { func(serialize_util::singleton::get()->deserialize(content.message_name, content.body)); } catch (std::exception& e) { log_warn(e.what()); } }; client_->async_call_one_way(flag_, content_); client_->add_bind_func(content_.call_id, task_); } void result(const std::function<void(const std::string&)>& func) { task_ = [&func, this](const response_content& content) { try { func(content.body); } catch (std::exception& e) { log_warn(e.what()); } }; client_->async_call_one_way(flag_, content_); client_->add_bind_func(content_.call_id, task_); } private: client_flag flag_; request_content content_; task_t task_; async_rpc_client* client_; }; auto async_call(const std::string& func_name, const message_ptr& message) { serialize_util::singleton::get()->check_message(message); sync_connect(); request_content content; content.call_id = gen_uuid(); content.protocol = func_name; content.message_name = message->GetDescriptor()->full_name(); content.body = serialize_util::singleton::get()->serialize(message); client_flag flag{ serialize_mode::serialize, client_type_ }; return rpc_task{ flag, content, this }; } auto async_call_raw(const std::string& func_name, const std::string& body) { sync_connect(); request_content content; content.call_id = gen_uuid(); content.protocol = func_name; content.body = body; client_flag flag{ serialize_mode::non_serialize, client_type_ }; return rpc_task{ flag, content, this }; } private: void async_read_head() { boost::asio::async_read(get_socket(), boost::asio::buffer(res_head_buf_), [this](boost::system::error_code ec, std::size_t) { if (!get_socket().is_open()) { log_warn("Socket is not open"); return; } if (ec) { log_warn(ec.message()); return; } if (async_check_head()) { async_read_content(); } else { async_read_head(); } }); } bool async_check_head() { memcpy(&res_head_, res_head_buf_, sizeof(res_head_buf_)); if (res_head_.call_id_len + res_head_.message_name_len + res_head_.body_len > max_buffer_len) { log_warn("Content len is too big"); return false; } return true; } void async_read_content() { content_.clear(); content_.resize(res_head_.call_id_len + res_head_.message_name_len + res_head_.body_len); boost::asio::async_read(get_socket(), boost::asio::buffer(content_), [this](boost::system::error_code ec, std::size_t) { async_read_head(); if (!get_socket().is_open()) { log_warn("Socket is not open"); return; } if (ec) { log_warn(ec.message()); return; } response_content content; content.call_id.assign(&content_[0], res_head_.call_id_len); content.message_name.assign(&content_[res_head_.call_id_len], res_head_.message_name_len); content.body.assign(&content_[res_head_.call_id_len + res_head_.message_name_len], res_head_.body_len); if (res_head_.error_code == rpc_error_code::ok) { route(content); } else { log_warn(get_rpc_error_string(res_head_.error_code)); task_map_.erase(content.call_id); } }); } void add_bind_func(const std::string& call_id, const task_t& task) { task_map_.emplace(call_id, task); } void route(const response_content& content) { task_t task; if (task_map_.find(content.call_id, task)) { task(content); task_map_.erase(content.call_id); std::cout << "map size: " << task_map_.size() << std::endl; } } void sync_connect() { if (try_connect()) { task_map_.clear(); async_read_head(); } } private: char res_head_buf_[response_header_len]; response_header res_head_; std::vector<char> content_; threadsafe_unordered_map<std::string, task_t> task_map_; }; } } <commit_msg>update<commit_after>#pragma once #include <unordered_map> #include <mutex> #include "base/common_util.hpp" #include "base/table/threadsafe_unordered_map.hpp" #include "client_base.hpp" using namespace czrpc::base::table; namespace czrpc { namespace client { class async_rpc_client : public client_base { public: async_rpc_client(const async_rpc_client&) = delete; async_rpc_client& operator=(const async_rpc_client&) = delete; async_rpc_client() { client_type_ = client_type::async_rpc_client; } virtual void run() override final { client_base::run(); sync_connect(); } using task_t = std::function<void(const response_content&)>; class rpc_task { public: rpc_task(const client_flag& flag, const request_content& content, async_rpc_client* client) : flag_(flag), content_(content), client_(client) {} void result(const std::function<void(const message_ptr&)>& func) { task_ = [func, this](const response_content& content) { try { func(serialize_util::singleton::get()->deserialize(content.message_name, content.body)); } catch (std::exception& e) { log_warn(e.what()); } }; client_->async_call_one_way(flag_, content_); client_->add_bind_func(content_.call_id, task_); } void result(const std::function<void(const std::string&)>& func) { task_ = [func, this](const response_content& content) { try { func(content.body); } catch (std::exception& e) { log_warn(e.what()); } }; client_->async_call_one_way(flag_, content_); client_->add_bind_func(content_.call_id, task_); } private: client_flag flag_; request_content content_; task_t task_; async_rpc_client* client_; }; auto async_call(const std::string& func_name, const message_ptr& message) { serialize_util::singleton::get()->check_message(message); sync_connect(); request_content content; content.call_id = gen_uuid(); content.protocol = func_name; content.message_name = message->GetDescriptor()->full_name(); content.body = serialize_util::singleton::get()->serialize(message); client_flag flag{ serialize_mode::serialize, client_type_ }; return rpc_task{ flag, content, this }; } auto async_call_raw(const std::string& func_name, const std::string& body) { sync_connect(); request_content content; content.call_id = gen_uuid(); content.protocol = func_name; content.body = body; client_flag flag{ serialize_mode::non_serialize, client_type_ }; return rpc_task{ flag, content, this }; } private: void async_read_head() { boost::asio::async_read(get_socket(), boost::asio::buffer(res_head_buf_), [this](boost::system::error_code ec, std::size_t) { if (!get_socket().is_open()) { log_warn("Socket is not open"); return; } if (ec) { log_warn(ec.message()); return; } if (async_check_head()) { async_read_content(); } else { async_read_head(); } }); } bool async_check_head() { memcpy(&res_head_, res_head_buf_, sizeof(res_head_buf_)); if (res_head_.call_id_len + res_head_.message_name_len + res_head_.body_len > max_buffer_len) { log_warn("Content len is too big"); return false; } return true; } void async_read_content() { content_.clear(); content_.resize(res_head_.call_id_len + res_head_.message_name_len + res_head_.body_len); boost::asio::async_read(get_socket(), boost::asio::buffer(content_), [this](boost::system::error_code ec, std::size_t) { async_read_head(); if (!get_socket().is_open()) { log_warn("Socket is not open"); return; } if (ec) { log_warn(ec.message()); return; } response_content content; content.call_id.assign(&content_[0], res_head_.call_id_len); content.message_name.assign(&content_[res_head_.call_id_len], res_head_.message_name_len); content.body.assign(&content_[res_head_.call_id_len + res_head_.message_name_len], res_head_.body_len); if (res_head_.error_code == rpc_error_code::ok) { route(content); } else { log_warn(get_rpc_error_string(res_head_.error_code)); task_map_.erase(content.call_id); } }); } void add_bind_func(const std::string& call_id, const task_t& task) { task_map_.emplace(call_id, task); } void route(const response_content& content) { task_t task; if (task_map_.find(content.call_id, task)) { task(content); task_map_.erase(content.call_id); std::cout << "map size: " << task_map_.size() << std::endl; } } void sync_connect() { if (try_connect()) { task_map_.clear(); async_read_head(); } } private: char res_head_buf_[response_header_len]; response_header res_head_; std::vector<char> content_; threadsafe_unordered_map<std::string, task_t> task_map_; }; } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 NorthScale, 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 <stdlib.h> #include "flusher.hh" bool FlusherStepper::callback(Dispatcher &d, TaskId t) { return flusher->step(d, t); } bool Flusher::stop(void) { return transition_state(stopping); } void Flusher::wait(void) { while (_state != stopped) { usleep(1000); } } bool Flusher::pause(void) { return transition_state(pausing); } bool Flusher::resume(void) { return transition_state(running); } static bool validTransition(enum flusher_state from, enum flusher_state to) { bool rv(true); if (from == initializing && to == running) { } else if (from == running && to == pausing) { } else if (from == running && to == stopping) { } else if (from == pausing && to == paused) { } else if (from == stopping && to == stopped) { } else if (from == paused && to == running) { } else if (from == paused && to == stopping) { } else if (from == pausing && to == stopping) { } else { rv = false; } return rv; } const char * Flusher::stateName(enum flusher_state st) const { static const char * const stateNames[] = { "initializing", "running", "pausing", "paused", "stopping", "stopped" }; assert(st >= initializing && st <= stopped); return stateNames[st]; } bool Flusher::transition_state(enum flusher_state to) { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Attempting transition from %s to %s\n", stateName(_state), stateName(to)); if (!validTransition(_state, to)) { return false; } getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Transitioning from %s to %s\n", stateName(_state), stateName(to)); _state = to; //Reschedule the task LockHolder lh(taskMutex); assert(task.get()); dispatcher->cancel(task); schedule_UNLOCKED(); return true; } const char * Flusher::stateName() const { return stateName(_state); } enum flusher_state Flusher::state() const { return _state; } void Flusher::initialize(TaskId tid) { assert(task.get() == tid.get()); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Initializing flusher; warming up\n"); time_t startTime = time(NULL); store->warmup(); store->stats.warmupTime.set(time(NULL) - startTime); store->stats.warmupComplete.set(true); store->stats.curr_items.incr(store->stats.warmedUp.get()); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Warmup completed in %ds\n", store->stats.warmupTime.get()); transition_state(running); } void Flusher::schedule_UNLOCKED() { dispatcher->schedule(shared_ptr<FlusherStepper>(new FlusherStepper(this)), &task); assert(task.get()); } void Flusher::start(void) { LockHolder lh(taskMutex); schedule_UNLOCKED(); } void Flusher::wake(void) { LockHolder lh(taskMutex); assert(task.get()); dispatcher->wake(task, &task); } bool Flusher::step(Dispatcher &d, TaskId tid) { assert(task.get() == tid.get()); try { switch (_state) { case initializing: initialize(tid); return true; case paused: return false; case pausing: transition_state(paused); return false; case running: { int n = doFlush(); if (n > 0) { if (_state == running) { d.snooze(tid, n); return true; } else { return false; } } else { return true; } } case stopping: { std::stringstream ss; ss << "Shutting down flusher (Write of all dirty items)" << std::endl; getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "%s", ss.str().c_str()); } store->stats.min_data_age = 0; doFlush(); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Flusher stopped\n"); transition_state(stopped); return false; case stopped: return false; default: getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Unexpected state in flusher: %s", stateName()); assert(false); } } catch(std::runtime_error &e) { std::stringstream ss; ss << "Exception in flusher loop: " << e.what() << std::endl; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "%s", ss.str().c_str()); assert(false); } } int Flusher::doFlush() { int rv(store->stats.min_data_age); std::queue<QueuedItem> *q = store->beginFlush(); if (q) { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Flushing a write queue.\n"); std::queue<QueuedItem> *rejectQueue = new std::queue<QueuedItem>(); rel_time_t flush_start = ep_current_time(); while (!q->empty()) { int n = store->flushSome(q, rejectQueue); if (_state == pausing) { transition_state(paused); } if (n < rv) { rv = n; } } store->completeFlush(rejectQueue, flush_start); getLogger()->log(EXTENSION_LOG_INFO, NULL, "Completed a flush, age of oldest item was %ds\n", rv); delete rejectQueue; } return rv; } <commit_msg>Always sleep a minimum of 1s between flushes.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 NorthScale, 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 <stdlib.h> #include "flusher.hh" bool FlusherStepper::callback(Dispatcher &d, TaskId t) { return flusher->step(d, t); } bool Flusher::stop(void) { return transition_state(stopping); } void Flusher::wait(void) { while (_state != stopped) { usleep(1000); } } bool Flusher::pause(void) { return transition_state(pausing); } bool Flusher::resume(void) { return transition_state(running); } static bool validTransition(enum flusher_state from, enum flusher_state to) { bool rv(true); if (from == initializing && to == running) { } else if (from == running && to == pausing) { } else if (from == running && to == stopping) { } else if (from == pausing && to == paused) { } else if (from == stopping && to == stopped) { } else if (from == paused && to == running) { } else if (from == paused && to == stopping) { } else if (from == pausing && to == stopping) { } else { rv = false; } return rv; } const char * Flusher::stateName(enum flusher_state st) const { static const char * const stateNames[] = { "initializing", "running", "pausing", "paused", "stopping", "stopped" }; assert(st >= initializing && st <= stopped); return stateNames[st]; } bool Flusher::transition_state(enum flusher_state to) { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Attempting transition from %s to %s\n", stateName(_state), stateName(to)); if (!validTransition(_state, to)) { return false; } getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Transitioning from %s to %s\n", stateName(_state), stateName(to)); _state = to; //Reschedule the task LockHolder lh(taskMutex); assert(task.get()); dispatcher->cancel(task); schedule_UNLOCKED(); return true; } const char * Flusher::stateName() const { return stateName(_state); } enum flusher_state Flusher::state() const { return _state; } void Flusher::initialize(TaskId tid) { assert(task.get() == tid.get()); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Initializing flusher; warming up\n"); time_t startTime = time(NULL); store->warmup(); store->stats.warmupTime.set(time(NULL) - startTime); store->stats.warmupComplete.set(true); store->stats.curr_items.incr(store->stats.warmedUp.get()); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Warmup completed in %ds\n", store->stats.warmupTime.get()); transition_state(running); } void Flusher::schedule_UNLOCKED() { dispatcher->schedule(shared_ptr<FlusherStepper>(new FlusherStepper(this)), &task); assert(task.get()); } void Flusher::start(void) { LockHolder lh(taskMutex); schedule_UNLOCKED(); } void Flusher::wake(void) { LockHolder lh(taskMutex); assert(task.get()); dispatcher->wake(task, &task); } bool Flusher::step(Dispatcher &d, TaskId tid) { assert(task.get() == tid.get()); try { switch (_state) { case initializing: initialize(tid); return true; case paused: return false; case pausing: transition_state(paused); return false; case running: { int n = doFlush(); if (_state == running) { d.snooze(tid, std::max(n, 1)); return true; } else { return false; } } case stopping: { std::stringstream ss; ss << "Shutting down flusher (Write of all dirty items)" << std::endl; getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "%s", ss.str().c_str()); } store->stats.min_data_age = 0; doFlush(); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Flusher stopped\n"); transition_state(stopped); return false; case stopped: return false; default: getLogger()->log(EXTENSION_LOG_WARNING, NULL, "Unexpected state in flusher: %s", stateName()); assert(false); } } catch(std::runtime_error &e) { std::stringstream ss; ss << "Exception in flusher loop: " << e.what() << std::endl; getLogger()->log(EXTENSION_LOG_WARNING, NULL, "%s", ss.str().c_str()); assert(false); } } int Flusher::doFlush() { int rv(store->stats.min_data_age); std::queue<QueuedItem> *q = store->beginFlush(); if (q) { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Flushing a write queue.\n"); std::queue<QueuedItem> *rejectQueue = new std::queue<QueuedItem>(); rel_time_t flush_start = ep_current_time(); while (!q->empty()) { int n = store->flushSome(q, rejectQueue); if (_state == pausing) { transition_state(paused); } if (n < rv) { rv = n; } } store->completeFlush(rejectQueue, flush_start); getLogger()->log(EXTENSION_LOG_INFO, NULL, "Completed a flush, age of oldest item was %ds\n", rv); delete rejectQueue; } return rv; } <|endoftext|>
<commit_before>#include <string> #include <iostream> #include <iomanip> #include <sstream> #include <cassert> #include <msgpack_fwd.hpp> // declarations class my_class; namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { object const& operator>> (msgpack::object const& o, my_class& v); template <typename Stream> packer<Stream>& operator<< (msgpack::packer<Stream>& o, my_class const& v); } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) } // namespace msgpack #include <msgpack.hpp> class my_class { public: my_class() {} // When you want to convert from msgpack::object to my_class, // my_class should be default constractible. my_class(std::string const& name, int age):name_(name), age_(age) {} // my_class should provide getters for the data members you want to pack. std::string get_name() const { return name_; } int get_age() const { return age_; } friend bool operator==(my_class const& lhs, my_class const& rhs) { return lhs.name_ == rhs.name_ && lhs.age_ == rhs.age_; } private: std::string name_; int age_; }; // definitions namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { inline object const& operator>> (msgpack::object const& o, my_class& v) { if (o.type != msgpack::type::ARRAY) throw msgpack::type_error(); if (o.via.array.size != 2) throw msgpack::type_error(); v = my_class( o.via.array.ptr[0].as<std::string>(), o.via.array.ptr[1].as<int>()); return o; } template <typename Stream> inline packer<Stream>& operator<< (msgpack::packer<Stream>& o, my_class const& v) { // packing member variables as an array. o.pack_array(2); o.pack(v.get_name()); o.pack(v.get_age()); return o; } } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) } // namespace msgpack void print(std::string const& buf) { for (std::string::const_iterator it = buf.begin(), end = buf.end(); it != end; ++it) { std::cout << std::setw(2) << std::hex << std::setfill('0') << (static_cast<int>(*it) & 0xff) << ' '; } std::cout << std::endl; } int main() { my_class my("John Smith", 42); std::stringstream ss; msgpack::pack(ss, my); print(ss.str()); msgpack::unpacked unp; msgpack::unpack(unp, ss.str().data(), ss.str().size()); msgpack::object obj = unp.get(); assert(obj.as<my_class>() == my); } <commit_msg>Change the type of the return value to a const reference<commit_after>#include <string> #include <iostream> #include <iomanip> #include <sstream> #include <cassert> #include <msgpack_fwd.hpp> // declarations class my_class; namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { object const& operator>> (msgpack::object const& o, my_class& v); template <typename Stream> packer<Stream>& operator<< (msgpack::packer<Stream>& o, my_class const& v); } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) } // namespace msgpack #include <msgpack.hpp> class my_class { public: my_class() {} // When you want to convert from msgpack::object to my_class, // my_class should be default constractible. my_class(std::string const& name, int age):name_(name), age_(age) {} // my_class should provide getters for the data members you want to pack. std::string const& get_name() const { return name_; } int get_age() const { return age_; } friend bool operator==(my_class const& lhs, my_class const& rhs) { return lhs.name_ == rhs.name_ && lhs.age_ == rhs.age_; } private: std::string name_; int age_; }; // definitions namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { inline object const& operator>> (msgpack::object const& o, my_class& v) { if (o.type != msgpack::type::ARRAY) throw msgpack::type_error(); if (o.via.array.size != 2) throw msgpack::type_error(); v = my_class( o.via.array.ptr[0].as<std::string>(), o.via.array.ptr[1].as<int>()); return o; } template <typename Stream> inline packer<Stream>& operator<< (msgpack::packer<Stream>& o, my_class const& v) { // packing member variables as an array. o.pack_array(2); o.pack(v.get_name()); o.pack(v.get_age()); return o; } } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) } // namespace msgpack void print(std::string const& buf) { for (std::string::const_iterator it = buf.begin(), end = buf.end(); it != end; ++it) { std::cout << std::setw(2) << std::hex << std::setfill('0') << (static_cast<int>(*it) & 0xff) << ' '; } std::cout << std::endl; } int main() { my_class my("John Smith", 42); std::stringstream ss; msgpack::pack(ss, my); print(ss.str()); msgpack::unpacked unp; msgpack::unpack(unp, ss.str().data(), ss.str().size()); msgpack::object obj = unp.get(); assert(obj.as<my_class>() == my); } <|endoftext|>
<commit_before>/* * DesktopPosixApplicationLaunch.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopApplicationLaunch.hpp" #include "DesktopPosixApplication.hpp" #include "DesktopOptions.hpp" #include <core/system/Environment.hpp> #include <core/r_util/RUserData.hpp> #include <boost/foreach.hpp> #include <QKeyEvent> namespace rstudio { namespace desktop { namespace { PosixApplication* app() { return qobject_cast<PosixApplication*>(qApp); } // helper for swapping Ctrl, Meta modifiers // https://bugreports.qt.io/browse/QTBUG-51293 class MacEventFilter : public QObject { public: MacEventFilter(QObject* parent) : QObject(parent) { } protected: bool eventFilter(QObject* pObject, QEvent* pEvent) { if (pEvent->type() == QEvent::KeyPress) { auto* pKeyEvent = static_cast<QKeyEvent*>(pEvent); auto modifiers = pKeyEvent->modifiers(); // translate backtab to regular tab if (pKeyEvent->key() == Qt::Key_Backtab) { auto* pTabEvent = new QKeyEvent( pKeyEvent->type(), Qt::Key_Tab, pKeyEvent->modifiers() | Qt::ShiftModifier); QCoreApplication::postEvent(pObject, pTabEvent); return true; } } return QObject::eventFilter(pObject, pEvent); } }; } // anonymous namespace ApplicationLaunch::ApplicationLaunch() : QWidget(nullptr), pMainWindow_(nullptr) { connect(app(), SIGNAL(messageReceived(QString)), this, SIGNAL(openFileRequest(QString))); launchEnv_ = QProcessEnvironment::systemEnvironment(); } void ApplicationLaunch::init(QString appName, int& argc, char* argv[], boost::scoped_ptr<QApplication>* ppApp, boost::scoped_ptr<ApplicationLaunch>* ppAppLaunch) { // Immediately stuffed into scoped_ptr PosixApplication* pSingleApplication = new PosixApplication(appName, argc, argv); // create app launch instance pSingleApplication->setApplicationName(appName); ppApp->reset(pSingleApplication); ppAppLaunch->reset(new ApplicationLaunch()); pSingleApplication->setAppLauncher(ppAppLaunch->get()); // connect app open file signal to app launch connect(app(), SIGNAL(openFileRequest(QString)), ppAppLaunch->get(), SIGNAL(openFileRequest(QString))); #ifdef Q_OS_MAC pSingleApplication->installEventFilter(new MacEventFilter(pSingleApplication)); #endif } void ApplicationLaunch::setActivationWindow(QWidget* pWindow) { pMainWindow_ = pWindow; app()->setActivationWindow(pWindow, true); } void ApplicationLaunch::activateWindow() { app()->activateWindow(); } void ApplicationLaunch::attemptToRegisterPeer() { // side-effect of is running is to try to register ourselves as a peer app()->isRunning(); } bool ApplicationLaunch::sendMessage(QString filename) { return app()->sendMessage(filename); } QString ApplicationLaunch::startupOpenFileRequest() const { return app()->startupOpenFileRequest(); } void ApplicationLaunch::launchRStudio(const std::vector<std::string>& args, const std::string& initialDir) { QStringList argList; BOOST_FOREACH(const std::string& arg, args) { argList.append(QString::fromStdString(arg)); } QString exePath = QString::fromUtf8( desktop::options().executablePath().absolutePath().c_str()); // temporarily restore the library path to the one we were launched with std::string ldPath = core::system::getenv("LD_LIBRARY_PATH"); core::system::setenv("LD_LIBRARY_PATH", launchEnv_.value(QString::fromUtf8("LD_LIBRARY_PATH")).toStdString()); // set environment variable indicating initial launch dir core::system::setenv(kRStudioInitialWorkingDir, initialDir); // start RStudio detached QProcess::startDetached(exePath, argList); // restore environment core::system::setenv("LD_LIBRARY_PATH", ldPath); core::system::unsetenv(kRStudioInitialWorkingDir); } } // namespace desktop } // namespace rstudio <commit_msg>Remove unused modifier variable plus couple minor C++ tweaks while I was in there<commit_after>/* * DesktopPosixApplicationLaunch.cpp * * Copyright (C) 2009-18 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopApplicationLaunch.hpp" #include "DesktopPosixApplication.hpp" #include "DesktopOptions.hpp" #include <core/system/Environment.hpp> #include <core/r_util/RUserData.hpp> #include <QKeyEvent> namespace rstudio { namespace desktop { namespace { PosixApplication* app() { return qobject_cast<PosixApplication*>(qApp); } // helper for swapping Ctrl, Meta modifiers // https://bugreports.qt.io/browse/QTBUG-51293 class MacEventFilter : public QObject { public: explicit MacEventFilter(QObject* parent) : QObject(parent) { } protected: bool eventFilter(QObject* pObject, QEvent* pEvent) override { if (pEvent->type() == QEvent::KeyPress) { auto* pKeyEvent = static_cast<QKeyEvent*>(pEvent); // translate backtab to regular tab if (pKeyEvent->key() == Qt::Key_Backtab) { auto* pTabEvent = new QKeyEvent( pKeyEvent->type(), Qt::Key_Tab, pKeyEvent->modifiers() | Qt::ShiftModifier); QCoreApplication::postEvent(pObject, pTabEvent); return true; } } return QObject::eventFilter(pObject, pEvent); } }; } // anonymous namespace ApplicationLaunch::ApplicationLaunch() : QWidget(nullptr), pMainWindow_(nullptr) { connect(app(), SIGNAL(messageReceived(QString)), this, SIGNAL(openFileRequest(QString))); launchEnv_ = QProcessEnvironment::systemEnvironment(); } void ApplicationLaunch::init(QString appName, int& argc, char* argv[], boost::scoped_ptr<QApplication>* ppApp, boost::scoped_ptr<ApplicationLaunch>* ppAppLaunch) { // Immediately stuffed into scoped_ptr auto* pSingleApplication = new PosixApplication(appName, argc, argv); // create app launch instance PosixApplication::setApplicationName(appName); ppApp->reset(pSingleApplication); ppAppLaunch->reset(new ApplicationLaunch()); pSingleApplication->setAppLauncher(ppAppLaunch->get()); // connect app open file signal to app launch connect(app(), SIGNAL(openFileRequest(QString)), ppAppLaunch->get(), SIGNAL(openFileRequest(QString))); #ifdef Q_OS_MAC pSingleApplication->installEventFilter(new MacEventFilter(pSingleApplication)); #endif } void ApplicationLaunch::setActivationWindow(QWidget* pWindow) { pMainWindow_ = pWindow; app()->setActivationWindow(pWindow, true); } void ApplicationLaunch::activateWindow() { app()->activateWindow(); } void ApplicationLaunch::attemptToRegisterPeer() { // side-effect of is running is to try to register ourselves as a peer app()->isRunning(); } bool ApplicationLaunch::sendMessage(QString filename) { return app()->sendMessage(filename); } QString ApplicationLaunch::startupOpenFileRequest() const { return app()->startupOpenFileRequest(); } void ApplicationLaunch::launchRStudio(const std::vector<std::string>& args, const std::string& initialDir) { QStringList argList; for (const std::string& arg : args) { argList.append(QString::fromStdString(arg)); } QString exePath = QString::fromUtf8( desktop::options().executablePath().absolutePath().c_str()); // temporarily restore the library path to the one we were launched with std::string ldPath = core::system::getenv("LD_LIBRARY_PATH"); core::system::setenv("LD_LIBRARY_PATH", launchEnv_.value(QString::fromUtf8("LD_LIBRARY_PATH")).toStdString()); // set environment variable indicating initial launch dir core::system::setenv(kRStudioInitialWorkingDir, initialDir); // start RStudio detached QProcess::startDetached(exePath, argList); // restore environment core::system::setenv("LD_LIBRARY_PATH", ldPath); core::system::unsetenv(kRStudioInitialWorkingDir); } } // namespace desktop } // namespace rstudio <|endoftext|>
<commit_before>/* * SessionCompilePdf.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionCompilePdf.hpp" #include <core/FilePath.hpp> #include <core/Exec.hpp> #include <core/FileSerializer.hpp> #include <r/RSexp.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <session/SessionModuleContext.hpp> #include "SessionPdfLatex.hpp" #include "SessionTexi2Dvi.hpp" #include "SessionRnwWeave.hpp" // TODO: emulate texi2dvi on linux to workaround debian tilde // escaping bug (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=534458) // TODO: re-write compilePdf in C++ // // - sustain overridability using PDFLATEX // - test on all platforms // TODO: consider option for texi2dvi // TODO: investigate luatex, xelatex (ConTeXt?) // (engines names must be compatible with TexShop/Texworks // magic markers) // TODO: check spaces in path constraint on various platforms // TODO: investigate other texi2dvi and pdflatex options // -- shell-escape // -- clean // -- alternative output file location using namespace core; namespace session { namespace modules { namespace tex { namespace compile_pdf { namespace { void viewPdf(const FilePath& texPath) { FilePath pdfPath = texPath.parent().complete(texPath.stem() + ".pdf"); module_context::showFile(pdfPath, "_rstudio_compile_pdf"); } void publishPdf(const FilePath& texPath) { std::string aliasedPath = module_context::createAliasedPath(texPath); ClientEvent event(client_events::kPublishPdf, aliasedPath); module_context::enqueClientEvent(event); } void showCompilationErrors(const FilePath& texPath) { std::string errors; Error error = r::exec::RFunction(".rs.getCompilationErrors", texPath.absolutePath()).call(&errors); if (error) LOG_ERROR(error); if (!errors.empty()) { module_context::consoleWriteOutput(errors); } else { FilePath logPath = texPath.parent().complete(texPath.stem() + ".log"); std::string logContents; Error error = core::readStringFromFile(logPath, &logContents, string_utils::LineEndingPosix); if (error) LOG_ERROR(error); module_context::consoleWriteOutput(logContents); } } bool compilePdf(const FilePath& targetFilePath, const std::string& completedAction, std::string* pUserErrMsg) { // set the working directory for the duration of the compile RestoreCurrentPathScope pathScope(module_context::safeCurrentPath()); Error error = targetFilePath.parent().makeCurrentPath(); if (error) { *pUserErrMsg = "Error setting current path: " + error.summary(); return false; } // ensure no spaces in path std::string filename = targetFilePath.filename(); if (filename.find(' ') != std::string::npos) { *pUserErrMsg = "Invalid filename: '" + filename + "' (TeX does not understand paths with spaces)"; return false; } // see if we need to sweave std::string ext = targetFilePath.extensionLowerCase(); if (ext == ".rnw" || ext == ".snw" || ext == ".nw") { // attempt to weave the rnw bool success = rnw_weave::runWeave(targetFilePath, pUserErrMsg); if (!success) return false; } // configure pdflatex options pdflatex::PdfLatexOptions options; options.fileLineError = false; options.syncTex = true; // run tex compile FilePath texFilePath = targetFilePath.parent().complete( targetFilePath.stem() + ".tex"); core::system::ProcessResult result; #if defined(_WIN32) || defined(__APPLE__) error = tex::texi2dvi::texToPdf(options, texFilePath, &result); #else // workaround for tex2dvi special character bug on linux: // http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=577741 error = tex::pdflatex::texToPdf(options, texFilePath, &result); #endif if (error) { *pUserErrMsg = "Unable to compile pdf: " + error.summary(); return false; } else if (result.exitStatus != EXIT_SUCCESS) { showCompilationErrors(texFilePath); return false; } else { if (completedAction == "view") viewPdf(targetFilePath); else if (completedAction == "publish") publishPdf(targetFilePath); return true; } } SEXP rs_compilePdf(SEXP filePathSEXP, SEXP completedActionSEXP) { try { // extract parameters FilePath targetFilePath = module_context::resolveAliasedPath( r::sexp::asString(filePathSEXP)); std::string completedAction = r::sexp::asString(completedActionSEXP); // compile pdf std::string userErrMsg; if (!compilePdf(targetFilePath, completedAction, &userErrMsg)) { if (!userErrMsg.empty()) throw r::exec::RErrorException(userErrMsg); } } catch(const r::exec::RErrorException& e) { r::exec::error(e.message()); } CATCH_UNEXPECTED_EXCEPTION return R_NilValue; } } // anonymous namespace Error initialize() { R_CallMethodDef compilePdfMethodDef; compilePdfMethodDef.name = "rs_compilePdf" ; compilePdfMethodDef.fun = (DL_FUNC) rs_compilePdf ; compilePdfMethodDef.numArgs = 2; r::routines::addCallMethod(compilePdfMethodDef); using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionCompilePdf.R")); return initBlock.execute(); } } // namespace compile_pdf } // namespace tex } // namespace modules } // namesapce session <commit_msg>update todo comments<commit_after>/* * SessionCompilePdf.cpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "SessionCompilePdf.hpp" #include <core/FilePath.hpp> #include <core/Exec.hpp> #include <core/FileSerializer.hpp> #include <r/RSexp.hpp> #include <r/RExec.hpp> #include <r/RRoutines.hpp> #include <session/SessionModuleContext.hpp> #include "SessionPdfLatex.hpp" #include "SessionTexi2Dvi.hpp" #include "SessionRnwWeave.hpp" // TODO: emulate texi2dvi on linux to workaround debian tilde // escaping bug (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=534458) // TODO: consider option for texi2dvi // TODO: support !TeX program = pdfLaTeX, XeLaTeX, LuaLaTeX // TODO: check spaces in path constraint on various platforms // TODO: investigate other texi2dvi and pdflatex options // -- shell-escape // -- clean // -- alternative output file location using namespace core; namespace session { namespace modules { namespace tex { namespace compile_pdf { namespace { void viewPdf(const FilePath& texPath) { FilePath pdfPath = texPath.parent().complete(texPath.stem() + ".pdf"); module_context::showFile(pdfPath, "_rstudio_compile_pdf"); } void publishPdf(const FilePath& texPath) { std::string aliasedPath = module_context::createAliasedPath(texPath); ClientEvent event(client_events::kPublishPdf, aliasedPath); module_context::enqueClientEvent(event); } void showCompilationErrors(const FilePath& texPath) { std::string errors; Error error = r::exec::RFunction(".rs.getCompilationErrors", texPath.absolutePath()).call(&errors); if (error) LOG_ERROR(error); if (!errors.empty()) { module_context::consoleWriteOutput(errors); } else { FilePath logPath = texPath.parent().complete(texPath.stem() + ".log"); std::string logContents; Error error = core::readStringFromFile(logPath, &logContents, string_utils::LineEndingPosix); if (error) LOG_ERROR(error); module_context::consoleWriteOutput(logContents); } } bool compilePdf(const FilePath& targetFilePath, const std::string& completedAction, std::string* pUserErrMsg) { // set the working directory for the duration of the compile RestoreCurrentPathScope pathScope(module_context::safeCurrentPath()); Error error = targetFilePath.parent().makeCurrentPath(); if (error) { *pUserErrMsg = "Error setting current path: " + error.summary(); return false; } // ensure no spaces in path std::string filename = targetFilePath.filename(); if (filename.find(' ') != std::string::npos) { *pUserErrMsg = "Invalid filename: '" + filename + "' (TeX does not understand paths with spaces)"; return false; } // see if we need to sweave std::string ext = targetFilePath.extensionLowerCase(); if (ext == ".rnw" || ext == ".snw" || ext == ".nw") { // attempt to weave the rnw bool success = rnw_weave::runWeave(targetFilePath, pUserErrMsg); if (!success) return false; } // configure pdflatex options pdflatex::PdfLatexOptions options; options.fileLineError = false; options.syncTex = true; // run tex compile FilePath texFilePath = targetFilePath.parent().complete( targetFilePath.stem() + ".tex"); core::system::ProcessResult result; #if defined(_WIN32) || defined(__APPLE__) error = tex::texi2dvi::texToPdf(options, texFilePath, &result); #else // workaround for tex2dvi special character bug on linux: // http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=577741 error = tex::pdflatex::texToPdf(options, texFilePath, &result); #endif if (error) { *pUserErrMsg = "Unable to compile pdf: " + error.summary(); return false; } else if (result.exitStatus != EXIT_SUCCESS) { showCompilationErrors(texFilePath); return false; } else { if (completedAction == "view") viewPdf(targetFilePath); else if (completedAction == "publish") publishPdf(targetFilePath); return true; } } SEXP rs_compilePdf(SEXP filePathSEXP, SEXP completedActionSEXP) { try { // extract parameters FilePath targetFilePath = module_context::resolveAliasedPath( r::sexp::asString(filePathSEXP)); std::string completedAction = r::sexp::asString(completedActionSEXP); // compile pdf std::string userErrMsg; if (!compilePdf(targetFilePath, completedAction, &userErrMsg)) { if (!userErrMsg.empty()) throw r::exec::RErrorException(userErrMsg); } } catch(const r::exec::RErrorException& e) { r::exec::error(e.message()); } CATCH_UNEXPECTED_EXCEPTION return R_NilValue; } } // anonymous namespace Error initialize() { R_CallMethodDef compilePdfMethodDef; compilePdfMethodDef.name = "rs_compilePdf" ; compilePdfMethodDef.fun = (DL_FUNC) rs_compilePdf ; compilePdfMethodDef.numArgs = 2; r::routines::addCallMethod(compilePdfMethodDef); using boost::bind; using namespace module_context; ExecBlock initBlock ; initBlock.addFunctions() (bind(sourceModuleRFile, "SessionCompilePdf.R")); return initBlock.execute(); } } // namespace compile_pdf } // namespace tex } // namespace modules } // namesapce session <|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 "content/gpu/gpu_info_collector.h" #include <dlfcn.h> #include <vector> #include "app/gfx/gl/gl_bindings.h" #include "app/gfx/gl/gl_context.h" #include "app/gfx/gl/gl_implementation.h" #include "base/file_util.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/string_piece.h" #include "base/string_split.h" #include "base/string_util.h" namespace { // PciDevice and PciAccess are defined to access libpci functions. Their // members match the corresponding structures defined by libpci in size up to // fields we may access. For those members we don't use, their names are // defined as "fieldX", etc., or, left out if they are declared after the // members we care about in libpci. struct PciDevice { PciDevice* next; uint16 field0; uint8 field1; uint8 field2; uint8 field3; int field4; uint16 vendor_id; uint16 device_id; uint16 device_class; }; struct PciAccess { unsigned int field0; int field1; int field2; char* field3; int field4; int field5; unsigned int field6; int field7; void (*function0)(); void (*function1)(); void (*function2)(); PciDevice* device_list; }; // Define function types. typedef PciAccess* (*FT_pci_alloc)(); typedef void (*FT_pci_init)(PciAccess*); typedef void (*FT_pci_cleanup)(PciAccess*); typedef void (*FT_pci_scan_bus)(PciAccess*); typedef void (*FT_pci_scan_bus)(PciAccess*); typedef int (*FT_pci_fill_info)(PciDevice*, int); typedef char* (*FT_pci_lookup_name)(PciAccess*, char*, int, int, ...); // This includes dynamically linked library handle and functions pointers from // libpci. struct PciInterface { void* lib_handle; FT_pci_alloc pci_alloc; FT_pci_init pci_init; FT_pci_cleanup pci_cleanup; FT_pci_scan_bus pci_scan_bus; FT_pci_fill_info pci_fill_info; FT_pci_lookup_name pci_lookup_name; }; // This checks if a system supports PCI bus. // We check the existence of /sys/bus/pci or /sys/bug/pci_express. bool IsPciSupported() { const FilePath pci_path("/sys/bus/pci/"); const FilePath pcie_path("/sys/bus/pci_express/"); return (file_util::PathExists(pci_path) || file_util::PathExists(pcie_path)); } // This dynamically opens libpci and get function pointers we need. Return // NULL if library fails to open or any functions can not be located. // Returned interface (if not NULL) should be deleted in FinalizeLibPci. PciInterface* InitializeLibPci(const char* lib_name) { void* handle = dlopen(lib_name, RTLD_LAZY); if (handle == NULL) { VLOG(1) << "Failed to dlopen " << lib_name; return NULL; } PciInterface* interface = new struct PciInterface; interface->lib_handle = handle; interface->pci_alloc = reinterpret_cast<FT_pci_alloc>( dlsym(handle, "pci_alloc")); interface->pci_init = reinterpret_cast<FT_pci_init>( dlsym(handle, "pci_init")); interface->pci_cleanup = reinterpret_cast<FT_pci_cleanup>( dlsym(handle, "pci_cleanup")); interface->pci_scan_bus = reinterpret_cast<FT_pci_scan_bus>( dlsym(handle, "pci_scan_bus")); interface->pci_fill_info = reinterpret_cast<FT_pci_fill_info>( dlsym(handle, "pci_fill_info")); interface->pci_lookup_name = reinterpret_cast<FT_pci_lookup_name>( dlsym(handle, "pci_lookup_name")); if (interface->pci_alloc == NULL || interface->pci_init == NULL || interface->pci_cleanup == NULL || interface->pci_scan_bus == NULL || interface->pci_fill_info == NULL || interface->pci_lookup_name == NULL) { VLOG(1) << "Missing required function(s) from " << lib_name; dlclose(handle); delete interface; return NULL; } return interface; } // This close the dynamically opened libpci and delete the interface. void FinalizeLibPci(PciInterface** interface) { DCHECK(interface && *interface && (*interface)->lib_handle); dlclose((*interface)->lib_handle); delete (*interface); *interface = NULL; } } // namespace anonymous namespace gpu_info_collector { bool CollectGraphicsInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); // TODO(zmo): need to consider the case where we are running on top of // desktop GL and GL_ARB_robustness extension is available. gpu_info->can_lose_context = (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2); gpu_info->finalized = true; return CollectGraphicsInfoGL(gpu_info); } bool CollectPreliminaryGraphicsInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); bool rt = true; if (!CollectVideoCardInfo(gpu_info)) rt = false; // TODO(zmo): if vendor is ATI, consider passing /etc/ati/amdpcsdb.default // for driver information. return rt; } bool CollectVideoCardInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); if (IsPciSupported() == false) { VLOG(1) << "PCI bus scanning is not supported"; return false; } // TODO(zmo): be more flexible about library name. PciInterface* interface = InitializeLibPci("libpci.so.3"); if (interface == NULL) interface = InitializeLibPci("libpci.so"); if (interface == NULL) { VLOG(1) << "Failed to locate libpci"; return false; } PciAccess* access = (interface->pci_alloc)(); DCHECK(access != NULL); (interface->pci_init)(access); (interface->pci_scan_bus)(access); std::vector<PciDevice*> gpu_list; PciDevice* gpu_active = NULL; for (PciDevice* device = access->device_list; device != NULL; device = device->next) { (interface->pci_fill_info)(device, 33); // Fill the IDs and class fields. // TODO(zmo): there might be other classes that qualify as display devices. if (device->device_class == 0x0300) { // Device class is DISPLAY_VGA. gpu_list.push_back(device); } } if (gpu_list.size() == 1) { gpu_active = gpu_list[0]; } else { // If more than one graphics card are identified, find the one that matches // gl VENDOR and RENDERER info. std::string gl_vendor_string = gpu_info->gl_vendor; std::string gl_renderer_string = gpu_info->gl_renderer; const int buffer_size = 255; scoped_array<char> buffer(new char[buffer_size]); std::vector<PciDevice*> candidates; for (size_t i = 0; i < gpu_list.size(); ++i) { PciDevice* gpu = gpu_list[i]; // The current implementation of pci_lookup_name returns the same pointer // as the passed in upon success, and a different one (NULL or a pointer // to an error message) upon failure. if ((interface->pci_lookup_name)(access, buffer.get(), buffer_size, 1, gpu->vendor_id) != buffer.get()) continue; std::string vendor_string = buffer.get(); const bool kCaseSensitive = false; if (!StartsWithASCII(gl_vendor_string, vendor_string, kCaseSensitive)) continue; if ((interface->pci_lookup_name)(access, buffer.get(), buffer_size, 2, gpu->vendor_id, gpu->device_id) != buffer.get()) continue; std::string device_string = buffer.get(); size_t begin = device_string.find_first_of('['); size_t end = device_string.find_last_of(']'); if (begin != std::string::npos && end != std::string::npos && begin < end) { device_string = device_string.substr(begin + 1, end - begin - 1); } if (StartsWithASCII(gl_renderer_string, device_string, kCaseSensitive)) { gpu_active = gpu; break; } // If a device's vendor matches gl VENDOR string, we want to consider the // possibility that libpci may not return the exact same name as gl // RENDERER string. candidates.push_back(gpu); } if (gpu_active == NULL && candidates.size() == 1) gpu_active = candidates[0]; } if (gpu_active != NULL) { gpu_info->vendor_id = gpu_active->vendor_id; gpu_info->device_id = gpu_active->device_id; } (interface->pci_cleanup)(access); FinalizeLibPci(&interface); return (gpu_active != NULL); } bool CollectDriverInfoGL(GPUInfo* gpu_info) { DCHECK(gpu_info); std::string gl_version_string = gpu_info->gl_version_string; std::vector<std::string> pieces; base::SplitStringAlongWhitespace(gl_version_string, &pieces); // In linux, the gl version string might be in the format of // GLVersion DriverVendor DriverVersion if (pieces.size() < 3) return false; std::string driver_version = pieces[2]; size_t pos = driver_version.find_first_not_of("0123456789."); if (pos == 0) return false; if (pos != std::string::npos) driver_version = driver_version.substr(0, pos); gpu_info->driver_vendor = pieces[1]; gpu_info->driver_version = driver_version; return true; } } // namespace gpu_info_collector <commit_msg>Collect ATI driver version through scanning /etc/ati. This will enable us to blacklist only older ATI drivers on linux in the future.<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 "content/gpu/gpu_info_collector.h" #include <dlfcn.h> #include <vector> #include "app/gfx/gl/gl_bindings.h" #include "app/gfx/gl/gl_context.h" #include "app/gfx/gl/gl_implementation.h" #include "base/file_util.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/string_piece.h" #include "base/string_split.h" #include "base/string_tokenizer.h" #include "base/string_util.h" namespace { // PciDevice and PciAccess are defined to access libpci functions. Their // members match the corresponding structures defined by libpci in size up to // fields we may access. For those members we don't use, their names are // defined as "fieldX", etc., or, left out if they are declared after the // members we care about in libpci. struct PciDevice { PciDevice* next; uint16 field0; uint8 field1; uint8 field2; uint8 field3; int field4; uint16 vendor_id; uint16 device_id; uint16 device_class; }; struct PciAccess { unsigned int field0; int field1; int field2; char* field3; int field4; int field5; unsigned int field6; int field7; void (*function0)(); void (*function1)(); void (*function2)(); PciDevice* device_list; }; // Define function types. typedef PciAccess* (*FT_pci_alloc)(); typedef void (*FT_pci_init)(PciAccess*); typedef void (*FT_pci_cleanup)(PciAccess*); typedef void (*FT_pci_scan_bus)(PciAccess*); typedef void (*FT_pci_scan_bus)(PciAccess*); typedef int (*FT_pci_fill_info)(PciDevice*, int); typedef char* (*FT_pci_lookup_name)(PciAccess*, char*, int, int, ...); // This includes dynamically linked library handle and functions pointers from // libpci. struct PciInterface { void* lib_handle; FT_pci_alloc pci_alloc; FT_pci_init pci_init; FT_pci_cleanup pci_cleanup; FT_pci_scan_bus pci_scan_bus; FT_pci_fill_info pci_fill_info; FT_pci_lookup_name pci_lookup_name; }; // This checks if a system supports PCI bus. // We check the existence of /sys/bus/pci or /sys/bug/pci_express. bool IsPciSupported() { const FilePath pci_path("/sys/bus/pci/"); const FilePath pcie_path("/sys/bus/pci_express/"); return (file_util::PathExists(pci_path) || file_util::PathExists(pcie_path)); } // This dynamically opens libpci and get function pointers we need. Return // NULL if library fails to open or any functions can not be located. // Returned interface (if not NULL) should be deleted in FinalizeLibPci. PciInterface* InitializeLibPci(const char* lib_name) { void* handle = dlopen(lib_name, RTLD_LAZY); if (handle == NULL) { VLOG(1) << "Failed to dlopen " << lib_name; return NULL; } PciInterface* interface = new struct PciInterface; interface->lib_handle = handle; interface->pci_alloc = reinterpret_cast<FT_pci_alloc>( dlsym(handle, "pci_alloc")); interface->pci_init = reinterpret_cast<FT_pci_init>( dlsym(handle, "pci_init")); interface->pci_cleanup = reinterpret_cast<FT_pci_cleanup>( dlsym(handle, "pci_cleanup")); interface->pci_scan_bus = reinterpret_cast<FT_pci_scan_bus>( dlsym(handle, "pci_scan_bus")); interface->pci_fill_info = reinterpret_cast<FT_pci_fill_info>( dlsym(handle, "pci_fill_info")); interface->pci_lookup_name = reinterpret_cast<FT_pci_lookup_name>( dlsym(handle, "pci_lookup_name")); if (interface->pci_alloc == NULL || interface->pci_init == NULL || interface->pci_cleanup == NULL || interface->pci_scan_bus == NULL || interface->pci_fill_info == NULL || interface->pci_lookup_name == NULL) { VLOG(1) << "Missing required function(s) from " << lib_name; dlclose(handle); delete interface; return NULL; } return interface; } // This close the dynamically opened libpci and delete the interface. void FinalizeLibPci(PciInterface** interface) { DCHECK(interface && *interface && (*interface)->lib_handle); dlclose((*interface)->lib_handle); delete (*interface); *interface = NULL; } // Scan /etc/ati/amdpcsdb.default for "ReleaseVersion". // Return "" on failing. std::string CollectDriverVersionATI() { const FilePath::CharType kATIFileName[] = FILE_PATH_LITERAL("/etc/ati/amdpcsdb.default"); FilePath ati_file_path(kATIFileName); if (!file_util::PathExists(ati_file_path)) return ""; std::string contents; if (!file_util::ReadFileToString(ati_file_path, &contents)) return ""; StringTokenizer t(contents, "\r\n"); while (t.GetNext()) { std::string line = t.token(); if (StartsWithASCII(line, "ReleaseVersion=", true)) { size_t begin = line.find_first_of("0123456789"); if (begin != std::string::npos) { size_t end = line.find_first_not_of("0123456789.", begin); if (end == std::string::npos) return line.substr(begin); else return line.substr(begin, end - begin); } } } return ""; } } // namespace anonymous namespace gpu_info_collector { bool CollectGraphicsInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); // TODO(zmo): need to consider the case where we are running on top of // desktop GL and GL_ARB_robustness extension is available. gpu_info->can_lose_context = (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2); gpu_info->finalized = true; return CollectGraphicsInfoGL(gpu_info); } bool CollectPreliminaryGraphicsInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); bool rt = true; if (!CollectVideoCardInfo(gpu_info)) rt = false; if (gpu_info->vendor_id == 0x1002) { // ATI std::string ati_driver_version = CollectDriverVersionATI(); if (ati_driver_version != "") { gpu_info->driver_vendor = "ATI / AMD"; gpu_info->driver_version = ati_driver_version; } } return rt; } bool CollectVideoCardInfo(GPUInfo* gpu_info) { DCHECK(gpu_info); if (IsPciSupported() == false) { VLOG(1) << "PCI bus scanning is not supported"; return false; } // TODO(zmo): be more flexible about library name. PciInterface* interface = InitializeLibPci("libpci.so.3"); if (interface == NULL) interface = InitializeLibPci("libpci.so"); if (interface == NULL) { VLOG(1) << "Failed to locate libpci"; return false; } PciAccess* access = (interface->pci_alloc)(); DCHECK(access != NULL); (interface->pci_init)(access); (interface->pci_scan_bus)(access); std::vector<PciDevice*> gpu_list; PciDevice* gpu_active = NULL; for (PciDevice* device = access->device_list; device != NULL; device = device->next) { (interface->pci_fill_info)(device, 33); // Fill the IDs and class fields. // TODO(zmo): there might be other classes that qualify as display devices. if (device->device_class == 0x0300) { // Device class is DISPLAY_VGA. gpu_list.push_back(device); } } if (gpu_list.size() == 1) { gpu_active = gpu_list[0]; } else { // If more than one graphics card are identified, find the one that matches // gl VENDOR and RENDERER info. std::string gl_vendor_string = gpu_info->gl_vendor; std::string gl_renderer_string = gpu_info->gl_renderer; const int buffer_size = 255; scoped_array<char> buffer(new char[buffer_size]); std::vector<PciDevice*> candidates; for (size_t i = 0; i < gpu_list.size(); ++i) { PciDevice* gpu = gpu_list[i]; // The current implementation of pci_lookup_name returns the same pointer // as the passed in upon success, and a different one (NULL or a pointer // to an error message) upon failure. if ((interface->pci_lookup_name)(access, buffer.get(), buffer_size, 1, gpu->vendor_id) != buffer.get()) continue; std::string vendor_string = buffer.get(); const bool kCaseSensitive = false; if (!StartsWithASCII(gl_vendor_string, vendor_string, kCaseSensitive)) continue; if ((interface->pci_lookup_name)(access, buffer.get(), buffer_size, 2, gpu->vendor_id, gpu->device_id) != buffer.get()) continue; std::string device_string = buffer.get(); size_t begin = device_string.find_first_of('['); size_t end = device_string.find_last_of(']'); if (begin != std::string::npos && end != std::string::npos && begin < end) { device_string = device_string.substr(begin + 1, end - begin - 1); } if (StartsWithASCII(gl_renderer_string, device_string, kCaseSensitive)) { gpu_active = gpu; break; } // If a device's vendor matches gl VENDOR string, we want to consider the // possibility that libpci may not return the exact same name as gl // RENDERER string. candidates.push_back(gpu); } if (gpu_active == NULL && candidates.size() == 1) gpu_active = candidates[0]; } if (gpu_active != NULL) { gpu_info->vendor_id = gpu_active->vendor_id; gpu_info->device_id = gpu_active->device_id; } (interface->pci_cleanup)(access); FinalizeLibPci(&interface); return (gpu_active != NULL); } bool CollectDriverInfoGL(GPUInfo* gpu_info) { DCHECK(gpu_info); std::string gl_version_string = gpu_info->gl_version_string; std::vector<std::string> pieces; base::SplitStringAlongWhitespace(gl_version_string, &pieces); // In linux, the gl version string might be in the format of // GLVersion DriverVendor DriverVersion if (pieces.size() < 3) return false; std::string driver_version = pieces[2]; size_t pos = driver_version.find_first_not_of("0123456789."); if (pos == 0) return false; if (pos != std::string::npos) driver_version = driver_version.substr(0, pos); gpu_info->driver_vendor = pieces[1]; gpu_info->driver_version = driver_version; return true; } } // namespace gpu_info_collector <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006-2012, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #define L10N // Localization complete. #include <vector> #include <sstream> #include <algorithm> #include <text.h> #include <i18n.h> #include <main.h> #include <Context.h> #include <Directory.h> #include <ViewText.h> #include <CmdShow.h> #include <Uri.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdShow::CmdShow () { _keyword = "show"; _usage = "task show [all | substring]"; _description = STRING_CMD_SHOW; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdShow::execute (std::string& output) { int rc = 0; std::stringstream out; // Obtain the arguments from the description. That way, things like '--' // have already been handled. std::vector <std::string> words = context.a3.extract_words (); if (words.size () > 2) throw std::string (STRING_CMD_SHOW_ARGS); int width = context.getWidth (); // Complain about configuration variables that are not recognized. // These are the regular configuration variables. // Note that there is a leading and trailing space, to make it easier to // search for whole words. std::string recognized = " abbreviation.minimum" " active.indicator" " avoidlastcolumn" " bulk" " burndown.bias" " calendar.details" " calendar.details.report" " calendar.holidays" " calendar.legend" " calendar.offset" " calendar.offset.value" " color" " color.active" " color.alternate" " color.blocked" " color.blocking" " color.burndown.done" " color.burndown.pending" " color.burndown.started" " color.calendar.due" " color.calendar.due.today" " color.calendar.holiday" " color.calendar.overdue" " color.calendar.today" " color.calendar.weekend" " color.calendar.weeknumber" " color.completed" " color.debug" " color.deleted" " color.due" " color.due.today" " color.error" " color.footnote" " color.header" " color.history.add" " color.history.delete" " color.history.done" " color.label" " color.overdue" " color.pri.H" " color.pri.L" " color.pri.M" " color.pri.none" " color.recurring" " color.scheduled" " color.summary.background" " color.summary.bar" " color.sync.added" " color.sync.changed" " color.sync.rejected" " color.tagged" " color.undo.after" " color.undo.before" " column.padding" " complete.all.projects" " complete.all.tags" " confirmation" " data.location" " dateformat" " dateformat.annotation" " dateformat.edit" " dateformat.holiday" " dateformat.info" " dateformat.report" " debug" " default.command" " default.due" " default.priority" " default.project" " defaultheight" " defaultwidth" " dependency.confirmation" " dependency.indicator" " dependency.reminder" " detection" " displayweeknumber" " dom" " due" " echo.command" // Deprecated 2.0 " edit.verbose" // Deprecated 2.0 " editor" " exit.on.missing.db" " expressions" " extensions" " fontunderline" " gc" " hyphenate" " indent.annotation" " indent.report" " journal.info" " journal.time" " journal.time.start.annotation" " journal.time.stop.annotation" " json.array" " list.all.projects" " list.all.tags" " locale" " locking" " merge.autopush" " merge.default.uri" " monthsperline" " nag" " patterns" " pull.default.uri" " push.default.uri" " recurrence.indicator" " recurrence.limit" " regex" " row.padding" " rule.precedence.color" " search.case.sensitive" " shadow.command" " shadow.file" " shadow.notify" " shell.prompt" " tag.indicator" " taskd.server" " taskd.credentials" " undo.style" " urgency.active.coefficient" " urgency.scheduled.coefficient" " urgency.annotations.coefficient" " urgency.blocked.coefficient" " urgency.blocking.coefficient" " urgency.due.coefficient" " urgency.next.coefficient" " urgency.priority.coefficient" " urgency.project.coefficient" " urgency.tags.coefficient" " urgency.waiting.coefficient" " urgency.age.coefficient" " urgency.age.max" " verbose" " weekstart" " xterm.title" " "; // This configuration variable is supported, but not documented. It exists // so that unit tests can force color to be on even when the output from task // is redirected to a file, or stdout is not a tty. recognized += "_forcecolor "; std::vector <std::string> all; context.config.all (all); std::vector <std::string> unrecognized; std::vector <std::string>::iterator i; for (i = all.begin (); i != all.end (); ++i) { // Disallow partial matches by tacking a leading and trailing space on each // variable name. std::string pattern = " " + *i + " "; if (recognized.find (pattern) == std::string::npos) { // These are special configuration variables, because their name is // dynamic. if (i->substr (0, 14) != "color.keyword." && i->substr (0, 14) != "color.project." && i->substr (0, 10) != "color.tag." && i->substr (0, 8) != "holiday." && i->substr (0, 7) != "report." && i->substr (0, 6) != "alias." && i->substr (0, 5) != "hook." && i->substr (0, 5) != "push." && i->substr (0, 5) != "pull." && i->substr (0, 6) != "merge." && i->substr (0, 4) != "uda." && i->substr (0, 21) != "urgency.user.project." && i->substr (0, 17) != "urgency.user.tag." && i->substr (0, 12) != "urgency.uda.") { unrecognized.push_back (*i); } } } // Find all the values that match the defaults, for highlighting. std::vector <std::string> default_values; Config default_config; default_config.setDefaults (); for (i = all.begin (); i != all.end (); ++i) if (context.config.get (*i) != default_config.get (*i)) default_values.push_back (*i); // Create output view. ViewText view; view.width (width); view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VAR)); view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VALUE)); Color error ("bold white on red"); Color warning ("black on yellow"); bool issue_error = false; bool issue_warning = false; std::string section; // Look for the first plausible argument which could be a pattern if (words.size ()) section = words[0]; if (section == "all") section = ""; for (i = all.begin (); i != all.end (); ++i) { std::string::size_type loc = i->find (section, 0); if (loc != std::string::npos) { // Look for unrecognized. Color color; if (std::find (unrecognized.begin (), unrecognized.end (), *i) != unrecognized.end ()) { issue_error = true; color = error; } else if (std::find (default_values.begin (), default_values.end (), *i) != default_values.end ()) { issue_warning = true; color = warning; } std::string value = context.config.get (*i); // hide sensible information if ( (i->substr (0, 5) == "push." || i->substr (0, 5) == "pull." || i->substr (0, 6) == "merge.") && (i->find (".uri") != std::string::npos) ) { Uri uri (value); uri.parse (); value = uri.ToString (); } int row = view.addRow (); view.set (row, 0, *i, color); view.set (row, 1, value, color); } } out << "\n" << view.render () << (view.rows () == 0 ? STRING_CMD_SHOW_NONE : "") << (view.rows () == 0 ? "\n\n" : "\n"); if (issue_warning) { out << STRING_CMD_SHOW_DIFFER; if (context.color ()) out << " " << format (STRING_CMD_SHOW_DIFFER_COLOR, warning.colorize ("color")) << "\n\n"; } // Display the unrecognized variables. if (issue_error) { out << STRING_CMD_SHOW_UNREC << "\n"; for (i = unrecognized.begin (); i != unrecognized.end (); ++i) out << " " << *i << "\n"; if (context.color ()) out << "\n " << format (STRING_CMD_SHOW_DIFFER_COLOR, error.colorize ("color")); out << "\n\n"; } out << legacyCheckForDeprecatedVariables (); out << legacyCheckForDeprecatedColor (); out << legacyCheckForDeprecatedColumns (); // TODO Check for referenced but missing theme files. // TODO Check for referenced but missing string files. // TODO Check for referenced but missing tips files. // Check for referenced but missing hook scripts. #ifdef HAVE_LIBLUA std::vector <std::string> missing_scripts; for (i = all.begin (); i != all.end (); ++i) { if (i->substr (0, 5) == "hook.") { std::string value = context.config.get (*i); Nibbler n (value); // <path>:<function> [, ...] while (!n.depleted ()) { std::string file; std::string function; if (n.getUntil (':', file) && n.skip (':') && n.getUntil (',', function)) { Path script (file); if (!script.exists () || !script.readable ()) missing_scripts.push_back (file); (void) n.skip (','); } } } } if (missing_scripts.size ()) { out << STRING_CMD_SHOW_HOOKS << "\n"; for (i = missing_scripts.begin (); i != missing_scripts.end (); ++i) out << " " << *i << "\n"; out << "\n"; } #endif // Check for bad values in rc.calendar.details. std::string calendardetails = context.config.get ("calendar.details"); if (calendardetails != "full" && calendardetails != "sparse" && calendardetails != "none") out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.details", calendardetails) << "\n"; // Check for bad values in rc.calendar.holidays. std::string calendarholidays = context.config.get ("calendar.holidays"); if (calendarholidays != "full" && calendarholidays != "sparse" && calendarholidays != "none") out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.holidays", calendarholidays) << "\n"; // Check for bad values in rc.default.priority. std::string defaultPriority = context.config.get ("default.priority"); if (defaultPriority != "H" && defaultPriority != "M" && defaultPriority != "L" && defaultPriority != "") out << format (STRING_CMD_SHOW_CONFIG_ERROR, "default.priority", defaultPriority) << "\n"; // Verify installation. This is mentioned in the documentation as the way // to ensure everything is properly installed. if (all.size () == 0) { out << STRING_CMD_SHOW_EMPTY << "\n"; rc = 1; } else { Directory location (context.config.get ("data.location")); if (location._data == "") out << STRING_CMD_SHOW_NO_LOCATION << "\n"; if (! location.exists ()) out << STRING_CMD_SHOW_LOC_EXIST << "\n"; } output = out.str (); return rc; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Code Cleanup<commit_after>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006-2012, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #define L10N // Localization complete. #include <vector> #include <sstream> #include <algorithm> #include <text.h> #include <i18n.h> #include <main.h> #include <Context.h> #include <Directory.h> #include <ViewText.h> #include <CmdShow.h> #include <Uri.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// CmdShow::CmdShow () { _keyword = "show"; _usage = "task show [all | substring]"; _description = STRING_CMD_SHOW; _read_only = true; _displays_id = false; } //////////////////////////////////////////////////////////////////////////////// int CmdShow::execute (std::string& output) { int rc = 0; std::stringstream out; // Obtain the arguments from the description. That way, things like '--' // have already been handled. std::vector <std::string> words = context.a3.extract_words (); if (words.size () > 1) throw std::string (STRING_CMD_SHOW_ARGS); int width = context.getWidth (); // Complain about configuration variables that are not recognized. // These are the regular configuration variables. // Note that there is a leading and trailing space, to make it easier to // search for whole words. std::string recognized = " abbreviation.minimum" " active.indicator" " avoidlastcolumn" " bulk" " burndown.bias" " calendar.details" " calendar.details.report" " calendar.holidays" " calendar.legend" " calendar.offset" " calendar.offset.value" " color" " color.active" " color.alternate" " color.blocked" " color.blocking" " color.burndown.done" " color.burndown.pending" " color.burndown.started" " color.calendar.due" " color.calendar.due.today" " color.calendar.holiday" " color.calendar.overdue" " color.calendar.today" " color.calendar.weekend" " color.calendar.weeknumber" " color.completed" " color.debug" " color.deleted" " color.due" " color.due.today" " color.error" " color.footnote" " color.header" " color.history.add" " color.history.delete" " color.history.done" " color.label" " color.overdue" " color.pri.H" " color.pri.L" " color.pri.M" " color.pri.none" " color.recurring" " color.scheduled" " color.summary.background" " color.summary.bar" " color.sync.added" " color.sync.changed" " color.sync.rejected" " color.tagged" " color.undo.after" " color.undo.before" " column.padding" " complete.all.projects" " complete.all.tags" " confirmation" " data.location" " dateformat" " dateformat.annotation" " dateformat.edit" " dateformat.holiday" " dateformat.info" " dateformat.report" " debug" " default.command" " default.due" " default.priority" " default.project" " defaultheight" " defaultwidth" " dependency.confirmation" " dependency.indicator" " dependency.reminder" " detection" " displayweeknumber" " dom" " due" " echo.command" // Deprecated 2.0 " edit.verbose" // Deprecated 2.0 " editor" " exit.on.missing.db" " expressions" " extensions" " fontunderline" " gc" " hyphenate" " indent.annotation" " indent.report" " journal.info" " journal.time" " journal.time.start.annotation" " journal.time.stop.annotation" " json.array" " list.all.projects" " list.all.tags" " locale" " locking" " merge.autopush" " merge.default.uri" " monthsperline" " nag" " patterns" " pull.default.uri" " push.default.uri" " recurrence.indicator" " recurrence.limit" " regex" " row.padding" " rule.precedence.color" " search.case.sensitive" " shadow.command" " shadow.file" " shadow.notify" " shell.prompt" " tag.indicator" " taskd.server" " taskd.credentials" " undo.style" " urgency.active.coefficient" " urgency.scheduled.coefficient" " urgency.annotations.coefficient" " urgency.blocked.coefficient" " urgency.blocking.coefficient" " urgency.due.coefficient" " urgency.next.coefficient" " urgency.priority.coefficient" " urgency.project.coefficient" " urgency.tags.coefficient" " urgency.waiting.coefficient" " urgency.age.coefficient" " urgency.age.max" " verbose" " weekstart" " xterm.title" " "; // This configuration variable is supported, but not documented. It exists // so that unit tests can force color to be on even when the output from task // is redirected to a file, or stdout is not a tty. recognized += "_forcecolor "; std::vector <std::string> all; context.config.all (all); std::vector <std::string> unrecognized; std::vector <std::string>::iterator i; for (i = all.begin (); i != all.end (); ++i) { // Disallow partial matches by tacking a leading and trailing space on each // variable name. std::string pattern = " " + *i + " "; if (recognized.find (pattern) == std::string::npos) { // These are special configuration variables, because their name is // dynamic. if (i->substr (0, 14) != "color.keyword." && i->substr (0, 14) != "color.project." && i->substr (0, 10) != "color.tag." && i->substr (0, 8) != "holiday." && i->substr (0, 7) != "report." && i->substr (0, 6) != "alias." && i->substr (0, 5) != "hook." && i->substr (0, 5) != "push." && i->substr (0, 5) != "pull." && i->substr (0, 6) != "merge." && i->substr (0, 4) != "uda." && i->substr (0, 21) != "urgency.user.project." && i->substr (0, 17) != "urgency.user.tag." && i->substr (0, 12) != "urgency.uda.") { unrecognized.push_back (*i); } } } // Find all the values that match the defaults, for highlighting. std::vector <std::string> default_values; Config default_config; default_config.setDefaults (); for (i = all.begin (); i != all.end (); ++i) if (context.config.get (*i) != default_config.get (*i)) default_values.push_back (*i); // Create output view. ViewText view; view.width (width); view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VAR)); view.add (Column::factory ("string", STRING_CMD_SHOW_CONF_VALUE)); Color error ("bold white on red"); Color warning ("black on yellow"); bool issue_error = false; bool issue_warning = false; std::string section; // Look for the first plausible argument which could be a pattern if (words.size ()) section = words[0]; if (section == "all") section = ""; std::string::size_type loc; for (i = all.begin (); i != all.end (); ++i) { loc = i->find (section, 0); if (loc != std::string::npos) { // Look for unrecognized. Color color; if (std::find (unrecognized.begin (), unrecognized.end (), *i) != unrecognized.end ()) { issue_error = true; color = error; } else if (std::find (default_values.begin (), default_values.end (), *i) != default_values.end ()) { issue_warning = true; color = warning; } std::string value = context.config.get (*i); // hide sensible information if ( (i->substr (0, 5) == "push." || i->substr (0, 5) == "pull." || i->substr (0, 6) == "merge.") && (i->find (".uri") != std::string::npos) ) { Uri uri (value); uri.parse (); value = uri.ToString (); } int row = view.addRow (); view.set (row, 0, *i, color); view.set (row, 1, value, color); } } out << "\n" << view.render () << (view.rows () == 0 ? STRING_CMD_SHOW_NONE : "") << (view.rows () == 0 ? "\n\n" : "\n"); if (issue_warning) { out << STRING_CMD_SHOW_DIFFER; if (context.color ()) out << " " << format (STRING_CMD_SHOW_DIFFER_COLOR, warning.colorize ("color")) << "\n\n"; } // Display the unrecognized variables. if (issue_error) { out << STRING_CMD_SHOW_UNREC << "\n"; for (i = unrecognized.begin (); i != unrecognized.end (); ++i) out << " " << *i << "\n"; if (context.color ()) out << "\n " << format (STRING_CMD_SHOW_DIFFER_COLOR, error.colorize ("color")); out << "\n\n"; } out << legacyCheckForDeprecatedVariables (); out << legacyCheckForDeprecatedColor (); out << legacyCheckForDeprecatedColumns (); // TODO Check for referenced but missing theme files. // TODO Check for referenced but missing string files. // TODO Check for referenced but missing tips files. // Check for referenced but missing hook scripts. #ifdef HAVE_LIBLUA std::vector <std::string> missing_scripts; for (i = all.begin (); i != all.end (); ++i) { if (i->substr (0, 5) == "hook.") { std::string value = context.config.get (*i); Nibbler n (value); // <path>:<function> [, ...] while (!n.depleted ()) { std::string file; std::string function; if (n.getUntil (':', file) && n.skip (':') && n.getUntil (',', function)) { Path script (file); if (!script.exists () || !script.readable ()) missing_scripts.push_back (file); (void) n.skip (','); } } } } if (missing_scripts.size ()) { out << STRING_CMD_SHOW_HOOKS << "\n"; for (i = missing_scripts.begin (); i != missing_scripts.end (); ++i) out << " " << *i << "\n"; out << "\n"; } #endif // Check for bad values in rc.calendar.details. std::string calendardetails = context.config.get ("calendar.details"); if (calendardetails != "full" && calendardetails != "sparse" && calendardetails != "none") out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.details", calendardetails) << "\n"; // Check for bad values in rc.calendar.holidays. std::string calendarholidays = context.config.get ("calendar.holidays"); if (calendarholidays != "full" && calendarholidays != "sparse" && calendarholidays != "none") out << format (STRING_CMD_SHOW_CONFIG_ERROR, "calendar.holidays", calendarholidays) << "\n"; // Check for bad values in rc.default.priority. std::string defaultPriority = context.config.get ("default.priority"); if (defaultPriority != "H" && defaultPriority != "M" && defaultPriority != "L" && defaultPriority != "") out << format (STRING_CMD_SHOW_CONFIG_ERROR, "default.priority", defaultPriority) << "\n"; // Verify installation. This is mentioned in the documentation as the way // to ensure everything is properly installed. if (all.size () == 0) { out << STRING_CMD_SHOW_EMPTY << "\n"; rc = 1; } else { Directory location (context.config.get ("data.location")); if (location._data == "") out << STRING_CMD_SHOW_NO_LOCATION << "\n"; if (! location.exists ()) out << STRING_CMD_SHOW_LOC_EXIST << "\n"; } output = out.str (); return rc; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "compilation-cache.h" namespace v8 { namespace internal { enum { // The number of script generations tell how many GCs a script can // survive in the compilation cache, before it will be flushed if it // hasn't been used. NUMBER_OF_SCRIPT_GENERATIONS = 5, // The compilation cache consists of tables - one for each entry // kind plus extras for the script generations. NUMBER_OF_TABLE_ENTRIES = CompilationCache::LAST_ENTRY + NUMBER_OF_SCRIPT_GENERATIONS }; // Keep separate tables for the different entry kinds. static Object* tables[NUMBER_OF_TABLE_ENTRIES] = { 0, }; static Handle<CompilationCacheTable> AllocateTable(int size) { CALL_HEAP_FUNCTION(CompilationCacheTable::Allocate(size), CompilationCacheTable); } static Handle<CompilationCacheTable> GetTable(CompilationCache::Entry entry) { Handle<CompilationCacheTable> result; if (tables[entry]->IsUndefined()) { static const int kInitialCacheSize = 64; result = AllocateTable(kInitialCacheSize); tables[entry] = *result; } else { CompilationCacheTable* table = CompilationCacheTable::cast(tables[entry]); result = Handle<CompilationCacheTable>(table); } return result; } static Handle<JSFunction> Lookup(Handle<String> source, Handle<Context> context, CompilationCache::Entry entry) { // Make sure not to leak the table into the surrounding handle // scope. Otherwise, we risk keeping old tables around even after // having cleared the cache. Object* result; { HandleScope scope; Handle<CompilationCacheTable> table = GetTable(entry); result = table->LookupEval(*source, *context); } if (result->IsJSFunction()) { return Handle<JSFunction>(JSFunction::cast(result)); } else { return Handle<JSFunction>::null(); } } static Handle<FixedArray> Lookup(Handle<String> source, JSRegExp::Flags flags) { // Make sure not to leak the table into the surrounding handle // scope. Otherwise, we risk keeping old tables around even after // having cleared the cache. Object* result; { HandleScope scope; Handle<CompilationCacheTable> table = GetTable(CompilationCache::REGEXP); result = table->LookupRegExp(*source, flags); } if (result->IsFixedArray()) { return Handle<FixedArray>(FixedArray::cast(result)); } else { return Handle<FixedArray>::null(); } } // We only re-use a cached function for some script source code if the // script originates from the same place. This is to avoid issues // when reporting errors, etc. static bool HasOrigin(Handle<JSFunction> boilerplate, Handle<Object> name, int line_offset, int column_offset) { Handle<Script> script = Handle<Script>(Script::cast(boilerplate->shared()->script())); // If the script name isn't set, the boilerplate script should have // an undefined name to have the same origin. if (name.is_null()) { return script->name()->IsUndefined(); } // Do the fast bailout checks first. if (line_offset != script->line_offset()->value()) return false; if (column_offset != script->column_offset()->value()) return false; // Check that both names are strings. If not, no match. if (!name->IsString() || !script->name()->IsString()) return false; // Compare the two name strings for equality. return String::cast(*name)->Equals(String::cast(script->name())); } // TODO(245): Need to allow identical code from different contexts to // be cached in the same script generation. Currently the first use // will be cached, but subsequent code from different source / line // won't. Handle<JSFunction> CompilationCache::LookupScript(Handle<String> source, Handle<Object> name, int line_offset, int column_offset) { Object* result = NULL; Entry generation = SCRIPT; // First generation. // Probe the script generation tables. Make sure not to leak handles // into the caller's handle scope. { HandleScope scope; while (generation < SCRIPT + NUMBER_OF_SCRIPT_GENERATIONS) { Handle<CompilationCacheTable> table = GetTable(generation); Handle<Object> probe(table->Lookup(*source)); if (probe->IsJSFunction()) { Handle<JSFunction> boilerplate = Handle<JSFunction>::cast(probe); // Break when we've found a suitable boilerplate function that // matches the origin. if (HasOrigin(boilerplate, name, line_offset, column_offset)) { result = *boilerplate; break; } } // Go to the next generation. generation = static_cast<Entry>(generation + 1); } } // Once outside the menacles of the handle scope, we need to recheck // to see if we actually found a cached script. If so, we return a // handle created in the caller's handle scope. if (result != NULL) { Handle<JSFunction> boilerplate(JSFunction::cast(result)); ASSERT(HasOrigin(boilerplate, name, line_offset, column_offset)); // If the script was found in a later generation, we promote it to // the first generation to let it survive longer in the cache. if (generation != SCRIPT) PutScript(source, boilerplate); Counters::compilation_cache_hits.Increment(); return boilerplate; } else { Counters::compilation_cache_misses.Increment(); return Handle<JSFunction>::null(); } } Handle<JSFunction> CompilationCache::LookupEval(Handle<String> source, Handle<Context> context, Entry entry) { ASSERT(entry == EVAL_GLOBAL || entry == EVAL_CONTEXTUAL); Handle<JSFunction> result = Lookup(source, context, entry); if (result.is_null()) { Counters::compilation_cache_misses.Increment(); } else { Counters::compilation_cache_hits.Increment(); } return result; } Handle<FixedArray> CompilationCache::LookupRegExp(Handle<String> source, JSRegExp::Flags flags) { Handle<FixedArray> result = Lookup(source, flags); if (result.is_null()) { Counters::compilation_cache_misses.Increment(); } else { Counters::compilation_cache_hits.Increment(); } return result; } void CompilationCache::PutScript(Handle<String> source, Handle<JSFunction> boilerplate) { HandleScope scope; ASSERT(boilerplate->IsBoilerplate()); Handle<CompilationCacheTable> table = GetTable(SCRIPT); CALL_HEAP_FUNCTION_VOID(table->Put(*source, *boilerplate)); } void CompilationCache::PutEval(Handle<String> source, Handle<Context> context, Entry entry, Handle<JSFunction> boilerplate) { HandleScope scope; ASSERT(boilerplate->IsBoilerplate()); Handle<CompilationCacheTable> table = GetTable(entry); CALL_HEAP_FUNCTION_VOID(table->PutEval(*source, *context, *boilerplate)); } void CompilationCache::PutRegExp(Handle<String> source, JSRegExp::Flags flags, Handle<FixedArray> data) { HandleScope scope; Handle<CompilationCacheTable> table = GetTable(REGEXP); CALL_HEAP_FUNCTION_VOID(table->PutRegExp(*source, flags, *data)); } void CompilationCache::Clear() { for (int i = 0; i < NUMBER_OF_TABLE_ENTRIES; i++) { tables[i] = Heap::undefined_value(); } } void CompilationCache::Iterate(ObjectVisitor* v) { v->VisitPointers(&tables[0], &tables[NUMBER_OF_TABLE_ENTRIES]); } void CompilationCache::MarkCompactPrologue() { ASSERT(LAST_ENTRY == SCRIPT); for (int i = NUMBER_OF_TABLE_ENTRIES - 1; i > SCRIPT; i--) { tables[i] = tables[i - 1]; } for (int j = 0; j <= LAST_ENTRY; j++) { tables[j] = Heap::undefined_value(); } } } } // namespace v8::internal <commit_msg>Fix compilation for gcc 4.3+. Patch by Lei Zhang. Review URL: http://codereview.chromium.org/113621<commit_after>// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "compilation-cache.h" namespace v8 { namespace internal { enum { // The number of script generations tell how many GCs a script can // survive in the compilation cache, before it will be flushed if it // hasn't been used. NUMBER_OF_SCRIPT_GENERATIONS = 5, // The compilation cache consists of tables - one for each entry // kind plus extras for the script generations. NUMBER_OF_TABLE_ENTRIES = CompilationCache::LAST_ENTRY + NUMBER_OF_SCRIPT_GENERATIONS }; // Keep separate tables for the different entry kinds. static Object* tables[NUMBER_OF_TABLE_ENTRIES] = { 0, }; static Handle<CompilationCacheTable> AllocateTable(int size) { CALL_HEAP_FUNCTION(CompilationCacheTable::Allocate(size), CompilationCacheTable); } static Handle<CompilationCacheTable> GetTable(int index) { ASSERT(index >= 0 && index < NUMBER_OF_TABLE_ENTRIES); Handle<CompilationCacheTable> result; if (tables[index]->IsUndefined()) { static const int kInitialCacheSize = 64; result = AllocateTable(kInitialCacheSize); tables[index] = *result; } else { CompilationCacheTable* table = CompilationCacheTable::cast(tables[index]); result = Handle<CompilationCacheTable>(table); } return result; } static Handle<JSFunction> Lookup(Handle<String> source, Handle<Context> context, CompilationCache::Entry entry) { // Make sure not to leak the table into the surrounding handle // scope. Otherwise, we risk keeping old tables around even after // having cleared the cache. Object* result; { HandleScope scope; Handle<CompilationCacheTable> table = GetTable(entry); result = table->LookupEval(*source, *context); } if (result->IsJSFunction()) { return Handle<JSFunction>(JSFunction::cast(result)); } else { return Handle<JSFunction>::null(); } } static Handle<FixedArray> Lookup(Handle<String> source, JSRegExp::Flags flags) { // Make sure not to leak the table into the surrounding handle // scope. Otherwise, we risk keeping old tables around even after // having cleared the cache. Object* result; { HandleScope scope; Handle<CompilationCacheTable> table = GetTable(CompilationCache::REGEXP); result = table->LookupRegExp(*source, flags); } if (result->IsFixedArray()) { return Handle<FixedArray>(FixedArray::cast(result)); } else { return Handle<FixedArray>::null(); } } // We only re-use a cached function for some script source code if the // script originates from the same place. This is to avoid issues // when reporting errors, etc. static bool HasOrigin(Handle<JSFunction> boilerplate, Handle<Object> name, int line_offset, int column_offset) { Handle<Script> script = Handle<Script>(Script::cast(boilerplate->shared()->script())); // If the script name isn't set, the boilerplate script should have // an undefined name to have the same origin. if (name.is_null()) { return script->name()->IsUndefined(); } // Do the fast bailout checks first. if (line_offset != script->line_offset()->value()) return false; if (column_offset != script->column_offset()->value()) return false; // Check that both names are strings. If not, no match. if (!name->IsString() || !script->name()->IsString()) return false; // Compare the two name strings for equality. return String::cast(*name)->Equals(String::cast(script->name())); } // TODO(245): Need to allow identical code from different contexts to // be cached in the same script generation. Currently the first use // will be cached, but subsequent code from different source / line // won't. Handle<JSFunction> CompilationCache::LookupScript(Handle<String> source, Handle<Object> name, int line_offset, int column_offset) { // Use an int for the generation index, so value range propagation // in gcc 4.3+ won't assume it can only go up to LAST_ENTRY when in // fact it can go up to SCRIPT + NUMBER_OF_SCRIPT_GENERATIONS. int generation = SCRIPT; Object* result = NULL; // Probe the script generation tables. Make sure not to leak handles // into the caller's handle scope. { HandleScope scope; while (generation < SCRIPT + NUMBER_OF_SCRIPT_GENERATIONS) { Handle<CompilationCacheTable> table = GetTable(generation); Handle<Object> probe(table->Lookup(*source)); if (probe->IsJSFunction()) { Handle<JSFunction> boilerplate = Handle<JSFunction>::cast(probe); // Break when we've found a suitable boilerplate function that // matches the origin. if (HasOrigin(boilerplate, name, line_offset, column_offset)) { result = *boilerplate; break; } } // Go to the next generation. generation++; } } // Once outside the menacles of the handle scope, we need to recheck // to see if we actually found a cached script. If so, we return a // handle created in the caller's handle scope. if (result != NULL) { Handle<JSFunction> boilerplate(JSFunction::cast(result)); ASSERT(HasOrigin(boilerplate, name, line_offset, column_offset)); // If the script was found in a later generation, we promote it to // the first generation to let it survive longer in the cache. if (generation != SCRIPT) PutScript(source, boilerplate); Counters::compilation_cache_hits.Increment(); return boilerplate; } else { Counters::compilation_cache_misses.Increment(); return Handle<JSFunction>::null(); } } Handle<JSFunction> CompilationCache::LookupEval(Handle<String> source, Handle<Context> context, Entry entry) { ASSERT(entry == EVAL_GLOBAL || entry == EVAL_CONTEXTUAL); Handle<JSFunction> result = Lookup(source, context, entry); if (result.is_null()) { Counters::compilation_cache_misses.Increment(); } else { Counters::compilation_cache_hits.Increment(); } return result; } Handle<FixedArray> CompilationCache::LookupRegExp(Handle<String> source, JSRegExp::Flags flags) { Handle<FixedArray> result = Lookup(source, flags); if (result.is_null()) { Counters::compilation_cache_misses.Increment(); } else { Counters::compilation_cache_hits.Increment(); } return result; } void CompilationCache::PutScript(Handle<String> source, Handle<JSFunction> boilerplate) { HandleScope scope; ASSERT(boilerplate->IsBoilerplate()); Handle<CompilationCacheTable> table = GetTable(SCRIPT); CALL_HEAP_FUNCTION_VOID(table->Put(*source, *boilerplate)); } void CompilationCache::PutEval(Handle<String> source, Handle<Context> context, Entry entry, Handle<JSFunction> boilerplate) { HandleScope scope; ASSERT(boilerplate->IsBoilerplate()); Handle<CompilationCacheTable> table = GetTable(entry); CALL_HEAP_FUNCTION_VOID(table->PutEval(*source, *context, *boilerplate)); } void CompilationCache::PutRegExp(Handle<String> source, JSRegExp::Flags flags, Handle<FixedArray> data) { HandleScope scope; Handle<CompilationCacheTable> table = GetTable(REGEXP); CALL_HEAP_FUNCTION_VOID(table->PutRegExp(*source, flags, *data)); } void CompilationCache::Clear() { for (int i = 0; i < NUMBER_OF_TABLE_ENTRIES; i++) { tables[i] = Heap::undefined_value(); } } void CompilationCache::Iterate(ObjectVisitor* v) { v->VisitPointers(&tables[0], &tables[NUMBER_OF_TABLE_ENTRIES]); } void CompilationCache::MarkCompactPrologue() { ASSERT(LAST_ENTRY == SCRIPT); for (int i = NUMBER_OF_TABLE_ENTRIES - 1; i > SCRIPT; i--) { tables[i] = tables[i - 1]; } for (int j = 0; j <= LAST_ENTRY; j++) { tables[j] = Heap::undefined_value(); } } } } // namespace v8::internal <|endoftext|>
<commit_before>// @(#)root/gpad:$Id$ // Author: Rene Brun 08/01/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TGuiFactory.h" #include "TInspectCanvas.h" #include "TButton.h" #include "TClass.h" #include "TLine.h" #include "TLink.h" #include "TDataMember.h" #include "TDataType.h" #include "TRealData.h" #include "TLatex.h" ClassImp(TInspectCanvas) ////////////////////////////////////////////////////////////////////////// // // // TInspectorObject // // // ////////////////////////////////////////////////////////////////////////// class TInspectorObject : public TObject { // This class is designed to wrap a Foreign object in order to // inject it into the Browse sub-system. public: TInspectorObject(void *obj, TClass *cl) : fObj(obj),fClass(cl) {}; ~TInspectorObject(){;} void *GetObject() const { return fObj; }; void Inspect() const { gGuiFactory->CreateInspectorImp(this, 400, 200); }; TClass *IsA() const { return fClass; } private: void *fObj; //! pointer to the foreign object TClass *fClass; //! pointer to class of the foreign object }; //______________________________________________________________________________//*-* //*-* A InspectCanvas is a canvas specialized to inspect Root objects. // //Begin_Html /* <img src="gif/InspectCanvas.gif"> */ //End_Html // //______________________________________________________________________________ TInspectCanvas::TInspectCanvas() : TCanvas() { // InspectCanvas default constructor. fBackward = 0; fForward = 0; fCurObject = 0; fObjects = 0; fLogx = kFALSE; fLogy = kFALSE; } //_____________________________________________________________________________ TInspectCanvas::TInspectCanvas(UInt_t ww, UInt_t wh) : TCanvas("inspect","ROOT Object Inspector",ww,wh) { // InspectCanvas constructor. fBackward = 0; fForward = 0; fCurObject = 0; fObjects = new TList; fLogx = kFALSE; fLogy = kFALSE; } //______________________________________________________________________________ TInspectCanvas::~TInspectCanvas() { // InspectCanvas default destructor. if (fObjects) { fObjects->Clear("nodelete"); delete fObjects; } } //______________________________________________________________________________ void TInspectCanvas::InspectObject(TObject *obj) { // Dump contents of obj in a graphics canvas. // Same action as TObject::Dump but in a graphical form. // In addition pointers to other objects can be followed. // // The following picture is the Inspect of a histogram object: //Begin_Html /* <img src="gif/hpxinspect.gif"> */ //End_Html Int_t cdate = 0; Int_t ctime = 0; UInt_t *cdatime = 0; Bool_t isdate = kFALSE; Bool_t isbits = kFALSE; const Int_t kname = 1; const Int_t kvalue = 25; const Int_t ktitle = 37; const Int_t kline = 1024; char line[kline]; char *pname; TClass *cl = obj->IsA(); if (cl == 0) return; TInspectorObject *proxy=0; if (!cl->InheritsFrom(TObject::Class())) { // This is possible only if obj is actually a TInspectorObject // wrapping a non-TObject. proxy = (TInspectorObject*)obj; obj = (TObject*)proxy->GetObject(); } if (!cl->GetListOfRealData()) cl->BuildRealData(obj); // Count number of data members in order to resize the canvas TRealData *rd; TIter next(cl->GetListOfRealData()); Int_t nreal = cl->GetListOfRealData()->GetSize(); if (nreal == 0) return; Int_t nrows = 33; if (nreal+7 > nrows) nrows = nreal+7; Int_t nh = nrows*15; Int_t nw = 700; TVirtualPad *canvas = GetVirtCanvas(); canvas->Clear(); // remove primitives from canvas canvas->SetCanvasSize(nw, nh); // set new size of drawing area canvas->Range(0,-3,20,nreal+4); Float_t xvalue = 5; Float_t xtitle = 8; Float_t dy = 1; Float_t ytext = Float_t(nreal) - 1.5; Float_t tsize = 0.99/ytext; if (tsize < 0.02) tsize = 0.02; if (tsize > 0.03) tsize = 0.03; // Create text objects TText tname, tvalue, ttitle; TText *tval; tname.SetTextFont(61); tname.SetTextAngle(0); tname.SetTextAlign(12); tname.SetTextColor(1); tname.SetTextSize(tsize); tvalue.SetTextFont(61); tvalue.SetTextAngle(0); tvalue.SetTextAlign(12); tvalue.SetTextColor(1); tvalue.SetTextSize(tsize); ttitle.SetTextFont(62); ttitle.SetTextAngle(0); ttitle.SetTextAlign(12); ttitle.SetTextColor(1); ttitle.SetTextSize(tsize); Float_t x1 = 0.2; Float_t x2 = 19.8; Float_t y1 = -0.5; Float_t y2 = Float_t(nreal) - 0.5; Float_t y3 = y2 + 1; Float_t y4 = y3 + 1.5; Float_t db = 25./GetWh(); Float_t btop = 0.999; // Draw buttons fBackward = new TButton("backward","TInspectCanvas::GoBackward();",.01,btop-db,.15,btop); fBackward->Draw(); fBackward->SetToolTipText("Inspect previous object"); fForward = new TButton("forward", "TInspectCanvas::GoForward();", .21,btop-db,.35,btop); fForward->Draw(); fForward->SetToolTipText("Inspect next object"); // Draw surrounding box and title areas TLine frame; frame.SetLineColor(1); frame.SetLineStyle(1); frame.SetLineWidth(1); frame.DrawLine(x1, y1, x2, y1); frame.DrawLine(x2, y1, x2, y4); frame.DrawLine(x2, y4, x1, y4); frame.DrawLine(x1, y4, x1, y1); frame.DrawLine(x1, y2, x2, y2); frame.DrawLine(x1, y3, x2, y3); frame.DrawLine(xvalue, y1, xvalue, y3); frame.DrawLine(xtitle, y1, xtitle, y3); ttitle.SetTextSize(0.8*tsize); ttitle.SetTextAlign(21); ttitle.DrawText(0.5*(x1+xvalue), y2+0.1, "Member Name"); ttitle.DrawText(0.5*(xvalue+xtitle), y2+0.1, "Value"); ttitle.DrawText(0.5*(xtitle+x2), y2+0.1, "Title"); ttitle.SetTextSize(1.2*tsize); ttitle.SetTextColor(2); ttitle.SetTextAlign(11); ttitle.DrawText(x1+0.2, y3+0.1, cl->GetName()); if (proxy==0) { ttitle.SetTextColor(4); strlcpy(line,obj->GetName(),kline); ttitle.DrawText(xvalue+0.2, y3+0.1, line); ttitle.SetTextColor(6); ttitle.DrawText(xtitle+2, y3+0.1, obj->GetTitle()); } else { ttitle.SetTextColor(4); snprintf(line,1023,"%s:%d","Foreign object",0); ttitle.DrawText(xvalue+0.2, y3+0.1, line); ttitle.SetTextColor(6); ttitle.DrawText(xtitle+2, y3+0.1, "no title given"); } ttitle.SetTextSize(tsize); ttitle.SetTextColor(1); ttitle.SetTextFont(11); ttitle.SetTextAlign(12); //---Now loop on data members----------------------- // We make 3 passes. Faster than one single pass because changing // font parameters is time consuming for (Int_t pass = 0; pass < 3; pass++) { ytext = y2 - 0.5; next.Reset(); while ((rd = (TRealData*) next())) { TDataMember *member = rd->GetDataMember(); if (!member) continue; TDataType *membertype = member->GetDataType(); isdate = kFALSE; if (strcmp(member->GetName(),"fDatime") == 0 && strcmp(member->GetTypeName(),"UInt_t") == 0) { isdate = kTRUE; } isbits = kFALSE; if (strcmp(member->GetName(),"fBits") == 0 && strcmp(member->GetTypeName(),"UInt_t") == 0) { isbits = kTRUE; } // Encode data member name pname = &line[kname]; for (Int_t i=0;i<kline;i++) line[i] = ' '; line[kline-1] = 0; strlcpy(pname,rd->GetName(),kline-kname); if (strstr(member->GetFullTypeName(),"**")) strlcat(pname,"**",kline-kname); // Encode data value or pointer value tval = &tvalue; Int_t offset = rd->GetThisOffset(); char *pointer = (char*)obj + offset; char **ppointer = (char**)(pointer); TLink *tlink = 0; TClass *clm=0; if (!membertype) { clm = member->GetClass(); } if (member->IsaPointer()) { char **p3pointer = (char**)(*ppointer); if (clm && !clm->IsStartingWithTObject() ) { //NOTE: memory leak! p3pointer = (char**)new TInspectorObject(p3pointer,clm); } if (!p3pointer) { snprintf(&line[kvalue],kline-kvalue,"->0"); } else if (!member->IsBasic()) { if (pass == 1) { tlink = new TLink(xvalue+0.1, ytext, p3pointer); } } else if (membertype) { if (!strcmp(membertype->GetTypeName(), "char")) strlcpy(&line[kvalue], *ppointer,kline-kvalue); else strlcpy(&line[kvalue], membertype->AsString(p3pointer),kline-kvalue); } else if (!strcmp(member->GetFullTypeName(), "char*") || !strcmp(member->GetFullTypeName(), "const char*")) { strlcpy(&line[kvalue], *ppointer,kline-kvalue); } else { if (pass == 1) tlink = new TLink(xvalue+0.1, ytext, p3pointer); } } else if (membertype) if (isdate) { cdatime = (UInt_t*)pointer; TDatime::GetDateTime(cdatime[0],cdate,ctime); snprintf(&line[kvalue],kline-kvalue,"%d/%d",cdate,ctime); } else if (isbits) { snprintf(&line[kvalue],kline-kvalue,"0x%08x", *(UInt_t*)pointer); } else { strlcpy(&line[kvalue], membertype->AsString(pointer),kline-kvalue); } else snprintf(&line[kvalue],kline-kvalue,"->%lx ", (Long_t)pointer); // Encode data member title Int_t ltit = 0; if (isdate == kFALSE && strcmp(member->GetFullTypeName(), "char*") && strcmp(member->GetFullTypeName(), "const char*")) { Int_t lentit = strlen(member->GetTitle()); if (lentit >= kline-ktitle) lentit = kline-ktitle-1; strlcpy(&line[ktitle],member->GetTitle(),kline-ktitle); line[ktitle+lentit] = 0; ltit = ktitle; } // Ready to draw the name, value and title columns if (pass == 0)tname.DrawText( x1+0.1, ytext, &line[kname]); if (pass == 1) { if (tlink) { tlink->SetTextFont(61); tlink->SetTextAngle(0); tlink->SetTextAlign(12); tlink->SetTextColor(2); tlink->SetTextSize(tsize); tlink->SetBit(kCanDelete); tlink->Draw(); if (strstr(member->GetFullTypeName(),"**")) tlink->SetBit(TLink::kIsStarStar); tlink->SetName(member->GetTypeName()); } else { tval->DrawText(xvalue+0.1, ytext, &line[kvalue]); } } if (pass == 2 && ltit) ttitle.DrawText(xtitle+0.3, ytext, &line[ltit]); ytext -= dy; } } Update(); fCurObject = obj; } //______________________________________________________________________________ void TInspectCanvas::GoBackward() { // static function , inspect previous object TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect"); TObject *cur = inspect->GetCurObject(); TObject *obj = inspect->GetObjects()->Before(cur); if (obj) inspect->InspectObject(obj); } //______________________________________________________________________________ void TInspectCanvas::GoForward() { // static function , inspect next object TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect"); TObject *cur = inspect->GetCurObject(); TObject *obj = inspect->GetObjects()->After(cur); if (obj) inspect->InspectObject(obj); } //______________________________________________________________________________ void TInspectCanvas::Inspector(TObject *obj) { // static function , interface to InspectObject. // Create the InspectCanvas if it does not exist yet. TVirtualPad *padsav = gPad; TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect"); if (!inspect) inspect = new TInspectCanvas(700,600); else inspect->cd(); inspect->InspectObject(obj); inspect->GetObjects()->Add(obj); //obj->SetBit(kMustCleanup); if (padsav) padsav->cd(); } //______________________________________________________________________________ void TInspectCanvas::RecursiveRemove(TObject *obj) { // Recursively remove object from the list of objects. fObjects->Remove(obj); TPad::RecursiveRemove(obj); } <commit_msg>From Bertrand: - Make sure the inspector canvas background is white.<commit_after>// @(#)root/gpad:$Id$ // Author: Rene Brun 08/01/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TROOT.h" #include "TGuiFactory.h" #include "TInspectCanvas.h" #include "TButton.h" #include "TClass.h" #include "TLine.h" #include "TLink.h" #include "TDataMember.h" #include "TDataType.h" #include "TRealData.h" #include "TLatex.h" ClassImp(TInspectCanvas) ////////////////////////////////////////////////////////////////////////// // // // TInspectorObject // // // ////////////////////////////////////////////////////////////////////////// class TInspectorObject : public TObject { // This class is designed to wrap a Foreign object in order to // inject it into the Browse sub-system. public: TInspectorObject(void *obj, TClass *cl) : fObj(obj),fClass(cl) {}; ~TInspectorObject(){;} void *GetObject() const { return fObj; }; void Inspect() const { gGuiFactory->CreateInspectorImp(this, 400, 200); }; TClass *IsA() const { return fClass; } private: void *fObj; //! pointer to the foreign object TClass *fClass; //! pointer to class of the foreign object }; //______________________________________________________________________________//*-* //*-* A InspectCanvas is a canvas specialized to inspect Root objects. // //Begin_Html /* <img src="gif/InspectCanvas.gif"> */ //End_Html // //______________________________________________________________________________ TInspectCanvas::TInspectCanvas() : TCanvas() { // InspectCanvas default constructor. fBackward = 0; fForward = 0; fCurObject = 0; fObjects = 0; fLogx = kFALSE; fLogy = kFALSE; SetFillColor(0); } //_____________________________________________________________________________ TInspectCanvas::TInspectCanvas(UInt_t ww, UInt_t wh) : TCanvas("inspect","ROOT Object Inspector",ww,wh) { // InspectCanvas constructor. fBackward = 0; fForward = 0; fCurObject = 0; fObjects = new TList; fLogx = kFALSE; fLogy = kFALSE; SetFillColor(0); } //______________________________________________________________________________ TInspectCanvas::~TInspectCanvas() { // InspectCanvas default destructor. if (fObjects) { fObjects->Clear("nodelete"); delete fObjects; } } //______________________________________________________________________________ void TInspectCanvas::InspectObject(TObject *obj) { // Dump contents of obj in a graphics canvas. // Same action as TObject::Dump but in a graphical form. // In addition pointers to other objects can be followed. // // The following picture is the Inspect of a histogram object: //Begin_Html /* <img src="gif/hpxinspect.gif"> */ //End_Html Int_t cdate = 0; Int_t ctime = 0; UInt_t *cdatime = 0; Bool_t isdate = kFALSE; Bool_t isbits = kFALSE; const Int_t kname = 1; const Int_t kvalue = 25; const Int_t ktitle = 37; const Int_t kline = 1024; char line[kline]; char *pname; TClass *cl = obj->IsA(); if (cl == 0) return; TInspectorObject *proxy=0; if (!cl->InheritsFrom(TObject::Class())) { // This is possible only if obj is actually a TInspectorObject // wrapping a non-TObject. proxy = (TInspectorObject*)obj; obj = (TObject*)proxy->GetObject(); } if (!cl->GetListOfRealData()) cl->BuildRealData(obj); // Count number of data members in order to resize the canvas TRealData *rd; TIter next(cl->GetListOfRealData()); Int_t nreal = cl->GetListOfRealData()->GetSize(); if (nreal == 0) return; Int_t nrows = 33; if (nreal+7 > nrows) nrows = nreal+7; Int_t nh = nrows*15; Int_t nw = 700; TVirtualPad *canvas = GetVirtCanvas(); canvas->Clear(); // remove primitives from canvas canvas->SetCanvasSize(nw, nh); // set new size of drawing area canvas->Range(0,-3,20,nreal+4); Float_t xvalue = 5; Float_t xtitle = 8; Float_t dy = 1; Float_t ytext = Float_t(nreal) - 1.5; Float_t tsize = 0.99/ytext; if (tsize < 0.02) tsize = 0.02; if (tsize > 0.03) tsize = 0.03; // Create text objects TText tname, tvalue, ttitle; TText *tval; tname.SetTextFont(61); tname.SetTextAngle(0); tname.SetTextAlign(12); tname.SetTextColor(1); tname.SetTextSize(tsize); tvalue.SetTextFont(61); tvalue.SetTextAngle(0); tvalue.SetTextAlign(12); tvalue.SetTextColor(1); tvalue.SetTextSize(tsize); ttitle.SetTextFont(62); ttitle.SetTextAngle(0); ttitle.SetTextAlign(12); ttitle.SetTextColor(1); ttitle.SetTextSize(tsize); Float_t x1 = 0.2; Float_t x2 = 19.8; Float_t y1 = -0.5; Float_t y2 = Float_t(nreal) - 0.5; Float_t y3 = y2 + 1; Float_t y4 = y3 + 1.5; Float_t db = 25./GetWh(); Float_t btop = 0.999; // Draw buttons fBackward = new TButton("backward","TInspectCanvas::GoBackward();",.01,btop-db,.15,btop); fBackward->Draw(); fBackward->SetToolTipText("Inspect previous object"); fForward = new TButton("forward", "TInspectCanvas::GoForward();", .21,btop-db,.35,btop); fForward->Draw(); fForward->SetToolTipText("Inspect next object"); // Draw surrounding box and title areas TLine frame; frame.SetLineColor(1); frame.SetLineStyle(1); frame.SetLineWidth(1); frame.DrawLine(x1, y1, x2, y1); frame.DrawLine(x2, y1, x2, y4); frame.DrawLine(x2, y4, x1, y4); frame.DrawLine(x1, y4, x1, y1); frame.DrawLine(x1, y2, x2, y2); frame.DrawLine(x1, y3, x2, y3); frame.DrawLine(xvalue, y1, xvalue, y3); frame.DrawLine(xtitle, y1, xtitle, y3); ttitle.SetTextSize(0.8*tsize); ttitle.SetTextAlign(21); ttitle.DrawText(0.5*(x1+xvalue), y2+0.1, "Member Name"); ttitle.DrawText(0.5*(xvalue+xtitle), y2+0.1, "Value"); ttitle.DrawText(0.5*(xtitle+x2), y2+0.1, "Title"); ttitle.SetTextSize(1.2*tsize); ttitle.SetTextColor(2); ttitle.SetTextAlign(11); ttitle.DrawText(x1+0.2, y3+0.1, cl->GetName()); if (proxy==0) { ttitle.SetTextColor(4); strlcpy(line,obj->GetName(),kline); ttitle.DrawText(xvalue+0.2, y3+0.1, line); ttitle.SetTextColor(6); ttitle.DrawText(xtitle+2, y3+0.1, obj->GetTitle()); } else { ttitle.SetTextColor(4); snprintf(line,1023,"%s:%d","Foreign object",0); ttitle.DrawText(xvalue+0.2, y3+0.1, line); ttitle.SetTextColor(6); ttitle.DrawText(xtitle+2, y3+0.1, "no title given"); } ttitle.SetTextSize(tsize); ttitle.SetTextColor(1); ttitle.SetTextFont(11); ttitle.SetTextAlign(12); //---Now loop on data members----------------------- // We make 3 passes. Faster than one single pass because changing // font parameters is time consuming for (Int_t pass = 0; pass < 3; pass++) { ytext = y2 - 0.5; next.Reset(); while ((rd = (TRealData*) next())) { TDataMember *member = rd->GetDataMember(); if (!member) continue; TDataType *membertype = member->GetDataType(); isdate = kFALSE; if (strcmp(member->GetName(),"fDatime") == 0 && strcmp(member->GetTypeName(),"UInt_t") == 0) { isdate = kTRUE; } isbits = kFALSE; if (strcmp(member->GetName(),"fBits") == 0 && strcmp(member->GetTypeName(),"UInt_t") == 0) { isbits = kTRUE; } // Encode data member name pname = &line[kname]; for (Int_t i=0;i<kline;i++) line[i] = ' '; line[kline-1] = 0; strlcpy(pname,rd->GetName(),kline-kname); if (strstr(member->GetFullTypeName(),"**")) strlcat(pname,"**",kline-kname); // Encode data value or pointer value tval = &tvalue; Int_t offset = rd->GetThisOffset(); char *pointer = (char*)obj + offset; char **ppointer = (char**)(pointer); TLink *tlink = 0; TClass *clm=0; if (!membertype) { clm = member->GetClass(); } if (member->IsaPointer()) { char **p3pointer = (char**)(*ppointer); if (clm && !clm->IsStartingWithTObject() ) { //NOTE: memory leak! p3pointer = (char**)new TInspectorObject(p3pointer,clm); } if (!p3pointer) { snprintf(&line[kvalue],kline-kvalue,"->0"); } else if (!member->IsBasic()) { if (pass == 1) { tlink = new TLink(xvalue+0.1, ytext, p3pointer); } } else if (membertype) { if (!strcmp(membertype->GetTypeName(), "char")) strlcpy(&line[kvalue], *ppointer,kline-kvalue); else strlcpy(&line[kvalue], membertype->AsString(p3pointer),kline-kvalue); } else if (!strcmp(member->GetFullTypeName(), "char*") || !strcmp(member->GetFullTypeName(), "const char*")) { strlcpy(&line[kvalue], *ppointer,kline-kvalue); } else { if (pass == 1) tlink = new TLink(xvalue+0.1, ytext, p3pointer); } } else if (membertype) if (isdate) { cdatime = (UInt_t*)pointer; TDatime::GetDateTime(cdatime[0],cdate,ctime); snprintf(&line[kvalue],kline-kvalue,"%d/%d",cdate,ctime); } else if (isbits) { snprintf(&line[kvalue],kline-kvalue,"0x%08x", *(UInt_t*)pointer); } else { strlcpy(&line[kvalue], membertype->AsString(pointer),kline-kvalue); } else snprintf(&line[kvalue],kline-kvalue,"->%lx ", (Long_t)pointer); // Encode data member title Int_t ltit = 0; if (isdate == kFALSE && strcmp(member->GetFullTypeName(), "char*") && strcmp(member->GetFullTypeName(), "const char*")) { Int_t lentit = strlen(member->GetTitle()); if (lentit >= kline-ktitle) lentit = kline-ktitle-1; strlcpy(&line[ktitle],member->GetTitle(),kline-ktitle); line[ktitle+lentit] = 0; ltit = ktitle; } // Ready to draw the name, value and title columns if (pass == 0)tname.DrawText( x1+0.1, ytext, &line[kname]); if (pass == 1) { if (tlink) { tlink->SetTextFont(61); tlink->SetTextAngle(0); tlink->SetTextAlign(12); tlink->SetTextColor(2); tlink->SetTextSize(tsize); tlink->SetBit(kCanDelete); tlink->Draw(); if (strstr(member->GetFullTypeName(),"**")) tlink->SetBit(TLink::kIsStarStar); tlink->SetName(member->GetTypeName()); } else { tval->DrawText(xvalue+0.1, ytext, &line[kvalue]); } } if (pass == 2 && ltit) ttitle.DrawText(xtitle+0.3, ytext, &line[ltit]); ytext -= dy; } } Update(); fCurObject = obj; } //______________________________________________________________________________ void TInspectCanvas::GoBackward() { // static function , inspect previous object TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect"); TObject *cur = inspect->GetCurObject(); TObject *obj = inspect->GetObjects()->Before(cur); if (obj) inspect->InspectObject(obj); } //______________________________________________________________________________ void TInspectCanvas::GoForward() { // static function , inspect next object TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect"); TObject *cur = inspect->GetCurObject(); TObject *obj = inspect->GetObjects()->After(cur); if (obj) inspect->InspectObject(obj); } //______________________________________________________________________________ void TInspectCanvas::Inspector(TObject *obj) { // static function , interface to InspectObject. // Create the InspectCanvas if it does not exist yet. TVirtualPad *padsav = gPad; TInspectCanvas *inspect = (TInspectCanvas*)(gROOT->GetListOfCanvases())->FindObject("inspect"); if (!inspect) inspect = new TInspectCanvas(700,600); else inspect->cd(); inspect->InspectObject(obj); inspect->GetObjects()->Add(obj); //obj->SetBit(kMustCleanup); if (padsav) padsav->cd(); } //______________________________________________________________________________ void TInspectCanvas::RecursiveRemove(TObject *obj) { // Recursively remove object from the list of objects. fObjects->Remove(obj); TPad::RecursiveRemove(obj); } <|endoftext|>
<commit_before>#include "vtkActor.h" #include "vtkPolyData.h" #include "vtkUnstructuredGrid.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkPointPicker.h" #include "vtkRenderWindowInteractor.h" #include "vtkPolyDataMapper.h" #include "vtkSphereSource.h" #include "vtkPolyDataReader.h" #include "vtkPolyDataMapper.h" #include "vtkShrinkFilter.h" #include "vtkDataSetMapper.h" #include "vtkRenderWindowInteractor.h" #include "vtkIdList.h" static void PickCells(void *); static vtkActor *sphereActor; static vtkPolyData *plateOutput; static vtkUnstructuredGrid *cells; static vtkRenderWindow *renWin; static vtkActor *cellsActor, *plateActor; main () { vtkRenderer *renderer = vtkRenderer::New(); renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkPointPicker *picker = vtkPointPicker::New(); picker->SetTolerance(0.01); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); iren->SetPicker(picker); // read data file vtkPolyDataReader *plate = vtkPolyDataReader::New(); plate->SetFileName("../../../vtkdata/plate.vtk"); plate->DebugOn(); plateOutput = plate->GetOutput(); vtkPolyDataMapper *plateMapper = vtkPolyDataMapper::New(); plateMapper->SetInput(plate->GetOutput()); plateActor = vtkActor::New(); plateActor->SetMapper(plateMapper); plateActor->GetProperty()->SetColor(0.5000,0.5400,0.5300); // create marker for pick vtkSphereSource *sphere = vtkSphereSource::New(); sphere->SetThetaResolution(8); sphere->SetPhiResolution(8); sphere->SetRadius(0.01); vtkPolyDataMapper *sphereMapper = vtkPolyDataMapper::New(); sphereMapper->SetInput(sphere->GetOutput()); sphereActor = vtkActor::New(); sphereActor->SetMapper(sphereMapper); sphereActor->GetProperty()->SetColor(1,0,0); sphereActor->PickableOff(); // create actor and mapper to display picked cells cells = vtkUnstructuredGrid::New(); vtkShrinkFilter *shrink = vtkShrinkFilter::New(); shrink->SetInput(cells); shrink->SetShrinkFactor(0.75); vtkDataSetMapper *cellsMapper = vtkDataSetMapper::New(); cellsMapper->SetInput(shrink->GetOutput()); cellsActor = vtkActor::New(); cellsActor->SetMapper(cellsMapper); cellsActor->VisibilityOff(); cellsActor->GetProperty()->SetColor(0.5000,0.5400,0.5300); renderer->AddActor(cellsActor); renderer->AddActor(plateActor); renderer->AddActor(sphereActor); renderer->SetBackground(1,1,1); renWin->SetSize(750,750); // interact with data renWin->Render(); iren->SetEndPickMethod(PickCells,(void *)iren); iren->Start(); // Clean up renderer->Delete(); renWin->Delete(); picker->Delete(); iren->Delete(); plate->Delete(); plateMapper->Delete(); plateActor->Delete(); sphere->Delete(); sphereMapper->Delete(); sphereActor->Delete(); cells->Delete(); shrink->Delete(); cellsMapper->Delete(); cellsActor->Delete(); } static void PickCells(void *arg) { vtkRenderWindowInteractor *iren = (vtkRenderWindowInteractor *)arg; vtkPointPicker *picker = (vtkPointPicker *)iren->GetPicker(); int i, cellId; vtkIdList cellIds(12), ptIds(12); sphereActor->SetPosition(picker->GetPickPosition()); if ( picker->GetPointId() >= 0 ) { cout << "Point id: " << picker->GetPointId() << "\n"; cellsActor->VisibilityOn(); plateActor->VisibilityOff(); cells->Initialize(); cells->Allocate(100); cells->SetPoints(plateOutput->GetPoints()); plateOutput->GetPointCells(picker->GetPointId(), cellIds); for (i=0; i < cellIds.GetNumberOfIds(); i++) { cellId = cellIds.GetId(i); plateOutput->GetCellPoints(cellId, ptIds); cells->InsertNextCell(plateOutput->GetCellType(cellId), ptIds); } } else { cellsActor->VisibilityOff(); plateActor->VisibilityOn(); } renWin->Render(); } <commit_msg>ERR: PR#1496 Date: Wed, 25 Nov 1998 11:42:47 -0500 From: aa8vb@vislab.epa.gov To: vtk-bugs@vtk.scorec.rpi.edu Subject: v2.2 pickCells example; ref count errs & picking often doesn't work<commit_after>#include "vtkActor.h" #include "vtkPolyData.h" #include "vtkUnstructuredGrid.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkPointPicker.h" #include "vtkRenderWindowInteractor.h" #include "vtkPolyDataMapper.h" #include "vtkSphereSource.h" #include "vtkPolyDataReader.h" #include "vtkPolyDataMapper.h" #include "vtkShrinkFilter.h" #include "vtkDataSetMapper.h" #include "vtkRenderWindowInteractor.h" #include "vtkIdList.h" static void PickCells(void *); static vtkActor *sphereActor; static vtkPolyData *plateOutput; static vtkUnstructuredGrid *cells; static vtkRenderWindow *renWin; static vtkActor *cellsActor, *plateActor; main () { vtkRenderer *renderer = vtkRenderer::New(); renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkPointPicker *picker = vtkPointPicker::New(); picker->SetTolerance(0.01); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); iren->SetPicker(picker); // read data file vtkPolyDataReader *plate = vtkPolyDataReader::New(); plate->SetFileName("../../../vtkdata/plate.vtk"); plate->DebugOn(); plateOutput = plate->GetOutput(); vtkPolyDataMapper *plateMapper = vtkPolyDataMapper::New(); plateMapper->SetInput(plate->GetOutput()); plateActor = vtkActor::New(); plateActor->SetMapper(plateMapper); plateActor->GetProperty()->SetColor(0.5000,0.5400,0.5300); // create marker for pick vtkSphereSource *sphere = vtkSphereSource::New(); sphere->SetThetaResolution(8); sphere->SetPhiResolution(8); sphere->SetRadius(0.01); vtkPolyDataMapper *sphereMapper = vtkPolyDataMapper::New(); sphereMapper->SetInput(sphere->GetOutput()); sphereActor = vtkActor::New(); sphereActor->SetMapper(sphereMapper); sphereActor->GetProperty()->SetColor(1,0,0); sphereActor->PickableOff(); // create actor and mapper to display picked cells cells = vtkUnstructuredGrid::New(); vtkShrinkFilter *shrink = vtkShrinkFilter::New(); shrink->SetInput(cells); shrink->SetShrinkFactor(0.75); vtkDataSetMapper *cellsMapper = vtkDataSetMapper::New(); cellsMapper->SetInput(shrink->GetOutput()); cellsActor = vtkActor::New(); cellsActor->SetMapper(cellsMapper); cellsActor->PickableOff(); cellsActor->VisibilityOff(); cellsActor->GetProperty()->SetColor(0.5000,0.5400,0.5300); renderer->AddActor(cellsActor); renderer->AddActor(plateActor); renderer->AddActor(sphereActor); renderer->SetBackground(1,1,1); renWin->SetSize(750,750); // interact with data renWin->Render(); iren->SetEndPickMethod(PickCells,(void *)iren); iren->Start(); // Clean up renderer->Delete(); renWin->Delete(); picker->Delete(); iren->Delete(); plate->Delete(); plateMapper->Delete(); plateActor->Delete(); sphere->Delete(); sphereMapper->Delete(); sphereActor->Delete(); cells->Delete(); shrink->Delete(); cellsMapper->Delete(); cellsActor->Delete(); } static void PickCells(void *arg) { vtkRenderWindowInteractor *iren = (vtkRenderWindowInteractor *)arg; vtkPointPicker *picker = (vtkPointPicker *)iren->GetPicker(); int i, cellId; vtkIdList *cellIds = vtkIdList::New(); cellIds->Allocate(12); vtkIdList *ptIds = vtkIdList::New(); ptIds->Allocate(12); sphereActor->SetPosition(picker->GetPickPosition()); if ( picker->GetPointId() >= 0 ) { cout << "Point id: " << picker->GetPointId() << "\n"; cellsActor->VisibilityOn(); plateActor->VisibilityOff(); cells->Initialize(); cells->Allocate(100); cells->SetPoints(plateOutput->GetPoints()); plateOutput->GetPointCells(picker->GetPointId(), cellIds); for (i=0; i < cellIds->GetNumberOfIds(); i++) { cellId = cellIds->GetId(i); plateOutput->GetCellPoints(cellId, ptIds); cells->InsertNextCell(plateOutput->GetCellType(cellId), ptIds); } } else { cellsActor->VisibilityOff(); plateActor->VisibilityOn(); } renWin->Render(); cellIds->Delete(); ptIds->Delete(); } <|endoftext|>
<commit_before>/* * strings.cpp * * Created on: 20.11.2014 г. * Author: trifon */ #include <iostream> #include <cstring> using namespace std; const int MAX = 100; void palindrome() { char s[MAX]; cin.getline(s, MAX); int n = strlen(s); int i = 0; while (i < n / 2 && s[i] == s[n - i - 1]) i++; // a[i] != a[j], j е "огледалното" на i // j = n - i - 1 // прегледали сме всички k огледални двойки // k == n / 2 // i == k == n / 2 --> прегледали сме всички двойки if (i == n / 2) cout << "Палиндром е!\n"; else cout << "Не е палиндром!\n"; } int testStrings() { int a[] = { 1, 2, 3 }; char w1[] = "He\nllo"; char w2[MAX] = { 'H', 'e', 'l', 'l', 'o', '\0' }; cout << w1 << endl; cout << w2 << endl; cout << a << endl; //cin >> w1; //cout << w1 << endl; // !!! cin >> a; cin.getline(w2, MAX); //cin.getline(w2, 10, '!'); cout << w2 << endl; cout << strlen(w2) << endl; cout << strcpy(w2, "Goodbye!") << endl; cout << w2 << endl; // !!! strcpy("Goodbye!", w2); cout << strcmp(w1, w2) << endl; // !!! if (strcmp(w2, "Goodbye!")) if (strcmp(w2, "Goodbye!") == 0) cout << "Да!" << endl; cout << strcat(w2, " See you soon!") << endl; cout << w2 << endl; cout << strchr(w2, 'b') << endl; // !!! cout << strchr(w2, 'X') << endl; if (strchr(w2, 'X')) cout << "Има X!\n"; else cout << "Няма X!\n"; cout << strstr(w2, "you") << endl; if (strstr(w2, "Hello")) cout << "Има Hello!\n"; else cout << "Няма Hello!\n"; return 0; } bool isSeparator(char c) { return c == ' ' || c == ',' || c == '.' || c == '\0'; } void countWords() { char s[MAX]; cin.getline(s, MAX); int counter = 0, i = 0; bool onWord = false; /* while (s[i] != '\0') { bool onWordNext = !isSeparator(s[i]); if (onWord && !onWordNext) counter++; onWord = onWordNext; i++; } if (onWord) counter++; */ do { bool onWordNext = !isSeparator(s[i]); if (onWord && !onWordNext) counter++; onWord = onWordNext; i++; } while(s[i-1] != '\0'); cout << "Намерени са " << counter << " думи" << endl; } int main() { // testStrings(); // palindrome(); countWords(); return 0; } <commit_msg>Реализация на прост калкулатор.<commit_after>/* * strings.cpp * * Created on: 20.11.2014 г. * Author: trifon */ #include <iostream> #include <cstring> using namespace std; const int MAX = 100; void palindrome() { char s[MAX]; cin.getline(s, MAX); int n = strlen(s); int i = 0; while (i < n / 2 && s[i] == s[n - i - 1]) i++; // a[i] != a[j], j е "огледалното" на i // j = n - i - 1 // прегледали сме всички k огледални двойки // k == n / 2 // i == k == n / 2 --> прегледали сме всички двойки if (i == n / 2) cout << "Палиндром е!\n"; else cout << "Не е палиндром!\n"; } int testStrings() { int a[] = { 1, 2, 3 }; char w1[] = "He\nllo"; char w2[MAX] = { 'H', 'e', 'l', 'l', 'o', '\0' }; cout << w1 << endl; cout << w2 << endl; cout << a << endl; //cin >> w1; //cout << w1 << endl; // !!! cin >> a; cin.getline(w2, MAX); //cin.getline(w2, 10, '!'); cout << w2 << endl; cout << strlen(w2) << endl; cout << strcpy(w2, "Goodbye!") << endl; cout << w2 << endl; // !!! strcpy("Goodbye!", w2); cout << strcmp(w1, w2) << endl; // !!! if (strcmp(w2, "Goodbye!")) if (strcmp(w2, "Goodbye!") == 0) cout << "Да!" << endl; cout << strcat(w2, " See you soon!") << endl; cout << w2 << endl; cout << strchr(w2, 'b') << endl; // !!! cout << strchr(w2, 'X') << endl; if (strchr(w2, 'X')) cout << "Има X!\n"; else cout << "Няма X!\n"; cout << strstr(w2, "you") << endl; if (strstr(w2, "Hello")) cout << "Има Hello!\n"; else cout << "Няма Hello!\n"; return 0; } bool isSeparator(char c) { return c == ' ' || c == ',' || c == '.' || c == '\0'; } void countWords() { char s[MAX]; cin.getline(s, MAX); int counter = 0, i = 0; bool onWord = false; /* while (s[i] != '\0') { bool onWordNext = !isSeparator(s[i]); if (onWord && !onWordNext) counter++; onWord = onWordNext; i++; } if (onWord) counter++; */ do { bool onWordNext = !isSeparator(s[i]); if (onWord && !onWordNext) counter++; onWord = onWordNext; i++; } while(s[i-1] != '\0'); cout << "Намерени са " << counter << " думи" << endl; } bool isDigit(char c) { return c >= '0' && c <= '9'; } int toDigit(char c) { return c - '0'; } int applyOperation(int left, char op, int right) { switch(op) { case '+':return left + right; case '-':return left - right; case '*':return left * right; case '/':return left / right; case '%':return left % right; } return left; } void calculator() { char input[MAX]; cin.getline(input, MAX); // 2+3-4*5/6%7= // допускаме, че низът въведен коректно int i = 0; int result = 0; // резултатът до момента int arg = 0; // последният аргумент char op = '+'; // предишна операция do { if (isDigit(input[i])) { // цифра (arg *= 10) += toDigit(input[i]); } else { // операция // 1. изпълняваме предишната операция // върху result и arg result = applyOperation(result, op, arg); // 2. запомняме новата операция op = input[i]; // 3. нулираме аргумента, за да можем да // Натрупаме новите цифри отначало arg = 0; } i++; } while(input[i-1] != '='); // input[i] == '=' cout << result << endl; } int main() { // testStrings(); // palindrome(); // countWords(); calculator(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsFontProvider.cxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "view/SlsFontProvider.hxx" #include "controller/SlideSorterController.hxx" #include <sfx2/app.hxx> #include <com/sun/star/uno/RuntimeException.hpp> using namespace ::sd::slidesorter; namespace sd { namespace slidesorter { namespace view { FontProvider* FontProvider::mpInstance = NULL; FontProvider& FontProvider::Instance (void) { if (mpInstance == NULL) { ::osl::GetGlobalMutex aMutexFunctor; ::osl::MutexGuard aGuard (aMutexFunctor()); if (mpInstance == NULL) { // Create an instance of the class and register it at the // SdGlobalResourceContainer so that it is eventually released. FontProvider* pInstance = new FontProvider(); SdGlobalResourceContainer::Instance().AddResource ( ::std::auto_ptr<SdGlobalResource>(pInstance)); OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); mpInstance = pInstance; } } else { OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); } // We throw an exception when for some strange reason no instance of // this class exists. if (mpInstance == NULL) throw ::com::sun::star::uno::RuntimeException(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.IndexedPropertyValues")), NULL); return *mpInstance; } FontProvider::FontProvider (void) : maFont(), maMapMode() { } FontProvider::~FontProvider (void) { } void FontProvider::Invalidate (void) { maFont.reset(); } FontProvider::SharedFontPointer FontProvider::GetFont (const OutputDevice& rDevice) { // Reset the font when the map mode has changed since its creation. if (maMapMode != rDevice.GetMapMode()) maFont.reset(); if (maFont.get() == NULL) { // Initialize the font from the application style settings. maFont.reset(new Font (Application::GetSettings().GetStyleSettings().GetAppFont())); maFont->SetTransparent(TRUE); maFont->SetWeight(WEIGHT_NORMAL); // Transform the point size to pixel size. MapMode aFontMapMode (MAP_POINT); Size aFontSize (rDevice.LogicToPixel(maFont->GetSize(), aFontMapMode)); // Transform the font size to the logical coordinates of the device. maFont->SetSize (rDevice.PixelToLogic(aFontSize)); // Remember the map mode of the given device to detect different // devices or modified zoom scales on future calls. maMapMode = rDevice.GetMapMode(); } return maFont; } } } } // end of namespace ::sd::slidesorter::view <commit_msg>INTEGRATION: CWS hub01 (1.5.324); FILE MERGED 2008/06/18 20:41:31 thb 1.5.324.2: RESYNC: (1.5-1.7); FILE MERGED 2008/01/23 02:13:14 hub 1.5.324.1: Fix a build warning about empty else statement (gcc 4.2.1)<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsFontProvider.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "view/SlsFontProvider.hxx" #include "controller/SlideSorterController.hxx" #include <sfx2/app.hxx> #include <com/sun/star/uno/RuntimeException.hpp> using namespace ::sd::slidesorter; namespace sd { namespace slidesorter { namespace view { FontProvider* FontProvider::mpInstance = NULL; FontProvider& FontProvider::Instance (void) { if (mpInstance == NULL) { ::osl::GetGlobalMutex aMutexFunctor; ::osl::MutexGuard aGuard (aMutexFunctor()); if (mpInstance == NULL) { // Create an instance of the class and register it at the // SdGlobalResourceContainer so that it is eventually released. FontProvider* pInstance = new FontProvider(); SdGlobalResourceContainer::Instance().AddResource ( ::std::auto_ptr<SdGlobalResource>(pInstance)); OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); mpInstance = pInstance; } } else { OSL_DOUBLE_CHECKED_LOCKING_MEMORY_BARRIER(); } // We throw an exception when for some strange reason no instance of // this class exists. if (mpInstance == NULL) throw ::com::sun::star::uno::RuntimeException(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.IndexedPropertyValues")), NULL); return *mpInstance; } FontProvider::FontProvider (void) : maFont(), maMapMode() { } FontProvider::~FontProvider (void) { } void FontProvider::Invalidate (void) { maFont.reset(); } FontProvider::SharedFontPointer FontProvider::GetFont (const OutputDevice& rDevice) { // Reset the font when the map mode has changed since its creation. if (maMapMode != rDevice.GetMapMode()) maFont.reset(); if (maFont.get() == NULL) { // Initialize the font from the application style settings. maFont.reset(new Font (Application::GetSettings().GetStyleSettings().GetAppFont())); maFont->SetTransparent(TRUE); maFont->SetWeight(WEIGHT_NORMAL); // Transform the point size to pixel size. MapMode aFontMapMode (MAP_POINT); Size aFontSize (rDevice.LogicToPixel(maFont->GetSize(), aFontMapMode)); // Transform the font size to the logical coordinates of the device. maFont->SetSize (rDevice.PixelToLogic(aFontSize)); // Remember the map mode of the given device to detect different // devices or modified zoom scales on future calls. maMapMode = rDevice.GetMapMode(); } return maFont; } } } } // end of namespace ::sd::slidesorter::view <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * * Authors: * Christian Surlykke <christian@surlykke.dk> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <QDebug> #include <QStringList> #include "batteryhelper.h" #include "powermanagementd.h" #include "../config/powermanagementsettings.h" #include "idlenesswatcher.h" #include "lidwatcher.h" #include "batterywatcher.h" #define CURRENT_RUNCHECK_LEVEL 1 PowerManagementd::PowerManagementd() : mBatterywatcherd(0), mLidwatcherd(0), mIdlenesswatcherd(0), mSettings() { connect(&mSettings, SIGNAL(settingsChanged()), this, SLOT(settingsChanged())); settingsChanged(); if (mSettings.getRunCheckLevel() < CURRENT_RUNCHECK_LEVEL) { performRunCheck(); mSettings.setRunCheckLevel(CURRENT_RUNCHECK_LEVEL); } } PowerManagementd::~PowerManagementd() { } void PowerManagementd::settingsChanged() { if (mSettings.isBatteryWatcherEnabled() && !mBatterywatcherd) mBatterywatcherd = new BatteryWatcher(this); else if (mBatterywatcherd && ! mSettings.isBatteryWatcherEnabled()) { mBatterywatcherd->deleteLater(); mBatterywatcherd = 0; } if (mSettings.isLidWatcherEnabled() && !mLidwatcherd) { mLidwatcherd = new LidWatcher(this); } else if (mLidwatcherd && ! mSettings.isLidWatcherEnabled()) { mLidwatcherd->deleteLater(); mLidwatcherd = 0; } if (mSettings.isIdlenessWatcherEnabled() && !mIdlenesswatcherd) { mIdlenesswatcherd = new IdlenessWatcher(this); } else if (mIdlenesswatcherd && !mSettings.isIdlenessWatcherEnabled()) { mIdlenesswatcherd->deleteLater(); mIdlenesswatcherd = 0; } } void PowerManagementd::runConfigure() { mNotification.close(); QProcess::startDetached("lxqt-config-powermanagement"); } void PowerManagementd::performRunCheck() { mSettings.setLidWatcherEnabled(Lid().haveLid()); mSettings.setBatteryWatcherEnabled(!Solid::Device::listFromType(Solid::DeviceInterface::Battery, QString()).isEmpty()); qDebug() << "performRunCheck, lidWatcherEnabled:" << mSettings.isLidWatcherEnabled() << ", batteryWatcherEnabled:" << mSettings.isBatteryWatcherEnabled(); mSettings.sync(); mNotification.setSummary(tr("Power Management")); mNotification.setBody(tr("You are running LXQt Power Management for the first time.\nYou can configure it from settings... ")); mNotification.setActions(QStringList() << tr("Configure...")); mNotification.setTimeout(10000); connect(&mNotification, SIGNAL(actionActivated(int)), SLOT(runConfigure())); mNotification.update(); } <commit_msg>Correctly check for batteries on first run<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXDE-Qt - a lightweight, Qt based, desktop toolset * * Authors: * Christian Surlykke <christian@surlykke.dk> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include <QDebug> #include <QStringList> #include "batteryhelper.h" #include "powermanagementd.h" #include "../config/powermanagementsettings.h" #include "idlenesswatcher.h" #include "lidwatcher.h" #include "batterywatcher.h" #define CURRENT_RUNCHECK_LEVEL 1 PowerManagementd::PowerManagementd() : mBatterywatcherd(0), mLidwatcherd(0), mIdlenesswatcherd(0), mSettings() { connect(&mSettings, SIGNAL(settingsChanged()), this, SLOT(settingsChanged())); settingsChanged(); if (mSettings.getRunCheckLevel() < CURRENT_RUNCHECK_LEVEL) { performRunCheck(); mSettings.setRunCheckLevel(CURRENT_RUNCHECK_LEVEL); } } PowerManagementd::~PowerManagementd() { } void PowerManagementd::settingsChanged() { if (mSettings.isBatteryWatcherEnabled() && !mBatterywatcherd) mBatterywatcherd = new BatteryWatcher(this); else if (mBatterywatcherd && ! mSettings.isBatteryWatcherEnabled()) { mBatterywatcherd->deleteLater(); mBatterywatcherd = 0; } if (mSettings.isLidWatcherEnabled() && !mLidwatcherd) { mLidwatcherd = new LidWatcher(this); } else if (mLidwatcherd && ! mSettings.isLidWatcherEnabled()) { mLidwatcherd->deleteLater(); mLidwatcherd = 0; } if (mSettings.isIdlenessWatcherEnabled() && !mIdlenesswatcherd) { mIdlenesswatcherd = new IdlenessWatcher(this); } else if (mIdlenesswatcherd && !mSettings.isIdlenessWatcherEnabled()) { mIdlenesswatcherd->deleteLater(); mIdlenesswatcherd = 0; } } void PowerManagementd::runConfigure() { mNotification.close(); QProcess::startDetached("lxqt-config-powermanagement"); } void PowerManagementd::performRunCheck() { mSettings.setLidWatcherEnabled(Lid().haveLid()); bool hasBattery = false; for (Solid::Device device : Solid::Device::listFromType(Solid::DeviceInterface::Battery, QString())) if (device.as<Solid::Battery>()->type() == Solid::Battery::PrimaryBattery) hasBattery = true; mSettings.setBatteryWatcherEnabled(hasBattery); mSettings.setIdlenessWatcherEnabled(true); mSettings.sync(); mNotification.setSummary(tr("Power Management")); mNotification.setBody(tr("You are running LXQt Power Management for the first time.\nYou can configure it from settings... ")); mNotification.setActions(QStringList() << tr("Configure...")); mNotification.setTimeout(10000); connect(&mNotification, SIGNAL(actionActivated(int)), SLOT(runConfigure())); mNotification.update(); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 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 "primitives/block.h" #include "hash.h" #include "tinyformat.h" #include "utilstrencodings.h" #include "crypto/common.h" #include "compat/endian.h" #include "crypto/egihash.h" extern std::unique_ptr<egihash::dag_t> const & dagActive; namespace { #pragma pack(push, 1) /** * The Keccak-256 hash of this structure is used as input for egihash * It is a truncated block header with a deterministic encoding * All integer values are little endian * Hashes are the nul-terminated hex encoded representation as if ToString() was called */ struct CBlockHeaderTruncatedLE { int32_t nVersion; char hashPrevBlock[65]; char hashMerkleRoot[65]; uint32_t nTime; uint32_t nBits; uint32_t nHeight; CBlockHeaderTruncatedLE(CBlockHeader const & h) : nVersion(htole32(h.nVersion)) , hashPrevBlock{0} , hashMerkleRoot{0} , nTime(htole32(h.nTime)) , nBits(htole32(h.nBits)) , nHeight(htole32(h.nHeight)) { auto prevHash = h.hashPrevBlock.ToString(); memcpy(hashPrevBlock, prevHash.c_str(), (std::min)(prevHash.size(), sizeof(hashPrevBlock))); auto merkleRoot = h.hashMerkleRoot.ToString(); memcpy(hashMerkleRoot, merkleRoot.c_str(), (std::min)(merkleRoot.size(), sizeof(hashMerkleRoot))); } }; #pragma pack(pop) } uint256 CBlockHeader::GetHash() const { CBlockHeaderTruncatedLE truncatedBlockHeader(*this); egihash::h256_t headerHash(&truncatedBlockHeader, sizeof(truncatedBlockHeader)); egihash::result_t ret; // if we have a DAG loaded, use it if (dagActive && ((nHeight / egihash::constants::EPOCH_LENGTH) == dagActive->epoch())) { ret = egihash::full::hash(*dagActive, headerHash, nNonce); } else // otherwise all we can do is generate a light hash { // TODO: pre-load caches and seed hashes ret = egihash::light::hash(egihash::cache_t(nHeight, egihash::get_seedhash(nHeight)), headerHash, nNonce); } hashMix = uint256(ret.mixhash); return uint256(ret.value); } std::string CBlock::ToString() const { std::stringstream s; s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nHeight=%u, hashMix=%s, nNonce=%u, vtx=%u)\n", GetHash().ToString(), nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nHeight, hashMix.ToString(), nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { s << " " << vtx[i].ToString() << "\n"; } return s.str(); } <commit_msg>include main.h in block.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 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 "primitives/block.h" #include "hash.h" #include "tinyformat.h" #include "utilstrencodings.h" #include "crypto/common.h" #include "compat/endian.h" #include "main.h" namespace { #pragma pack(push, 1) /** * The Keccak-256 hash of this structure is used as input for egihash * It is a truncated block header with a deterministic encoding * All integer values are little endian * Hashes are the nul-terminated hex encoded representation as if ToString() was called */ struct CBlockHeaderTruncatedLE { int32_t nVersion; char hashPrevBlock[65]; char hashMerkleRoot[65]; uint32_t nTime; uint32_t nBits; uint32_t nHeight; CBlockHeaderTruncatedLE(CBlockHeader const & h) : nVersion(htole32(h.nVersion)) , hashPrevBlock{0} , hashMerkleRoot{0} , nTime(htole32(h.nTime)) , nBits(htole32(h.nBits)) , nHeight(htole32(h.nHeight)) { auto prevHash = h.hashPrevBlock.ToString(); memcpy(hashPrevBlock, prevHash.c_str(), (std::min)(prevHash.size(), sizeof(hashPrevBlock))); auto merkleRoot = h.hashMerkleRoot.ToString(); memcpy(hashMerkleRoot, merkleRoot.c_str(), (std::min)(merkleRoot.size(), sizeof(hashMerkleRoot))); } }; #pragma pack(pop) } uint256 CBlockHeader::GetHash() const { CBlockHeaderTruncatedLE truncatedBlockHeader(*this); egihash::h256_t headerHash(&truncatedBlockHeader, sizeof(truncatedBlockHeader)); egihash::result_t ret; // if we have a DAG loaded, use it if (dagActive && ((nHeight / egihash::constants::EPOCH_LENGTH) == dagActive->epoch())) { ret = egihash::full::hash(*dagActive, headerHash, nNonce); } else // otherwise all we can do is generate a light hash { // TODO: pre-load caches and seed hashes ret = egihash::light::hash(egihash::cache_t(nHeight, egihash::get_seedhash(nHeight)), headerHash, nNonce); } hashMix = uint256(ret.mixhash); return uint256(ret.value); } std::string CBlock::ToString() const { std::stringstream s; s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nHeight=%u, hashMix=%s, nNonce=%u, vtx=%u)\n", GetHash().ToString(), nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nHeight, hashMix.ToString(), nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { s << " " << vtx[i].ToString() << "\n"; } return s.str(); } <|endoftext|>
<commit_before>/************************************************************************* * * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * * * Author: The ALICE Off-line Project. * * * Contributors are mentioned in the code where appropriate. * * * * * * Permission to use, copy, modify and distribute this software and its * * * documentation strictly for non-commercial purposes is hereby granted * * * without fee, provided that the above copyright notice appears in all * * * copies and that both the copyright notice and this permission notice * * * appear in the supporting documentation. The authors make no claims * * * about the suitability of this software for any purpose. It is * * * provided "as is" without express or implied warranty. * * **************************************************************************/ /* $Id: AliTRDSaxHandler.cxx 26327 2008-06-02 15:36:18Z cblume $ */ //////////////////////////////////////////////////////////////////////////// // // // The SAX XML file handler used in the preprocessor // // // // Author: // // Frederick Kramer (kramer@ikf.uni-frankfurt.de) // // // //////////////////////////////////////////////////////////////////////////// #include <cstdlib> #include <Riostream.h> #include <TList.h> #include <TXMLAttr.h> #include <TSAXParser.h> #include <TObjArray.h> #include "AliLog.h" #include "AliTRDSaxHandler.h" #include "AliTRDgeometry.h" #include "Cal/AliTRDCalDCS.h" #include "Cal/AliTRDCalDCSFEE.h" #include "Cal/AliTRDCalDCSPTR.h" #include "Cal/AliTRDCalDCSGTU.h" ClassImp(AliTRDSaxHandler) //_____________________________________________________________________________ AliTRDSaxHandler::AliTRDSaxHandler() :TObject() ,fHandlerStatus(0) ,fNDCSPTR(0) ,fNDCSGTU(0) ,fFEEArr(new TObjArray(540)) ,fPTRArr(new TObjArray(6)) ,fGTUArr(new TObjArray(19)) ,fSystem(0) ,fCurrentSM(0) ,fCurrentStack(0) ,fContent(0) ,fDCSFEEObj(0) ,fDCSPTRObj(0) ,fDCSGTUObj(0) ,fCalDCSObj(new AliTRDCalDCS()) { // // AliTRDSaxHandler default constructor // fFEEArr->SetOwner(); fPTRArr->SetOwner(); fGTUArr->SetOwner(); } //_____________________________________________________________________________ AliTRDSaxHandler::AliTRDSaxHandler(const AliTRDSaxHandler &sh) :TObject(sh) ,fHandlerStatus(0) ,fNDCSPTR(0) ,fNDCSGTU(0) ,fFEEArr(0) ,fPTRArr(0) ,fGTUArr(0) ,fSystem(0) ,fCurrentSM(0) ,fCurrentStack(0) ,fContent(0) ,fDCSFEEObj(0) ,fDCSPTRObj(0) ,fDCSGTUObj(0) ,fCalDCSObj(0) { // // AliTRDSaxHandler copy constructor // } //_____________________________________________________________________________ AliTRDSaxHandler &AliTRDSaxHandler::operator=(const AliTRDSaxHandler &sh) { // // Assignment operator // if (&sh == this) return *this; new (this) AliTRDSaxHandler(sh); return *this; } //_____________________________________________________________________________ AliTRDSaxHandler::~AliTRDSaxHandler() { // // AliTRDSaxHandler destructor // if (fFEEArr) { delete fFEEArr; fFEEArr = 0x0; } if (fPTRArr) { delete fPTRArr; fPTRArr = 0x0; } if (fGTUArr) { delete fGTUArr; fGTUArr = 0x0; } if (fCalDCSObj) { delete fCalDCSObj; fCalDCSObj = 0x0; } } //_____________________________________________________________________________ AliTRDCalDCS* AliTRDSaxHandler::GetCalDCSObj() { // put the arrays in the global calibration object and return this fCalDCSObj->SetNumberOfTimeBins(0); //test test test fCalDCSObj->SetFEEArr(fFEEArr); fCalDCSObj->SetPTRArr(fPTRArr); fCalDCSObj->SetGTUArr(fGTUArr); return fCalDCSObj; } //_____________________________________________________________________________ void AliTRDSaxHandler::OnStartDocument() { // if something should happen right at the beginning of the // XML document, this must happen here } //_____________________________________________________________________________ void AliTRDSaxHandler::OnEndDocument() { // if something should happen at the end of the XML document // this must be done here } //_____________________________________________________________________________ void AliTRDSaxHandler::OnStartElement(const char *name, const TList *attributes) { // when a new XML element is found, it is processed here fContent = ""; Int_t dcsId = 0; TString strName = name; TString dcsTitle = ""; // set the current system if necessary if (strName.Contains("FEE")) fSystem = kInsideFEE; if (strName.Contains("PTR")) fSystem = kInsidePTR; if (strName.Contains("GTU")) fSystem = kInsideGTU; // get the attributes of the element TXMLAttr *attr; TIter next(attributes); while ((attr = (TXMLAttr*) next())) { TString attribName = attr->GetName(); if (attribName.Contains("id") && strName.Contains("DCS")) { dcsTitle = name; dcsId = atoi(attr->GetValue()); } if (attribName.Contains("roc") && strName.Contains("ack")) { if (atoi(attr->GetValue()) != fDCSFEEObj->GetDCSid()) fDCSFEEObj->SetStatusBit(3); // consistence check } if (attribName.Contains("sm") && strName.Contains("DCS")) { fCurrentSM = atoi(attr->GetValue()); // only for GTU/PTR } if (attribName.Contains("id") && strName.Contains("STACK")) { fCurrentStack = atoi(attr->GetValue()); // only for GTU/PTR } } // if there is a new DCS element put it in the correct array if (strName.Contains("DCS")) { if (fSystem == kInsideFEE) { fDCSFEEObj = new AliTRDCalDCSFEE(name,dcsTitle); fDCSFEEObj->SetDCSid(dcsId); } if (fSystem == kInsidePTR) { fDCSPTRObj = new AliTRDCalDCSPTR(name,dcsTitle); fDCSPTRObj->SetDCSid(dcsId); } if (fSystem == kInsideGTU) { fDCSGTUObj = new AliTRDCalDCSGTU(name,dcsTitle); fDCSGTUObj->SetDCSid(dcsId); } } } //_____________________________________________________________________________ void AliTRDSaxHandler::OnEndElement(const char *name) { // do everything that needs to be done when an end tag of an element is found TString strName = name; // if done with this DCS board, put it in the correct array // no check for </ack> necessary since this check is done during XML validation if (strName.Contains("DCS")) { if (fSystem == kInsideFEE) { Int_t detID = 0; if (fDCSFEEObj->GetStatusBit() == 0) { // if there were no errors (StatusBit==0) the following should match detID = fDCSFEEObj->GetDCSid(); AliTRDgeometry aliGeo; Int_t calDetID = aliGeo.GetDetector(fDCSFEEObj->GetLayer(), fDCSFEEObj->GetStack(), fDCSFEEObj->GetSM()); if (detID != calDetID) fDCSFEEObj->SetStatusBit(4); } else { // if the dcs board didn't properly respond, don't compare detID = fDCSFEEObj->GetDCSid(); } fFEEArr->AddAt(fDCSFEEObj,detID); } if (fSystem == kInsidePTR) { fPTRArr->AddAt(fDCSPTRObj,fNDCSPTR); fNDCSPTR++; } if (fSystem == kInsideGTU) { fGTUArr->AddAt(fDCSGTUObj,fNDCSGTU); fNDCSGTU++; } fCurrentSM = 99; // 99 for no SM set fDCSFEEObj = 0; // just to be sure return; } // done with this stack? if (strName.Contains("STACK")) { fCurrentStack = 99; // 99 for no stack set } // store informations of the FEE DCS-Board if (fSystem == kInsideFEE) { if (strName.Contains("DNR")) fDCSFEEObj->SetStatusBit(fContent.Atoi()); if (strName.Contains("CFGNME")) fDCSFEEObj->SetConfigName(fContent); if (strName.Contains("CFGTAG")) fDCSFEEObj->SetConfigTag(fContent.Atoi()); if (strName.Contains("CFGVRSN")) fDCSFEEObj->SetConfigVersion(fContent); if (strName.Contains("NTB")) fDCSFEEObj->SetNumberOfTimeBins(fContent.Atoi()); if (strName.Contains("SM-ID")) fDCSFEEObj->SetSM(fContent.Atoi()); if (strName.Contains("STACK-ID")) fDCSFEEObj->SetStack(fContent.Atoi()); if (strName.Contains("LAYER-ID")) fDCSFEEObj->SetLayer(fContent.Atoi()); if (strName.Contains("SINGLEHITTHRES")) fDCSFEEObj->SetSingleHitThres(fContent.Atoi()); if (strName.Contains("THRPDCLSTHRS")) fDCSFEEObj->SetThreePadClustThres(fContent.Atoi()); if (strName.Contains("SELNOZS")) fDCSFEEObj->SetSelectiveNoZS(fContent.Atoi()); if (strName.Contains("FASTSTATNOISE")) fDCSFEEObj->SetFastStatNoise(fContent.Atoi()); if (strName.Contains("FILTWEIGHT")) fDCSFEEObj->SetTCFilterWeight(fContent.Atoi()); if (strName.Contains("FILTSHRTDCYPRM")) fDCSFEEObj->SetTCFilterShortDecPar(fContent.Atoi()); if (strName.Contains("FILTLNGDCYPRM")) fDCSFEEObj->SetTCFilterLongDecPar(fContent.Atoi()); if (strName.Contains("FLTR")) fDCSFEEObj->SetFilterType(fContent); if (strName.Contains("READOURPAR")) fDCSFEEObj->SetReadoutParam(fContent); if (strName.Contains("TESTPATTERN")) fDCSFEEObj->SetTestPattern(fContent); if (strName.Contains("TRCKLTMODE")) fDCSFEEObj->SetTrackletMode(fContent); if (strName.Contains("TRCKLTDEF")) fDCSFEEObj->SetTrackletDef(fContent); if (strName.Contains("TRGGRSTP")) fDCSFEEObj->SetTriggerSetup(fContent); if (strName.Contains("ADDOPTIONS")) fDCSFEEObj->SetAddOptions(fContent); } // store pretrigger informations if (fSystem == kInsidePTR) { // no informations available yet } // store GTU informations if (fSystem == kInsideGTU) { if (strName.Contains("SMMASK")) fHandlerStatus = fDCSGTUObj->SetSMMask(fContent); if (strName.Contains("LINKMASK")) fHandlerStatus = fDCSGTUObj->SetLinkMask(fCurrentSM, fCurrentStack, fContent); if (strName.Contains("STMASK")) fDCSGTUObj->SetStackMaskBit(fCurrentSM, fCurrentStack, fContent.Atoi()); } } //_____________________________________________________________________________ void AliTRDSaxHandler::OnCharacters(const char *characters) { // copy the the text content of an XML element fContent = characters; } //_____________________________________________________________________________ void AliTRDSaxHandler::OnComment(const char* /*text*/) { // comments within the XML file are ignored } //_____________________________________________________________________________ void AliTRDSaxHandler::OnWarning(const char *text) { // process warnings here AliInfo(Form("Warning: %s",text)); } //_____________________________________________________________________________ void AliTRDSaxHandler::OnError(const char *text) { // process errors here AliError(Form("Error: %s",text)); } //_____________________________________________________________________________ void AliTRDSaxHandler::OnFatalError(const char *text) { // process fatal errors here AliError(Form("Fatal error: %s",text)); // use AliFatal? } //_____________________________________________________________________________ void AliTRDSaxHandler::OnCdataBlock(const char* /*text*/, Int_t /*len*/) { // process character data blocks here // not implemented and should not be used here } <commit_msg>Slight change of tags<commit_after>/************************************************************************* * * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * * * Author: The ALICE Off-line Project. * * * Contributors are mentioned in the code where appropriate. * * * * * * Permission to use, copy, modify and distribute this software and its * * * documentation strictly for non-commercial purposes is hereby granted * * * without fee, provided that the above copyright notice appears in all * * * copies and that both the copyright notice and this permission notice * * * appear in the supporting documentation. The authors make no claims * * * about the suitability of this software for any purpose. It is * * * provided "as is" without express or implied warranty. * * **************************************************************************/ /* $Id: AliTRDSaxHandler.cxx 26327 2008-06-02 15:36:18Z cblume $ */ //////////////////////////////////////////////////////////////////////////// // // // The SAX XML file handler used in the preprocessor // // // // Author: // // Frederick Kramer (kramer@ikf.uni-frankfurt.de) // // // //////////////////////////////////////////////////////////////////////////// #include <cstdlib> #include <Riostream.h> #include <TList.h> #include <TXMLAttr.h> #include <TSAXParser.h> #include <TObjArray.h> #include "AliLog.h" #include "AliTRDSaxHandler.h" #include "AliTRDgeometry.h" #include "Cal/AliTRDCalDCS.h" #include "Cal/AliTRDCalDCSFEE.h" #include "Cal/AliTRDCalDCSPTR.h" #include "Cal/AliTRDCalDCSGTU.h" ClassImp(AliTRDSaxHandler) //_____________________________________________________________________________ AliTRDSaxHandler::AliTRDSaxHandler() :TObject() ,fHandlerStatus(0) ,fNDCSPTR(0) ,fNDCSGTU(0) ,fFEEArr(new TObjArray(540)) ,fPTRArr(new TObjArray(6)) ,fGTUArr(new TObjArray(19)) ,fSystem(0) ,fCurrentSM(0) ,fCurrentStack(0) ,fContent(0) ,fDCSFEEObj(0) ,fDCSPTRObj(0) ,fDCSGTUObj(0) ,fCalDCSObj(new AliTRDCalDCS()) { // // AliTRDSaxHandler default constructor // fFEEArr->SetOwner(); fPTRArr->SetOwner(); fGTUArr->SetOwner(); } //_____________________________________________________________________________ AliTRDSaxHandler::AliTRDSaxHandler(const AliTRDSaxHandler &sh) :TObject(sh) ,fHandlerStatus(0) ,fNDCSPTR(0) ,fNDCSGTU(0) ,fFEEArr(0) ,fPTRArr(0) ,fGTUArr(0) ,fSystem(0) ,fCurrentSM(0) ,fCurrentStack(0) ,fContent(0) ,fDCSFEEObj(0) ,fDCSPTRObj(0) ,fDCSGTUObj(0) ,fCalDCSObj(0) { // // AliTRDSaxHandler copy constructor // } //_____________________________________________________________________________ AliTRDSaxHandler &AliTRDSaxHandler::operator=(const AliTRDSaxHandler &sh) { // // Assignment operator // if (&sh == this) return *this; new (this) AliTRDSaxHandler(sh); return *this; } //_____________________________________________________________________________ AliTRDSaxHandler::~AliTRDSaxHandler() { // // AliTRDSaxHandler destructor // if (fFEEArr) { delete fFEEArr; fFEEArr = 0x0; } if (fPTRArr) { delete fPTRArr; fPTRArr = 0x0; } if (fGTUArr) { delete fGTUArr; fGTUArr = 0x0; } if (fCalDCSObj) { delete fCalDCSObj; fCalDCSObj = 0x0; } } //_____________________________________________________________________________ AliTRDCalDCS* AliTRDSaxHandler::GetCalDCSObj() { // put the arrays in the global calibration object and return this fCalDCSObj->SetNumberOfTimeBins(0); //test test test fCalDCSObj->SetFEEArr(fFEEArr); fCalDCSObj->SetPTRArr(fPTRArr); fCalDCSObj->SetGTUArr(fGTUArr); return fCalDCSObj; } //_____________________________________________________________________________ void AliTRDSaxHandler::OnStartDocument() { // if something should happen right at the beginning of the // XML document, this must happen here } //_____________________________________________________________________________ void AliTRDSaxHandler::OnEndDocument() { // if something should happen at the end of the XML document // this must be done here } //_____________________________________________________________________________ void AliTRDSaxHandler::OnStartElement(const char *name, const TList *attributes) { // when a new XML element is found, it is processed here fContent = ""; Int_t dcsId = 0; TString strName = name; TString dcsTitle = ""; // set the current system if necessary if (strName.Contains("FEE")) fSystem = kInsideFEE; if (strName.Contains("PTR")) fSystem = kInsidePTR; if (strName.Contains("GTU")) fSystem = kInsideGTU; // get the attributes of the element TXMLAttr *attr; TIter next(attributes); while ((attr = (TXMLAttr*) next())) { TString attribName = attr->GetName(); if (attribName.Contains("id") && strName.Contains("DCS")) { dcsTitle = name; dcsId = atoi(attr->GetValue()); } if (attribName.Contains("roc") && strName.Contains("ack")) { if (atoi(attr->GetValue()) != fDCSFEEObj->GetDCSid()) fDCSFEEObj->SetStatusBit(3); // consistence check } if (attribName.Contains("sm") && strName.Contains("DCS")) { fCurrentSM = atoi(attr->GetValue()); // only for GTU/PTR } if (attribName.Contains("id") && strName.Contains("STACK")) { fCurrentStack = atoi(attr->GetValue()); // only for GTU/PTR } } // if there is a new DCS element put it in the correct array if (strName.Contains("DCS")) { if (fSystem == kInsideFEE) { fDCSFEEObj = new AliTRDCalDCSFEE(name,dcsTitle); fDCSFEEObj->SetDCSid(dcsId); } if (fSystem == kInsidePTR) { fDCSPTRObj = new AliTRDCalDCSPTR(name,dcsTitle); fDCSPTRObj->SetDCSid(dcsId); } if (fSystem == kInsideGTU) { fDCSGTUObj = new AliTRDCalDCSGTU(name,dcsTitle); fDCSGTUObj->SetDCSid(dcsId); } } } //_____________________________________________________________________________ void AliTRDSaxHandler::OnEndElement(const char *name) { // do everything that needs to be done when an end tag of an element is found TString strName = name; // if done with this DCS board, put it in the correct array // no check for </ack> necessary since this check is done during XML validation if (strName.Contains("DCS")) { if (fSystem == kInsideFEE) { Int_t detID = 0; if (fDCSFEEObj->GetStatusBit() == 0) { // if there were no errors (StatusBit==0) the following should match detID = fDCSFEEObj->GetDCSid(); AliTRDgeometry aliGeo; Int_t calDetID = aliGeo.GetDetector(fDCSFEEObj->GetLayer(), fDCSFEEObj->GetStack(), fDCSFEEObj->GetSM()); if (detID != calDetID) fDCSFEEObj->SetStatusBit(4); } else { // if the dcs board didn't properly respond, don't compare detID = fDCSFEEObj->GetDCSid(); } fFEEArr->AddAt(fDCSFEEObj,detID); } if (fSystem == kInsidePTR) { fPTRArr->AddAt(fDCSPTRObj,fNDCSPTR); fNDCSPTR++; } if (fSystem == kInsideGTU) { fGTUArr->AddAt(fDCSGTUObj,fNDCSGTU); fNDCSGTU++; } fCurrentSM = 99; // 99 for no SM set fDCSFEEObj = 0; // just to be sure return; } // done with this stack? if (strName.Contains("STACK")) { fCurrentStack = 99; // 99 for no stack set } // store informations of the FEE DCS-Board if (fSystem == kInsideFEE) { if (strName.Contains("DNR")) fDCSFEEObj->SetStatusBit(fContent.Atoi()); if (strName.Contains("CFGNME")) fDCSFEEObj->SetConfigName(fContent); if (strName.Contains("CFGTAG")) fDCSFEEObj->SetConfigTag(fContent.Atoi()); if (strName.Contains("CFGVRSN")) fDCSFEEObj->SetConfigVersion(fContent); if (strName.Contains("NTB")) fDCSFEEObj->SetNumberOfTimeBins(fContent.Atoi()); if (strName.Contains("SM-ID")) fDCSFEEObj->SetSM(fContent.Atoi()); if (strName.Contains("STACK-ID")) fDCSFEEObj->SetStack(fContent.Atoi()); if (strName.Contains("LAYER-ID")) fDCSFEEObj->SetLayer(fContent.Atoi()); if (strName.Contains("SINGLEHITTHRES")) fDCSFEEObj->SetSingleHitThres(fContent.Atoi()); if (strName.Contains("THRPADCLSTHRS")) fDCSFEEObj->SetThreePadClustThres(fContent.Atoi()); if (strName.Contains("SELNOZS")) fDCSFEEObj->SetSelectiveNoZS(fContent.Atoi()); if (strName.Contains("FASTSTATNOISE")) fDCSFEEObj->SetFastStatNoise(fContent.Atoi()); if (strName.Contains("FILTWEIGHT")) fDCSFEEObj->SetTCFilterWeight(fContent.Atoi()); if (strName.Contains("FILTSHRTDCYPRM")) fDCSFEEObj->SetTCFilterShortDecPar(fContent.Atoi()); if (strName.Contains("FILTLNGDCYPRM")) fDCSFEEObj->SetTCFilterLongDecPar(fContent.Atoi()); if (strName.Contains("FLTR")) fDCSFEEObj->SetFilterType(fContent); if (strName.Contains("READOUTPAR")) fDCSFEEObj->SetReadoutParam(fContent); if (strName.Contains("TESTPATTERN")) fDCSFEEObj->SetTestPattern(fContent); if (strName.Contains("TRCKLTMODE")) fDCSFEEObj->SetTrackletMode(fContent); if (strName.Contains("TRCKLTDEF")) fDCSFEEObj->SetTrackletDef(fContent); if (strName.Contains("TRIGGERSETUP")) fDCSFEEObj->SetTriggerSetup(fContent); if (strName.Contains("ADDOPTIONS")) fDCSFEEObj->SetAddOptions(fContent); } // store pretrigger informations if (fSystem == kInsidePTR) { // no informations available yet } // store GTU informations if (fSystem == kInsideGTU) { if (strName.Contains("SMMASK")) fHandlerStatus = fDCSGTUObj->SetSMMask(fContent); if (strName.Contains("LINKMASK")) fHandlerStatus = fDCSGTUObj->SetLinkMask(fCurrentSM, fCurrentStack, fContent); if (strName.Contains("STMASK")) fDCSGTUObj->SetStackMaskBit(fCurrentSM, fCurrentStack, fContent.Atoi()); } } //_____________________________________________________________________________ void AliTRDSaxHandler::OnCharacters(const char *characters) { // copy the the text content of an XML element fContent = characters; } //_____________________________________________________________________________ void AliTRDSaxHandler::OnComment(const char* /*text*/) { // comments within the XML file are ignored } //_____________________________________________________________________________ void AliTRDSaxHandler::OnWarning(const char *text) { // process warnings here AliInfo(Form("Warning: %s",text)); } //_____________________________________________________________________________ void AliTRDSaxHandler::OnError(const char *text) { // process errors here AliError(Form("Error: %s",text)); } //_____________________________________________________________________________ void AliTRDSaxHandler::OnFatalError(const char *text) { // process fatal errors here AliError(Form("Fatal error: %s",text)); // use AliFatal? } //_____________________________________________________________________________ void AliTRDSaxHandler::OnCdataBlock(const char* /*text*/, Int_t /*len*/) { // process character data blocks here // not implemented and should not be used here } <|endoftext|>
<commit_before>#include "stdafx.h" #include "TeardownNotifierTest.h" #include "Autowired.h" class SimpleMember: public ContextMember { }; TEST_F(TeardownNotifierTest, VerifySingleNotification) { bool hit; { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<SimpleMember> member; member->AddTeardownListener([&hit] {hit = true;}); } EXPECT_TRUE(hit) << "Teardown listener was not hit as expected during context teardown"; } TEST_F(TeardownNotifierTest, ReferenceMemberInTeardown) { bool hit = false; { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired <SimpleMember> member; std::weak_ptr<SimpleMember> memberWeak; ctxt->AddTeardownListener([memberWeak, &hit] { try { if (!memberWeak.expired()) hit = true; } catch (autowiring_error) {} }); } EXPECT_TRUE(hit) << "Failed to reference a member of a context in it's teardown listener"; }<commit_msg>Fixed a bad teardownnotifier test<commit_after>#include "stdafx.h" #include "TeardownNotifierTest.h" #include "Autowired.h" class SimpleMember: public ContextMember { }; TEST_F(TeardownNotifierTest, VerifySingleNotification) { bool hit; { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<SimpleMember> member; member->AddTeardownListener([&hit] {hit = true;}); } EXPECT_TRUE(hit) << "Teardown listener was not hit as expected during context teardown"; } TEST_F(TeardownNotifierTest, ReferenceMemberInTeardown) { bool hit = false; { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired <SimpleMember> member; std::weak_ptr<SimpleMember> memberWeak(member); ctxt->AddTeardownListener([memberWeak, &hit] { try { if (!memberWeak.expired()) hit = true; } catch (autowiring_error) {} }); } EXPECT_TRUE(hit) << "Failed to reference a member of a context in it's teardown listener"; }<|endoftext|>
<commit_before>/* Message object used by text channel client-side proxy * * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2009 Nokia Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/Message> #include <TelepathyQt4/ReceivedMessage> #include <QDateTime> #include <QPointer> #include <QSet> #include <TelepathyQt4/TextChannel> #include "TelepathyQt4/debug-internal.h" namespace Tp { struct TELEPATHY_QT4_NO_EXPORT Message::Private : public QSharedData { Private(const MessagePartList &parts); ~Private(); MessagePartList parts; // if the Text interface says "non-text" we still only have the text, // because the interface can't tell us anything else... bool forceNonText; // for received messages only WeakPtr<TextChannel> textChannel; ContactPtr sender; inline QVariant value(uint index, const char *key) const; inline uint getUIntOrZero(uint index, const char *key) const; inline QString getStringOrEmpty(uint index, const char *key) const; inline bool getBoolean(uint index, const char *key, bool assumeIfAbsent) const; inline uint senderHandle() const; inline uint pendingId() const; void clearSenderHandle(); }; Message::Private::Private(const MessagePartList &parts) : parts(parts), forceNonText(false), sender(0) { } Message::Private::~Private() { } inline QVariant Message::Private::value(uint index, const char *key) const { return parts.at(index).value(QLatin1String(key)).variant(); } inline QString Message::Private::getStringOrEmpty(uint index, const char *key) const { QString s = value(index, key).toString(); if (s.isNull()) { s = QLatin1String(""); } return s; } inline uint Message::Private::getUIntOrZero(uint index, const char *key) const { return value(index, key).toUInt(); } inline bool Message::Private::getBoolean(uint index, const char *key, bool assumeIfAbsent) const { QVariant v = value(index, key); if (v.isValid() && v.type() == QVariant::Bool) { return v.toBool(); } return assumeIfAbsent; } inline uint Message::Private::senderHandle() const { return getUIntOrZero(0, "message-sender"); } inline uint Message::Private::pendingId() const { return getUIntOrZero(0, "pending-message-id"); } void Message::Private::clearSenderHandle() { parts[0].remove(QLatin1String("message-sender")); } /** * \class Message * \ingroup clientchannel * \headerfile <TelepathyQt4/text-channel.h> <TelepathyQt4/TextChannel> * * Object representing a message. These objects are implicitly shared, like * QString. */ /** * Default constructor, only used internally. */ Message::Message() { } /** * Constructor. * * \param parts The parts of a message as defined by the Telepathy D-Bus * specification. This list must have length at least 1. */ Message::Message(const MessagePartList &parts) : mPriv(new Private(parts)) { Q_ASSERT(parts.size() > 0); } /** * Constructor, from the parameters of the old Sent signal. * * \param timestamp The time the message was sent * \param type The message type * \param text The text of the message */ Message::Message(uint timestamp, uint type, const QString &text) : mPriv(new Private(MessagePartList() << MessagePart() << MessagePart())) { mPriv->parts[0].insert(QLatin1String("message-sent"), QDBusVariant(static_cast<qlonglong>(timestamp))); mPriv->parts[0].insert(QLatin1String("message-type"), QDBusVariant(type)); mPriv->parts[1].insert(QLatin1String("content-type"), QDBusVariant(QLatin1String("text/plain"))); mPriv->parts[1].insert(QLatin1String("content"), QDBusVariant(text)); } /** * Constructor, from the parameters of the old Send method. * * \param type The message type * \param text The text of the message */ Message::Message(ChannelTextMessageType type, const QString &text) : mPriv(new Private(MessagePartList() << MessagePart() << MessagePart())) { mPriv->parts[0].insert(QLatin1String("message-type"), QDBusVariant(static_cast<uint>(type))); mPriv->parts[1].insert(QLatin1String("content-type"), QDBusVariant(QLatin1String("text/plain"))); mPriv->parts[1].insert(QLatin1String("content"), QDBusVariant(text)); } /** * Copy constructor. */ Message::Message(const Message &other) : mPriv(other.mPriv) { } /** * Assignment operator. */ Message &Message::operator=(const Message &other) { if (this != &other) { mPriv = other.mPriv; } return *this; } /** * Equality operator. */ bool Message::operator==(const Message &other) const { return this->mPriv == other.mPriv; } /** * Destructor. */ Message::~Message() { } /** * Return the time the message was sent, or QDateTime() if that time is * unknown. * * \return A timestamp */ QDateTime Message::sent() const { // FIXME See http://bugs.freedesktop.org/show_bug.cgi?id=21690 uint stamp = mPriv->value(0, "message-sent").toUInt(); if (stamp != 0) { return QDateTime::fromTime_t(stamp); } else { return QDateTime(); } } /** * Return the type of message this is, or ChannelTextMessageTypeNormal * if the type is not recognised. * * \return The ChannelTextMessageType for this message */ ChannelTextMessageType Message::messageType() const { uint raw = mPriv->value(0, "message-type").toUInt(); if (raw < static_cast<uint>(NUM_CHANNEL_TEXT_MESSAGE_TYPES)) { return ChannelTextMessageType(raw); } else { return ChannelTextMessageTypeNormal; } } /** * Return whether this message was truncated during delivery. */ bool Message::isTruncated() const { for (int i = 1; i < size(); i++) { if (mPriv->getBoolean(i, "truncated", false)) { return true; } } return false; } /** * Return whether this message contains parts not representable as plain * text. * * \return true if this message cannot completely be represented as plain text */ bool Message::hasNonTextContent() const { if (mPriv->forceNonText || size() <= 1 || isSpecificToDBusInterface()) { return true; } QSet<QString> texts; QSet<QString> textNeeded; for (int i = 1; i < size(); i++) { QString altGroup = mPriv->getStringOrEmpty(i, "alternative"); QString contentType = mPriv->getStringOrEmpty(i, "content-type"); if (contentType == QLatin1String("text/plain")) { if (!altGroup.isEmpty()) { // we can use this as an alternative for a non-text part // with the same altGroup texts << altGroup; } } else { QString alt = mPriv->getStringOrEmpty(i, "alternative"); if (altGroup.isEmpty()) { // we can't possibly rescue this part by using a text/plain // alternative, because it's not in any alternative group return true; } else { // maybe we'll find a text/plain alternative for this textNeeded << altGroup; } } } textNeeded -= texts; return !textNeeded.isEmpty(); } /** * Return the unique token identifying this message (e.g. the id attribute * for XMPP messages), or an empty string if there is no suitable token. * * \return A non-empty message identifier, or an empty string if none */ QString Message::messageToken() const { return mPriv->getStringOrEmpty(0, "message-token"); } /** * Return whether this message is specific to a D-Bus interface. This is * false in almost all cases. * * If this function returns true, the message is specific to the interface * indicated by dbusInterface. Clients that don't understand that interface * should not display the message. However, if the client would acknowledge * an ordinary message, it must also acknowledge this interface-specific * message. * * \return true if dbusInterface would return a non-empty string */ bool Message::isSpecificToDBusInterface() const { return !dbusInterface().isEmpty(); } /** * Return the D-Bus interface to which this message is specific, or an * empty string for normal messages. */ QString Message::dbusInterface() const { return mPriv->getStringOrEmpty(0, "interface"); } QString Message::text() const { // Alternative-groups for which we've already emitted an alternative QSet<QString> altGroupsUsed; QString text; for (int i = 1; i < size(); i++) { QString altGroup = mPriv->getStringOrEmpty(i, "alternative"); QString contentType = mPriv->getStringOrEmpty(i, "content-type"); if (contentType == QLatin1String("text/plain")) { if (!altGroup.isEmpty()) { if (altGroupsUsed.contains(altGroup)) { continue; } else { altGroupsUsed << altGroup; } } QVariant content = mPriv->value(i, "content"); if (content.type() == QVariant::String) { text += content.toString(); } else { // O RLY? debug() << "allegedly text/plain part wasn't"; } } } return text; } /** * Return the message's header part, as defined by the Telepathy D-Bus API * specification. This is provided for advanced clients that need to access * additional information not available through the normal Message API. * * \return The same thing as messagepart(0) */ MessagePart Message::header() const { return part(0); } /** * Return the number of parts in this message. * * \return 1 greater than the largest valid argument to part */ int Message::size() const { return mPriv->parts.size(); } /** * Return the message's header part, as defined by the Telepathy D-Bus API * specification. This is provided for advanced clients that need to access * additional information not available through the normal Message API. * * \param index The part to access, which must be strictly less than size(); * part number 0 is the header, parts numbered 1 or greater * are the body of the message. * \return Part of the message */ MessagePart Message::part(uint index) const { return mPriv->parts.at(index); } MessagePartList Message::parts() const { return mPriv->parts; } /** * \class ReceivedMessage * \ingroup clientchannel * \headerfile <TelepathyQt4/text-channel.h> <TelepathyQt4/TextChannel> * * Subclass of Message, with additional information that's generally only * available on received messages. */ /** * Default constructor, only used internally. */ ReceivedMessage::ReceivedMessage() { } /** * Constructor. * * \param parts The parts of a message as defined by the Telepathy D-Bus * specification. This list must have length at least 1. */ ReceivedMessage::ReceivedMessage(const MessagePartList &parts, const TextChannelPtr &channel) : Message(parts) { if (!mPriv->parts[0].contains(QLatin1String("message-received"))) { mPriv->parts[0].insert(QLatin1String("message-received"), QDBusVariant(static_cast<qlonglong>( QDateTime::currentDateTime().toTime_t()))); } mPriv->textChannel = channel; } /** * Copy constructor. */ ReceivedMessage::ReceivedMessage(const ReceivedMessage &other) : Message(other) { } /** * Assignment operator. */ ReceivedMessage &ReceivedMessage::operator=(const ReceivedMessage &other) { if (this != &other) { mPriv = other.mPriv; } return *this; } /** * Destructor. */ ReceivedMessage::~ReceivedMessage() { } /** * Return the time the message was received. * * \return A timestamp */ QDateTime ReceivedMessage::received() const { // FIXME See http://bugs.freedesktop.org/show_bug.cgi?id=21690 uint stamp = mPriv->value(0, "message-received").toUInt(); if (stamp != 0) { return QDateTime::fromTime_t(stamp); } else { return QDateTime(); } } /** * Return the Contact who sent the message, or * ContactPtr(0) if unknown. * * \return The sender or ContactPtr(0) */ ContactPtr ReceivedMessage::sender() const { return mPriv->sender; } /** * Return whether the incoming message was part of a replay of message * history. * * If true, loggers can use this to improve their heuristics for elimination * of duplicate messages (a simple, correct implementation would be to avoid * logging any message that has this flag). * * \return whether the scrollback flag is set */ bool ReceivedMessage::isScrollback() const { return mPriv->getBoolean(0, "scrollback", false); } /** * Return whether the incoming message was seen in a previous channel during * the lifetime of this Connection, but was not acknowledged before that * chanenl closed, causing the channel in which it now appears to open. * * If true, loggers should not log this message again. * * \return whether the rescued flag is set */ bool ReceivedMessage::isRescued() const { return mPriv->getBoolean(0, "rescued", false); } bool ReceivedMessage::isFromChannel(const TextChannelPtr &channel) const { return TextChannelPtr(mPriv->textChannel) == channel; } uint ReceivedMessage::pendingId() const { return mPriv->pendingId(); } uint ReceivedMessage::senderHandle() const { return mPriv->senderHandle(); } void ReceivedMessage::setForceNonText() { mPriv->forceNonText = true; } void ReceivedMessage::clearSenderHandle() { mPriv->clearSenderHandle(); } void ReceivedMessage::setSender(const ContactPtr &sender) { mPriv->sender = sender; } } // Tp <commit_msg>message: Improve documentation (bugfixes+additions)<commit_after>/* Message object used by text channel client-side proxy * * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2009 Nokia Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/Message> #include <TelepathyQt4/ReceivedMessage> #include <QDateTime> #include <QPointer> #include <QSet> #include <TelepathyQt4/TextChannel> #include "TelepathyQt4/debug-internal.h" namespace Tp { struct TELEPATHY_QT4_NO_EXPORT Message::Private : public QSharedData { Private(const MessagePartList &parts); ~Private(); MessagePartList parts; // if the Text interface says "non-text" we still only have the text, // because the interface can't tell us anything else... bool forceNonText; // for received messages only WeakPtr<TextChannel> textChannel; ContactPtr sender; inline QVariant value(uint index, const char *key) const; inline uint getUIntOrZero(uint index, const char *key) const; inline QString getStringOrEmpty(uint index, const char *key) const; inline bool getBoolean(uint index, const char *key, bool assumeIfAbsent) const; inline uint senderHandle() const; inline uint pendingId() const; void clearSenderHandle(); }; Message::Private::Private(const MessagePartList &parts) : parts(parts), forceNonText(false), sender(0) { } Message::Private::~Private() { } inline QVariant Message::Private::value(uint index, const char *key) const { return parts.at(index).value(QLatin1String(key)).variant(); } inline QString Message::Private::getStringOrEmpty(uint index, const char *key) const { QString s = value(index, key).toString(); if (s.isNull()) { s = QLatin1String(""); } return s; } inline uint Message::Private::getUIntOrZero(uint index, const char *key) const { return value(index, key).toUInt(); } inline bool Message::Private::getBoolean(uint index, const char *key, bool assumeIfAbsent) const { QVariant v = value(index, key); if (v.isValid() && v.type() == QVariant::Bool) { return v.toBool(); } return assumeIfAbsent; } inline uint Message::Private::senderHandle() const { return getUIntOrZero(0, "message-sender"); } inline uint Message::Private::pendingId() const { return getUIntOrZero(0, "pending-message-id"); } void Message::Private::clearSenderHandle() { parts[0].remove(QLatin1String("message-sender")); } /** * \class Message * \ingroup clientchannel * \headerfile TelepathyQt4/text-channel.h <TelepathyQt4/TextChannel> * * \brief The Message class represents a Telepathy message in a text channel. * These objects are implicitly shared, like QString. */ /** * Default constructor, only used internally. */ Message::Message() { } /** * Constructor. * * \param parts The parts of a message as defined by the Telepathy D-Bus * specification. This list must have length at least 1. */ Message::Message(const MessagePartList &parts) : mPriv(new Private(parts)) { Q_ASSERT(parts.size() > 0); } /** * Constructor, from the parameters of the old Sent signal. * * \param timestamp The time the message was sent * \param type The message type * \param text The text of the message */ Message::Message(uint timestamp, uint type, const QString &text) : mPriv(new Private(MessagePartList() << MessagePart() << MessagePart())) { mPriv->parts[0].insert(QLatin1String("message-sent"), QDBusVariant(static_cast<qlonglong>(timestamp))); mPriv->parts[0].insert(QLatin1String("message-type"), QDBusVariant(type)); mPriv->parts[1].insert(QLatin1String("content-type"), QDBusVariant(QLatin1String("text/plain"))); mPriv->parts[1].insert(QLatin1String("content"), QDBusVariant(text)); } /** * Constructor, from the parameters of the old Send method. * * \param type The message type * \param text The text of the message */ Message::Message(ChannelTextMessageType type, const QString &text) : mPriv(new Private(MessagePartList() << MessagePart() << MessagePart())) { mPriv->parts[0].insert(QLatin1String("message-type"), QDBusVariant(static_cast<uint>(type))); mPriv->parts[1].insert(QLatin1String("content-type"), QDBusVariant(QLatin1String("text/plain"))); mPriv->parts[1].insert(QLatin1String("content"), QDBusVariant(text)); } /** * Copy constructor. */ Message::Message(const Message &other) : mPriv(other.mPriv) { } /** * Assignment operator. */ Message &Message::operator=(const Message &other) { if (this != &other) { mPriv = other.mPriv; } return *this; } /** * Equality operator. */ bool Message::operator==(const Message &other) const { return this->mPriv == other.mPriv; } /** * Class destructor. */ Message::~Message() { } /** * Return the time the message was sent, or QDateTime() if that time is * unknown. * * \return A timestamp */ QDateTime Message::sent() const { // FIXME See http://bugs.freedesktop.org/show_bug.cgi?id=21690 uint stamp = mPriv->value(0, "message-sent").toUInt(); if (stamp != 0) { return QDateTime::fromTime_t(stamp); } else { return QDateTime(); } } /** * Return the type of message this is, or ChannelTextMessageTypeNormal * if the type is not recognised. * * \return The ChannelTextMessageType for this message */ ChannelTextMessageType Message::messageType() const { uint raw = mPriv->value(0, "message-type").toUInt(); if (raw < static_cast<uint>(NUM_CHANNEL_TEXT_MESSAGE_TYPES)) { return ChannelTextMessageType(raw); } else { return ChannelTextMessageTypeNormal; } } /** * Return whether this message was truncated during delivery. */ bool Message::isTruncated() const { for (int i = 1; i < size(); i++) { if (mPriv->getBoolean(i, "truncated", false)) { return true; } } return false; } /** * Return whether this message contains parts not representable as plain * text. * * \return true if this message cannot completely be represented as plain text */ bool Message::hasNonTextContent() const { if (mPriv->forceNonText || size() <= 1 || isSpecificToDBusInterface()) { return true; } QSet<QString> texts; QSet<QString> textNeeded; for (int i = 1; i < size(); i++) { QString altGroup = mPriv->getStringOrEmpty(i, "alternative"); QString contentType = mPriv->getStringOrEmpty(i, "content-type"); if (contentType == QLatin1String("text/plain")) { if (!altGroup.isEmpty()) { // we can use this as an alternative for a non-text part // with the same altGroup texts << altGroup; } } else { QString alt = mPriv->getStringOrEmpty(i, "alternative"); if (altGroup.isEmpty()) { // we can't possibly rescue this part by using a text/plain // alternative, because it's not in any alternative group return true; } else { // maybe we'll find a text/plain alternative for this textNeeded << altGroup; } } } textNeeded -= texts; return !textNeeded.isEmpty(); } /** * Return the unique token identifying this message (e.g. the id attribute * for XMPP messages), or an empty string if there is no suitable token. * * \return A non-empty message identifier, or an empty string if none */ QString Message::messageToken() const { return mPriv->getStringOrEmpty(0, "message-token"); } /** * Return whether this message is specific to a D-Bus interface. This is * false in almost all cases. * * If this function returns true, the message is specific to the interface * indicated by dbusInterface. Clients that don't understand that interface * should not display the message. However, if the client would acknowledge * an ordinary message, it must also acknowledge this interface-specific * message. * * \return true if dbusInterface would return a non-empty string */ bool Message::isSpecificToDBusInterface() const { return !dbusInterface().isEmpty(); } /** * Return the D-Bus interface to which this message is specific, or an * empty string for normal messages. */ QString Message::dbusInterface() const { return mPriv->getStringOrEmpty(0, "interface"); } QString Message::text() const { // Alternative-groups for which we've already emitted an alternative QSet<QString> altGroupsUsed; QString text; for (int i = 1; i < size(); i++) { QString altGroup = mPriv->getStringOrEmpty(i, "alternative"); QString contentType = mPriv->getStringOrEmpty(i, "content-type"); if (contentType == QLatin1String("text/plain")) { if (!altGroup.isEmpty()) { if (altGroupsUsed.contains(altGroup)) { continue; } else { altGroupsUsed << altGroup; } } QVariant content = mPriv->value(i, "content"); if (content.type() == QVariant::String) { text += content.toString(); } else { // O RLY? debug() << "allegedly text/plain part wasn't"; } } } return text; } /** * Return the message's header part, as defined by the Telepathy D-Bus API * specification. This is provided for advanced clients that need to access * additional information not available through the normal Message API. * * \return The same thing as messagepart(0) */ MessagePart Message::header() const { return part(0); } /** * Return the number of parts in this message. * * \return 1 greater than the largest valid argument to part */ int Message::size() const { return mPriv->parts.size(); } /** * Return the message's header part, as defined by the Telepathy D-Bus API * specification. This is provided for advanced clients that need to access * additional information not available through the normal Message API. * * \param index The part to access, which must be strictly less than size(); * part number 0 is the header, parts numbered 1 or greater * are the body of the message. * \return Part of the message */ MessagePart Message::part(uint index) const { return mPriv->parts.at(index); } MessagePartList Message::parts() const { return mPriv->parts; } /** * \class ReceivedMessage * \ingroup clientchannel * \headerfile TelepathyQt4/text-channel.h <TelepathyQt4/TextChannel> * * \brief The ReceivedMessage class is a subclass of Message, representing a * received message. * * It contains additional information that's generally only * available on received messages. */ /** * Default constructor, only used internally. */ ReceivedMessage::ReceivedMessage() { } /** * Constructor. * * \param parts The parts of a message as defined by the Telepathy D-Bus * specification. This list must have length at least 1. */ ReceivedMessage::ReceivedMessage(const MessagePartList &parts, const TextChannelPtr &channel) : Message(parts) { if (!mPriv->parts[0].contains(QLatin1String("message-received"))) { mPriv->parts[0].insert(QLatin1String("message-received"), QDBusVariant(static_cast<qlonglong>( QDateTime::currentDateTime().toTime_t()))); } mPriv->textChannel = channel; } /** * Copy constructor. */ ReceivedMessage::ReceivedMessage(const ReceivedMessage &other) : Message(other) { } /** * Assignment operator. */ ReceivedMessage &ReceivedMessage::operator=(const ReceivedMessage &other) { if (this != &other) { mPriv = other.mPriv; } return *this; } /** * Destructor. */ ReceivedMessage::~ReceivedMessage() { } /** * Return the time the message was received. * * \return A timestamp */ QDateTime ReceivedMessage::received() const { // FIXME See http://bugs.freedesktop.org/show_bug.cgi?id=21690 uint stamp = mPriv->value(0, "message-received").toUInt(); if (stamp != 0) { return QDateTime::fromTime_t(stamp); } else { return QDateTime(); } } /** * Return the Contact who sent the message, or * ContactPtr(0) if unknown. * * \return The sender or ContactPtr(0) */ ContactPtr ReceivedMessage::sender() const { return mPriv->sender; } /** * Return whether the incoming message was part of a replay of message * history. * * If true, loggers can use this to improve their heuristics for elimination * of duplicate messages (a simple, correct implementation would be to avoid * logging any message that has this flag). * * \return whether the scrollback flag is set */ bool ReceivedMessage::isScrollback() const { return mPriv->getBoolean(0, "scrollback", false); } /** * Return whether the incoming message was seen in a previous channel during * the lifetime of this Connection, but was not acknowledged before that * chanenl closed, causing the channel in which it now appears to open. * * If true, loggers should not log this message again. * * \return whether the rescued flag is set */ bool ReceivedMessage::isRescued() const { return mPriv->getBoolean(0, "rescued", false); } bool ReceivedMessage::isFromChannel(const TextChannelPtr &channel) const { return TextChannelPtr(mPriv->textChannel) == channel; } uint ReceivedMessage::pendingId() const { return mPriv->pendingId(); } uint ReceivedMessage::senderHandle() const { return mPriv->senderHandle(); } void ReceivedMessage::setForceNonText() { mPriv->forceNonText = true; } void ReceivedMessage::clearSenderHandle() { mPriv->clearSenderHandle(); } void ReceivedMessage::setSender(const ContactPtr &sender) { mPriv->sender = sender; } } // Tp <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QLabel> #include <QPushButton> #include <QComboBox> #include <QCloseEvent> #include <QTimer> #include <QSignalMapper> #include <QGridLayout> #include <SDL_haptic.h> const int kHapticLength = 500; const int kSafeTimeout = 50; static const char __CLASS__[] = "MainWindow"; MainWindow::MainWindow(QWidget *parent) : QMainWindow{parent} , ui{new Ui::MainWindow} , eventThread{new SdlEventThread{this}} , joystick{0} , haptic{0} , hapticId{-1} , numAxis{0} , numButtons{0} , numHats{0} { ui->setupUi(this); fillJoystickList(); connect(eventThread, SIGNAL(axisEvent(SDL_JoyAxisEvent)), this, SLOT(axisMoved(SDL_JoyAxisEvent))); connect(eventThread, SIGNAL(joyButtonEvent(SDL_JoyButtonEvent)), this, SLOT(joystickButtonPressed(SDL_JoyButtonEvent))); connect(eventThread, SIGNAL(joyDeviceRemoved(SDL_JoyDeviceEvent)), this, SLOT(joyDeviceRemoved(SDL_JoyDeviceEvent))); connect(ui->choosePadBox, QOverload<int>::of(&QComboBox::activated), this, [this](int index){ setJoystick(index - 1); }); eventThread->start(); } MainWindow::~MainWindow() { closeJoystick(); delete ui; } void MainWindow::closeHaptic() { stopHaptic(); if (!haptic) return; SDL_HapticClose(haptic); haptic = 0; } void MainWindow::closeJoystick() { closeHaptic(); if (!joystick) return; qDebug("%s: close joystick %d %s", __CLASS__, SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick)); while (auto child = ui->buttonsLayout->takeAt(0)) { delete child; } joystick = 0; numAxis = 0; numButtons = 0; numHats = 0; } void MainWindow::closeEvent(QCloseEvent *event) { eventThread->stop(); eventThread->terminate(); event->accept(); } void MainWindow::setButtons(int num) { for (int i = 0; i<num; i++) { QPushButton *b = new QPushButton(this); b->setText(QString::number(i+1)); b->setCheckable(true); ui->buttonsLayout->addWidget(b, i / 6, i % 6); } } void MainWindow::setAxis(SdlAxisWidget *widget, int xaxis, int yaxis) { if (std::max(xaxis, yaxis) < numAxis) { widget->init(joystick, xaxis, yaxis); connect(eventThread, SIGNAL(axisEvent(SDL_JoyAxisEvent)), widget, SLOT(axisMoved(SDL_JoyAxisEvent))); } else { widget->reset(); disconnect(eventThread, SIGNAL(axisEvent(SDL_JoyAxisEvent)), widget, SLOT(axisMoved(SDL_JoyAxisEvent))); } } void MainWindow::setPov(SdlPovWidget *widget, int hat) { if (hat < numHats) { widget->init(joystick, hat); connect(eventThread, SIGNAL(hatEvent(SDL_JoyHatEvent)), widget, SLOT(povPressed(SDL_JoyHatEvent))); } else { widget->reset(); disconnect(eventThread, SIGNAL(hatEvent(SDL_JoyHatEvent)), widget, SLOT(povPressed(SDL_JoyHatEvent))); } } void MainWindow::setSlider(SdlSliderWidget *widget, int axis) { if (axis < numAxis) { widget->init(joystick, axis); connect(eventThread, SIGNAL(axisEvent(SDL_JoyAxisEvent)), widget, SLOT(axisMoved(SDL_JoyAxisEvent))); } else { widget->reset(); disconnect(eventThread, SIGNAL(axisEvent(SDL_JoyAxisEvent)), widget, SLOT(axisMoved(SDL_JoyAxisEvent))); } } void MainWindow::fillJoystickList() { while (ui->choosePadBox->count() > 1) ui->choosePadBox->removeItem(1); for (int i = 0; i < SDL_NumJoysticks(); ++i) ui->choosePadBox->addItem(SDL_JoystickNameForIndex(i)); } void MainWindow::setJoystick(int index) { closeJoystick(); joystick = SDL_JoystickOpen(index); if (!joystick) return; ui->choosePadBox->setCurrentIndex(index + 1); qDebug("%s: setup joystick %d %s", __CLASS__, SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick)); numAxis = SDL_JoystickNumAxes(joystick); numButtons = SDL_JoystickNumButtons(joystick); numHats = SDL_JoystickNumHats(joystick); setPov (ui->pov, 0); setAxis (ui->xyaxis, 0, 1); setAxis (ui->zaxis, 2, 3); setSlider(ui->axis4, 4); setSlider(ui->axis5, 5); setButtons(numButtons); int axisOffset = numButtons; while (axisOffset % 6) ++axisOffset; for (int i = 0; i<numAxis; i++) { QLabel *l = new QLabel(this); l->setText(QString("[%1]").arg(i)); ui->buttonsLayout->addWidget(l, (axisOffset + i) / 6, (axisOffset + i) % 6); } setHaptic(SDL_HapticOpenFromJoystick(joystick)); } void MainWindow::axisMoved(SDL_JoyAxisEvent event) { if (event.axis >= numAxis) return; QLabel *l = qobject_cast<QLabel*>( ui->buttonsLayout->itemAt(numButtons + event.axis)->widget()); if (!l) return; l->setText(QString("[%1]: %2").arg(event.axis).arg(event.value)); } void MainWindow::setHaptic(struct _SDL_Haptic *haptic) { this->haptic = haptic; } void MainWindow::stopHaptic() { if (!haptic) { SDL_JoystickRumble(joystick, 0, 0, 0); return; } SDL_HapticStopEffect(haptic, hapticId); SDL_HapticDestroyEffect(haptic, hapticId); hapticId = -1; } void MainWindow::joystickButtonPressed(SDL_JoyButtonEvent event) { //qDebug("%s: button %d type %x", __FUNCTION__, event.button, event.type); if (event.button >= numButtons) return; QLayoutItem *item = ui->buttonsLayout->itemAt(event.button); if (!item) { qDebug("%s: no item at %d", __FUNCTION__, event.button); return; } QPushButton *b = qobject_cast<QPushButton*>(item->widget()); if (!b) { qDebug("%s: cast failed at %d", __FUNCTION__, event.button); return; } b->setChecked(event.type == SDL_JOYBUTTONDOWN); if (!ui->testHaptic->isChecked()) return; if (b->isChecked() || hapticId >= 0) return; SDL_HapticEffect lr = {0}; lr.type = SDL_HAPTIC_LEFTRIGHT; lr.leftright.length = kHapticLength; lr.leftright.large_magnitude = (event.button & 1) ? 0x7FFF : 0; lr.leftright.small_magnitude = (event.button & 1) ? 0 : 0x7FFF; if (!haptic) { if (SDL_JoystickRumble(joystick, lr.leftright.large_magnitude, lr.leftright.small_magnitude, lr.leftright.length) < 0) qWarning("Failed to start rumble: %s\n", SDL_GetError()); return; } hapticId = SDL_HapticNewEffect(haptic, &lr); if (hapticId < 0) { qWarning("Failed to create effect: %s\n", SDL_GetError()); return; } //qDebug("[%04x; %04x] : id", lr.leftright.large_magnitude, lr.leftright.small_magnitude, hapticId); SDL_HapticRunEffect(haptic, hapticId, 1); QTimer::singleShot(kHapticLength + kSafeTimeout, this, SLOT(stopHaptic())); } void MainWindow::joyDeviceAdded(SDL_JoyDeviceEvent event) { if (!joystick) setJoystick(event.which); } void MainWindow::joyDeviceRemoved(SDL_JoyDeviceEvent event) { if (event.which == SDL_JoystickInstanceID(joystick)) closeJoystick(); if (SDL_NumJoysticks() > 0) setJoystick(0); } <commit_msg>Use new connect syntax<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QLabel> #include <QPushButton> #include <QComboBox> #include <QCloseEvent> #include <QTimer> #include <QSignalMapper> #include <QGridLayout> #include <SDL_haptic.h> const int kHapticLength = 500; const int kSafeTimeout = 50; static const char __CLASS__[] = "MainWindow"; MainWindow::MainWindow(QWidget *parent) : QMainWindow{parent} , ui{new Ui::MainWindow} , eventThread{new SdlEventThread{this}} , joystick{0} , haptic{0} , hapticId{-1} , numAxis{0} , numButtons{0} , numHats{0} { ui->setupUi(this); fillJoystickList(); connect(eventThread, &SdlEventThread::axisEvent, this, &MainWindow::axisMoved); connect(eventThread, &SdlEventThread::joyButtonEvent, this, &MainWindow::joystickButtonPressed); connect(eventThread, &SdlEventThread::joyDeviceRemoved, this, &MainWindow::joyDeviceRemoved); connect(ui->choosePadBox, QOverload<int>::of(&QComboBox::activated), this, [this](int index){ setJoystick(index - 1); }); eventThread->start(); } MainWindow::~MainWindow() { closeJoystick(); delete ui; } void MainWindow::closeHaptic() { stopHaptic(); if (!haptic) return; SDL_HapticClose(haptic); haptic = 0; } void MainWindow::closeJoystick() { closeHaptic(); if (!joystick) return; qDebug("%s: close joystick %d %s", __CLASS__, SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick)); while (auto child = ui->buttonsLayout->takeAt(0)) { delete child; } joystick = 0; numAxis = 0; numButtons = 0; numHats = 0; } void MainWindow::closeEvent(QCloseEvent *event) { eventThread->stop(); eventThread->terminate(); event->accept(); } void MainWindow::setButtons(int num) { for (int i = 0; i<num; i++) { QPushButton *b = new QPushButton(this); b->setText(QString::number(i+1)); b->setCheckable(true); ui->buttonsLayout->addWidget(b, i / 6, i % 6); } } void MainWindow::setAxis(SdlAxisWidget *widget, int xaxis, int yaxis) { if (std::max(xaxis, yaxis) < numAxis) { widget->init(joystick, xaxis, yaxis); connect(eventThread, &SdlEventThread::axisEvent, widget, &SdlAxisWidget::axisMoved); } else { disconnect(eventThread, &SdlEventThread::axisEvent, widget, &SdlAxisWidget::axisMoved); widget->reset(); } } void MainWindow::setPov(SdlPovWidget *widget, int hat) { if (hat < numHats) { widget->init(joystick, hat); connect(eventThread, &SdlEventThread::hatEvent, widget, &SdlPovWidget::povPressed); } else { disconnect(eventThread, &SdlEventThread::hatEvent, widget, &SdlPovWidget::povPressed); widget->reset(); } } void MainWindow::setSlider(SdlSliderWidget *widget, int axis) { if (axis < numAxis) { widget->init(joystick, axis); connect(eventThread, &SdlEventThread::axisEvent, widget, &SdlSliderWidget::axisMoved); } else { disconnect(eventThread, &SdlEventThread::axisEvent, widget, &SdlSliderWidget::axisMoved); widget->reset(); } } void MainWindow::fillJoystickList() { while (ui->choosePadBox->count() > 1) ui->choosePadBox->removeItem(1); for (int i = 0; i < SDL_NumJoysticks(); ++i) ui->choosePadBox->addItem(SDL_JoystickNameForIndex(i)); } void MainWindow::setJoystick(int index) { closeJoystick(); joystick = SDL_JoystickOpen(index); if (!joystick) return; ui->choosePadBox->setCurrentIndex(index + 1); qDebug("%s: setup joystick %d %s", __CLASS__, SDL_JoystickInstanceID(joystick), SDL_JoystickName(joystick)); numAxis = SDL_JoystickNumAxes(joystick); numButtons = SDL_JoystickNumButtons(joystick); numHats = SDL_JoystickNumHats(joystick); setPov (ui->pov, 0); setAxis (ui->xyaxis, 0, 1); setAxis (ui->zaxis, 2, 3); setSlider(ui->axis4, 4); setSlider(ui->axis5, 5); setButtons(numButtons); int axisOffset = numButtons; while (axisOffset % 6) ++axisOffset; for (int i = 0; i<numAxis; i++) { QLabel *l = new QLabel(this); l->setText(QString("[%1]").arg(i)); ui->buttonsLayout->addWidget(l, (axisOffset + i) / 6, (axisOffset + i) % 6); } setHaptic(SDL_HapticOpenFromJoystick(joystick)); } void MainWindow::axisMoved(SDL_JoyAxisEvent event) { if (event.axis >= numAxis) return; QLabel *l = qobject_cast<QLabel*>( ui->buttonsLayout->itemAt(numButtons + event.axis)->widget()); if (!l) return; l->setText(QString("[%1]: %2").arg(event.axis).arg(event.value)); } void MainWindow::setHaptic(struct _SDL_Haptic *haptic) { this->haptic = haptic; } void MainWindow::stopHaptic() { if (!haptic) { SDL_JoystickRumble(joystick, 0, 0, 0); return; } SDL_HapticStopEffect(haptic, hapticId); SDL_HapticDestroyEffect(haptic, hapticId); hapticId = -1; } void MainWindow::joystickButtonPressed(SDL_JoyButtonEvent event) { //qDebug("%s: button %d type %x", __FUNCTION__, event.button, event.type); if (event.button >= numButtons) return; QLayoutItem *item = ui->buttonsLayout->itemAt(event.button); if (!item) { qDebug("%s: no item at %d", __FUNCTION__, event.button); return; } QPushButton *b = qobject_cast<QPushButton*>(item->widget()); if (!b) { qDebug("%s: cast failed at %d", __FUNCTION__, event.button); return; } b->setChecked(event.type == SDL_JOYBUTTONDOWN); if (!ui->testHaptic->isChecked()) return; if (b->isChecked() || hapticId >= 0) return; SDL_HapticEffect lr = {0}; lr.type = SDL_HAPTIC_LEFTRIGHT; lr.leftright.length = kHapticLength; lr.leftright.large_magnitude = (event.button & 1) ? 0x7FFF : 0; lr.leftright.small_magnitude = (event.button & 1) ? 0 : 0x7FFF; if (!haptic) { if (SDL_JoystickRumble(joystick, lr.leftright.large_magnitude, lr.leftright.small_magnitude, lr.leftright.length) < 0) qWarning("Failed to start rumble: %s\n", SDL_GetError()); return; } hapticId = SDL_HapticNewEffect(haptic, &lr); if (hapticId < 0) { qWarning("Failed to create effect: %s\n", SDL_GetError()); return; } //qDebug("[%04x; %04x] : id", lr.leftright.large_magnitude, lr.leftright.small_magnitude, hapticId); SDL_HapticRunEffect(haptic, hapticId, 1); QTimer::singleShot(kHapticLength + kSafeTimeout, this, &MainWindow::stopHaptic); } void MainWindow::joyDeviceAdded(SDL_JoyDeviceEvent event) { if (!joystick) setJoystick(event.which); } void MainWindow::joyDeviceRemoved(SDL_JoyDeviceEvent event) { if (event.which == SDL_JoystickInstanceID(joystick)) closeJoystick(); if (SDL_NumJoysticks() > 0) setJoystick(0); } <|endoftext|>
<commit_before>/* Copyright 2013 - 2016 Yurii Litvinov, Anastasiia Kornilova and CyberTech Labs Ltd. * * 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 "powerMotor.h" #include <trikKernel/configurer.h> #include <trikKernel/exceptions/malformedConfigException.h> #include <trikKernel/exceptions/internalErrorException.h> #include <QTimer> #include "mspI2cCommunicator.h" #include "configurerHelper.h" using namespace trikControl; static const int maxControlValue = 100; static const int minControlValue = -100; PowerMotor::PowerMotor(const QString &port, const trikKernel::Configurer &configurer , MspCommunicatorInterface &communicator) : mCommunicator(communicator) , mInvert(configurer.attributeByPort(port, "invert") == "false") , mCurrentPower(0) , mState("Power Motor on" + port) { mMspCommandNumber = ConfigurerHelper::configureInt(configurer, mState, port, "i2cCommandNumber"); mCurrentPeriod = ConfigurerHelper::configureInt(configurer, mState, port, "period"); setPeriod(mCurrentPeriod); mPowerMap.reserve(maxControlValue + 1); lineariseMotor(port, configurer); mState.ready(); } PowerMotor::~PowerMotor() { } PowerMotor::Status PowerMotor::status() const { return combine(mCommunicator, mState.status()); } void PowerMotor::setPower(int power, bool constrain) { if (constrain) { if (power > maxControlValue) { power = maxControlValue; } else if (power < minControlValue) { power = minControlValue; } power = power <= 0 ? -mPowerMap[-power] : mPowerMap[power]; } mCurrentPower = power; power = mInvert ? -power : power; QByteArray command(3, '\0'); command[0] = static_cast<char>(mMspCommandNumber & 0xFF); command[1] = static_cast<char>((mMspCommandNumber >> 8) & 0xFF); command[2] = static_cast<char>(power & 0xFF); mCommunicator.send(command); } int PowerMotor::power() const { return mCurrentPower; } int PowerMotor::period() const { return mCurrentPeriod; } void PowerMotor::powerOff() { setPower(0, false); // ignore power units translation (linearisation) } void PowerMotor::forceBreak(int durationMs) { if (durationMs <= 0) forceBreak(); setPower(0xff, false); QTimer::singleShot(durationMs, this, SLOT(powerOff())); } void PowerMotor::setPeriod(int period) { mCurrentPeriod = period; QByteArray command(4, '\0'); command[0] = static_cast<char>((mMspCommandNumber - 4) & 0xFF); command[2] = static_cast<char>(period & 0xFF); command[3] = static_cast<char>(period >> 8); mCommunicator.send(command); } void PowerMotor::lineariseMotor(const QString &port, const trikKernel::Configurer &configurer) { QVector<QPair<double, double>> powerGraph; for (const QString &str : configurer.attributeByPort(port, "measures").split(")")) { if (!str.isEmpty()) { QPair<double, double> temp; temp.first = str.mid(1).split(";").at(0).toInt(); temp.second = str.mid(1).split(";").at(1).toInt(); powerGraph.append(temp); } } const int graphLength = powerGraph.size(); const int maxValue = powerGraph[graphLength - 1].second; for (int i = 0; i < graphLength; i++) { powerGraph[i].second *= maxControlValue; powerGraph[i].second /= maxValue; } for (int i = 0; i < maxControlValue; i++) { int k = 0; while (i >= powerGraph[k].second) { k++; } k--; const double measureDifference = powerGraph[k + 1].second - powerGraph[k].second; const double axeDifferenece = powerGraph[k + 1].first - powerGraph[k].first; if (measureDifference < 0 || axeDifferenece < 0) { throw trikKernel::MalformedConfigException("Nonmonotonic function"); } const double coef = axeDifferenece / measureDifference; const int power = powerGraph[k].first + coef * (i - powerGraph[k].second); mPowerMap.append(power); } mPowerMap.append(maxControlValue); } int PowerMotor::minControl() const { return minControlValue; } int PowerMotor::maxControl() const { return maxControlValue; } <commit_msg>Fixup: forceBreak is 0x7F<commit_after>/* Copyright 2013 - 2016 Yurii Litvinov, Anastasiia Kornilova and CyberTech Labs Ltd. * * 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 "powerMotor.h" #include <trikKernel/configurer.h> #include <trikKernel/exceptions/malformedConfigException.h> #include <trikKernel/exceptions/internalErrorException.h> #include <QTimer> #include "mspI2cCommunicator.h" #include "configurerHelper.h" using namespace trikControl; static const int maxControlValue = 100; static const int minControlValue = -100; PowerMotor::PowerMotor(const QString &port, const trikKernel::Configurer &configurer , MspCommunicatorInterface &communicator) : mCommunicator(communicator) , mInvert(configurer.attributeByPort(port, "invert") == "false") , mCurrentPower(0) , mState("Power Motor on" + port) { mMspCommandNumber = ConfigurerHelper::configureInt(configurer, mState, port, "i2cCommandNumber"); mCurrentPeriod = ConfigurerHelper::configureInt(configurer, mState, port, "period"); setPeriod(mCurrentPeriod); mPowerMap.reserve(maxControlValue + 1); lineariseMotor(port, configurer); mState.ready(); } PowerMotor::~PowerMotor() { } PowerMotor::Status PowerMotor::status() const { return combine(mCommunicator, mState.status()); } void PowerMotor::setPower(int power, bool constrain) { if (constrain) { if (power > maxControlValue) { power = maxControlValue; } else if (power < minControlValue) { power = minControlValue; } power = power <= 0 ? -mPowerMap[-power] : mPowerMap[power]; } mCurrentPower = power; power = mInvert ? -power : power; QByteArray command(3, '\0'); command[0] = static_cast<char>(mMspCommandNumber & 0xFF); command[1] = static_cast<char>((mMspCommandNumber >> 8) & 0xFF); command[2] = static_cast<char>(power & 0xFF); mCommunicator.send(command); } int PowerMotor::power() const { return mCurrentPower; } int PowerMotor::period() const { return mCurrentPeriod; } void PowerMotor::powerOff() { setPower(0, false); // ignore power units translation (linearisation) } void PowerMotor::forceBreak(int durationMs) { if (durationMs <= 0) forceBreak(); setPower(0x7f, false); QTimer::singleShot(durationMs, this, SLOT(powerOff())); } void PowerMotor::setPeriod(int period) { mCurrentPeriod = period; QByteArray command(4, '\0'); command[0] = static_cast<char>((mMspCommandNumber - 4) & 0xFF); command[2] = static_cast<char>(period & 0xFF); command[3] = static_cast<char>(period >> 8); mCommunicator.send(command); } void PowerMotor::lineariseMotor(const QString &port, const trikKernel::Configurer &configurer) { QVector<QPair<double, double>> powerGraph; for (const QString &str : configurer.attributeByPort(port, "measures").split(")")) { if (!str.isEmpty()) { QPair<double, double> temp; temp.first = str.mid(1).split(";").at(0).toInt(); temp.second = str.mid(1).split(";").at(1).toInt(); powerGraph.append(temp); } } const int graphLength = powerGraph.size(); const int maxValue = powerGraph[graphLength - 1].second; for (int i = 0; i < graphLength; i++) { powerGraph[i].second *= maxControlValue; powerGraph[i].second /= maxValue; } for (int i = 0; i < maxControlValue; i++) { int k = 0; while (i >= powerGraph[k].second) { k++; } k--; const double measureDifference = powerGraph[k + 1].second - powerGraph[k].second; const double axeDifferenece = powerGraph[k + 1].first - powerGraph[k].first; if (measureDifference < 0 || axeDifferenece < 0) { throw trikKernel::MalformedConfigException("Nonmonotonic function"); } const double coef = axeDifferenece / measureDifference; const int power = powerGraph[k].first + coef * (i - powerGraph[k].second); mPowerMap.append(power); } mPowerMap.append(maxControlValue); } int PowerMotor::minControl() const { return minControlValue; } int PowerMotor::maxControl() const { return maxControlValue; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); qDebug() << "hello"; } MainWindow::~MainWindow() { delete ui; } <commit_msg>something<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); qDebug() << "hello world"; } MainWindow::~MainWindow() { delete ui; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "defaults.h" #include "caller.h" #include "informerdialog.h" #include "websocketmanager.h" #include <QSystemTrayIcon> #include <QMenu> #include <QMessageBox> #include <QDesktopWidget> #include <QSettings> #include <QDesktopServices> #include <QTimer> #include <QDir> #ifdef Q_OS_MAC # include <QTemporaryFile> # include <QProcess> #endif MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowIcon(QIcon(":/res/kazoo_32.png")); createTrayIcon(); loadSettings(); m_wsMan = new WebSocketManager(this); connect(m_wsMan, &WebSocketManager::channelCreated, this, &MainWindow::onChannelCreated); connect(m_wsMan, &WebSocketManager::channelAnswered, this, &MainWindow::onChannelAnswered); connect(m_wsMan, &WebSocketManager::channelAnsweredAnother, this, &MainWindow::onChannelAnsweredAnother); connect(m_wsMan, &WebSocketManager::channelDestroyed, this, &MainWindow::onChannelDestroyed); connect(m_wsMan, &WebSocketManager::connected, this, &MainWindow::handleWsConnected); connect(m_wsMan, &WebSocketManager::connectionError, this, &MainWindow::handleWsConnectionError); connect(ui->cancelPushButton, &QPushButton::clicked, this, &MainWindow::close); connect(ui->okPushButton, &QPushButton::clicked, this, &MainWindow::saveSettings); m_wsMan->start(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::createTrayIcon() { m_trayIcon = new QSystemTrayIcon(QIcon(":/res/kazoo_32_disabled.png"), this); m_trayIcon->setToolTip(tr("Kazoo Popup - Connecting")); QMenu *menu = new QMenu(this); QAction *stateAction = menu->addAction(tr("Connecting")); stateAction->setDisabled(true); menu->addSeparator(); menu->addAction(tr("Settings"), this, SLOT(show())); menu->addAction(tr("Close all popups"), this, SLOT(closeAllPopups())); menu->addSeparator(); menu->addAction(tr("Quit"), this, SLOT(quit())); m_trayIcon->setContextMenu(menu); m_trayIcon->show(); } void MainWindow::onChannelCreated(const QString &callId, const Caller &caller) { InformerDialog *informerDialog = new InformerDialog(); connect(informerDialog, &InformerDialog::finished, this, &MainWindow::processDialogFinished); connect(informerDialog, &InformerDialog::dialogAttached, this, &MainWindow::processDialogAttached); informerDialog->setCaller(caller); informerDialog->adjustSize(); QRect rect = qApp->desktop()->availableGeometry(); informerDialog->setGeometry(rect.width() - informerDialog->width(), rect.height() - informerDialog->height(), informerDialog->width(), informerDialog->height()); informerDialog->show(); QTimer *timer = new QTimer(); connect(timer, &QTimer::timeout, this, &MainWindow::timeout); timer->setSingleShot(true); m_timersHash.insert(callId, timer); timer->start(ui->popupTimeoutSpinBox->value() * 1000); m_informerDialogsHash.insert(callId, informerDialog); if (ui->autoOpenUrlCheckBox->isChecked()) QDesktopServices::openUrl(QUrl(caller.callerUrl())); } void MainWindow::onChannelAnswered(const QString &callId) { if (!m_informerDialogsHash.contains(callId)) return; InformerDialog *informerDialog = m_informerDialogsHash.value(callId); if (informerDialog->isVisible()) informerDialog->setState(InformerDialog::kStateAnswered); if (m_timersHash.contains(callId)) { QTimer *timer = m_timersHash.value(callId); timer->start(); } } void MainWindow::onChannelAnsweredAnother(const QString &callId, const QString &calleeNumber, const QString &calleeName) { if (!m_informerDialogsHash.contains(callId)) return; InformerDialog *informerDialog = m_informerDialogsHash.value(callId); if (informerDialog->isVisible()) { informerDialog->setCallee(calleeNumber, calleeName); informerDialog->setState(InformerDialog::kStateAnsweredAnother); } if (m_timersHash.contains(callId)) { QTimer *timer = m_timersHash.value(callId); timer->start(); } } void MainWindow::timeout() { QTimer *timer = qobject_cast<QTimer*>(sender()); if (timer == nullptr) return; QString callId = m_timersHash.key(timer); if (!m_informerDialogsHash.contains(callId)) return; InformerDialog *informerDialog = m_informerDialogsHash.value(callId); if (informerDialog->isVisible()) informerDialog->close(); m_informerDialogsHash.remove(callId); informerDialog->deleteLater(); } void MainWindow::onChannelDestroyed(const QString &callId) { if (!m_informerDialogsHash.contains(callId)) return; InformerDialog *informerDialog = m_informerDialogsHash.value(callId); if (informerDialog->isVisible() && !informerDialog->isAttached()) informerDialog->close(); m_informerDialogsHash.remove(callId); informerDialog->deleteLater(); if (m_timersHash.contains(callId)) { QTimer *timer = m_timersHash.value(callId); m_timersHash.remove(callId); timer->stop(); timer->deleteLater(); } } bool MainWindow::isCorrectSettings() const { bool ok = true; ok &= !ui->loginLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->passwordLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->realmLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->authUrlLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->eventUrlLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->infoUrlLineEdit->text().isEmpty(); if (!ok) return false; return ok; } void setRunAtStartup() { #ifdef Q_OS_WIN QSettings settings(kRegistryKeyRun, QSettings::NativeFormat); if (settings.contains(qApp->applicationName())) return; QString appExePath = QString("%1/%2.exe").arg(qApp->applicationDirPath(), qApp->applicationName()); QString appExeNativePath = QDir::toNativeSeparators(appExePath); settings.setValue(qApp->applicationName(), appExeNativePath); #elif defined Q_OS_MAC QFile plistTemplateFile(":/res/mac/KazooPopup.restart.plist"); bool ok = plistTemplateFile.open(QIODevice::ReadOnly); QByteArray data = plistTemplateFile.readAll(); plistTemplateFile.close(); data.replace("/path/to/app", qApp->applicationDirPath().toLocal8Bit()); QTemporaryFile plistFile; ok = plistFile.open(); plistFile.write(data); plistFile.close(); QString fileName = plistFile.fileName(); QProcess shCp; shCp.start("sh", QStringList() << "-c" << "cp " + fileName + " ~/Library/LaunchAgents/KazooPopup.restart.plist"); shCp.waitForStarted(); shCp.close(); QProcess shLaunchctl; shLaunchctl.start("sh", QStringList() << "-c" << "launchctl load -w ~/Library/LaunchAgents/KazooPopup.restart.plist"); shLaunchctl.waitForStarted(); shLaunchctl.close(); #endif } void unsetRunAtStartup() { #ifdef Q_OS_WIN QSettings settings(kRegistryKeyRun, QSettings::NativeFormat); settings.remove(qApp->applicationName()); #elif defined Q_OS_MAC if (!QFile::exists("~/Library/LaunchAgents/KazooPopup.restart.plist")) return; QProcess process; process.start("launchctl unload -w ~/Library/LaunchAgents/KazooPopup.restart.plist"); process.waitForStarted(); process.close(); #endif } void MainWindow::saveSettings() { if (!isCorrectSettings()) { QMessageBox::warning(this, qApp->applicationName(), tr("All fields must be filled!")); return; } QSettings settings(dataDirPath() + "/settings.ini", QSettings::IniFormat); settings.setValue("login", ui->loginLineEdit->text()); settings.setValue("password", ui->passwordLineEdit->text()); settings.setValue("realm", ui->realmLineEdit->text()); settings.setValue("auth_url", ui->authUrlLineEdit->text()); settings.setValue("event_url", ui->eventUrlLineEdit->text()); settings.setValue("info_url", ui->infoUrlLineEdit->text()); settings.setValue("popup_timeout", ui->popupTimeoutSpinBox->value()); settings.setValue("auto_open_url", ui->autoOpenUrlCheckBox->isChecked()); settings.setValue("run_at_startup", ui->runAtStartupCheckBox->isChecked()); if (ui->runAtStartupCheckBox->isChecked()) { setRunAtStartup(); } else { unsetRunAtStartup(); } m_wsMan->start(); close(); } void MainWindow::loadSettings() { QSettings settings(dataDirPath() + "/settings.ini", QSettings::IniFormat); ui->loginLineEdit->setText(settings.value("login", kLogin).toString()); ui->passwordLineEdit->setText(settings.value("password", kPassword).toString()); ui->realmLineEdit->setText(settings.value("realm", kRealm).toString()); ui->authUrlLineEdit->setText(settings.value("auth_url", kAuthUrl).toString()); ui->eventUrlLineEdit->setText(settings.value("event_url", kEventUrl).toString()); ui->infoUrlLineEdit->setText(settings.value("info_url", kInfoUrl).toString()); ui->popupTimeoutSpinBox->setValue(settings.value("popup_timeout", kPopupTimeout).toInt()); ui->autoOpenUrlCheckBox->setChecked(settings.value("auto_open_url", kAutoOpenUrl).toBool()); ui->runAtStartupCheckBox->setChecked(settings.value("run_at_startup", kRunAtStartup).toBool()); } void MainWindow::processDialogFinished() { InformerDialog *informerDialog = qobject_cast<InformerDialog*>(sender()); if (m_informerDialogsHash.values().contains(informerDialog)) { QString callId = m_informerDialogsHash.key(informerDialog); m_informerDialogsHash.remove(callId); } else if (m_attachedDialogsHash.values().contains(informerDialog)) { QString callId = m_attachedDialogsHash.key(informerDialog); m_attachedDialogsHash.remove(callId); } } void MainWindow::processDialogAttached(bool attached) { InformerDialog *informerDialog = qobject_cast<InformerDialog*>(sender()); if (attached) { QString callId = m_informerDialogsHash.key(informerDialog); m_attachedDialogsHash.insert(callId, informerDialog); m_informerDialogsHash.remove(callId); } else { QString callId = m_attachedDialogsHash.key(informerDialog); m_attachedDialogsHash.remove(callId); m_informerDialogsHash.insert(callId, informerDialog); } } void MainWindow::closeAllPopups() { foreach (InformerDialog* informerDialog, m_informerDialogsHash) { informerDialog->close(); informerDialog->deleteLater(); } m_informerDialogsHash.clear(); foreach (InformerDialog* informerDialog, m_attachedDialogsHash) { informerDialog->close(); informerDialog->deleteLater(); } m_attachedDialogsHash.clear(); } void MainWindow::quit() { int result = QMessageBox::question(this, qApp->applicationName(), tr("Do you really want to quit?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (result != QMessageBox::Yes) return; QTimer::singleShot(0, qApp, SLOT(quit())); } void MainWindow::handleWsConnected() { m_trayIcon->setIcon(QIcon(":/res/kazoo_32.png")); m_trayIcon->setToolTip(tr("Kazoo Popup - Connected")); QMenu *menu = m_trayIcon->contextMenu(); QList<QAction*> actions = menu->actions(); QAction *stateAction = actions.first(); stateAction->setText(tr("Connected")); QAction *action = actions.at(2); QAction *separator = actions.at(3); if (action->text() != tr("Try reconnect...")) return; menu->removeAction(action); menu->removeAction(separator); m_trayIcon->showMessage(qApp->applicationName(), tr("Connection established")); } void MainWindow::handleWsConnectionError() { m_trayIcon->setIcon(QIcon(":/res/kazoo_32_error.png")); m_trayIcon->setToolTip(tr("Kazoo Popup - Cannot establish connection")); m_trayIcon->showMessage(qApp->applicationName(), tr("Cannot establish connection"), QSystemTrayIcon::Warning); QMenu *menu = m_trayIcon->contextMenu(); QAction *stateAction = menu->actions().first(); stateAction->setText(tr("Connection error")); QAction *action = menu->actions().at(2); if (action->text() == tr("Try reconnect...")) return; QAction *reconnectAction = new QAction(tr("Try reconnect..."), this); connect(reconnectAction, &QAction::triggered, m_wsMan, &WebSocketManager::start); menu->insertAction(action, reconnectAction); menu->insertSeparator(action); } <commit_msg>fix boot at startup on Mac OS X<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "defaults.h" #include "caller.h" #include "informerdialog.h" #include "websocketmanager.h" #include <QSystemTrayIcon> #include <QMenu> #include <QMessageBox> #include <QDesktopWidget> #include <QSettings> #include <QDesktopServices> #include <QTimer> #include <QDir> #ifdef Q_OS_MAC # include <QTemporaryFile> # include <QProcess> #endif MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setWindowIcon(QIcon(":/res/kazoo_32.png")); createTrayIcon(); loadSettings(); m_wsMan = new WebSocketManager(this); connect(m_wsMan, &WebSocketManager::channelCreated, this, &MainWindow::onChannelCreated); connect(m_wsMan, &WebSocketManager::channelAnswered, this, &MainWindow::onChannelAnswered); connect(m_wsMan, &WebSocketManager::channelAnsweredAnother, this, &MainWindow::onChannelAnsweredAnother); connect(m_wsMan, &WebSocketManager::channelDestroyed, this, &MainWindow::onChannelDestroyed); connect(m_wsMan, &WebSocketManager::connected, this, &MainWindow::handleWsConnected); connect(m_wsMan, &WebSocketManager::connectionError, this, &MainWindow::handleWsConnectionError); connect(ui->cancelPushButton, &QPushButton::clicked, this, &MainWindow::close); connect(ui->okPushButton, &QPushButton::clicked, this, &MainWindow::saveSettings); m_wsMan->start(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::createTrayIcon() { m_trayIcon = new QSystemTrayIcon(QIcon(":/res/kazoo_32_disabled.png"), this); m_trayIcon->setToolTip(tr("Kazoo Popup - Connecting")); QMenu *menu = new QMenu(this); QAction *stateAction = menu->addAction(tr("Connecting")); stateAction->setDisabled(true); menu->addSeparator(); menu->addAction(tr("Settings"), this, SLOT(show())); menu->addAction(tr("Close all popups"), this, SLOT(closeAllPopups())); menu->addSeparator(); menu->addAction(tr("Quit"), this, SLOT(quit())); m_trayIcon->setContextMenu(menu); m_trayIcon->show(); } void MainWindow::onChannelCreated(const QString &callId, const Caller &caller) { InformerDialog *informerDialog = new InformerDialog(); connect(informerDialog, &InformerDialog::finished, this, &MainWindow::processDialogFinished); connect(informerDialog, &InformerDialog::dialogAttached, this, &MainWindow::processDialogAttached); informerDialog->setCaller(caller); informerDialog->adjustSize(); QRect rect = qApp->desktop()->availableGeometry(); informerDialog->setGeometry(rect.width() - informerDialog->width(), rect.height() - informerDialog->height(), informerDialog->width(), informerDialog->height()); informerDialog->show(); QTimer *timer = new QTimer(); connect(timer, &QTimer::timeout, this, &MainWindow::timeout); timer->setSingleShot(true); m_timersHash.insert(callId, timer); timer->start(ui->popupTimeoutSpinBox->value() * 1000); m_informerDialogsHash.insert(callId, informerDialog); if (ui->autoOpenUrlCheckBox->isChecked()) QDesktopServices::openUrl(QUrl(caller.callerUrl())); } void MainWindow::onChannelAnswered(const QString &callId) { if (!m_informerDialogsHash.contains(callId)) return; InformerDialog *informerDialog = m_informerDialogsHash.value(callId); if (informerDialog->isVisible()) informerDialog->setState(InformerDialog::kStateAnswered); if (m_timersHash.contains(callId)) { QTimer *timer = m_timersHash.value(callId); timer->start(); } } void MainWindow::onChannelAnsweredAnother(const QString &callId, const QString &calleeNumber, const QString &calleeName) { if (!m_informerDialogsHash.contains(callId)) return; InformerDialog *informerDialog = m_informerDialogsHash.value(callId); if (informerDialog->isVisible()) { informerDialog->setCallee(calleeNumber, calleeName); informerDialog->setState(InformerDialog::kStateAnsweredAnother); } if (m_timersHash.contains(callId)) { QTimer *timer = m_timersHash.value(callId); timer->start(); } } void MainWindow::timeout() { QTimer *timer = qobject_cast<QTimer*>(sender()); if (timer == nullptr) return; QString callId = m_timersHash.key(timer); if (!m_informerDialogsHash.contains(callId)) return; InformerDialog *informerDialog = m_informerDialogsHash.value(callId); if (informerDialog->isVisible()) informerDialog->close(); m_informerDialogsHash.remove(callId); informerDialog->deleteLater(); } void MainWindow::onChannelDestroyed(const QString &callId) { if (!m_informerDialogsHash.contains(callId)) return; InformerDialog *informerDialog = m_informerDialogsHash.value(callId); if (informerDialog->isVisible() && !informerDialog->isAttached()) informerDialog->close(); m_informerDialogsHash.remove(callId); informerDialog->deleteLater(); if (m_timersHash.contains(callId)) { QTimer *timer = m_timersHash.value(callId); m_timersHash.remove(callId); timer->stop(); timer->deleteLater(); } } bool MainWindow::isCorrectSettings() const { bool ok = true; ok &= !ui->loginLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->passwordLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->realmLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->authUrlLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->eventUrlLineEdit->text().isEmpty(); if (!ok) return false; ok &= !ui->infoUrlLineEdit->text().isEmpty(); if (!ok) return false; return ok; } void setRunAtStartup() { #ifdef Q_OS_WIN QSettings settings(kRegistryKeyRun, QSettings::NativeFormat); if (settings.contains(qApp->applicationName())) return; QString appExePath = QString("%1/%2.exe").arg(qApp->applicationDirPath(), qApp->applicationName()); QString appExeNativePath = QDir::toNativeSeparators(appExePath); settings.setValue(qApp->applicationName(), appExeNativePath); #elif defined Q_OS_MAC if (QFile::exists("~/Library/LaunchAgents/KazooPopup.restart.plist")) return; QFile plistTemplateFile(":/res/mac/KazooPopup.restart.plist"); bool ok = plistTemplateFile.open(QIODevice::ReadOnly); QByteArray data = plistTemplateFile.readAll(); plistTemplateFile.close(); data.replace("/path/to/app", qApp->applicationDirPath().toLocal8Bit()); QTemporaryFile plistFile; ok = plistFile.open(); plistFile.write(data); plistFile.close(); QString fileName = plistFile.fileName(); QProcess::startDetached("sh", QStringList() << "-c" << "cp " + fileName + " ~/Library/LaunchAgents/KazooPopup.restart.plist"); QProcess::startDetached("sh", QStringList() << "-c" << "launchctl load -w ~/Library/LaunchAgents/KazooPopup.restart.plist"); #endif } void unsetRunAtStartup() { #ifdef Q_OS_WIN QSettings settings(kRegistryKeyRun, QSettings::NativeFormat); if (!settings.contains(qApp->applicationName())) return; settings.remove(qApp->applicationName()); #elif defined Q_OS_MAC if (!QFile::exists("~/Library/LaunchAgents/KazooPopup.restart.plist")) return; QProcess::startDetached("launchctl unload -w ~/Library/LaunchAgents/KazooPopup.restart.plist"); QFile::remove("~/Library/LaunchAgents/KazooPopup.restart.plist"); #endif } void MainWindow::saveSettings() { if (!isCorrectSettings()) { QMessageBox::warning(this, qApp->applicationName(), tr("All fields must be filled!")); return; } QSettings settings(dataDirPath() + "/settings.ini", QSettings::IniFormat); settings.setValue("login", ui->loginLineEdit->text()); settings.setValue("password", ui->passwordLineEdit->text()); settings.setValue("realm", ui->realmLineEdit->text()); settings.setValue("auth_url", ui->authUrlLineEdit->text()); settings.setValue("event_url", ui->eventUrlLineEdit->text()); settings.setValue("info_url", ui->infoUrlLineEdit->text()); settings.setValue("popup_timeout", ui->popupTimeoutSpinBox->value()); settings.setValue("auto_open_url", ui->autoOpenUrlCheckBox->isChecked()); settings.setValue("run_at_startup", ui->runAtStartupCheckBox->isChecked()); if (ui->runAtStartupCheckBox->isChecked()) setRunAtStartup(); else unsetRunAtStartup(); m_wsMan->start(); close(); } void MainWindow::loadSettings() { QSettings settings(dataDirPath() + "/settings.ini", QSettings::IniFormat); ui->loginLineEdit->setText(settings.value("login", kLogin).toString()); ui->passwordLineEdit->setText(settings.value("password", kPassword).toString()); ui->realmLineEdit->setText(settings.value("realm", kRealm).toString()); ui->authUrlLineEdit->setText(settings.value("auth_url", kAuthUrl).toString()); ui->eventUrlLineEdit->setText(settings.value("event_url", kEventUrl).toString()); ui->infoUrlLineEdit->setText(settings.value("info_url", kInfoUrl).toString()); ui->popupTimeoutSpinBox->setValue(settings.value("popup_timeout", kPopupTimeout).toInt()); ui->autoOpenUrlCheckBox->setChecked(settings.value("auto_open_url", kAutoOpenUrl).toBool()); ui->runAtStartupCheckBox->setChecked(settings.value("run_at_startup", kRunAtStartup).toBool()); if (ui->runAtStartupCheckBox->isChecked()) setRunAtStartup(); else unsetRunAtStartup(); } void MainWindow::processDialogFinished() { InformerDialog *informerDialog = qobject_cast<InformerDialog*>(sender()); if (m_informerDialogsHash.values().contains(informerDialog)) { QString callId = m_informerDialogsHash.key(informerDialog); m_informerDialogsHash.remove(callId); } else if (m_attachedDialogsHash.values().contains(informerDialog)) { QString callId = m_attachedDialogsHash.key(informerDialog); m_attachedDialogsHash.remove(callId); } } void MainWindow::processDialogAttached(bool attached) { InformerDialog *informerDialog = qobject_cast<InformerDialog*>(sender()); if (attached) { QString callId = m_informerDialogsHash.key(informerDialog); m_attachedDialogsHash.insert(callId, informerDialog); m_informerDialogsHash.remove(callId); } else { QString callId = m_attachedDialogsHash.key(informerDialog); m_attachedDialogsHash.remove(callId); m_informerDialogsHash.insert(callId, informerDialog); } } void MainWindow::closeAllPopups() { foreach (InformerDialog* informerDialog, m_informerDialogsHash) { informerDialog->close(); informerDialog->deleteLater(); } m_informerDialogsHash.clear(); foreach (InformerDialog* informerDialog, m_attachedDialogsHash) { informerDialog->close(); informerDialog->deleteLater(); } m_attachedDialogsHash.clear(); } void MainWindow::quit() { int result = QMessageBox::question(this, qApp->applicationName(), tr("Do you really want to quit?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (result != QMessageBox::Yes) return; QTimer::singleShot(0, qApp, SLOT(quit())); } void MainWindow::handleWsConnected() { m_trayIcon->setIcon(QIcon(":/res/kazoo_32.png")); m_trayIcon->setToolTip(tr("Kazoo Popup - Connected")); QMenu *menu = m_trayIcon->contextMenu(); QList<QAction*> actions = menu->actions(); QAction *stateAction = actions.first(); stateAction->setText(tr("Connected")); QAction *action = actions.at(2); QAction *separator = actions.at(3); if (action->text() != tr("Try reconnect...")) return; menu->removeAction(action); menu->removeAction(separator); m_trayIcon->showMessage(qApp->applicationName(), tr("Connection established")); } void MainWindow::handleWsConnectionError() { m_trayIcon->setIcon(QIcon(":/res/kazoo_32_error.png")); m_trayIcon->setToolTip(tr("Kazoo Popup - Cannot establish connection")); m_trayIcon->showMessage(qApp->applicationName(), tr("Cannot establish connection"), QSystemTrayIcon::Warning); QMenu *menu = m_trayIcon->contextMenu(); QAction *stateAction = menu->actions().first(); stateAction->setText(tr("Connection error")); QAction *action = menu->actions().at(2); if (action->text() == tr("Try reconnect...")) return; QAction *reconnectAction = new QAction(tr("Try reconnect..."), this); connect(reconnectAction, &QAction::triggered, m_wsMan, &WebSocketManager::start); menu->insertAction(action, reconnectAction); menu->insertSeparator(action); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <random> #include <iostream> namespace virtualBartender { MainWindow::MainWindow( QWidget *parent ) : QWidget{ parent } , ui_{ new Ui::MainWindow{} } { if (ui_) { ui_->setupUi( this ); } ui_->order_b->setEnabled( true ); connect( ui_->order_b, SIGNAL(clicked()), this, SLOT(Order())); connect( ui_->drink_b, SIGNAL(clicked()), this, SLOT(Drink())); } MainWindow::~MainWindow() { delete ui_; } void MainWindow::Order() { using namespace std::chrono; constexpr minutes timeForDrink{ 30 }; // TODO: CALCULATE const uint32_t ml{ 300 }; if ( 50 > ml ) { // well, shit // No more, bro } timeForMl_ = duration_cast< seconds >( timeForDrink / static_cast< double >( ml ) ); ui_->beverage->setMaximum( ml ); ui_->beverage->setValue( ml ); ui_->order_b->setEnabled( false ); ui_->beverage_gb->setEnabled( true ); ui_->company_gb->setEnabled( false ); } void MainWindow::Drink() { using namespace std; random_device rd{}; mt19937 generator{ rd() }; uniform_int_distribution<int32_t> int_dist{ 0, ui_->beverage->maximum() }; const int32_t will_drink{ qMin( int_dist( generator) , ui_->beverage->value() ) }; cout << will_drink << "\n"; // TODO: Calculate drunkness // Re-calculating time using namespace std::chrono; const minutes timeElapsed = duration_cast< minutes >( timeForMl_ * will_drink ); cout << timeElapsed.count() << "m\n"; ui_->time->setValue( ui_->time->value() - timeElapsed.count() ); // Sipping beverage ui_->beverage->setValue( ui_->beverage->value() - will_drink ); if (0 == ui_->beverage->value()) { ui_->order_b->setEnabled( true ); ui_->company_gb->setEnabled( true ); ui_->beverage_gb->setEnabled( false ); } } } // namespace virtualBartender <commit_msg>Added additional check in Drink method<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <random> #include <iostream> namespace virtualBartender { MainWindow::MainWindow( QWidget *parent ) : QWidget{ parent } , ui_{ new Ui::MainWindow{} } { if (ui_) { ui_->setupUi( this ); } ui_->order_b->setEnabled( true ); connect( ui_->order_b, SIGNAL(clicked()), this, SLOT(Order())); connect( ui_->drink_b, SIGNAL(clicked()), this, SLOT(Drink())); // TODO: remove this ui_->time->setValue( 30 ); } MainWindow::~MainWindow() { delete ui_; } void MainWindow::Order() { using namespace std::chrono; constexpr minutes timeForDrink{ 30 }; // TODO: CALCULATE const uint32_t ml{ 300 }; if ( 50 > ml ) { // well, shit // No more, bro } timeForMl_ = duration_cast< seconds >( timeForDrink / static_cast< double >( ml ) ); ui_->beverage->setMaximum( ml ); ui_->beverage->setValue( ml ); ui_->order_b->setEnabled( false ); ui_->beverage_gb->setEnabled( true ); ui_->company_gb->setEnabled( false ); } void MainWindow::Drink() { using namespace std; random_device rd{}; mt19937 generator{ rd() }; uniform_int_distribution<int32_t> int_dist{ 0, ui_->beverage->maximum() }; const int32_t will_drink{ qMin( int_dist( generator) , ui_->beverage->value() ) }; cout << will_drink << "\n"; // TODO: Calculate drunkness // Re-calculating time using namespace std::chrono; const minutes timeElapsed = duration_cast< minutes >( timeForMl_ * will_drink ); cout << timeElapsed.count() << "m\n"; ui_->time->setValue( ui_->time->value() - timeElapsed.count() ); // Sipping beverage ui_->beverage->setValue( ui_->beverage->value() - will_drink ); if (0 == ui_->beverage->value()) { ui_->beverage_gb->setEnabled( false ); if (30 > ui_->time->value()) { ui_->time->setValue( 0 ); // Sorry bro } else { ui_->order_b->setEnabled( true ); ui_->company_gb->setEnabled( true ); } } } } // namespace virtualBartender <|endoftext|>
<commit_before>// DT PS Tree // // Douglas Thrift // // $Id$ #include <climits> #include <cstdio> #include <iostream> #include <map> #include <set> #include <sstream> #include <string> #include <err.h> #include <fcntl.h> #include <kvm.h> #include <libgen.h> #include <paths.h> #include <popt.h> #include <pwd.h> #include <sys/param.h> #include <sys/sysctl.h> #include <sys/user.h> #include "foreach.hpp" #define DTPSTREE_PROGRAM "dtpstree" #define DTPSTREE_VERSION "1.0.1" class Proc; typedef std::map<pid_t, Proc *> PidMap; typedef std::multimap<std::string, Proc *> NameMap; enum Flags { Arguments = 0x0001, Ascii = 0x0002, Compact = 0x0004, Highlight = 0x0008, Vt100 = 0x0010, ShowKernel = 0x0020, Long = 0x0040, NumericSort = 0x0080, ShowPids = 0x0104, ShowTitles = 0x0200, UidChanges = 0x0400, Unicode = 0x0800, Version = 0x1000, Pid = 0x2000, User = 0x4000 }; class Proc { const int &flags_; kvm_t *kd_; kinfo_proc *proc_; Proc *parent_; PidMap childrenByPid_; NameMap childrenByName_; bool highlight_; public: Proc(const int &flags, kvm_t *kd, kinfo_proc *proc) : flags_(flags), kd_(kd), proc_(proc) {} inline std::string name() const { return proc_->ki_comm; } inline pid_t parent() const { return proc_->ki_ppid; } inline pid_t pid() const { return proc_->ki_pid; } void child(Proc *proc) { proc->parent_ = this; childrenByPid_[proc->pid()] = proc; childrenByName_.insert(NameMap::value_type(proc->name(), proc)); } void highlight() { highlight_ = true; if (parent_) parent_->highlight(); } inline bool root() const { return !parent_; } void printByPid(const std::string &indent = "") const { std::cout << indent << print(indent.size()) << std::endl; _foreach (const PidMap, child, childrenByPid_) child->second->printByPid(indent + " "); } void printByName(const std::string &indent = "") const { std::cout << indent << print(indent.size()) << std::endl; _foreach (const NameMap, child, childrenByName_) child->second->printByName(indent + " "); } private: std::string print(std::string::size_type indent) const { std::ostringstream print; if (highlight_) print << "\033[1m"; print << name(); bool _pid(flags_ & ShowPids), _args(flags_ & Arguments); bool change(flags_ & UidChanges && parent_ && uid() != parent_->uid()); bool parens((_pid || change) && !_args); if (parens) print << '('; if (_pid) { if (!parens) print << ','; print << pid(); } if (change) { if (!parens || _pid) print << ','; print << user(); } if (parens) print << ')'; if (highlight_) print << "\033[22m"; if (_args) print << args(indent + print.str().size()); return print.str(); } inline bool children() const { return childrenByPid_.size(); } inline uid_t uid() const { return proc_->ki_ruid; } std::string user() const { passwd *user(getpwuid(uid())); return user->pw_name; } std::string args(std::string::size_type indent) const { char **argv(kvm_getargv(kd_, proc_, 0)); std::ostringstream args; if (argv && *argv) for (++argv; *argv; ++argv) { if (!(flags_ & Long) && (indent += 1 + std::strlen(*argv)) > 75) { args << " ..."; break; } args << ' ' << *argv; } return args.str(); } }; int main(int argc, char *argv[]) { int flags(0); pid_t hpid, pid; char *user(NULL); { poptOption options[] = { { "arguments", 'a', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Arguments, "show command line arguments", NULL }, { "ascii", 'A', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Ascii, "use ASCII line drawing characters", NULL }, { "compact", 'c', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Compact, "don't compact identical subtrees", NULL }, { "highlight-all", 'h', POPT_ARG_NONE, NULL, 'h', "highlight current process and its ancestors", NULL }, { "highlight-pid", 'H', POPT_ARG_INT, &hpid, 'H', "highlight this process and its ancestors", "PID" }, { "vt100", 'G', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Vt100, "use VT100 line drawing characters", NULL }, { "show-kernel", 'k', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, ShowKernel, "show kernel processes", NULL }, { "long", 'l', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Long, "don't truncate long lines", NULL }, { "numeric-sort", 'n', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, NumericSort, "sort output by PID", NULL }, { "show-pids", 'p', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, ShowPids, "show PIDs; implies -c", NULL }, { "show-titles", 't', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, ShowTitles, "show process titles", NULL }, { "uid-changes", 'u', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, UidChanges, "show uid transitions", NULL }, { "unicode", 'U', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Unicode, "use Unicode line drawing characters", NULL }, { "version", 'V', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Version, "display version information", NULL }, { "pid", '\0', POPT_ARG_INT, &pid, 'p', "start at this PID", "PID" }, { "user", '\0', POPT_ARG_STRING, &user, 'u', "show only trees rooted at processes of this user", "USER" }, POPT_AUTOHELP POPT_TABLEEND }; poptContext context(poptGetContext(NULL, argc, const_cast<const char **>(argv), options, 0)); int versionArgc; const char **versionArgv; poptParseArgvString("-V", &versionArgc, &versionArgv); poptAlias versionAlias = { NULL, 'v', versionArgc, versionArgv }; poptAddAlias(context, versionAlias, 0); poptSetOtherOptionHelp(context, "[OPTION...] [PID|USER]"); int option; while ((option = poptGetNextOpt(context)) >= 0) switch (option) { case 'h': hpid = getpid(); case 'H': flags |= Highlight; break; case 'p': flags |= Pid; flags &= ~User; break; case 'u': flags |= User; flags &= ~Pid; } if (option != -1) errx(1, "%s: %s", poptStrerror(option), poptBadOption(context, 0)); for (const char **arg(poptGetArgs(context)); arg && *arg; ++arg) { char *end; long value(std::strtol(*arg, &end, 0)); if (*arg == end || *end != '\0') { std::free(user); user = strdup(*arg); flags |= User; flags &= ~Pid; } else if (value > INT_MAX || value < INT_MIN) errx(1, "%s: %s", poptStrerror(POPT_ERROR_OVERFLOW), *arg); else { pid = value; flags |= Pid; flags &= ~User; } } poptFreeContext(context); } if (flags & Version) { std::cout << DTPSTREE_PROGRAM " " DTPSTREE_VERSION << std::endl; return 0; } char error[_POSIX2_LINE_MAX]; kvm_t *kd(kvm_openfiles(NULL, _PATH_DEVNULL, NULL, O_RDONLY, error)); if (!kd) errx(1, "%s", error); typedef kinfo_proc *InfoProc; int count; InfoProc procs(kvm_getprocs(kd, KERN_PROC_PROC, 0, &count)); if (!procs) errx(1, "%s", kvm_geterr(kd)); PidMap pids; _forall (InfoProc, proc, procs, procs + count) if (flags & ShowKernel || proc->ki_ppid != 0 || proc->ki_pid == 1) pids[proc->ki_pid] = new Proc(flags, kd, proc); enum { PidSort, NameSort } sort(flags & NumericSort ? PidSort : NameSort); _foreach (PidMap, pid, pids) { Proc *proc(pid->second); PidMap::iterator parent(pids.find(proc->parent())); if (parent != pids.end()) parent->second->child(proc); } if (flags & Highlight) { PidMap::iterator pid(pids.find(hpid)); if (pid != pids.end()) pid->second->highlight(); } NameMap names; _foreach (PidMap, pid, pids) { Proc *proc(pid->second); if (proc->root()) switch (sort) { case PidSort: proc->printByPid(); break; case NameSort: names.insert(NameMap::value_type(proc->name(), proc)); } } switch (sort) { case NameSort: _foreach (NameMap, name, names) name->second->printByName(); default: break; } std::setlocale(LC_ALL, ""); char line[MB_LEN_MAX]; int size(std::wctomb(line, L'└')); if (size != -1) std::cout << std::string(line, size) << std::endl; return 0; } // display a tree of processes <commit_msg>Make show titles work and show kernel really work.<commit_after>// DT PS Tree // // Douglas Thrift // // $Id$ #include <climits> #include <cstdio> #include <iostream> #include <map> #include <set> #include <sstream> #include <string> #include <err.h> #include <fcntl.h> #include <kvm.h> #include <libgen.h> #include <paths.h> #include <popt.h> #include <pwd.h> #include <sys/param.h> #include <sys/sysctl.h> #include <sys/user.h> #include "foreach.hpp" #define DTPSTREE_PROGRAM "dtpstree" #define DTPSTREE_VERSION "1.0.1" class Proc; typedef std::map<pid_t, Proc *> PidMap; typedef std::multimap<std::string, Proc *> NameMap; enum Flags { Arguments = 0x0001, Ascii = 0x0002, Compact = 0x0004, Highlight = 0x0008, Vt100 = 0x0010, ShowKernel = 0x0020, Long = 0x0040, NumericSort = 0x0080, ShowPids = 0x0104, ShowTitles = 0x0200, UidChanges = 0x0400, Unicode = 0x0800, Version = 0x1000, Pid = 0x2000, User = 0x4000 }; class Proc { const int &flags_; kvm_t *kd_; kinfo_proc *proc_; Proc *parent_; PidMap childrenByPid_; NameMap childrenByName_; bool highlight_; public: Proc(const int &flags, kvm_t *kd, kinfo_proc *proc) : flags_(flags), kd_(kd), proc_(proc) {} inline std::string name() const { return proc_->ki_comm; } inline pid_t parent() const { return proc_->ki_ppid; } inline pid_t pid() const { return proc_->ki_pid; } void child(Proc *proc) { if (proc == this) return; proc->parent_ = this; childrenByPid_[proc->pid()] = proc; childrenByName_.insert(NameMap::value_type(proc->name(), proc)); } void highlight() { highlight_ = true; if (parent_) parent_->highlight(); } inline bool root() const { return !parent_; } void printByPid(const std::string &indent = "") const { std::cout << indent << print(indent.size()) << std::endl; _foreach (const PidMap, child, childrenByPid_) child->second->printByPid(indent + " "); } void printByName(const std::string &indent = "") const { std::cout << indent << print(indent.size()) << std::endl; _foreach (const NameMap, child, childrenByName_) child->second->printByName(indent + " "); } private: std::string print(std::string::size_type indent) const { std::ostringstream print; if (highlight_) print << "\033[1m"; if (flags_ & ShowTitles) { char **argv(kvm_getargv(kd_, proc_, 0)); if (argv) print << *argv; else print << name(); } else print << name(); bool _pid(flags_ & ShowPids), _args(flags_ & Arguments); bool change(flags_ & UidChanges && parent_ && uid() != parent_->uid()); bool parens((_pid || change) && !_args); if (parens) print << '('; if (_pid) { if (!parens) print << ','; print << pid(); } if (change) { if (!parens || _pid) print << ','; print << user(); } if (parens) print << ')'; if (highlight_) print << "\033[22m"; if (_args) print << args(indent + print.str().size()); return print.str(); } inline bool children() const { return childrenByPid_.size(); } inline uid_t uid() const { return proc_->ki_ruid; } std::string user() const { passwd *user(getpwuid(uid())); return user->pw_name; } std::string args(std::string::size_type indent) const { char **argv(kvm_getargv(kd_, proc_, 0)); std::ostringstream args; if (argv && *argv) for (++argv; *argv; ++argv) { if (!(flags_ & Long) && (indent += 1 + std::strlen(*argv)) > 75) { args << " ..."; break; } args << ' ' << *argv; } return args.str(); } }; int main(int argc, char *argv[]) { int flags(0); pid_t hpid, pid; char *user(NULL); { poptOption options[] = { { "arguments", 'a', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Arguments, "show command line arguments", NULL }, { "ascii", 'A', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Ascii, "use ASCII line drawing characters", NULL }, { "compact", 'c', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Compact, "don't compact identical subtrees", NULL }, { "highlight-all", 'h', POPT_ARG_NONE, NULL, 'h', "highlight current process and its ancestors", NULL }, { "highlight-pid", 'H', POPT_ARG_INT, &hpid, 'H', "highlight this process and its ancestors", "PID" }, { "vt100", 'G', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Vt100, "use VT100 line drawing characters", NULL }, { "show-kernel", 'k', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, ShowKernel, "show kernel processes", NULL }, { "long", 'l', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Long, "don't truncate long lines", NULL }, { "numeric-sort", 'n', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, NumericSort, "sort output by PID", NULL }, { "show-pids", 'p', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, ShowPids, "show PIDs; implies -c", NULL }, { "show-titles", 't', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, ShowTitles, "show process titles", NULL }, { "uid-changes", 'u', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, UidChanges, "show uid transitions", NULL }, { "unicode", 'U', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Unicode, "use Unicode line drawing characters", NULL }, { "version", 'V', POPT_ARG_VAL | POPT_ARGFLAG_OR, &flags, Version, "display version information", NULL }, { "pid", '\0', POPT_ARG_INT, &pid, 'p', "start at this PID", "PID" }, { "user", '\0', POPT_ARG_STRING, &user, 'u', "show only trees rooted at processes of this user", "USER" }, POPT_AUTOHELP POPT_TABLEEND }; poptContext context(poptGetContext(NULL, argc, const_cast<const char **>(argv), options, 0)); int versionArgc; const char **versionArgv; poptParseArgvString("-V", &versionArgc, &versionArgv); poptAlias versionAlias = { NULL, 'v', versionArgc, versionArgv }; poptAddAlias(context, versionAlias, 0); poptSetOtherOptionHelp(context, "[OPTION...] [PID|USER]"); int option; while ((option = poptGetNextOpt(context)) >= 0) switch (option) { case 'h': hpid = getpid(); case 'H': flags |= Highlight; break; case 'p': flags |= Pid; flags &= ~User; break; case 'u': flags |= User; flags &= ~Pid; } if (option != -1) errx(1, "%s: %s", poptStrerror(option), poptBadOption(context, 0)); for (const char **arg(poptGetArgs(context)); arg && *arg; ++arg) { char *end; long value(std::strtol(*arg, &end, 0)); if (*arg == end || *end != '\0') { std::free(user); user = strdup(*arg); flags |= User; flags &= ~Pid; } else if (value > INT_MAX || value < INT_MIN) errx(1, "%s: %s", poptStrerror(POPT_ERROR_OVERFLOW), *arg); else { pid = value; flags |= Pid; flags &= ~User; } } poptFreeContext(context); } if (flags & Version) { std::cout << DTPSTREE_PROGRAM " " DTPSTREE_VERSION << std::endl; return 0; } char error[_POSIX2_LINE_MAX]; kvm_t *kd(kvm_openfiles(NULL, _PATH_DEVNULL, NULL, O_RDONLY, error)); if (!kd) errx(1, "%s", error); typedef kinfo_proc *InfoProc; int count; InfoProc procs(kvm_getprocs(kd, KERN_PROC_PROC, 0, &count)); if (!procs) errx(1, "%s", kvm_geterr(kd)); PidMap pids; _forall (InfoProc, proc, procs, procs + count) if (flags & ShowKernel || proc->ki_ppid != 0 || proc->ki_pid == 1) pids[proc->ki_pid] = new Proc(flags, kd, proc); enum { PidSort, NameSort } sort(flags & NumericSort ? PidSort : NameSort); _foreach (PidMap, pid, pids) { Proc *proc(pid->second); PidMap::iterator parent(pids.find(proc->parent())); if (parent != pids.end()) parent->second->child(proc); } if (flags & Highlight) { PidMap::iterator pid(pids.find(hpid)); if (pid != pids.end()) pid->second->highlight(); } NameMap names; _foreach (PidMap, pid, pids) { Proc *proc(pid->second); if (proc->root()) switch (sort) { case PidSort: proc->printByPid(); break; case NameSort: names.insert(NameMap::value_type(proc->name(), proc)); } } switch (sort) { case NameSort: _foreach (NameMap, name, names) name->second->printByName(); default: break; } std::setlocale(LC_ALL, ""); char line[MB_LEN_MAX]; int size(std::wctomb(line, L'└')); if (size != -1) std::cout << std::string(line, size) << std::endl; return 0; } // display a tree of processes <|endoftext|>
<commit_before>/* -*- c-basic-offset: 2 -*- */ /* Copyright(C) 2011 Brazil 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 "file-impl.hpp" #include <sys/types.h> #include <sys/stat.h> #ifdef WIN32 # ifdef min # undef min # endif // min # ifdef max # undef max # endif // max #else // WIN32 #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #endif // WIN32 #include <algorithm> #include <limits> namespace grn { namespace dat { #ifdef WIN32 FileImpl::FileImpl() : ptr_(NULL), size_(0), file_(INVALID_HANDLE_VALUE), map_(INVALID_HANDLE_VALUE), addr_(NULL) {} FileImpl::~FileImpl() { if (addr_ != NULL) { ::UnmapViewOfFile(addr_); } if (map_ != INVALID_HANDLE_VALUE) { ::CloseHandle(map_); } if (file_ != INVALID_HANDLE_VALUE) { ::CloseHandle(file_); } } #else // WIN32 FileImpl::FileImpl() : ptr_(NULL), size_(0), fd_(-1), addr_(MAP_FAILED), length_(0) {} FileImpl::~FileImpl() { if (addr_ != MAP_FAILED) { ::munmap(addr_, length_); } if (fd_ != -1) { ::close(fd_); } } #endif // WIN32 void FileImpl::create(const char *path, UInt64 size) { GRN_DAT_THROW_IF(PARAM_ERROR, size == 0); GRN_DAT_THROW_IF(PARAM_ERROR, size > static_cast<UInt64>(std::numeric_limits< ::size_t>::max())); FileImpl new_impl; new_impl.create_(path, size); new_impl.swap(this); } void FileImpl::open(const char *path) { GRN_DAT_THROW_IF(PARAM_ERROR, path == NULL); GRN_DAT_THROW_IF(PARAM_ERROR, path[0] == '\0'); FileImpl new_impl; new_impl.open_(path); new_impl.swap(this); } void FileImpl::close() { FileImpl new_impl; new_impl.swap(this); } #ifdef WIN32 void FileImpl::swap(FileImpl *rhs) { std::swap(ptr_, rhs->ptr_); std::swap(size_, rhs->size_); std::swap(file_, rhs->file_); std::swap(map_, rhs->map_); std::swap(addr_, rhs->addr_); } void FileImpl::create_(const char *path, UInt64 size) { if ((path != NULL) && (path[0] != '\0')) { file_ = ::CreateFileA(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); GRN_DAT_THROW_IF(IO_ERROR, file_ == INVALID_HANDLE_VALUE); const LONG size_low = static_cast<LONG>(size & 0xFFFFFFFFU); LONG size_high = static_cast<LONG>(size >> 32); const DWORD file_pos = ::SetFilePointer(file_, size_low, &size_high, FILE_BEGIN); GRN_DAT_THROW_IF(IO_ERROR, (file_pos == INVALID_SET_FILE_POINTER) && (::GetLastError() != 0)); GRN_DAT_THROW_IF(IO_ERROR, ::SetEndOfFile(file_) == 0); map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, 0, 0, NULL); GRN_DAT_THROW_IF(IO_ERROR, map_ == INVALID_HANDLE_VALUE); } else { const DWORD size_low = static_cast<DWORD>(size & 0xFFFFFFFFU); const DWORD size_high = static_cast<DWORD>(size >> 32); map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, size_high, size_low, NULL); GRN_DAT_THROW_IF(IO_ERROR, map_ == INVALID_HANDLE_VALUE); } addr_ = ::MapViewOfFile(map_, FILE_MAP_WRITE, 0, 0, 0); GRN_DAT_THROW_IF(IO_ERROR, addr_ == NULL); ptr_ = addr_; size_ = static_cast< ::size_t>(size); } void FileImpl::open_(const char *path) { struct __stat64 st; GRN_DAT_THROW_IF(IO_ERROR, ::_stat64(path, &st) == -1); GRN_DAT_THROW_IF(IO_ERROR, st.st_size == 0); GRN_DAT_THROW_IF(IO_ERROR, static_cast<UInt64>(st.st_size) > std::numeric_limits< ::size_t>::max()); file_ = ::CreateFileA(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); GRN_DAT_THROW_IF(IO_ERROR, file_ == NULL); map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, 0, 0, NULL); GRN_DAT_THROW_IF(IO_ERROR, map_ == NULL); addr_ = ::MapViewOfFile(map_, FILE_MAP_READ, 0, 0, 0); GRN_DAT_THROW_IF(IO_ERROR, addr_ == NULL); ptr_ = addr_; size_ = static_cast< ::size_t>(st.st_size); } #else // WIN32 void FileImpl::swap(FileImpl *rhs) { std::swap(ptr_, rhs->ptr_); std::swap(size_, rhs->size_); std::swap(fd_, rhs->fd_); std::swap(addr_, rhs->addr_); std::swap(length_, rhs->length_); } void FileImpl::create_(const char *path, UInt64 size) { GRN_DAT_THROW_IF(PARAM_ERROR, size > static_cast<UInt64>(std::numeric_limits< ::off_t>::max())); if ((path != NULL) && (path[0] != '\0')) { fd_ = ::open(path, O_RDWR | O_CREAT | O_TRUNC, 0666); GRN_DAT_THROW_IF(IO_ERROR, fd_ == -1); const ::off_t file_size = static_cast< ::off_t>(size); GRN_DAT_THROW_IF(IO_ERROR, ::ftruncate(fd_, file_size) == -1); } #ifdef MAP_ANONYMOUS const int flags = (fd_ == -1) ? (MAP_PRIVATE | MAP_ANONYMOUS) : MAP_SHARED; #else // MAP_ANONYMOUS const int flags = (fd_ == -1) ? (MAP_PRIVATE | MAP_ANON) : MAP_SHARED; #endif // MAP_ANONYMOUS length_ = static_cast< ::size_t>(size); #ifdef MAP_HUGETLB addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, flags | MAP_HUGETLB, fd_, 0); #endif // MAP_HUGETLB if (addr_ == MAP_FAILED) { addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, flags, fd_, 0); GRN_DAT_THROW_IF(IO_ERROR, addr_ == MAP_FAILED); } ptr_ = addr_; size_ = length_; } void FileImpl::open_(const char *path) { struct stat st; GRN_DAT_THROW_IF(IO_ERROR, ::stat(path, &st) == -1); GRN_DAT_THROW_IF(IO_ERROR, (st.st_mode & S_IFMT) != S_IFREG); GRN_DAT_THROW_IF(IO_ERROR, st.st_size == 0); GRN_DAT_THROW_IF(IO_ERROR, static_cast<UInt64>(st.st_size) > std::numeric_limits< ::size_t>::max()); fd_ = ::open(path, O_RDWR); GRN_DAT_THROW_IF(IO_ERROR, fd_ == -1); length_ = static_cast<std::size_t>(st.st_size); addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0); GRN_DAT_THROW_IF(IO_ERROR, addr_ == MAP_FAILED); ptr_ = addr_; size_ = length_; } #endif // WIN32 } // namespace dat } // namespace grn <commit_msg>fixed a bug that grn_dat calls mmap() with FILE_MAP_READ.<commit_after>/* -*- c-basic-offset: 2 -*- */ /* Copyright(C) 2011 Brazil 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 "file-impl.hpp" #include <sys/types.h> #include <sys/stat.h> #ifdef WIN32 # ifdef min # undef min # endif // min # ifdef max # undef max # endif // max #else // WIN32 #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #endif // WIN32 #include <algorithm> #include <limits> namespace grn { namespace dat { #ifdef WIN32 FileImpl::FileImpl() : ptr_(NULL), size_(0), file_(INVALID_HANDLE_VALUE), map_(INVALID_HANDLE_VALUE), addr_(NULL) {} FileImpl::~FileImpl() { if (addr_ != NULL) { ::UnmapViewOfFile(addr_); } if (map_ != INVALID_HANDLE_VALUE) { ::CloseHandle(map_); } if (file_ != INVALID_HANDLE_VALUE) { ::CloseHandle(file_); } } #else // WIN32 FileImpl::FileImpl() : ptr_(NULL), size_(0), fd_(-1), addr_(MAP_FAILED), length_(0) {} FileImpl::~FileImpl() { if (addr_ != MAP_FAILED) { ::munmap(addr_, length_); } if (fd_ != -1) { ::close(fd_); } } #endif // WIN32 void FileImpl::create(const char *path, UInt64 size) { GRN_DAT_THROW_IF(PARAM_ERROR, size == 0); GRN_DAT_THROW_IF(PARAM_ERROR, size > static_cast<UInt64>(std::numeric_limits< ::size_t>::max())); FileImpl new_impl; new_impl.create_(path, size); new_impl.swap(this); } void FileImpl::open(const char *path) { GRN_DAT_THROW_IF(PARAM_ERROR, path == NULL); GRN_DAT_THROW_IF(PARAM_ERROR, path[0] == '\0'); FileImpl new_impl; new_impl.open_(path); new_impl.swap(this); } void FileImpl::close() { FileImpl new_impl; new_impl.swap(this); } #ifdef WIN32 void FileImpl::swap(FileImpl *rhs) { std::swap(ptr_, rhs->ptr_); std::swap(size_, rhs->size_); std::swap(file_, rhs->file_); std::swap(map_, rhs->map_); std::swap(addr_, rhs->addr_); } void FileImpl::create_(const char *path, UInt64 size) { if ((path != NULL) && (path[0] != '\0')) { file_ = ::CreateFileA(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); GRN_DAT_THROW_IF(IO_ERROR, file_ == INVALID_HANDLE_VALUE); const LONG size_low = static_cast<LONG>(size & 0xFFFFFFFFU); LONG size_high = static_cast<LONG>(size >> 32); const DWORD file_pos = ::SetFilePointer(file_, size_low, &size_high, FILE_BEGIN); GRN_DAT_THROW_IF(IO_ERROR, (file_pos == INVALID_SET_FILE_POINTER) && (::GetLastError() != 0)); GRN_DAT_THROW_IF(IO_ERROR, ::SetEndOfFile(file_) == 0); map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, 0, 0, NULL); GRN_DAT_THROW_IF(IO_ERROR, map_ == INVALID_HANDLE_VALUE); } else { const DWORD size_low = static_cast<DWORD>(size & 0xFFFFFFFFU); const DWORD size_high = static_cast<DWORD>(size >> 32); map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, size_high, size_low, NULL); GRN_DAT_THROW_IF(IO_ERROR, map_ == INVALID_HANDLE_VALUE); } addr_ = ::MapViewOfFile(map_, FILE_MAP_WRITE, 0, 0, 0); GRN_DAT_THROW_IF(IO_ERROR, addr_ == NULL); ptr_ = addr_; size_ = static_cast< ::size_t>(size); } void FileImpl::open_(const char *path) { struct __stat64 st; GRN_DAT_THROW_IF(IO_ERROR, ::_stat64(path, &st) == -1); GRN_DAT_THROW_IF(IO_ERROR, st.st_size == 0); GRN_DAT_THROW_IF(IO_ERROR, static_cast<UInt64>(st.st_size) > std::numeric_limits< ::size_t>::max()); file_ = ::CreateFileA(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); GRN_DAT_THROW_IF(IO_ERROR, file_ == NULL); map_ = ::CreateFileMapping(file_, NULL, PAGE_READWRITE, 0, 0, NULL); GRN_DAT_THROW_IF(IO_ERROR, map_ == NULL); addr_ = ::MapViewOfFile(map_, FILE_MAP_WRITE, 0, 0, 0); GRN_DAT_THROW_IF(IO_ERROR, addr_ == NULL); ptr_ = addr_; size_ = static_cast< ::size_t>(st.st_size); } #else // WIN32 void FileImpl::swap(FileImpl *rhs) { std::swap(ptr_, rhs->ptr_); std::swap(size_, rhs->size_); std::swap(fd_, rhs->fd_); std::swap(addr_, rhs->addr_); std::swap(length_, rhs->length_); } void FileImpl::create_(const char *path, UInt64 size) { GRN_DAT_THROW_IF(PARAM_ERROR, size > static_cast<UInt64>(std::numeric_limits< ::off_t>::max())); if ((path != NULL) && (path[0] != '\0')) { fd_ = ::open(path, O_RDWR | O_CREAT | O_TRUNC, 0666); GRN_DAT_THROW_IF(IO_ERROR, fd_ == -1); const ::off_t file_size = static_cast< ::off_t>(size); GRN_DAT_THROW_IF(IO_ERROR, ::ftruncate(fd_, file_size) == -1); } #ifdef MAP_ANONYMOUS const int flags = (fd_ == -1) ? (MAP_PRIVATE | MAP_ANONYMOUS) : MAP_SHARED; #else // MAP_ANONYMOUS const int flags = (fd_ == -1) ? (MAP_PRIVATE | MAP_ANON) : MAP_SHARED; #endif // MAP_ANONYMOUS length_ = static_cast< ::size_t>(size); #ifdef MAP_HUGETLB addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, flags | MAP_HUGETLB, fd_, 0); #endif // MAP_HUGETLB if (addr_ == MAP_FAILED) { addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, flags, fd_, 0); GRN_DAT_THROW_IF(IO_ERROR, addr_ == MAP_FAILED); } ptr_ = addr_; size_ = length_; } void FileImpl::open_(const char *path) { struct stat st; GRN_DAT_THROW_IF(IO_ERROR, ::stat(path, &st) == -1); GRN_DAT_THROW_IF(IO_ERROR, (st.st_mode & S_IFMT) != S_IFREG); GRN_DAT_THROW_IF(IO_ERROR, st.st_size == 0); GRN_DAT_THROW_IF(IO_ERROR, static_cast<UInt64>(st.st_size) > std::numeric_limits< ::size_t>::max()); fd_ = ::open(path, O_RDWR); GRN_DAT_THROW_IF(IO_ERROR, fd_ == -1); length_ = static_cast<std::size_t>(st.st_size); addr_ = ::mmap(NULL, length_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0); GRN_DAT_THROW_IF(IO_ERROR, addr_ == MAP_FAILED); ptr_ = addr_; size_ = length_; } #endif // WIN32 } // namespace dat } // namespace grn <|endoftext|>
<commit_before>#pragma once #include <c/EXIT_FAILURE.h> #include <c/_Exit.h> #if defined(__unix__) # include <c/strlen.h> # include <os/write.hxx> # define _write(string) ::os::write(2, string, strlen(string)) #else # error #endif __attribute__((__noreturn__, __nothrow__)) static inline void __debug_error(const char* kind, const char* file, const char* function, __attribute__((__unused__)) unsigned line, const char* message) { // Super naive. _write("\033[31;1m"); _write(kind); _write("\033[0m"); if (message) { _write("\n • message: "); _write(message); } _write("\n • function: "); _write(function); _write("\n • file: "); _write(file); _write("\n • line: TODO"); _write("\n"); _Exit(EXIT_FAILURE); } #undef _write <commit_msg>Missing some c++-ification<commit_after>#pragma once #include <c/EXIT_FAILURE.h> #include <c/_Exit.h> #if defined(__unix__) # include <c/strlen.h> # include <os/write.hxx> # define _write(string) ::os::write(2, string, strlen(string)) #else # error #endif namespace debug { __attribute__((__noreturn__, __nothrow__)) static inline void __error(const char* kind, const char* file, const char* function, __attribute__((__unused__)) unsigned line, const char* message) { // Super naive. _write("\033[31;1m"); _write(kind); _write("\033[0m"); if (message) { _write("\n • message: "); _write(message); } _write("\n • function: "); _write(function); _write("\n • file: "); _write(file); _write("\n • line: TODO"); _write("\n"); _Exit(EXIT_FAILURE); } } #undef _write <|endoftext|>
<commit_before>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "superfluxextractor.h" #include "algorithmfactory.h" #include "essentiamath.h" #include "poolstorage.h" #include "copy.h" using namespace std; using namespace essentia; using namespace essentia::streaming; const char* SuperFluxExtractor::name = "SuperFluxExtractor"; const char* SuperFluxExtractor::category = "Rhythm"; const char* SuperFluxExtractor::description = DOC("This algorithm detects onsets given an audio signal using SuperFlux algorithm [1]. This implementation is based on the available reference implementation in python [2]. The algorithm computes spectrum of the input signal, summarizes it into triangular band energies, and computes a onset detection function based on spectral flux tracking spectral trajectories with a maximum filter (SuperFluxNovelty). The peaks of the function are then detected (SuperFluxPeaks).\n" "\n" "References:\n" " [1] Böck, S. and Widmer, G., Maximum Filter Vibrato Suppression for Onset\n" " Detection, Proceedings of the 16th International Conference on Digital\n" " Audio Effects (DAFx-13), 2013\n" " [2] https://github.com/CPJKU/SuperFlux"); SuperFluxExtractor::SuperFluxExtractor() : _configured(false) { declareInput(_signal, "signal", "the input audio signal"); declareOutput(_onsets, "onsets","lists of onsets"); // create network (instantiate algorithms) createInnerNetwork(); // wire all this up! _signal >> _frameCutter->input("signal"); _frameCutter->output("frame") >> _w->input("frame"); _w->output("frame") >> _spectrum->input("frame"); _spectrum->output("spectrum") >> _triF->input("spectrum"); _triF->output("bands") >> _superFluxF->input("bands"); _superFluxF->output("differences") >> _superFluxP->input("novelty"); _superFluxP->output("peaks") >> _onsets; _network = new scheduler::Network(_frameCutter); } void SuperFluxExtractor::createInnerNetwork() { AlgorithmFactory& factory = AlgorithmFactory::instance(); _frameCutter = factory.create("FrameCutter"); _w = factory.create("Windowing", "type", "hann"); _spectrum = factory.create("Spectrum"); _triF = factory.create("TriangularBands", "log", false); _superFluxP = factory.create("SuperFluxPeaks"); _superFluxF = factory.create("SuperFluxNovelty", "binWidth", 8, "frameWidth", 2); _vout = new essentia::streaming::VectorOutput<Real>(); } void SuperFluxExtractor::configure() { int frameSize = parameter("frameSize").toInt(); int hopSize = parameter("hopSize").toInt(); Real sampleRate = parameter("sampleRate").toReal(); _frameCutter->configure("frameSize", frameSize, "hopSize", hopSize, "startFromZero", false, "validFrameThresholdRatio", 0, "lastFrameToEndOfFile", false, "silentFrames", "keep"); _superFluxP->configure(INHERIT("ratioThreshold"), INHERIT("threshold"), "frameRate", sampleRate/hopSize, INHERIT("combine"), "pre_avg", 100., "pre_max", 30.); } SuperFluxExtractor::~SuperFluxExtractor() { clearAlgos(); } void SuperFluxExtractor::clearAlgos() { if (!_configured) return; delete _network; } namespace essentia { namespace standard { const char* SuperFluxExtractor::name = streaming::SuperFluxExtractor::name; const char* SuperFluxExtractor::category = streaming::SuperFluxExtractor::category; const char* SuperFluxExtractor::description = streaming::SuperFluxExtractor::description; SuperFluxExtractor::SuperFluxExtractor() { declareInput(_signal, "signal", "the audio input signal"); declareOutput(_onsets, "onsets", "the onsets times"); createInnerNetwork(); } SuperFluxExtractor::~SuperFluxExtractor() { delete _network; } void SuperFluxExtractor::reset() { _network->reset(); } void SuperFluxExtractor::configure() { _SuperFluxExtractor->configure(INHERIT("frameSize"), INHERIT("hopSize"),INHERIT("sampleRate"),INHERIT("threshold"),INHERIT("combine"),INHERIT("ratioThreshold")); } void SuperFluxExtractor::createInnerNetwork() { _SuperFluxExtractor = streaming::AlgorithmFactory::create("SuperFluxExtractor"); _vectorInput = new streaming::VectorInput<Real>(); _vectorOut = new streaming::VectorOutput<std::vector<Real> >(); *_vectorInput >> _SuperFluxExtractor->input("signal"); _SuperFluxExtractor->output("onsets") >> _vectorOut->input("data"); //PC(_pool, "onsets.times"); _network = new scheduler::Network(_vectorInput); } void SuperFluxExtractor::compute() { const vector<Real>& signal = _signal.get(); vector<Real>& onsets = _onsets.get(); vector<vector<Real> > ll; _vectorInput->setVector(&signal); _vectorOut->setVector(&ll); _network->run(); onsets = ll[0]; // FIXME will this ever fail? } } // namespace standard } // namespace essentia <commit_msg>Fix segfault in case of the empty audio input<commit_after>/* * Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra * * This file is part of Essentia * * Essentia is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation (FSF), either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the Affero GNU General Public License * version 3 along with this program. If not, see http://www.gnu.org/licenses/ */ #include "superfluxextractor.h" #include "algorithmfactory.h" #include "essentiamath.h" #include "poolstorage.h" #include "copy.h" using namespace std; using namespace essentia; using namespace essentia::streaming; const char* SuperFluxExtractor::name = "SuperFluxExtractor"; const char* SuperFluxExtractor::category = "Rhythm"; const char* SuperFluxExtractor::description = DOC("This algorithm detects onsets given an audio signal using SuperFlux algorithm [1]. This implementation is based on the available reference implementation in python [2]. The algorithm computes spectrum of the input signal, summarizes it into triangular band energies, and computes a onset detection function based on spectral flux tracking spectral trajectories with a maximum filter (SuperFluxNovelty). The peaks of the function are then detected (SuperFluxPeaks).\n" "\n" "References:\n" " [1] Böck, S. and Widmer, G., Maximum Filter Vibrato Suppression for Onset\n" " Detection, Proceedings of the 16th International Conference on Digital\n" " Audio Effects (DAFx-13), 2013\n" " [2] https://github.com/CPJKU/SuperFlux"); SuperFluxExtractor::SuperFluxExtractor() : _configured(false) { declareInput(_signal, "signal", "the input audio signal"); declareOutput(_onsets, "onsets","lists of onsets"); // create network (instantiate algorithms) createInnerNetwork(); // wire all this up! _signal >> _frameCutter->input("signal"); _frameCutter->output("frame") >> _w->input("frame"); _w->output("frame") >> _spectrum->input("frame"); _spectrum->output("spectrum") >> _triF->input("spectrum"); _triF->output("bands") >> _superFluxF->input("bands"); _superFluxF->output("differences") >> _superFluxP->input("novelty"); _superFluxP->output("peaks") >> _onsets; _network = new scheduler::Network(_frameCutter); } void SuperFluxExtractor::createInnerNetwork() { AlgorithmFactory& factory = AlgorithmFactory::instance(); _frameCutter = factory.create("FrameCutter"); _w = factory.create("Windowing", "type", "hann"); _spectrum = factory.create("Spectrum"); _triF = factory.create("TriangularBands", "log", false); _superFluxP = factory.create("SuperFluxPeaks"); _superFluxF = factory.create("SuperFluxNovelty", "binWidth", 8, "frameWidth", 2); _vout = new essentia::streaming::VectorOutput<Real>(); } void SuperFluxExtractor::configure() { int frameSize = parameter("frameSize").toInt(); int hopSize = parameter("hopSize").toInt(); Real sampleRate = parameter("sampleRate").toReal(); _frameCutter->configure("frameSize", frameSize, "hopSize", hopSize, "startFromZero", false, "validFrameThresholdRatio", 0, "lastFrameToEndOfFile", false, "silentFrames", "keep"); _superFluxP->configure(INHERIT("ratioThreshold"), INHERIT("threshold"), "frameRate", sampleRate/hopSize, INHERIT("combine"), "pre_avg", 100., "pre_max", 30.); } SuperFluxExtractor::~SuperFluxExtractor() { clearAlgos(); } void SuperFluxExtractor::clearAlgos() { if (!_configured) return; delete _network; } namespace essentia { namespace standard { const char* SuperFluxExtractor::name = streaming::SuperFluxExtractor::name; const char* SuperFluxExtractor::category = streaming::SuperFluxExtractor::category; const char* SuperFluxExtractor::description = streaming::SuperFluxExtractor::description; SuperFluxExtractor::SuperFluxExtractor() { declareInput(_signal, "signal", "the audio input signal"); declareOutput(_onsets, "onsets", "the onsets times"); createInnerNetwork(); } SuperFluxExtractor::~SuperFluxExtractor() { delete _network; } void SuperFluxExtractor::reset() { _network->reset(); } void SuperFluxExtractor::configure() { _SuperFluxExtractor->configure(INHERIT("frameSize"), INHERIT("hopSize"),INHERIT("sampleRate"),INHERIT("threshold"),INHERIT("combine"),INHERIT("ratioThreshold")); } void SuperFluxExtractor::createInnerNetwork() { _SuperFluxExtractor = streaming::AlgorithmFactory::create("SuperFluxExtractor"); _vectorInput = new streaming::VectorInput<Real>(); _vectorOut = new streaming::VectorOutput<std::vector<Real> >(); *_vectorInput >> _SuperFluxExtractor->input("signal"); _SuperFluxExtractor->output("onsets") >> _vectorOut->input("data"); //PC(_pool, "onsets.times"); _network = new scheduler::Network(_vectorInput); } void SuperFluxExtractor::compute() { const vector<Real>& signal = _signal.get(); vector<Real>& onsets = _onsets.get(); vector<vector<Real> > ll; _vectorInput->setVector(&signal); _vectorOut->setVector(&ll); _network->run(); if (ll.size()) { onsets = ll[0]; // FIXME will this ever fail? } else { onsets.clear(); } } } // namespace standard } // namespace essentia <|endoftext|>
<commit_before>/* ** Copyright 2009 MERETHIS ** This file is part of CentreonBroker. ** ** CentreonBroker 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. ** ** CentreonBroker 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 CentreonBroker. If not, see <http://www.gnu.org/licenses/>. ** ** For more information : contact@centreon.com */ #include <assert.h> #include <time.h> #include "correlation/correlator.h" #include "correlation/parser.h" #include "events/host.h" #include "events/issue.h" #include "events/issue_update.h" #include "exception.h" #include "multiplexing/publisher.h" using namespace Correlation; /************************************** * * * Static Objects * * * **************************************/ // Dispatch table. void (Correlator::* Correlator::dispatch_table[])(Events::Event&) = { &Correlator::CorrelateNothing, // UNKNOWN &Correlator::CorrelateNothing, // ACKNOWLEDGEMENT &Correlator::CorrelateNothing, // COMMENT &Correlator::CorrelateNothing, // DOWNTIME &Correlator::CorrelateNothing, // HOST &Correlator::CorrelateNothing, // HOSTCHECK &Correlator::CorrelateNothing, // HOSTDEPENDENCY &Correlator::CorrelateNothing, // HOSTGROUP &Correlator::CorrelateNothing, // HOSTGROUPMEMBER &Correlator::CorrelateNothing, // HOSTPARENT &Correlator::CorrelateHostStatus, // HOSTSTATUS &Correlator::CorrelateNothing, // ISSUE &Correlator::CorrelateNothing, // ISSUEUPDATE &Correlator::CorrelateNothing, // LOG &Correlator::CorrelateNothing, // PROGRAM &Correlator::CorrelateNothing, // PROGRAMSTATUS &Correlator::CorrelateNothing, // SERVICE &Correlator::CorrelateNothing, // SERVICECHECK &Correlator::CorrelateNothing, // SERVICEDEPENDENCY &Correlator::CorrelateNothing, // SERVICEGROUP &Correlator::CorrelateNothing, // SERVICEGROUPMEMBER &Correlator::CorrelateServiceStatus // SERVICESTATUS }; /** * Determine whether or not a node should have the unknown state. * * \param[in] node Node to check. * * \return true if the node should be unknown. */ static bool ShouldBeUnknown(const Node& node) { bool all_parents_down; bool one_dependency_down; // If node has no parents, then all_parents_down will be false. if (node.parents.size()) { all_parents_down = true; for (std::list<Node*>::const_iterator it = node.parents.begin(), end = node.parents.end(); it != end; ++it) all_parents_down = (all_parents_down && (*it)->state); } else all_parents_down = false; // Check dependencies. one_dependency_down = false; for (std::list<Node*>::const_iterator it = node.depends_on.begin(), end = node.depends_on.end(); it != end; ++it) one_dependency_down = (one_dependency_down || (*it)->state); return (all_parents_down || one_dependency_down); } /************************************** * * * Private Methods * * * **************************************/ /** * Process a HostStatus or ServiceStatus event. * * \param[in] event Event to process. * \param[in] is_host true if the event is a HostStatus. */ void Correlator::CorrelateHostServiceStatus(Events::Event& event, bool is_host) { Events::HostServiceStatus& hss( *static_cast<Events::HostServiceStatus*>(&event)); std::map<int, Node>::iterator hss_it; // Find node in appropriate list. if (is_host) { if ((hss_it = this->hosts_.find(hss.id)) == this->hosts_.end()) throw (Exception(0, "Invalid host status provided.")); } else if ((hss_it = this->services_.find(hss.id)) == this->services_.end()) throw (Exception(0, "Invalid service status provided.")); Node& node(hss_it->second); if (node.state != hss.current_state) { if (hss.current_state) { Events::Issue* issue; // Check if unknown flag should be set. if (ShouldBeUnknown(node)) { hss.current_state = 3; // UNKNOWN issue = this->FindRelatedIssue(node); } // Warning -> Critical or Critical -> Warning. else if (node.state && hss.current_state) { issue = this->FindRelatedIssue(node); } else { // Set issue. node.issue = new Events::Issue; node.issue->Link(); node.issue->host_id = node.host_id; node.issue->output = hss.output; node.issue->service_id = node.service_id; node.issue->state = hss.current_state; node.issue->start_time = time(NULL); // Store issue. (XXX : not safe) this->events_.push_back(new Events::Issue(*(node.issue))); // Get current issue. issue = node.issue; } // Update state. node.state = hss.current_state; // Loop children. for (std::list<Node*>::iterator it = node.children.begin(), end = node.children.end(); it != end; ++it) if ((*it)->issue && ShouldBeUnknown(**it)) { std::auto_ptr<Events::IssueUpdate> update; (*it)->state = 3; update.reset(new Events::IssueUpdate); update->host_id1 = (*it)->host_id; update->service_id1 = (*it)->service_id; update->start_time1 = (*it)->issue->start_time; update->host_id2 = node.host_id; update->service_id2 = node.service_id; update->start_time2 = issue->start_time; update->update = Events::IssueUpdate::MERGE; this->events_.push_back(update.get()); update.release(); delete ((*it)->issue); (*it)->issue = NULL; } // Loop dependant nodes. for (std::list<Node*>::iterator it = node.depended_by.begin(), end = node.depended_by.end(); it != end; ++it) if ((*it)->issue && ShouldBeUnknown(**it)) { std::auto_ptr<Events::IssueUpdate> update; (*it)->state = 3; update.reset(new Events::IssueUpdate); update->host_id1 = (*it)->host_id; update->service_id1 = (*it)->service_id; update->start_time1 = (*it)->issue->start_time; update->host_id2 = node.host_id; update->service_id2 = node.service_id; update->start_time2 = issue->start_time; update->update = Events::IssueUpdate::MERGE; this->events_.push_back(update.get()); update.release(); delete ((*it)->issue); (*it)->issue = NULL; } } else { // Issue is over. node.state = hss.current_state; if (node.issue) { for (std::list<Node*>::iterator it = node.children.begin(), end = node.children.end(); it != end; ++it) if ((*it)->state && !(*it)->issue) { node.issue->Link(); (*it)->issue = node.issue; } for (std::list<Node*>::iterator it = node.depended_by.begin(), end = node.depended_by.end(); it != end; ++it) if ((*it)->state && !(*it)->issue) { node.issue->Link(); (*it)->issue = node.issue; } if (node.issue->Unlink()) { node.issue->end_time = time(NULL); this->events_.push_back(node.issue); } node.issue = NULL; } } } node.state = hss.current_state; return ; } /** * Process a HostStatus event. * * \param[in] event Event to process. */ void Correlator::CorrelateHostStatus(Events::Event& event) { this->CorrelateHostServiceStatus(event, true); return ; } /** * Process a Log event. */ void Correlator::CorrelateLog(Events::Event& event) { Events::Log* log(static_cast<Events::Log*>(&event)); std::map<int, Node>::iterator it; if (log->service_id) it = this->services_.find(log->service_id); else it = this->hosts_.find(log->host_id); if ((it != this->hosts_.end()) && (it == this->services_.end()) && it->second.state) { Events::Issue* issue; issue = this->FindRelatedIssue(it->second); if (issue) log->issue_start_time = issue->start_time; } return ; } /** * Do nothing (callback called on untreated event types). * * \param[in] event Unused. */ void Correlator::CorrelateNothing(Events::Event& event) { (void)event; return ; } /** * Process a ServiceStatus event. * * \param[in] event Event to process. */ void Correlator::CorrelateServiceStatus(Events::Event& event) { this->CorrelateHostServiceStatus(event, false); return ; } /** * Browse the parenting tree of the given node and find its ancestor's issue * which causes it to be in undetermined state. * * \param[in] node Base node. * * \return The issue associated with node. */ Events::Issue* Correlator::FindRelatedIssue(Node& node) { Events::Issue* issue; if (node.state && node.issue) issue = node.issue; else { issue = NULL; for (std::list<Node*>::iterator it = node.depends_on.begin(), end = node.depends_on.end(); it != end; ++it) if ((*it)->state) { issue = this->FindRelatedIssue(**it); break ; } if (!issue) { for (std::list<Node*>::iterator it = node.parents.begin(), end = node.parents.end(); it != end; ++it) if ((*it)->state) { issue = this->FindRelatedIssue(**it); break ; } } } return (issue); } /** * \brief Copy internal members. * * This method is used by the copy constructor and the assignment operator. * * \param[in] correlator Object to copy. */ void Correlator::InternalCopy(const Correlator& correlator) { this->hosts_ = correlator.hosts_; this->services_ = correlator.services_; return ; } /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. */ Correlator::Correlator() { assert((sizeof(dispatch_table) / sizeof(*dispatch_table)) == Events::Event::EVENT_TYPES_NB); } /** * Copy constructor. * * \param[in] correlator Object to copy. */ Correlator::Correlator(const Correlator& correlator) { this->InternalCopy(correlator); } /** * Destructor. */ Correlator::~Correlator() {} /** * Assignment operator overload. * * \param[in] correlator Object to copy. * * \return *this */ Correlator& Correlator::operator=(const Correlator& correlator) { this->InternalCopy(correlator); return (*this); } /** * Treat a new event. * * \param[inout] event Event to process. */ void Correlator::Event(Events::Event& event) { (this->*dispatch_table[event.GetType()])(event); return ; } /** * Get the next available correlated event. * * \return The next available correlated event. */ Events::Event* Correlator::Event() { Events::Event* event; if (this->events_.empty()) event = NULL; else { event = this->events_.front(); this->events_.pop_front(); } return (event); } /** * Load a correlation file. * * \param[in] correlation_file Path to a file containing host and service * relationships. */ void Correlator::Load(const char* correlation_file) { Parser parser; parser.Parse(correlation_file, this->hosts_, this->services_); return ; } <commit_msg>Resolved minor bug in log-issue linking.<commit_after>/* ** Copyright 2009 MERETHIS ** This file is part of CentreonBroker. ** ** CentreonBroker 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. ** ** CentreonBroker 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 CentreonBroker. If not, see <http://www.gnu.org/licenses/>. ** ** For more information : contact@centreon.com */ #include <assert.h> #include <time.h> #include "correlation/correlator.h" #include "correlation/parser.h" #include "events/host.h" #include "events/issue.h" #include "events/issue_update.h" #include "exception.h" #include "multiplexing/publisher.h" using namespace Correlation; /************************************** * * * Static Objects * * * **************************************/ // Dispatch table. void (Correlator::* Correlator::dispatch_table[])(Events::Event&) = { &Correlator::CorrelateNothing, // UNKNOWN &Correlator::CorrelateNothing, // ACKNOWLEDGEMENT &Correlator::CorrelateNothing, // COMMENT &Correlator::CorrelateNothing, // DOWNTIME &Correlator::CorrelateNothing, // HOST &Correlator::CorrelateNothing, // HOSTCHECK &Correlator::CorrelateNothing, // HOSTDEPENDENCY &Correlator::CorrelateNothing, // HOSTGROUP &Correlator::CorrelateNothing, // HOSTGROUPMEMBER &Correlator::CorrelateNothing, // HOSTPARENT &Correlator::CorrelateHostStatus, // HOSTSTATUS &Correlator::CorrelateNothing, // ISSUE &Correlator::CorrelateNothing, // ISSUEUPDATE &Correlator::CorrelateNothing, // LOG &Correlator::CorrelateNothing, // PROGRAM &Correlator::CorrelateNothing, // PROGRAMSTATUS &Correlator::CorrelateNothing, // SERVICE &Correlator::CorrelateNothing, // SERVICECHECK &Correlator::CorrelateNothing, // SERVICEDEPENDENCY &Correlator::CorrelateNothing, // SERVICEGROUP &Correlator::CorrelateNothing, // SERVICEGROUPMEMBER &Correlator::CorrelateServiceStatus // SERVICESTATUS }; /** * Determine whether or not a node should have the unknown state. * * \param[in] node Node to check. * * \return true if the node should be unknown. */ static bool ShouldBeUnknown(const Node& node) { bool all_parents_down; bool one_dependency_down; // If node has no parents, then all_parents_down will be false. if (node.parents.size()) { all_parents_down = true; for (std::list<Node*>::const_iterator it = node.parents.begin(), end = node.parents.end(); it != end; ++it) all_parents_down = (all_parents_down && (*it)->state); } else all_parents_down = false; // Check dependencies. one_dependency_down = false; for (std::list<Node*>::const_iterator it = node.depends_on.begin(), end = node.depends_on.end(); it != end; ++it) one_dependency_down = (one_dependency_down || (*it)->state); return (all_parents_down || one_dependency_down); } /************************************** * * * Private Methods * * * **************************************/ /** * Process a HostStatus or ServiceStatus event. * * \param[in] event Event to process. * \param[in] is_host true if the event is a HostStatus. */ void Correlator::CorrelateHostServiceStatus(Events::Event& event, bool is_host) { Events::HostServiceStatus& hss( *static_cast<Events::HostServiceStatus*>(&event)); std::map<int, Node>::iterator hss_it; // Find node in appropriate list. if (is_host) { if ((hss_it = this->hosts_.find(hss.id)) == this->hosts_.end()) throw (Exception(0, "Invalid host status provided.")); } else if ((hss_it = this->services_.find(hss.id)) == this->services_.end()) throw (Exception(0, "Invalid service status provided.")); Node& node(hss_it->second); if (node.state != hss.current_state) { if (hss.current_state) { Events::Issue* issue; // Check if unknown flag should be set. if (ShouldBeUnknown(node)) { hss.current_state = 3; // UNKNOWN issue = this->FindRelatedIssue(node); } // Warning -> Critical or Critical -> Warning. else if (node.state && hss.current_state) { issue = this->FindRelatedIssue(node); } else { // Set issue. node.issue = new Events::Issue; node.issue->Link(); node.issue->host_id = node.host_id; node.issue->output = hss.output; node.issue->service_id = node.service_id; node.issue->state = hss.current_state; node.issue->start_time = time(NULL); // Store issue. (XXX : not safe) this->events_.push_back(new Events::Issue(*(node.issue))); // Get current issue. issue = node.issue; } // Update state. node.state = hss.current_state; // Loop children. for (std::list<Node*>::iterator it = node.children.begin(), end = node.children.end(); it != end; ++it) if ((*it)->issue && ShouldBeUnknown(**it)) { std::auto_ptr<Events::IssueUpdate> update; (*it)->state = 3; update.reset(new Events::IssueUpdate); update->host_id1 = (*it)->host_id; update->service_id1 = (*it)->service_id; update->start_time1 = (*it)->issue->start_time; update->host_id2 = node.host_id; update->service_id2 = node.service_id; update->start_time2 = issue->start_time; update->update = Events::IssueUpdate::MERGE; this->events_.push_back(update.get()); update.release(); delete ((*it)->issue); (*it)->issue = NULL; } // Loop dependant nodes. for (std::list<Node*>::iterator it = node.depended_by.begin(), end = node.depended_by.end(); it != end; ++it) if ((*it)->issue && ShouldBeUnknown(**it)) { std::auto_ptr<Events::IssueUpdate> update; (*it)->state = 3; update.reset(new Events::IssueUpdate); update->host_id1 = (*it)->host_id; update->service_id1 = (*it)->service_id; update->start_time1 = (*it)->issue->start_time; update->host_id2 = node.host_id; update->service_id2 = node.service_id; update->start_time2 = issue->start_time; update->update = Events::IssueUpdate::MERGE; this->events_.push_back(update.get()); update.release(); delete ((*it)->issue); (*it)->issue = NULL; } } else { // Issue is over. node.state = hss.current_state; if (node.issue) { for (std::list<Node*>::iterator it = node.children.begin(), end = node.children.end(); it != end; ++it) if ((*it)->state && !(*it)->issue) { node.issue->Link(); (*it)->issue = node.issue; } for (std::list<Node*>::iterator it = node.depended_by.begin(), end = node.depended_by.end(); it != end; ++it) if ((*it)->state && !(*it)->issue) { node.issue->Link(); (*it)->issue = node.issue; } if (node.issue->Unlink()) { node.issue->end_time = time(NULL); this->events_.push_back(node.issue); } node.issue = NULL; } } } node.state = hss.current_state; return ; } /** * Process a HostStatus event. * * \param[in] event Event to process. */ void Correlator::CorrelateHostStatus(Events::Event& event) { this->CorrelateHostServiceStatus(event, true); return ; } /** * Process a Log event. */ void Correlator::CorrelateLog(Events::Event& event) { Events::Log* log(static_cast<Events::Log*>(&event)); std::map<int, Node>::iterator it; if (log->service_id) it = this->services_.find(log->service_id); else it = this->hosts_.find(log->host_id); if ((it != this->hosts_.end()) && (it != this->services_.end()) && it->second.state) { Events::Issue* issue; issue = this->FindRelatedIssue(it->second); if (issue) log->issue_start_time = issue->start_time; } return ; } /** * Do nothing (callback called on untreated event types). * * \param[in] event Unused. */ void Correlator::CorrelateNothing(Events::Event& event) { (void)event; return ; } /** * Process a ServiceStatus event. * * \param[in] event Event to process. */ void Correlator::CorrelateServiceStatus(Events::Event& event) { this->CorrelateHostServiceStatus(event, false); return ; } /** * Browse the parenting tree of the given node and find its ancestor's issue * which causes it to be in undetermined state. * * \param[in] node Base node. * * \return The issue associated with node. */ Events::Issue* Correlator::FindRelatedIssue(Node& node) { Events::Issue* issue; if (node.state && node.issue) issue = node.issue; else { issue = NULL; for (std::list<Node*>::iterator it = node.depends_on.begin(), end = node.depends_on.end(); it != end; ++it) if ((*it)->state) { issue = this->FindRelatedIssue(**it); break ; } if (!issue) { for (std::list<Node*>::iterator it = node.parents.begin(), end = node.parents.end(); it != end; ++it) if ((*it)->state) { issue = this->FindRelatedIssue(**it); break ; } } } return (issue); } /** * \brief Copy internal members. * * This method is used by the copy constructor and the assignment operator. * * \param[in] correlator Object to copy. */ void Correlator::InternalCopy(const Correlator& correlator) { this->hosts_ = correlator.hosts_; this->services_ = correlator.services_; return ; } /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. */ Correlator::Correlator() { assert((sizeof(dispatch_table) / sizeof(*dispatch_table)) == Events::Event::EVENT_TYPES_NB); } /** * Copy constructor. * * \param[in] correlator Object to copy. */ Correlator::Correlator(const Correlator& correlator) { this->InternalCopy(correlator); } /** * Destructor. */ Correlator::~Correlator() {} /** * Assignment operator overload. * * \param[in] correlator Object to copy. * * \return *this */ Correlator& Correlator::operator=(const Correlator& correlator) { this->InternalCopy(correlator); return (*this); } /** * Treat a new event. * * \param[inout] event Event to process. */ void Correlator::Event(Events::Event& event) { (this->*dispatch_table[event.GetType()])(event); return ; } /** * Get the next available correlated event. * * \return The next available correlated event. */ Events::Event* Correlator::Event() { Events::Event* event; if (this->events_.empty()) event = NULL; else { event = this->events_.front(); this->events_.pop_front(); } return (event); } /** * Load a correlation file. * * \param[in] correlation_file Path to a file containing host and service * relationships. */ void Correlator::Load(const char* correlation_file) { Parser parser; parser.Parse(correlation_file, this->hosts_, this->services_); return ; } <|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. // Provides wifi scan API binding for suitable for typical linux distributions. // Currently, only the NetworkManager API is used, accessed via D-Bus (in turn // accessed via the GLib wrapper). #include "chrome/browser/geolocation/wifi_data_provider_linux.h" #include <dbus/dbus-glib.h> #include <glib.h> #include "base/scoped_ptr.h" #include "base/utf_string_conversions.h" namespace { // The time periods between successive polls of the wifi data. const int kDefaultPollingIntervalMilliseconds = 10 * 1000; // 10s const int kNoChangePollingIntervalMilliseconds = 2 * 60 * 1000; // 2 mins const int kTwoNoChangePollingIntervalMilliseconds = 10 * 60 * 1000; // 10 mins const char kNetworkManagerServiceName[] = "org.freedesktop.NetworkManager"; const char kNetworkManagerPath[] = "/org/freedesktop/NetworkManager"; const char kNetworkManagerInterface[] = "org.freedesktop.NetworkManager"; // From http://projects.gnome.org/NetworkManager/developers/spec.html enum { NM_DEVICE_TYPE_WIFI = 2 }; // Utility wrappers to make various GLib & DBus structs into scoped objects. class ScopedGPtrArrayFree { public: void operator()(GPtrArray* x) const { if (x) g_ptr_array_free(x, TRUE); } }; // Use ScopedGPtrArrayPtr as if it were scoped_ptr<GPtrArray> typedef scoped_ptr_malloc<GPtrArray, ScopedGPtrArrayFree> ScopedGPtrArrayPtr; class ScopedGObjectFree { public: void operator()(void* x) const { if (x) g_object_unref(x); } }; // Use ScopedDBusGProxyPtr as if it were scoped_ptr<DBusGProxy> typedef scoped_ptr_malloc<DBusGProxy, ScopedGObjectFree> ScopedDBusGProxyPtr; // Use ScopedGValue::v as an instance of GValue with automatic cleanup. class ScopedGValue { public: ScopedGValue() : v(empty_gvalue()) { } ~ScopedGValue() { g_value_unset(&v); } static GValue empty_gvalue() { GValue value = {0}; return value; } GValue v; }; // Wifi API binding to NetworkManager, to allow reuse of the polling behavior // defined in WifiDataProviderCommon. // TODO(joth): NetworkManager also allows for notification based handling, // however this will require reworking of the threading code to run a GLib // event loop (GMainLoop). class NetworkManagerWlanApi : public WifiDataProviderCommon::WlanApiInterface { public: NetworkManagerWlanApi(); ~NetworkManagerWlanApi(); // Must be called before any other interface method. Will return false if the // NetworkManager session cannot be created (e.g. not present on this distro), // in which case no other method may be called. bool Init(); // WifiDataProviderCommon::WlanApiInterface bool GetAccessPointData(WifiData::AccessPointDataSet* data); private: // Checks if the last dbus call returned an error. If it did, logs the error // message, frees it and returns true. // This must be called after every dbus call that accepts |&error_| bool CheckError(); // Enumerates the list of available network adapter devices known to // NetworkManager. Ownership of the array (and contained objects) is returned // to the caller. GPtrArray* GetAdapterDeviceList(); // Given the NetworkManager path to a wireless adapater, dumps the wifi scan // results and appends them to |data|. Returns false if a fatal error is // encountered such that the data set could not be populated. bool GetAccessPointsForAdapter(const gchar* adapter_path, WifiData::AccessPointDataSet* data); // Internal method used by |GetAccessPointsForAdapter|, given a wifi access // point proxy retrieves the named property into |value_out|. Returns false if // the property could not be read, or is not of type |expected_gvalue_type|. bool GetAccessPointProperty(DBusGProxy* proxy, const char* property_name, int expected_gvalue_type, GValue* value_out); // Error from the last dbus call. NULL when there's no error. Freed and // cleared by CheckError(). GError* error_; // Connection to the dbus system bus. DBusGConnection* connection_; // Proxy to the network maanger dbus service. ScopedDBusGProxyPtr proxy_; DISALLOW_COPY_AND_ASSIGN(NetworkManagerWlanApi); }; // Convert a wifi frequency to the corresponding channel. Adapted from // geolocaiton/wifilib.cc in googleclient (internal to google). int frquency_in_khz_to_channel(int frequency_khz) { if (frequency_khz >= 2412000 && frequency_khz <= 2472000) // Channels 1-13. return (frequency_khz - 2407000) / 5000; if (frequency_khz == 2484000) return 14; if (frequency_khz > 5000000 && frequency_khz < 6000000) // .11a bands. return (frequency_khz - 5000000) / 5000; // Ignore everything else. return AccessPointData().channel; // invalid channel } NetworkManagerWlanApi::NetworkManagerWlanApi() : error_(NULL), connection_(NULL) { } NetworkManagerWlanApi::~NetworkManagerWlanApi() { proxy_.reset(); if (connection_) { dbus_g_connection_unref(connection_); } DCHECK(!error_) << "Missing a call to CheckError() to clear |error_|"; } bool NetworkManagerWlanApi::Init() { // Chrome DLL init code handles initializing the thread system, so rather than // get caught up with that nonsense here, lets just assert our requirement. CHECK(g_thread_supported()); // We should likely do this higher up too, the docs say it must only be done // once but there's no way to know if it already was or not. dbus_g_thread_init(); // Get a connection to the session bus. connection_ = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error_); if (CheckError()) return false; DCHECK(connection_); proxy_.reset(dbus_g_proxy_new_for_name(connection_, kNetworkManagerServiceName, kNetworkManagerPath, kNetworkManagerInterface)); DCHECK(proxy_.get()); // Validate the proxy object by checking we can enumerate devices. ScopedGPtrArrayPtr device_list(GetAdapterDeviceList()); return !!device_list.get(); } bool NetworkManagerWlanApi::GetAccessPointData( WifiData::AccessPointDataSet* data) { ScopedGPtrArrayPtr device_list(GetAdapterDeviceList()); if (device_list == NULL) { DLOG(WARNING) << "Could not enumerate access points"; return false; } int success_count = 0; int fail_count = 0; // Iterate the devices, getting APs for each wireless adapter found for (guint i = 0; i < device_list->len; i++) { const gchar* device_path = reinterpret_cast<const gchar*>(g_ptr_array_index(device_list, i)); ScopedDBusGProxyPtr device_properties_proxy(dbus_g_proxy_new_from_proxy( proxy_.get(), DBUS_INTERFACE_PROPERTIES, device_path)); ScopedGValue device_type_g_value; dbus_g_proxy_call(device_properties_proxy.get(), "Get", &error_, G_TYPE_STRING, "org.freedesktop.NetworkManager.Device", G_TYPE_STRING, "DeviceType", G_TYPE_INVALID, G_TYPE_VALUE, &device_type_g_value.v, G_TYPE_INVALID); if (CheckError()) continue; const guint device_type = g_value_get_uint(&device_type_g_value.v); if (device_type == NM_DEVICE_TYPE_WIFI) { // Found a wlan adapter if (GetAccessPointsForAdapter(device_path, data)) ++success_count; else ++fail_count; } } // At least one successfull scan overrides any other adapter reporting error. return success_count || fail_count == 0; } bool NetworkManagerWlanApi::CheckError() { if (error_) { LOG(ERROR) << "Failed to complete NetworkManager call: " << error_->message; g_error_free(error_); error_ = NULL; return true; } return false; } GPtrArray* NetworkManagerWlanApi::GetAdapterDeviceList() { GPtrArray* device_list = NULL; dbus_g_proxy_call(proxy_.get(), "GetDevices", &error_, G_TYPE_INVALID, dbus_g_type_get_collection("GPtrArray", DBUS_TYPE_G_OBJECT_PATH), &device_list, G_TYPE_INVALID); if (CheckError()) return NULL; return device_list; } bool NetworkManagerWlanApi::GetAccessPointsForAdapter( const gchar* adapter_path, WifiData::AccessPointDataSet* data) { DCHECK(proxy_.get()); // Create a proxy object for this wifi adapter, and ask it to do a scan // (or at least, dump its scan results). ScopedDBusGProxyPtr wifi_adapter_proxy(dbus_g_proxy_new_from_proxy( proxy_.get(), "org.freedesktop.NetworkManager.Device.Wireless", adapter_path)); GPtrArray* ap_list_raw = NULL; // Enumerate the access points for this adapter. dbus_g_proxy_call(wifi_adapter_proxy.get(), "GetAccessPoints", &error_, G_TYPE_INVALID, dbus_g_type_get_collection("GPtrArray", DBUS_TYPE_G_OBJECT_PATH), &ap_list_raw, G_TYPE_INVALID); ScopedGPtrArrayPtr ap_list(ap_list_raw); // Takes ownership. ap_list_raw = NULL; if (CheckError()) return false; DLOG(INFO) << "Wireless adapter " << adapter_path << " found " << ap_list->len << " access points."; for (guint i = 0; i < ap_list->len; i++) { const gchar* ap_path = reinterpret_cast<const gchar*>(g_ptr_array_index(ap_list, i)); ScopedDBusGProxyPtr access_point_proxy(dbus_g_proxy_new_from_proxy( proxy_.get(), DBUS_INTERFACE_PROPERTIES, ap_path)); AccessPointData access_point_data; { // Read SSID. ScopedGValue ssid_g_value; if (!GetAccessPointProperty(access_point_proxy.get(), "Ssid", G_TYPE_BOXED, &ssid_g_value.v)) continue; const GArray* ssid = reinterpret_cast<const GArray*>(g_value_get_boxed(&ssid_g_value.v)); UTF8ToUTF16(ssid->data, ssid->len, &access_point_data.ssid); } { // Read the mac address ScopedGValue mac_g_value; if (!GetAccessPointProperty(access_point_proxy.get(), "HwAddress", G_TYPE_STRING, &mac_g_value.v)) continue; std::string mac = g_value_get_string(&mac_g_value.v); ReplaceSubstringsAfterOffset(&mac, 0U, ":", ""); std::vector<uint8> mac_bytes; if (!HexStringToBytes(mac, &mac_bytes) || mac_bytes.size() != 6) { DLOG(WARNING) << "Can't parse mac address (found " << mac_bytes.size() << " bytes) so using raw string: " << mac; access_point_data.mac_address = UTF8ToUTF16(mac); } else { access_point_data.mac_address = MacAddressAsString16(&mac_bytes[0]); } } { // Read signal strength. ScopedGValue signal_g_value; if (!GetAccessPointProperty(access_point_proxy.get(), "Strength", G_TYPE_UCHAR, &signal_g_value.v)) continue; // Convert strength as a percentage into dBs. access_point_data.radio_signal_strength = -100 + g_value_get_uchar(&signal_g_value.v) / 2; } { // Read the channel ScopedGValue freq_g_value; if (!GetAccessPointProperty(access_point_proxy.get(), "Frequency", G_TYPE_UINT, &freq_g_value.v)) continue; // NetworkManager returns frequency in MHz. access_point_data.channel = frquency_in_khz_to_channel(g_value_get_uint(&freq_g_value.v) * 1000); } data->insert(access_point_data); } return true; } bool NetworkManagerWlanApi::GetAccessPointProperty(DBusGProxy* proxy, const char* property_name, int expected_gvalue_type, GValue* value_out) { dbus_g_proxy_call(proxy, "Get", &error_, G_TYPE_STRING, "org.freedesktop.NetworkManager.AccessPoint", G_TYPE_STRING, property_name, G_TYPE_INVALID, G_TYPE_VALUE, value_out, G_TYPE_INVALID); if (CheckError()) return false; if (!G_VALUE_HOLDS(value_out, expected_gvalue_type)) { DLOG(WARNING) << "Property " << property_name << " unexptected type " << G_VALUE_TYPE(value_out); return false; } return true; } } // namespace // static template<> WifiDataProviderImplBase* WifiDataProvider::DefaultFactoryFunction() { return new WifiDataProviderLinux(); } WifiDataProviderLinux::WifiDataProviderLinux() { } WifiDataProviderLinux::~WifiDataProviderLinux() { } WifiDataProviderCommon::WlanApiInterface* WifiDataProviderLinux::NewWlanApi() { scoped_ptr<NetworkManagerWlanApi> wlan_api(new NetworkManagerWlanApi); if (wlan_api->Init()) return wlan_api.release(); return NULL; } PollingPolicyInterface* WifiDataProviderLinux::NewPollingPolicy() { return new GenericPollingPolicy<kDefaultPollingIntervalMilliseconds, kNoChangePollingIntervalMilliseconds, kTwoNoChangePollingIntervalMilliseconds>; } <commit_msg>Work-around for DBus crash due to timers firing on the wrong thread.<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. // Provides wifi scan API binding for suitable for typical linux distributions. // Currently, only the NetworkManager API is used, accessed via D-Bus (in turn // accessed via the GLib wrapper). #include "chrome/browser/geolocation/wifi_data_provider_linux.h" #include <dbus/dbus-glib.h> #include <dbus/dbus-glib-lowlevel.h> #include <dbus/dbus.h> #include <glib.h> #include "base/scoped_ptr.h" #include "base/utf_string_conversions.h" namespace { // The time periods between successive polls of the wifi data. const int kDefaultPollingIntervalMilliseconds = 10 * 1000; // 10s const int kNoChangePollingIntervalMilliseconds = 2 * 60 * 1000; // 2 mins const int kTwoNoChangePollingIntervalMilliseconds = 10 * 60 * 1000; // 10 mins const char kNetworkManagerServiceName[] = "org.freedesktop.NetworkManager"; const char kNetworkManagerPath[] = "/org/freedesktop/NetworkManager"; const char kNetworkManagerInterface[] = "org.freedesktop.NetworkManager"; // From http://projects.gnome.org/NetworkManager/developers/spec.html enum { NM_DEVICE_TYPE_WIFI = 2 }; // Utility wrappers to make various GLib & DBus structs into scoped objects. class ScopedGPtrArrayFree { public: void operator()(GPtrArray* x) const { if (x) g_ptr_array_free(x, TRUE); } }; // Use ScopedGPtrArrayPtr as if it were scoped_ptr<GPtrArray> typedef scoped_ptr_malloc<GPtrArray, ScopedGPtrArrayFree> ScopedGPtrArrayPtr; class ScopedGObjectFree { public: void operator()(void* x) const { if (x) g_object_unref(x); } }; // Use ScopedDBusGProxyPtr as if it were scoped_ptr<DBusGProxy> typedef scoped_ptr_malloc<DBusGProxy, ScopedGObjectFree> ScopedDBusGProxyPtr; // Use ScopedGValue::v as an instance of GValue with automatic cleanup. class ScopedGValue { public: ScopedGValue() : v(empty_gvalue()) { } ~ScopedGValue() { g_value_unset(&v); } static GValue empty_gvalue() { GValue value = {0}; return value; } GValue v; }; // Wifi API binding to NetworkManager, to allow reuse of the polling behavior // defined in WifiDataProviderCommon. // TODO(joth): NetworkManager also allows for notification based handling, // however this will require reworking of the threading code to run a GLib // event loop (GMainLoop). class NetworkManagerWlanApi : public WifiDataProviderCommon::WlanApiInterface { public: NetworkManagerWlanApi(); ~NetworkManagerWlanApi(); // Must be called before any other interface method. Will return false if the // NetworkManager session cannot be created (e.g. not present on this distro), // in which case no other method may be called. bool Init(); // WifiDataProviderCommon::WlanApiInterface bool GetAccessPointData(WifiData::AccessPointDataSet* data); private: // Checks if the last dbus call returned an error. If it did, logs the error // message, frees it and returns true. // This must be called after every dbus call that accepts |&error_| bool CheckError(); // Enumerates the list of available network adapter devices known to // NetworkManager. Ownership of the array (and contained objects) is returned // to the caller. GPtrArray* GetAdapterDeviceList(); // Given the NetworkManager path to a wireless adapater, dumps the wifi scan // results and appends them to |data|. Returns false if a fatal error is // encountered such that the data set could not be populated. bool GetAccessPointsForAdapter(const gchar* adapter_path, WifiData::AccessPointDataSet* data); // Internal method used by |GetAccessPointsForAdapter|, given a wifi access // point proxy retrieves the named property into |value_out|. Returns false if // the property could not be read, or is not of type |expected_gvalue_type|. bool GetAccessPointProperty(DBusGProxy* proxy, const char* property_name, int expected_gvalue_type, GValue* value_out); // Error from the last dbus call. NULL when there's no error. Freed and // cleared by CheckError(). GError* error_; // Connection to the dbus system bus. DBusGConnection* connection_; // Proxy to the network maanger dbus service. ScopedDBusGProxyPtr proxy_; DISALLOW_COPY_AND_ASSIGN(NetworkManagerWlanApi); }; // Convert a wifi frequency to the corresponding channel. Adapted from // geolocaiton/wifilib.cc in googleclient (internal to google). int frquency_in_khz_to_channel(int frequency_khz) { if (frequency_khz >= 2412000 && frequency_khz <= 2472000) // Channels 1-13. return (frequency_khz - 2407000) / 5000; if (frequency_khz == 2484000) return 14; if (frequency_khz > 5000000 && frequency_khz < 6000000) // .11a bands. return (frequency_khz - 5000000) / 5000; // Ignore everything else. return AccessPointData().channel; // invalid channel } NetworkManagerWlanApi::NetworkManagerWlanApi() : error_(NULL), connection_(NULL) { } NetworkManagerWlanApi::~NetworkManagerWlanApi() { proxy_.reset(); if (connection_) { dbus_g_connection_unref(connection_); } DCHECK(!error_) << "Missing a call to CheckError() to clear |error_|"; } bool NetworkManagerWlanApi::Init() { // Chrome DLL init code handles initializing the thread system, so rather than // get caught up with that nonsense here, lets just assert our requirement. CHECK(g_thread_supported()); // We should likely do this higher up too, the docs say it must only be done // once but there's no way to know if it already was or not. dbus_g_thread_init(); // Get a connection to the session bus. connection_ = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error_); if (CheckError()) return false; DCHECK(connection_); // dbus-glib queues timers that get fired on the default loop, unfortunately // it isn't thread safe in it's handling of these timers. We can't easily // tell it which loop to queue them on instead, but as we only make // blocking sync calls we don't need timers anyway, so disable them. // See http://crbug.com/40803 TODO(joth): This is not an ideal solution, as // we're reconfiguring the process global system bus connection, so could // impact other users of DBus. dbus_bool_t ok = dbus_connection_set_timeout_functions( dbus_g_connection_get_connection(connection_), NULL, NULL, NULL, NULL, NULL); DCHECK(ok); proxy_.reset(dbus_g_proxy_new_for_name(connection_, kNetworkManagerServiceName, kNetworkManagerPath, kNetworkManagerInterface)); DCHECK(proxy_.get()); // Validate the proxy object by checking we can enumerate devices. ScopedGPtrArrayPtr device_list(GetAdapterDeviceList()); return !!device_list.get(); } bool NetworkManagerWlanApi::GetAccessPointData( WifiData::AccessPointDataSet* data) { ScopedGPtrArrayPtr device_list(GetAdapterDeviceList()); if (device_list == NULL) { DLOG(WARNING) << "Could not enumerate access points"; return false; } int success_count = 0; int fail_count = 0; // Iterate the devices, getting APs for each wireless adapter found for (guint i = 0; i < device_list->len; i++) { const gchar* device_path = reinterpret_cast<const gchar*>(g_ptr_array_index(device_list, i)); ScopedDBusGProxyPtr device_properties_proxy(dbus_g_proxy_new_from_proxy( proxy_.get(), DBUS_INTERFACE_PROPERTIES, device_path)); ScopedGValue device_type_g_value; dbus_g_proxy_call(device_properties_proxy.get(), "Get", &error_, G_TYPE_STRING, "org.freedesktop.NetworkManager.Device", G_TYPE_STRING, "DeviceType", G_TYPE_INVALID, G_TYPE_VALUE, &device_type_g_value.v, G_TYPE_INVALID); if (CheckError()) continue; const guint device_type = g_value_get_uint(&device_type_g_value.v); if (device_type == NM_DEVICE_TYPE_WIFI) { // Found a wlan adapter if (GetAccessPointsForAdapter(device_path, data)) ++success_count; else ++fail_count; } } // At least one successfull scan overrides any other adapter reporting error. return success_count || fail_count == 0; } bool NetworkManagerWlanApi::CheckError() { if (error_) { LOG(ERROR) << "Failed to complete NetworkManager call: " << error_->message; g_error_free(error_); error_ = NULL; return true; } return false; } GPtrArray* NetworkManagerWlanApi::GetAdapterDeviceList() { GPtrArray* device_list = NULL; dbus_g_proxy_call(proxy_.get(), "GetDevices", &error_, G_TYPE_INVALID, dbus_g_type_get_collection("GPtrArray", DBUS_TYPE_G_OBJECT_PATH), &device_list, G_TYPE_INVALID); if (CheckError()) return NULL; return device_list; } bool NetworkManagerWlanApi::GetAccessPointsForAdapter( const gchar* adapter_path, WifiData::AccessPointDataSet* data) { DCHECK(proxy_.get()); // Create a proxy object for this wifi adapter, and ask it to do a scan // (or at least, dump its scan results). ScopedDBusGProxyPtr wifi_adapter_proxy(dbus_g_proxy_new_from_proxy( proxy_.get(), "org.freedesktop.NetworkManager.Device.Wireless", adapter_path)); GPtrArray* ap_list_raw = NULL; // Enumerate the access points for this adapter. dbus_g_proxy_call(wifi_adapter_proxy.get(), "GetAccessPoints", &error_, G_TYPE_INVALID, dbus_g_type_get_collection("GPtrArray", DBUS_TYPE_G_OBJECT_PATH), &ap_list_raw, G_TYPE_INVALID); ScopedGPtrArrayPtr ap_list(ap_list_raw); // Takes ownership. ap_list_raw = NULL; if (CheckError()) return false; DLOG(INFO) << "Wireless adapter " << adapter_path << " found " << ap_list->len << " access points."; for (guint i = 0; i < ap_list->len; i++) { const gchar* ap_path = reinterpret_cast<const gchar*>(g_ptr_array_index(ap_list, i)); ScopedDBusGProxyPtr access_point_proxy(dbus_g_proxy_new_from_proxy( proxy_.get(), DBUS_INTERFACE_PROPERTIES, ap_path)); AccessPointData access_point_data; { // Read SSID. ScopedGValue ssid_g_value; if (!GetAccessPointProperty(access_point_proxy.get(), "Ssid", G_TYPE_BOXED, &ssid_g_value.v)) continue; const GArray* ssid = reinterpret_cast<const GArray*>(g_value_get_boxed(&ssid_g_value.v)); UTF8ToUTF16(ssid->data, ssid->len, &access_point_data.ssid); } { // Read the mac address ScopedGValue mac_g_value; if (!GetAccessPointProperty(access_point_proxy.get(), "HwAddress", G_TYPE_STRING, &mac_g_value.v)) continue; std::string mac = g_value_get_string(&mac_g_value.v); ReplaceSubstringsAfterOffset(&mac, 0U, ":", ""); std::vector<uint8> mac_bytes; if (!HexStringToBytes(mac, &mac_bytes) || mac_bytes.size() != 6) { DLOG(WARNING) << "Can't parse mac address (found " << mac_bytes.size() << " bytes) so using raw string: " << mac; access_point_data.mac_address = UTF8ToUTF16(mac); } else { access_point_data.mac_address = MacAddressAsString16(&mac_bytes[0]); } } { // Read signal strength. ScopedGValue signal_g_value; if (!GetAccessPointProperty(access_point_proxy.get(), "Strength", G_TYPE_UCHAR, &signal_g_value.v)) continue; // Convert strength as a percentage into dBs. access_point_data.radio_signal_strength = -100 + g_value_get_uchar(&signal_g_value.v) / 2; } { // Read the channel ScopedGValue freq_g_value; if (!GetAccessPointProperty(access_point_proxy.get(), "Frequency", G_TYPE_UINT, &freq_g_value.v)) continue; // NetworkManager returns frequency in MHz. access_point_data.channel = frquency_in_khz_to_channel(g_value_get_uint(&freq_g_value.v) * 1000); } data->insert(access_point_data); } return true; } bool NetworkManagerWlanApi::GetAccessPointProperty(DBusGProxy* proxy, const char* property_name, int expected_gvalue_type, GValue* value_out) { dbus_g_proxy_call(proxy, "Get", &error_, G_TYPE_STRING, "org.freedesktop.NetworkManager.AccessPoint", G_TYPE_STRING, property_name, G_TYPE_INVALID, G_TYPE_VALUE, value_out, G_TYPE_INVALID); if (CheckError()) return false; if (!G_VALUE_HOLDS(value_out, expected_gvalue_type)) { DLOG(WARNING) << "Property " << property_name << " unexptected type " << G_VALUE_TYPE(value_out); return false; } return true; } } // namespace // static template<> WifiDataProviderImplBase* WifiDataProvider::DefaultFactoryFunction() { return new WifiDataProviderLinux(); } WifiDataProviderLinux::WifiDataProviderLinux() { } WifiDataProviderLinux::~WifiDataProviderLinux() { } WifiDataProviderCommon::WlanApiInterface* WifiDataProviderLinux::NewWlanApi() { scoped_ptr<NetworkManagerWlanApi> wlan_api(new NetworkManagerWlanApi); if (wlan_api->Init()) return wlan_api.release(); return NULL; } PollingPolicyInterface* WifiDataProviderLinux::NewPollingPolicy() { return new GenericPollingPolicy<kDefaultPollingIntervalMilliseconds, kNoChangePollingIntervalMilliseconds, kTwoNoChangePollingIntervalMilliseconds>; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/defaults.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/tab_restore_service.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/page_transition_types.h" namespace { // BrowserList::Observer implementation that waits for a browser to be // removed. class BrowserListObserverImpl : public BrowserList::Observer { public: BrowserListObserverImpl() : did_remove_(false), running_(false) { BrowserList::AddObserver(this); } ~BrowserListObserverImpl() { BrowserList::RemoveObserver(this); } // Returns when a browser has been removed. void Run() { running_ = true; if (!did_remove_) ui_test_utils::RunMessageLoop(); } // BrowserList::Observer virtual void OnBrowserAdded(const Browser* browser) OVERRIDE { } virtual void OnBrowserRemoved(const Browser* browser) OVERRIDE { did_remove_ = true; if (running_) MessageLoop::current()->Quit(); } private: // Was OnBrowserRemoved invoked? bool did_remove_; // Was Run invoked? bool running_; DISALLOW_COPY_AND_ASSIGN(BrowserListObserverImpl); }; } // namespace typedef InProcessBrowserTest SessionRestoreTest; #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Crashes on Linux Views: http://crbug.com/39476 #define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \ DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers #else #define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \ RestoreOnNewWindowWithNoTabbedBrowsers #endif // Makes sure when session restore is triggered in the same process we don't end // up with an extra tab. IN_PROC_BROWSER_TEST_F(SessionRestoreTest, MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers) { if (browser_defaults::kRestorePopups) return; const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html"); GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle1File))); ui_test_utils::NavigateToURL(browser(), url); // Turn on session restore. SessionStartupPref::SetStartupPref( browser()->profile(), SessionStartupPref(SessionStartupPref::LAST)); // Create a new popup. Profile* profile = browser()->profile(); Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP, profile); popup->window()->Show(); // Close the browser. browser()->window()->Close(); // Create a new window, which should trigger session restore. popup->NewWindow(); Browser* new_browser = ui_test_utils::WaitForNewBrowser(); ASSERT_TRUE(new_browser != NULL); // The browser should only have one tab. ASSERT_EQ(1, new_browser->tab_count()); // And the first url should be url. EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL()); } IN_PROC_BROWSER_TEST_F(SessionRestoreTest, RestoreIndividualTabFromWindow) { GURL url1(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); GURL url2(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title2.html")))); GURL url3(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title3.html")))); // Add and navigate three tabs. ui_test_utils::NavigateToURL(browser(), url1); browser()->AddSelectedTabWithURL(url2, PageTransition::LINK); ui_test_utils::WaitForNavigationInCurrentTab(browser()); browser()->AddSelectedTabWithURL(url3, PageTransition::LINK); ui_test_utils::WaitForNavigationInCurrentTab(browser()); TabRestoreService* service = browser()->profile()->GetTabRestoreService(); service->ClearEntries(); browser()->window()->Close(); // Expect a window with three tabs. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type); const TabRestoreService::Window* window = static_cast<TabRestoreService::Window*>(service->entries().front()); EXPECT_EQ(3U, window->tabs.size()); // Find the SessionID for entry2. Since the session service was destroyed, // there is no guarantee that the SessionID for the tab has remained the same. std::vector<TabRestoreService::Tab>::const_iterator it = window->tabs.begin(); for ( ; it != window->tabs.end(); ++it) { const TabRestoreService::Tab& tab = *it; // If this tab held url2, then restore this single tab. if (tab.navigations[0].virtual_url() == url2) { service->RestoreEntryById(NULL, tab.id, false); break; } } // Make sure that the Window got updated. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type); window = static_cast<TabRestoreService::Window*>(service->entries().front()); EXPECT_EQ(2U, window->tabs.size()); } IN_PROC_BROWSER_TEST_F(SessionRestoreTest, WindowWithOneTab) { GURL url(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); // Add a single tab. ui_test_utils::NavigateToURL(browser(), url); TabRestoreService* service = browser()->profile()->GetTabRestoreService(); service->ClearEntries(); EXPECT_EQ(0U, service->entries().size()); // Close the window. browser()->window()->Close(); // Expect the window to be converted to a tab by the TRS. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::TAB, service->entries().front()->type); const TabRestoreService::Tab* tab = static_cast<TabRestoreService::Tab*>(service->entries().front()); // Restore the tab. service->RestoreEntryById(NULL, tab->id, false); // Make sure the restore was successful. EXPECT_EQ(0U, service->entries().size()); } // Verifies we remember the last browser window when closing the last // non-incognito window while an incognito window is open. IN_PROC_BROWSER_TEST_F(SessionRestoreTest, IncognitotoNonIncognito) { // Turn on session restore. SessionStartupPref pref(SessionStartupPref::LAST); SessionStartupPref::SetStartupPref(browser()->profile(), pref); GURL url(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); // Add a single tab. ui_test_utils::NavigateToURL(browser(), url); // Create a new incognito window. Browser* incognito_browser = CreateIncognitoBrowser(); incognito_browser->AddBlankTab(true); incognito_browser->window()->Show(); // Close the normal browser. After this we only have the incognito window // open. We wait until the window closes as window closing is async. { BrowserListObserverImpl observer; browser()->window()->Close(); observer.Run(); } // Create a new window, which should trigger session restore. incognito_browser->NewWindow(); // The first tab should have 'url' as its url. Browser* new_browser = ui_test_utils::WaitForNewBrowser(); ASSERT_TRUE(new_browser); EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL()); } <commit_msg>Fix header inlude.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/defaults.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/tab_restore_service.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/page_transition_types.h" namespace { // BrowserList::Observer implementation that waits for a browser to be // removed. class BrowserListObserverImpl : public BrowserList::Observer { public: BrowserListObserverImpl() : did_remove_(false), running_(false) { BrowserList::AddObserver(this); } ~BrowserListObserverImpl() { BrowserList::RemoveObserver(this); } // Returns when a browser has been removed. void Run() { running_ = true; if (!did_remove_) ui_test_utils::RunMessageLoop(); } // BrowserList::Observer virtual void OnBrowserAdded(const Browser* browser) OVERRIDE { } virtual void OnBrowserRemoved(const Browser* browser) OVERRIDE { did_remove_ = true; if (running_) MessageLoop::current()->Quit(); } private: // Was OnBrowserRemoved invoked? bool did_remove_; // Was Run invoked? bool running_; DISALLOW_COPY_AND_ASSIGN(BrowserListObserverImpl); }; } // namespace typedef InProcessBrowserTest SessionRestoreTest; #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Crashes on Linux Views: http://crbug.com/39476 #define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \ DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers #else #define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \ RestoreOnNewWindowWithNoTabbedBrowsers #endif // Makes sure when session restore is triggered in the same process we don't end // up with an extra tab. IN_PROC_BROWSER_TEST_F(SessionRestoreTest, MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers) { if (browser_defaults::kRestorePopups) return; const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html"); GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle1File))); ui_test_utils::NavigateToURL(browser(), url); // Turn on session restore. SessionStartupPref::SetStartupPref( browser()->profile(), SessionStartupPref(SessionStartupPref::LAST)); // Create a new popup. Profile* profile = browser()->profile(); Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP, profile); popup->window()->Show(); // Close the browser. browser()->window()->Close(); // Create a new window, which should trigger session restore. popup->NewWindow(); Browser* new_browser = ui_test_utils::WaitForNewBrowser(); ASSERT_TRUE(new_browser != NULL); // The browser should only have one tab. ASSERT_EQ(1, new_browser->tab_count()); // And the first url should be url. EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL()); } IN_PROC_BROWSER_TEST_F(SessionRestoreTest, RestoreIndividualTabFromWindow) { GURL url1(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); GURL url2(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title2.html")))); GURL url3(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title3.html")))); // Add and navigate three tabs. ui_test_utils::NavigateToURL(browser(), url1); browser()->AddSelectedTabWithURL(url2, PageTransition::LINK); ui_test_utils::WaitForNavigationInCurrentTab(browser()); browser()->AddSelectedTabWithURL(url3, PageTransition::LINK); ui_test_utils::WaitForNavigationInCurrentTab(browser()); TabRestoreService* service = browser()->profile()->GetTabRestoreService(); service->ClearEntries(); browser()->window()->Close(); // Expect a window with three tabs. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type); const TabRestoreService::Window* window = static_cast<TabRestoreService::Window*>(service->entries().front()); EXPECT_EQ(3U, window->tabs.size()); // Find the SessionID for entry2. Since the session service was destroyed, // there is no guarantee that the SessionID for the tab has remained the same. std::vector<TabRestoreService::Tab>::const_iterator it = window->tabs.begin(); for ( ; it != window->tabs.end(); ++it) { const TabRestoreService::Tab& tab = *it; // If this tab held url2, then restore this single tab. if (tab.navigations[0].virtual_url() == url2) { service->RestoreEntryById(NULL, tab.id, false); break; } } // Make sure that the Window got updated. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type); window = static_cast<TabRestoreService::Window*>(service->entries().front()); EXPECT_EQ(2U, window->tabs.size()); } IN_PROC_BROWSER_TEST_F(SessionRestoreTest, WindowWithOneTab) { GURL url(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); // Add a single tab. ui_test_utils::NavigateToURL(browser(), url); TabRestoreService* service = browser()->profile()->GetTabRestoreService(); service->ClearEntries(); EXPECT_EQ(0U, service->entries().size()); // Close the window. browser()->window()->Close(); // Expect the window to be converted to a tab by the TRS. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::TAB, service->entries().front()->type); const TabRestoreService::Tab* tab = static_cast<TabRestoreService::Tab*>(service->entries().front()); // Restore the tab. service->RestoreEntryById(NULL, tab->id, false); // Make sure the restore was successful. EXPECT_EQ(0U, service->entries().size()); } // Verifies we remember the last browser window when closing the last // non-incognito window while an incognito window is open. IN_PROC_BROWSER_TEST_F(SessionRestoreTest, IncognitotoNonIncognito) { // Turn on session restore. SessionStartupPref pref(SessionStartupPref::LAST); SessionStartupPref::SetStartupPref(browser()->profile(), pref); GURL url(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); // Add a single tab. ui_test_utils::NavigateToURL(browser(), url); // Create a new incognito window. Browser* incognito_browser = CreateIncognitoBrowser(); incognito_browser->AddBlankTab(true); incognito_browser->window()->Show(); // Close the normal browser. After this we only have the incognito window // open. We wait until the window closes as window closing is async. { BrowserListObserverImpl observer; browser()->window()->Close(); observer.Run(); } // Create a new window, which should trigger session restore. incognito_browser->NewWindow(); // The first tab should have 'url' as its url. Browser* new_browser = ui_test_utils::WaitForNewBrowser(); ASSERT_TRUE(new_browser); EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL()); } <|endoftext|>
<commit_before>#ifndef __ZOMBYE_RENDERING_SYSTEM_HPP__ #define __ZOMBYE_RENDERING_SYSTEM_HPP__ #include <memory> #include <unordered_map> #include <vector> #include <GL/glew.h> #include <SDL2/SDL.h> #include <zombye/rendering/buffer.hpp> #include <zombye/rendering/mesh_manager.hpp> #include <zombye/rendering/shader.hpp> #include <zombye/rendering/shader_manager.hpp> #include <zombye/rendering/skeleton_manager.hpp> #include <zombye/rendering/skinned_mesh_manager.hpp> #include <zombye/rendering/texture.hpp> #include <zombye/rendering/texture_manager.hpp> #include <zombye/rendering/vertex_array.hpp> #include <zombye/rendering/vertex_layout.hpp> namespace zombye { class game; class animation_component; class camera_component; class light_component; class directional_light_component; class framebuffer; class program; class screen_quad; class staticmesh_component; class shadow_component; } namespace zombye { class rendering_system { friend class animation_component; friend class camera_component; friend class directional_light_component; friend class light_component; friend class staticmesh_component; friend class shadow_component; game& game_; SDL_Window* window_; SDL_GLContext context_; float width_; float height_; std::vector<animation_component*> animation_components_; std::unordered_map<unsigned long, camera_component*> camera_components_; std::vector<light_component*> light_components_; std::vector<directional_light_component*> directional_light_components_; std::vector<staticmesh_component*> staticmesh_components_; std::vector<shadow_component*> shadow_components_; std::unique_ptr<program> animation_program_; std::unique_ptr<program> staticmesh_program_; vertex_layout skinnedmesh_layout_; vertex_layout staticmesh_layout_; zombye::mesh_manager mesh_manager_; zombye::texture_manager texture_manager_; zombye::shader_manager shader_manager_; zombye::skinned_mesh_manager skinned_mesh_manager_; zombye::skeleton_manager skeleton_manager_; unsigned long active_camera_; glm::mat4 projection_; glm::mat4 view_; glm::mat4 ortho_projection_; std::unique_ptr<framebuffer> g_buffer_; std::unique_ptr<program> screen_quad_program_; std::vector<std::unique_ptr<screen_quad>> debug_screen_quads_; std::unique_ptr<screen_quad> screen_quad_; std::unique_ptr<program> composition_program_; float shadow_resolution_; std::unique_ptr<framebuffer> shadow_map_; glm::mat4 shadow_projection_; std::unique_ptr<program> shadow_staticmesh_program_; std::unique_ptr<program> shadow_animation_program_; public: rendering_system(game& game, SDL_Window* window); rendering_system(const rendering_system& other) = delete; rendering_system(rendering_system&& other) = delete; ~rendering_system(); rendering_system& operator=(const rendering_system& other) = delete; rendering_system& operator=(rendering_system&& other) = delete; void begin_scene(); void end_scene(); void update(float delta_time); void clear_color(float red, float green, float blue, float alpha); void activate_camera(unsigned long owner_id) { if (camera_components_.find(owner_id) != camera_components_.end()) { active_camera_ = owner_id; } } unsigned long active_camera_id() { return active_camera_; } camera_component* active_camera() { if (camera_components_.find(active_camera_) != camera_components_.end()) { return camera_components_[active_camera_]; } return nullptr; } auto& mesh_manager() noexcept { return mesh_manager_; } auto& shader_manager() noexcept { return shader_manager_; } auto& skinnedmesh_layout() noexcept { return skinnedmesh_layout_; } auto& skinned_mesh_manager() noexcept { return skinned_mesh_manager_; } auto& skeleton_manager() noexcept { return skeleton_manager_; } auto& staticmesh_layout() noexcept { return staticmesh_layout_; } auto& texture_manager() noexcept { return texture_manager_; } auto projection() const noexcept { return projection_; } auto view() const noexcept { return view_; } private: void render_debug_screen_quads() const; void render_screen_quad(); void render_shadowmap(); void register_component(animation_component* component); void unregister_component(animation_component* component); void register_component(camera_component* component); void unregister_component(camera_component* component); void register_component(directional_light_component* component); void unregister_component(directional_light_component* component); void register_component(light_component* component); void unregister_component(light_component* component); void register_component(staticmesh_component* component); void unregister_component(staticmesh_component* component); void register_component(shadow_component* component); void unregister_component(shadow_component* component); }; } #endif <commit_msg>change shadow_resolution type to int<commit_after>#ifndef __ZOMBYE_RENDERING_SYSTEM_HPP__ #define __ZOMBYE_RENDERING_SYSTEM_HPP__ #include <memory> #include <unordered_map> #include <vector> #include <GL/glew.h> #include <SDL2/SDL.h> #include <zombye/rendering/buffer.hpp> #include <zombye/rendering/mesh_manager.hpp> #include <zombye/rendering/shader.hpp> #include <zombye/rendering/shader_manager.hpp> #include <zombye/rendering/skeleton_manager.hpp> #include <zombye/rendering/skinned_mesh_manager.hpp> #include <zombye/rendering/texture.hpp> #include <zombye/rendering/texture_manager.hpp> #include <zombye/rendering/vertex_array.hpp> #include <zombye/rendering/vertex_layout.hpp> namespace zombye { class game; class animation_component; class camera_component; class light_component; class directional_light_component; class framebuffer; class program; class screen_quad; class staticmesh_component; class shadow_component; } namespace zombye { class rendering_system { friend class animation_component; friend class camera_component; friend class directional_light_component; friend class light_component; friend class staticmesh_component; friend class shadow_component; game& game_; SDL_Window* window_; SDL_GLContext context_; float width_; float height_; std::vector<animation_component*> animation_components_; std::unordered_map<unsigned long, camera_component*> camera_components_; std::vector<light_component*> light_components_; std::vector<directional_light_component*> directional_light_components_; std::vector<staticmesh_component*> staticmesh_components_; std::vector<shadow_component*> shadow_components_; std::unique_ptr<program> animation_program_; std::unique_ptr<program> staticmesh_program_; vertex_layout skinnedmesh_layout_; vertex_layout staticmesh_layout_; zombye::mesh_manager mesh_manager_; zombye::texture_manager texture_manager_; zombye::shader_manager shader_manager_; zombye::skinned_mesh_manager skinned_mesh_manager_; zombye::skeleton_manager skeleton_manager_; unsigned long active_camera_; glm::mat4 projection_; glm::mat4 view_; glm::mat4 ortho_projection_; std::unique_ptr<framebuffer> g_buffer_; std::unique_ptr<program> screen_quad_program_; std::vector<std::unique_ptr<screen_quad>> debug_screen_quads_; std::unique_ptr<screen_quad> screen_quad_; std::unique_ptr<program> composition_program_; int shadow_resolution_; std::unique_ptr<framebuffer> shadow_map_; glm::mat4 shadow_projection_; std::unique_ptr<program> shadow_staticmesh_program_; std::unique_ptr<program> shadow_animation_program_; public: rendering_system(game& game, SDL_Window* window); rendering_system(const rendering_system& other) = delete; rendering_system(rendering_system&& other) = delete; ~rendering_system(); rendering_system& operator=(const rendering_system& other) = delete; rendering_system& operator=(rendering_system&& other) = delete; void begin_scene(); void end_scene(); void update(float delta_time); void clear_color(float red, float green, float blue, float alpha); void activate_camera(unsigned long owner_id) { if (camera_components_.find(owner_id) != camera_components_.end()) { active_camera_ = owner_id; } } unsigned long active_camera_id() { return active_camera_; } camera_component* active_camera() { if (camera_components_.find(active_camera_) != camera_components_.end()) { return camera_components_[active_camera_]; } return nullptr; } auto& mesh_manager() noexcept { return mesh_manager_; } auto& shader_manager() noexcept { return shader_manager_; } auto& skinnedmesh_layout() noexcept { return skinnedmesh_layout_; } auto& skinned_mesh_manager() noexcept { return skinned_mesh_manager_; } auto& skeleton_manager() noexcept { return skeleton_manager_; } auto& staticmesh_layout() noexcept { return staticmesh_layout_; } auto& texture_manager() noexcept { return texture_manager_; } auto projection() const noexcept { return projection_; } auto view() const noexcept { return view_; } private: void render_debug_screen_quads() const; void render_screen_quad(); void render_shadowmap(); void register_component(animation_component* component); void unregister_component(animation_component* component); void register_component(camera_component* component); void unregister_component(camera_component* component); void register_component(directional_light_component* component); void unregister_component(directional_light_component* component); void register_component(light_component* component); void unregister_component(light_component* component); void register_component(staticmesh_component* component); void unregister_component(staticmesh_component* component); void register_component(shadow_component* component); void unregister_component(shadow_component* component); }; } #endif <|endoftext|>
<commit_before>/* ** Author(s): ** - Pierre Roullon <proullon@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <qimessaging/c/api_c.h> #include <qimessaging/c/qi_c.h> #include <qi/os.hpp> #include <gtest/gtest.h> #include <qimessaging/service_directory.hpp> #include <string> #include <iostream> void reply(const char *signature, qi_message_t *message, qi_message_t *answer, void *data) { char* msg = qi_message_read_string(message); char* rep = (char *) malloc(strlen(msg) + 4); memcpy(rep, msg, strlen(msg) + 1); printf("Message recv: %s\n", msg); strcat(rep, "bim"); qi_message_write_string(answer, rep); } qi_message_t* message; qi_application_t* app; qi_session_t* session; qi_session_t* client_session; qi_object_t* object; qi_object_t* remote; qi::ServiceDirectory* sd; std::string connectionAddr; int id; TEST(TestCBindings, InitService) { assert(app != 0); object = qi_object_create("replyObj"); assert(object != 0); } TEST(TestCBindings, BindMethod) { qi_object_register_method(object, "reply::s(s)", &reply, 0); // TODO find a way to test this } TEST(TestCBindings, ConnectSession) { session = qi_session_create(); assert(session != 0); qi_session_connect(session, connectionAddr.c_str()); qi_session_wait_for_connected(session, 3000); assert(qi_session_listen(session, "tcp://0.0.0.0:0")); id = qi_session_register_service(session, "serviceTest", object); } TEST(TestCBindings, InitClient) { client_session = qi_session_create(); assert(client_session != 0); qi_session_connect(client_session, connectionAddr.c_str()); qi_session_wait_for_connected(client_session, 3000); remote = qi_session_get_service(client_session, "serviceTest"); assert(remote != 0); assert(qi_session_get_service(client_session, "pute") == 0); } TEST(TestCBindings, CallReply) { message = qi_message_create(); assert(message != 0); char* result = 0; // call qi_message_write_string(message, "plaf"); qi_future_t* fut = qi_object_call(object, "reply::s(s)", message); qi_future_wait(fut); qi_message_t *msg = 0; assert((bool) qi_future_is_error(fut) == false); assert((bool) qi_future_is_ready(fut) == true); msg = (qi_message_t*) qi_future_get_value(fut); assert(msg != 0); result = qi_message_read_string(msg); assert(strcmp(result, "plafbim") == 0); } TEST(TestCBindings, TearDown) { sd->close(); qi_message_destroy(message); qi_session_unregister_service(session, id); qi_session_destroy(session); qi_session_destroy(client_session); qi_object_destroy(object); qi_object_destroy(remote); qi_application_destroy(app); } int main(int argc, char **argv) { app = qi_application_create(&argc, argv); ::testing::InitGoogleTest(&argc, argv); unsigned int sdPort = qi::os::findAvailablePort(5555); std::stringstream sdAddr; sdAddr << "tcp://127.0.0.1:" << sdPort; connectionAddr = sdAddr.str(); sd = new qi::ServiceDirectory(); sd->listen(sdAddr.str()); std::cout << "Service Directory ready." << std::endl; return RUN_ALL_TESTS(); } <commit_msg>fix test_c_bindings<commit_after>/* ** Author(s): ** - Pierre Roullon <proullon@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <qimessaging/c/api_c.h> #include <qimessaging/c/qi_c.h> #include <qi/os.hpp> #include <gtest/gtest.h> #include <qimessaging/service_directory.hpp> #include <string> #include <iostream> void reply(const char *signature, qi_message_t *message, qi_message_t *answer, void *data) { char* msg = qi_message_read_string(message); char* rep = (char *) malloc(strlen(msg) + 4); memcpy(rep, msg, strlen(msg) + 1); printf("Message recv: %s\n", msg); strcat(rep, "bim"); qi_message_write_string(answer, rep); } qi_message_t* message; qi_application_t* app; qi_session_t* session; qi_session_t* client_session; qi_object_t* object; qi_object_t* remote; qi::ServiceDirectory* sd; std::string connectionAddr; int id; TEST(TestCBindings, InitService) { assert(app != 0); object = qi_object_create("replyObj"); assert(object != 0); } TEST(TestCBindings, BindMethod) { qi_object_register_method(object, "reply::s(s)", &reply, 0); // TODO find a way to test this } TEST(TestCBindings, ConnectSession) { session = qi_session_create(); assert(session != 0); qi_session_connect(session, connectionAddr.c_str()); qi_session_wait_for_connected(session, 3000); assert(qi_session_listen(session, "tcp://0.0.0.0:0")); id = qi_session_register_service(session, "serviceTest", object); } TEST(TestCBindings, InitClient) { client_session = qi_session_create(); assert(client_session != 0); qi_session_connect(client_session, connectionAddr.c_str()); qi_session_wait_for_connected(client_session, 3000); remote = qi_session_get_service(client_session, "serviceTest"); assert(remote != 0); assert(qi_session_get_service(client_session, "pute") == 0); } TEST(TestCBindings, CallReply) { message = qi_message_create(); assert(message != 0); char* result = 0; // call qi_message_write_string(message, "plaf"); qi_future_t* fut = qi_object_call(object, "reply::(s)", message); qi_future_wait(fut); qi_message_t *msg = 0; assert((bool) qi_future_is_error(fut) == false); assert((bool) qi_future_is_ready(fut) == true); msg = (qi_message_t*) qi_future_get_value(fut); assert(msg != 0); result = qi_message_read_string(msg); assert(strcmp(result, "plafbim") == 0); } TEST(TestCBindings, TearDown) { sd->close(); qi_message_destroy(message); qi_session_unregister_service(session, id); qi_session_destroy(session); qi_session_destroy(client_session); qi_object_destroy(object); qi_object_destroy(remote); qi_application_destroy(app); } int main(int argc, char **argv) { app = qi_application_create(&argc, argv); ::testing::InitGoogleTest(&argc, argv); unsigned int sdPort = qi::os::findAvailablePort(5555); std::stringstream sdAddr; sdAddr << "tcp://127.0.0.1:" << sdPort; connectionAddr = sdAddr.str(); sd = new qi::ServiceDirectory(); sd->listen(sdAddr.str()); std::cout << "Service Directory ready." << std::endl; return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/automation/ui_controls.h" #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> #include "base/gfx/rect.h" #include "base/logging.h" #include "base/message_loop.h" #include "chrome/common/gtk_util.h" #include "chrome/test/automation/automation_constants.h" #if defined(TOOLKIT_VIEWS) #include "views/view.h" #include "views/widget/widget.h" #endif namespace { guint32 EventTimeNow() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } class EventWaiter : public MessageLoopForUI::Observer { public: EventWaiter(Task* task, GdkEventType type, int count) : task_(task), type_(type), count_(count) { MessageLoopForUI::current()->AddObserver(this); } virtual ~EventWaiter() { MessageLoopForUI::current()->RemoveObserver(this); } // MessageLoop::Observer implementation: virtual void WillProcessEvent(GdkEvent* event) { if ((event->type == type_) && (--count_ == 0)) { // At the time we're invoked the event has not actually been processed. // Use PostTask to make sure the event has been processed before // notifying. // NOTE: if processing a message results in running a nested message // loop, then DidProcessEvent isn't immediately sent. As such, we do // the processing in WillProcessEvent rather than DidProcessEvent. MessageLoop::current()->PostTask(FROM_HERE, task_); delete this; } } virtual void DidProcessEvent(GdkEvent* event) { // No-op. } private: // We pass ownership of task_ to MessageLoop when the current event is // received. Task* task_; GdkEventType type_; // The number of events of this type to wait for. int count_; }; class ClickTask : public Task { public: ClickTask(ui_controls::MouseButton button, int state, Task* followup) : button_(button), state_(state), followup_(followup) { } virtual ~ClickTask() {} virtual void Run() { if (followup_) ui_controls::SendMouseEventsNotifyWhenDone(button_, state_, followup_); else ui_controls::SendMouseEvents(button_, state_); } private: ui_controls::MouseButton button_; int state_; Task* followup_; }; bool SendKeyEvent(GdkWindow* window, bool press, guint key, guint state) { GdkEvent* event = gdk_event_new(press ? GDK_KEY_PRESS : GDK_KEY_RELEASE); event->key.type = press ? GDK_KEY_PRESS : GDK_KEY_RELEASE; event->key.window = window; g_object_ref(event->key.window); event->key.send_event = false; event->key.time = EventTimeNow(); event->key.state = state; event->key.keyval = key; GdkKeymapKey* keys; gint n_keys; if (!gdk_keymap_get_entries_for_keyval(gdk_keymap_get_default(), event->key.keyval, &keys, &n_keys)) { return false; } event->key.hardware_keycode = keys[0].keycode; event->key.group = keys[0].group; g_free(keys); gdk_event_put(event); // gdk_event_put appends a copy of the event. gdk_event_free(event); return true; } void FakeAMouseMotionEvent(gint x, gint y) { GdkEvent* event = gdk_event_new(GDK_MOTION_NOTIFY); event->motion.send_event = false; event->motion.time = EventTimeNow(); GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, we need to target all events at it regardless of // what widget the mouse is over. event->motion.window = grab_widget->window; } else { event->motion.window = gdk_window_at_pointer(&x, &y); } g_object_ref(event->motion.window); event->motion.x = x; event->motion.y = y; gint origin_x, origin_y; gdk_window_get_origin(event->motion.window, &origin_x, &origin_y); event->motion.x_root = x + origin_x; event->motion.y_root = y + origin_y; event->motion.device = gdk_device_get_core_pointer(); event->type = GDK_MOTION_NOTIFY; gdk_event_put(event); gdk_event_free(event); } } // namespace namespace ui_controls { bool SendKeyPress(gfx::NativeWindow window, wchar_t key, bool control, bool shift, bool alt) { GdkWindow* event_window = NULL; GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, send all events to the grabbed widget. event_window = grab_widget->window; } else if (window) { event_window = GTK_WIDGET(window)->window; } else { // No target was specified. Send the events to the active toplevel. GList* windows = gtk_window_list_toplevels(); for (GList* element = windows; element; element = g_list_next(element)) { GtkWindow* this_window = GTK_WINDOW(element->data); if (gtk_window_is_active(this_window)) { event_window = GTK_WIDGET(this_window)->window; break; } } g_list_free(windows); } if (!event_window) { NOTREACHED() << "Window not specified and none is active"; return false; } bool rv = true; if (control) rv = rv && SendKeyEvent(event_window, true, GDK_Control_L, 0); if (shift) { rv = rv && SendKeyEvent(event_window, true, GDK_Shift_L, control ? GDK_CONTROL_MASK : 0); } if (alt) { guint state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0); rv = rv && SendKeyEvent(event_window, true, GDK_Alt_L, state); } // TODO(estade): handle other state flags besides control, shift, alt? // For example caps lock. guint state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0) | (alt ? GDK_MOD1_MASK : 0); rv = rv && SendKeyEvent(event_window, true, key, state); rv = rv && SendKeyEvent(event_window, false, key, state); if (alt) { guint state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0); rv = rv && SendKeyEvent(event_window, false, GDK_Alt_L, state); } if (shift) { rv = rv && SendKeyEvent(event_window, false, GDK_Shift_L, control ? GDK_CONTROL_MASK : 0); } if (control) rv = rv && SendKeyEvent(event_window, false, GDK_Control_L, 0); return rv; } bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, wchar_t key, bool control, bool shift, bool alt, Task* task) { int release_count = 1; if (control) release_count++; if (shift) release_count++; if (alt) release_count++; // This object will delete itself after running |task|. new EventWaiter(task, GDK_KEY_RELEASE, release_count); return SendKeyPress(window, key, control, shift, alt); } bool SendMouseMove(long x, long y) { gdk_display_warp_pointer(gdk_display_get_default(), gdk_screen_get_default(), x, y); // Sometimes gdk_display_warp_pointer fails to send back any indication of // the move, even though it succesfully moves the server cursor. We fake it in // order to get drags to work. FakeAMouseMotionEvent(x, y); return true; } bool SendMouseMoveNotifyWhenDone(long x, long y, Task* task) { bool rv = SendMouseMove(x, y); // We can't rely on any particular event signalling the completion of the // mouse move. Posting the task to the message loop hopefully guarantees // the pointer has moved before task is run (although it may not run it as // soon as it could). MessageLoop::current()->PostTask(FROM_HERE, task); return rv; } bool SendMouseEvents(MouseButton type, int state) { GdkEvent* event = gdk_event_new(GDK_BUTTON_PRESS); event->button.send_event = false; event->button.time = EventTimeNow(); gint x, y; GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, we need to target all events at it regardless of // what widget the mouse is over. event->button.window = grab_widget->window; gdk_window_get_pointer(event->button.window, &x, &y, NULL); } else { event->button.window = gdk_window_at_pointer(&x, &y); } g_object_ref(event->button.window); event->button.x = x; event->button.y = y; gint origin_x, origin_y; gdk_window_get_origin(event->button.window, &origin_x, &origin_y); event->button.x_root = x + origin_x; event->button.y_root = y + origin_y; event->button.axes = NULL; gdk_window_get_pointer(event->button.window, NULL, NULL, reinterpret_cast<GdkModifierType*>(&event->button.state)); event->button.button = type == LEFT ? 1 : (type == MIDDLE ? 2 : 3); event->button.device = gdk_device_get_core_pointer(); event->button.type = GDK_BUTTON_PRESS; if (state & DOWN) gdk_event_put(event); // Also send a release event. GdkEvent* release_event = gdk_event_copy(event); release_event->button.type = GDK_BUTTON_RELEASE; release_event->button.time++; if (state & UP) gdk_event_put(release_event); gdk_event_free(event); gdk_event_free(release_event); return false; } bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, Task* task) { bool rv = SendMouseEvents(type, state); GdkEventType wait_type; if (state & UP) { wait_type = GDK_BUTTON_RELEASE; } else { if (type == LEFT) wait_type = GDK_BUTTON_PRESS; else if (type == MIDDLE) wait_type = GDK_2BUTTON_PRESS; else wait_type = GDK_3BUTTON_PRESS; } new EventWaiter(task, wait_type, 1); return rv; } bool SendMouseClick(MouseButton type) { return SendMouseEvents(type, UP | DOWN); } #if defined(TOOLKIT_VIEWS) void MoveMouseToCenterAndPress(views::View* view, MouseButton button, int state, Task* task) { gfx::Point view_center(view->width() / 2, view->height() / 2); views::View::ConvertPointToScreen(view, &view_center); SendMouseMoveNotifyWhenDone(view_center.x(), view_center.y(), new ClickTask(button, state, task)); } #else void MoveMouseToCenterAndPress(GtkWidget* widget, MouseButton button, int state, Task* task) { gfx::Rect bounds = gtk_util::GetWidgetScreenBounds(widget); SendMouseMoveNotifyWhenDone(bounds.x() + bounds.width() / 2, bounds.y() + bounds.height() / 2, new ClickTask(button, state, task)); } #endif } // namespace ui_controls <commit_msg>Fix gcc warning in chrome os compile.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/automation/ui_controls.h" #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> #include "base/gfx/rect.h" #include "base/logging.h" #include "base/message_loop.h" #include "chrome/common/gtk_util.h" #include "chrome/test/automation/automation_constants.h" #if defined(TOOLKIT_VIEWS) #include "views/view.h" #include "views/widget/widget.h" #endif namespace { guint32 EventTimeNow() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } class EventWaiter : public MessageLoopForUI::Observer { public: EventWaiter(Task* task, GdkEventType type, int count) : task_(task), type_(type), count_(count) { MessageLoopForUI::current()->AddObserver(this); } virtual ~EventWaiter() { MessageLoopForUI::current()->RemoveObserver(this); } // MessageLoop::Observer implementation: virtual void WillProcessEvent(GdkEvent* event) { if ((event->type == type_) && (--count_ == 0)) { // At the time we're invoked the event has not actually been processed. // Use PostTask to make sure the event has been processed before // notifying. // NOTE: if processing a message results in running a nested message // loop, then DidProcessEvent isn't immediately sent. As such, we do // the processing in WillProcessEvent rather than DidProcessEvent. MessageLoop::current()->PostTask(FROM_HERE, task_); delete this; } } virtual void DidProcessEvent(GdkEvent* event) { // No-op. } private: // We pass ownership of task_ to MessageLoop when the current event is // received. Task* task_; GdkEventType type_; // The number of events of this type to wait for. int count_; }; class ClickTask : public Task { public: ClickTask(ui_controls::MouseButton button, int state, Task* followup) : button_(button), state_(state), followup_(followup) { } virtual ~ClickTask() {} virtual void Run() { if (followup_) ui_controls::SendMouseEventsNotifyWhenDone(button_, state_, followup_); else ui_controls::SendMouseEvents(button_, state_); } private: ui_controls::MouseButton button_; int state_; Task* followup_; }; bool SendKeyEvent(GdkWindow* window, bool press, guint key, guint state) { GdkEvent* event = gdk_event_new(press ? GDK_KEY_PRESS : GDK_KEY_RELEASE); event->key.type = press ? GDK_KEY_PRESS : GDK_KEY_RELEASE; event->key.window = window; g_object_ref(event->key.window); event->key.send_event = false; event->key.time = EventTimeNow(); event->key.state = state; event->key.keyval = key; GdkKeymapKey* keys; gint n_keys; if (!gdk_keymap_get_entries_for_keyval(gdk_keymap_get_default(), event->key.keyval, &keys, &n_keys)) { return false; } event->key.hardware_keycode = keys[0].keycode; event->key.group = keys[0].group; g_free(keys); gdk_event_put(event); // gdk_event_put appends a copy of the event. gdk_event_free(event); return true; } void FakeAMouseMotionEvent(gint x, gint y) { GdkEvent* event = gdk_event_new(GDK_MOTION_NOTIFY); event->motion.send_event = false; event->motion.time = EventTimeNow(); GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, we need to target all events at it regardless of // what widget the mouse is over. event->motion.window = grab_widget->window; } else { event->motion.window = gdk_window_at_pointer(&x, &y); } g_object_ref(event->motion.window); event->motion.x = x; event->motion.y = y; gint origin_x, origin_y; gdk_window_get_origin(event->motion.window, &origin_x, &origin_y); event->motion.x_root = x + origin_x; event->motion.y_root = y + origin_y; event->motion.device = gdk_device_get_core_pointer(); event->type = GDK_MOTION_NOTIFY; gdk_event_put(event); gdk_event_free(event); } } // namespace namespace ui_controls { bool SendKeyPress(gfx::NativeWindow window, wchar_t key, bool control, bool shift, bool alt) { GdkWindow* event_window = NULL; GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, send all events to the grabbed widget. event_window = grab_widget->window; } else if (window) { event_window = GTK_WIDGET(window)->window; } else { // No target was specified. Send the events to the active toplevel. GList* windows = gtk_window_list_toplevels(); for (GList* element = windows; element; element = g_list_next(element)) { GtkWindow* this_window = GTK_WINDOW(element->data); if (gtk_window_is_active(this_window)) { event_window = GTK_WIDGET(this_window)->window; break; } } g_list_free(windows); } if (!event_window) { NOTREACHED() << "Window not specified and none is active"; return false; } bool rv = true; if (control) rv = rv && SendKeyEvent(event_window, true, GDK_Control_L, 0); if (shift) { rv = rv && SendKeyEvent(event_window, true, GDK_Shift_L, control ? GDK_CONTROL_MASK : 0); } if (alt) { guint state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0); rv = rv && SendKeyEvent(event_window, true, GDK_Alt_L, state); } // TODO(estade): handle other state flags besides control, shift, alt? // For example caps lock. guint state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0) | (alt ? GDK_MOD1_MASK : 0); rv = rv && SendKeyEvent(event_window, true, key, state); rv = rv && SendKeyEvent(event_window, false, key, state); if (alt) { guint state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0); rv = rv && SendKeyEvent(event_window, false, GDK_Alt_L, state); } if (shift) { rv = rv && SendKeyEvent(event_window, false, GDK_Shift_L, control ? GDK_CONTROL_MASK : 0); } if (control) rv = rv && SendKeyEvent(event_window, false, GDK_Control_L, 0); return rv; } bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, wchar_t key, bool control, bool shift, bool alt, Task* task) { int release_count = 1; if (control) release_count++; if (shift) release_count++; if (alt) release_count++; // This object will delete itself after running |task|. new EventWaiter(task, GDK_KEY_RELEASE, release_count); return SendKeyPress(window, key, control, shift, alt); } bool SendMouseMove(long x, long y) { gdk_display_warp_pointer(gdk_display_get_default(), gdk_screen_get_default(), x, y); // Sometimes gdk_display_warp_pointer fails to send back any indication of // the move, even though it succesfully moves the server cursor. We fake it in // order to get drags to work. FakeAMouseMotionEvent(x, y); return true; } bool SendMouseMoveNotifyWhenDone(long x, long y, Task* task) { bool rv = SendMouseMove(x, y); // We can't rely on any particular event signalling the completion of the // mouse move. Posting the task to the message loop hopefully guarantees // the pointer has moved before task is run (although it may not run it as // soon as it could). MessageLoop::current()->PostTask(FROM_HERE, task); return rv; } bool SendMouseEvents(MouseButton type, int state) { GdkEvent* event = gdk_event_new(GDK_BUTTON_PRESS); event->button.send_event = false; event->button.time = EventTimeNow(); gint x, y; GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, we need to target all events at it regardless of // what widget the mouse is over. event->button.window = grab_widget->window; gdk_window_get_pointer(event->button.window, &x, &y, NULL); } else { event->button.window = gdk_window_at_pointer(&x, &y); } g_object_ref(event->button.window); event->button.x = x; event->button.y = y; gint origin_x, origin_y; gdk_window_get_origin(event->button.window, &origin_x, &origin_y); event->button.x_root = x + origin_x; event->button.y_root = y + origin_y; event->button.axes = NULL; GdkModifierType modifier; gdk_window_get_pointer(event->button.window, NULL, NULL, &modifier); event->button.state = modifier; event->button.button = type == LEFT ? 1 : (type == MIDDLE ? 2 : 3); event->button.device = gdk_device_get_core_pointer(); event->button.type = GDK_BUTTON_PRESS; if (state & DOWN) gdk_event_put(event); // Also send a release event. GdkEvent* release_event = gdk_event_copy(event); release_event->button.type = GDK_BUTTON_RELEASE; release_event->button.time++; if (state & UP) gdk_event_put(release_event); gdk_event_free(event); gdk_event_free(release_event); return false; } bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, Task* task) { bool rv = SendMouseEvents(type, state); GdkEventType wait_type; if (state & UP) { wait_type = GDK_BUTTON_RELEASE; } else { if (type == LEFT) wait_type = GDK_BUTTON_PRESS; else if (type == MIDDLE) wait_type = GDK_2BUTTON_PRESS; else wait_type = GDK_3BUTTON_PRESS; } new EventWaiter(task, wait_type, 1); return rv; } bool SendMouseClick(MouseButton type) { return SendMouseEvents(type, UP | DOWN); } #if defined(TOOLKIT_VIEWS) void MoveMouseToCenterAndPress(views::View* view, MouseButton button, int state, Task* task) { gfx::Point view_center(view->width() / 2, view->height() / 2); views::View::ConvertPointToScreen(view, &view_center); SendMouseMoveNotifyWhenDone(view_center.x(), view_center.y(), new ClickTask(button, state, task)); } #else void MoveMouseToCenterAndPress(GtkWidget* widget, MouseButton button, int state, Task* task) { gfx::Rect bounds = gtk_util::GetWidgetScreenBounds(widget); SendMouseMoveNotifyWhenDone(bounds.x() + bounds.width() / 2, bounds.y() + bounds.height() / 2, new ClickTask(button, state, task)); } #endif } // namespace ui_controls <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/automation/ui_controls.h" #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> #include "base/gfx/rect.h" #include "base/logging.h" #include "base/message_loop.h" #include "chrome/common/gtk_util.h" #include "chrome/test/automation/automation_constants.h" #if defined(TOOLKIT_VIEWS) #include "views/view.h" #include "views/widget/widget.h" #endif namespace { guint32 EventTimeNow() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } class EventWaiter : public MessageLoopForUI::Observer { public: EventWaiter(Task* task, GdkEventType type) : task_(task), type_(type) { MessageLoopForUI::current()->AddObserver(this); } virtual ~EventWaiter() { MessageLoopForUI::current()->RemoveObserver(this); } // MessageLoop::Observer implementation: virtual void WillProcessEvent(GdkEvent* event) { if (event->type == type_) { // At the time we're invoked the event has not actually been processed. // Use PostTask to make sure the event has been processed before // notifying. // NOTE: if processing a message results in running a nested message // loop, then DidProcessEvent isn't immediately sent. As such, we do // the processing in WillProcessEvent rather than DidProcessEvent. MessageLoop::current()->PostTask(FROM_HERE, task_); delete this; } } virtual void DidProcessEvent(GdkEvent* event) { // No-op. } private: // We pass ownership of task_ to MessageLoop when the corrent event is // received. Task *task_; GdkEventType type_; }; class ClickTask : public Task { public: ClickTask(ui_controls::MouseButton button, int state, Task* followup) : button_(button), state_(state), followup_(followup) { } virtual ~ClickTask() {} virtual void Run() { if (followup_) ui_controls::SendMouseEventsNotifyWhenDone(button_, state_, followup_); else ui_controls::SendMouseEvents(button_, state_); } private: ui_controls::MouseButton button_; int state_; Task* followup_; }; } // namespace namespace ui_controls { bool SendKeyPress(gfx::NativeWindow window, wchar_t key, bool control, bool shift, bool alt) { // TODO(estade): send a release as well? GdkEvent* event = gdk_event_new(GDK_KEY_PRESS); event->key.type = GDK_KEY_PRESS; GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, send all events to the grabbed widget. event->key.window = grab_widget->window; } else if (window) { event->key.window = GTK_WIDGET(window)->window; } else { // No target was specified. Send the events to the focused window. GList* windows = gtk_window_list_toplevels(); for (GList* element = windows; element; element = g_list_next(element)) { GtkWindow* window = GTK_WINDOW(element->data); if (gtk_window_is_active(window)) { event->key.window = GTK_WIDGET(window)->window; break; } } g_list_free(windows); } DCHECK(event->key.window); g_object_ref(event->key.window); event->key.send_event = false; event->key.time = EventTimeNow(); // TODO(estade): handle other state flags besides control, shift, alt? // For example caps lock. event->key.state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0) | (alt ? GDK_MOD1_MASK : 0); event->key.keyval = key; // TODO(estade): fill in the string? GdkKeymapKey* keys; gint n_keys; if (!gdk_keymap_get_entries_for_keyval(gdk_keymap_get_default(), event->key.keyval, &keys, &n_keys)) { return false; } event->key.hardware_keycode = keys[0].keycode; event->key.group = keys[0].group; g_free(keys); gdk_event_put(event); // gdk_event_put appends a copy of the event. gdk_event_free(event); return true; } bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, wchar_t key, bool control, bool shift, bool alt, Task* task) { // This object will delete itself after running |task|. new EventWaiter(task, GDK_KEY_PRESS); return SendKeyPress(window, key, control, shift, alt); } bool SendMouseMove(long x, long y) { gdk_display_warp_pointer(gdk_display_get_default(), gdk_screen_get_default(), x, y); return true; } bool SendMouseMoveNotifyWhenDone(long x, long y, Task* task) { bool rv = SendMouseMove(x, y); // We can't rely on any particular event signalling the completion of the // mouse move. Posting the task to the message loop should gaurantee // the pointer has moved before task is run (although it may not run it as // soon as it could). MessageLoop::current()->PostTask(FROM_HERE, task); return rv; } bool SendMouseEvents(MouseButton type, int state) { GdkEvent* event = gdk_event_new(GDK_BUTTON_PRESS); event->button.send_event = false; event->button.time = EventTimeNow(); gint x, y; GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, we need to target all events at it regardless of // what widget the mouse is over. event->button.window = grab_widget->window; gdk_window_get_pointer(event->button.window, &x, &y, NULL); } else { event->button.window = gdk_window_at_pointer(&x, &y); } g_object_ref(event->button.window); event->motion.x = x; event->motion.y = y; gint origin_x, origin_y; gdk_window_get_origin(event->button.window, &origin_x, &origin_y); event->button.x_root = x + origin_x; event->button.y_root = y + origin_y; event->button.axes = NULL; // TODO(estade): as above, we may want to pack this with the actual state. event->button.state = 0; event->button.button = type == LEFT ? 1 : (type == MIDDLE ? 2 : 3); event->button.device = gdk_device_get_core_pointer(); event->button.type = GDK_BUTTON_PRESS; if (state & DOWN) gdk_event_put(event); // Also send a release event. GdkEvent* release_event = gdk_event_copy(event); release_event->button.type = GDK_BUTTON_RELEASE; release_event->button.time++; if (state & UP) gdk_event_put(release_event); gdk_event_free(event); gdk_event_free(release_event); return false; } bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, Task* task) { bool rv = SendMouseEvents(type, state); GdkEventType wait_type; if (state & UP) { wait_type = GDK_BUTTON_RELEASE; } else { if (type == LEFT) wait_type = GDK_BUTTON_PRESS; else if (type == MIDDLE) wait_type = GDK_2BUTTON_PRESS; else wait_type = GDK_3BUTTON_PRESS; } new EventWaiter(task, wait_type); return rv; } bool SendMouseClick(MouseButton type) { return SendMouseEvents(type, UP | DOWN); } #if defined(TOOLKIT_VIEWS) void MoveMouseToCenterAndPress(views::View* view, MouseButton button, int state, Task* task) { gfx::Point view_center(view->width() / 2, view->height() / 2); views::View::ConvertPointToScreen(view, &view_center); SendMouseMoveNotifyWhenDone(view_center.x(), view_center.y(), new ClickTask(button, state, task)); } #else void MoveMouseToCenterAndPress(GtkWidget* widget, MouseButton button, int state, Task* task) { gfx::Rect bounds = gtk_util::GetWidgetScreenBounds(widget); SendMouseMoveNotifyWhenDone(bounds.x() + bounds.width() / 2, bounds.y() + bounds.height() / 2, new ClickTask(button, state, task)); } #endif } // namespace ui_controls <commit_msg>Send release events as well as press events in linux event mocking infrastructure.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/automation/ui_controls.h" #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> #include "base/gfx/rect.h" #include "base/logging.h" #include "base/message_loop.h" #include "chrome/common/gtk_util.h" #include "chrome/test/automation/automation_constants.h" #if defined(TOOLKIT_VIEWS) #include "views/view.h" #include "views/widget/widget.h" #endif namespace { guint32 EventTimeNow() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } class EventWaiter : public MessageLoopForUI::Observer { public: EventWaiter(Task* task, GdkEventType type, int count) : task_(task), type_(type), count_(count) { MessageLoopForUI::current()->AddObserver(this); } virtual ~EventWaiter() { MessageLoopForUI::current()->RemoveObserver(this); } // MessageLoop::Observer implementation: virtual void WillProcessEvent(GdkEvent* event) { if ((event->type == type_) && (--count_ == 0)) { // At the time we're invoked the event has not actually been processed. // Use PostTask to make sure the event has been processed before // notifying. // NOTE: if processing a message results in running a nested message // loop, then DidProcessEvent isn't immediately sent. As such, we do // the processing in WillProcessEvent rather than DidProcessEvent. MessageLoop::current()->PostTask(FROM_HERE, task_); delete this; } } virtual void DidProcessEvent(GdkEvent* event) { // No-op. } private: // We pass ownership of task_ to MessageLoop when the corrent event is // received. Task *task_; GdkEventType type_; // The number of events of this type to wait for. int count_; }; class ClickTask : public Task { public: ClickTask(ui_controls::MouseButton button, int state, Task* followup) : button_(button), state_(state), followup_(followup) { } virtual ~ClickTask() {} virtual void Run() { if (followup_) ui_controls::SendMouseEventsNotifyWhenDone(button_, state_, followup_); else ui_controls::SendMouseEvents(button_, state_); } private: ui_controls::MouseButton button_; int state_; Task* followup_; }; bool SendKeyEvent(GdkWindow* window, bool press, guint key, guint state) { GdkEvent* event = gdk_event_new(press ? GDK_KEY_PRESS : GDK_KEY_RELEASE); event->key.type = press ? GDK_KEY_PRESS : GDK_KEY_RELEASE; event->key.window = window; g_object_ref(event->key.window); event->key.send_event = false; event->key.time = EventTimeNow(); event->key.state = state; event->key.keyval = key; GdkKeymapKey* keys; gint n_keys; if (!gdk_keymap_get_entries_for_keyval(gdk_keymap_get_default(), event->key.keyval, &keys, &n_keys)) { return false; } event->key.hardware_keycode = keys[0].keycode; event->key.group = keys[0].group; g_free(keys); gdk_event_put(event); // gdk_event_put appends a copy of the event. gdk_event_free(event); return true; } } // namespace namespace ui_controls { bool SendKeyPress(gfx::NativeWindow window, wchar_t key, bool control, bool shift, bool alt) { GdkWindow* event_window = NULL; GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, send all events to the grabbed widget. event_window = grab_widget->window; } else if (window) { event_window = GTK_WIDGET(window)->window; } else { // No target was specified. Send the events to the active toplevel. GList* windows = gtk_window_list_toplevels(); for (GList* element = windows; element; element = g_list_next(element)) { GtkWindow* this_window = GTK_WINDOW(element->data); if (gtk_window_is_active(this_window)) { event_window = GTK_WIDGET(this_window)->window; break; } } g_list_free(windows); } if (!event_window) { NOTREACHED() << "Window not specified and none is active"; return false; } bool rv = true; if (control) rv = rv && SendKeyEvent(event_window, true, GDK_Control_L, 0); if (shift) { rv = rv && SendKeyEvent(event_window, true, GDK_Shift_L, control ? GDK_CONTROL_MASK : 0); } if (alt) { guint state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0); rv = rv && SendKeyEvent(event_window, true, GDK_Alt_L, state); } // TODO(estade): handle other state flags besides control, shift, alt? // For example caps lock. guint state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0) | (alt ? GDK_MOD1_MASK : 0); rv = rv && SendKeyEvent(event_window, true, key, state); rv = rv && SendKeyEvent(event_window, false, key, state); if (alt) { guint state = (control ? GDK_CONTROL_MASK : 0) | (shift ? GDK_SHIFT_MASK : 0); rv = rv && SendKeyEvent(event_window, false, GDK_Alt_L, state); } if (shift) { rv = rv && SendKeyEvent(event_window, false, GDK_Shift_L, control ? GDK_CONTROL_MASK : 0); } if (control) rv = rv && SendKeyEvent(event_window, false, GDK_Control_L, 0); return rv; } bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, wchar_t key, bool control, bool shift, bool alt, Task* task) { int release_count = 1; if (control) release_count++; if (shift) release_count++; if (alt) release_count++; // This object will delete itself after running |task|. new EventWaiter(task, GDK_KEY_RELEASE, release_count); return SendKeyPress(window, key, control, shift, alt); } bool SendMouseMove(long x, long y) { gdk_display_warp_pointer(gdk_display_get_default(), gdk_screen_get_default(), x, y); return true; } bool SendMouseMoveNotifyWhenDone(long x, long y, Task* task) { bool rv = SendMouseMove(x, y); // We can't rely on any particular event signalling the completion of the // mouse move. Posting the task to the message loop should gaurantee // the pointer has moved before task is run (although it may not run it as // soon as it could). MessageLoop::current()->PostTask(FROM_HERE, task); return rv; } bool SendMouseEvents(MouseButton type, int state) { GdkEvent* event = gdk_event_new(GDK_BUTTON_PRESS); event->button.send_event = false; event->button.time = EventTimeNow(); gint x, y; GtkWidget* grab_widget = gtk_grab_get_current(); if (grab_widget) { // If there is a grab, we need to target all events at it regardless of // what widget the mouse is over. event->button.window = grab_widget->window; gdk_window_get_pointer(event->button.window, &x, &y, NULL); } else { event->button.window = gdk_window_at_pointer(&x, &y); } g_object_ref(event->button.window); event->motion.x = x; event->motion.y = y; gint origin_x, origin_y; gdk_window_get_origin(event->button.window, &origin_x, &origin_y); event->button.x_root = x + origin_x; event->button.y_root = y + origin_y; event->button.axes = NULL; // TODO(estade): as above, we may want to pack this with the actual state. event->button.state = 0; event->button.button = type == LEFT ? 1 : (type == MIDDLE ? 2 : 3); event->button.device = gdk_device_get_core_pointer(); event->button.type = GDK_BUTTON_PRESS; if (state & DOWN) gdk_event_put(event); // Also send a release event. GdkEvent* release_event = gdk_event_copy(event); release_event->button.type = GDK_BUTTON_RELEASE; release_event->button.time++; if (state & UP) gdk_event_put(release_event); gdk_event_free(event); gdk_event_free(release_event); return false; } bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, Task* task) { bool rv = SendMouseEvents(type, state); GdkEventType wait_type; if (state & UP) { wait_type = GDK_BUTTON_RELEASE; } else { if (type == LEFT) wait_type = GDK_BUTTON_PRESS; else if (type == MIDDLE) wait_type = GDK_2BUTTON_PRESS; else wait_type = GDK_3BUTTON_PRESS; } new EventWaiter(task, wait_type, 1); return rv; } bool SendMouseClick(MouseButton type) { return SendMouseEvents(type, UP | DOWN); } #if defined(TOOLKIT_VIEWS) void MoveMouseToCenterAndPress(views::View* view, MouseButton button, int state, Task* task) { gfx::Point view_center(view->width() / 2, view->height() / 2); views::View::ConvertPointToScreen(view, &view_center); SendMouseMoveNotifyWhenDone(view_center.x(), view_center.y(), new ClickTask(button, state, task)); } #else void MoveMouseToCenterAndPress(GtkWidget* widget, MouseButton button, int state, Task* task) { gfx::Rect bounds = gtk_util::GetWidgetScreenBounds(widget); SendMouseMoveNotifyWhenDone(bounds.x() + bounds.width() / 2, bounds.y() + bounds.height() / 2, new ClickTask(button, state, task)); } #endif } // namespace ui_controls <|endoftext|>