blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M â | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 â | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 â | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9b2aa5c08a445d1d3483c1d28963f8976b13f850 | 436adbbd309a6d2d283a4e9fe2e7c5c671ce0db7 | /Classes/UIWidgets/GuideLayer.cpp | f43c50e520c0f5c4de6aa26fd9679b0de5f92fa6 | [] | no_license | daxingyou/q_card | 87077b343445acf04132cdd0701952d941f19036 | 3b458ee32ec03509f293324ab8de88efad3d2501 | refs/heads/master | 2021-12-23T19:59:58.341338 | 2017-11-21T06:36:57 | 2017-11-21T06:36:57 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,434 | cpp | #include "GuideLayer.h"
#include "UIWidgets/RichLabel.h"
NS_GAME_FRM_BEGIN
CCPoint GuideLayer::m_ArrowPos = ccp(CCDirector::sharedDirector()->getWinSize().width/2.0f,CCDirector::sharedDirector()->getWinSize().height/2.0f);
GuideLayer* GuideLayer::createGuideLayer()
{
GuideLayer *guideLayer = new GuideLayer;
if (guideLayer && guideLayer->init())
{
guideLayer->autorelease();
return guideLayer;
}
CC_SAFE_DELETE(guideLayer);
return NULL;
}
//æå¯Œé®çœ©
bool GuideLayer::init()
{
if( CCLayer::init() )
{
setKeypadEnabled(true);
setTouchEnabled(true);
for (int i = 0; i<sizeof(m_pSquareVertexes) / sizeof( m_pSquareVertexes[0]); i++ )
{
m_pSquareVertexes[i].x = 0.0f;
m_pSquareVertexes[i].y = 0.0f;
}
setMaskColorsWithA(0.0);
setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionColor));
return true;
}
return false;
}
void GuideLayer::onEnter()
{
CCLayer::onEnter();
}
void GuideLayer::draw()
{
CC_NODE_DRAW_SETUP();
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position | kCCVertexAttribFlag_Color );
//
// Attributes
//
glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, m_pSquareVertexes);
glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_FLOAT, GL_FALSE, 0, m_pSquareColors);
//ccGLBlendFunc( m_tBlendFunc.src, m_tBlendFunc.dst );
glDrawArrays(GL_TRIANGLE_STRIP, 0, 10);
CC_INCREMENT_GL_DRAWS(1);
}
void GuideLayer::setMaskRect(CCRect rect)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
if(rect.size.width == winSize.width || rect.size.height == winSize.height || rect.size.width == 0 ||rect .size.height == 0)
{
m_bIsHideArrowsw = true;
}
else
{
m_bIsHideArrowsw = false;
}
float midHeight = rect.origin.y + rect.size.height/2.0f;
if(midHeight <= winSize.height/2)
{
m_fGirlPosY = midHeight+ rect.size.height/2.0f + 120 ;
}
else if(midHeight > winSize.height/2 && midHeight <winSize.height )
{
m_fGirlPosY = midHeight - rect.size.height/2.0f - 220 ;
}
else
{
m_fGirlPosY = winSize.height/3.0;
}
m_showRect = rect;
m_pSquareVertexes[0].x = rect.origin.x;
m_pSquareVertexes[0].y = rect.origin.y;
m_pSquareVertexes[1].x = 0;
m_pSquareVertexes[1].y = 0;
m_pSquareVertexes[2].x = rect.origin.x+rect.size.width;
m_pSquareVertexes[2].y = rect.origin.y;
m_pSquareVertexes[3].x = winSize.width;
m_pSquareVertexes[3].y = 0;
m_pSquareVertexes[4].x = rect.origin.x+rect.size.width;
m_pSquareVertexes[4].y = rect.origin.y+rect.size.height;
m_pSquareVertexes[5].x = winSize.width;
m_pSquareVertexes[5].y = winSize.height;
m_pSquareVertexes[6].x = rect.origin.x;
m_pSquareVertexes[6].y = rect.origin.y+rect.size.height;
m_pSquareVertexes[7].x = 0;
m_pSquareVertexes[7].y = winSize.height;
m_pSquareVertexes[8] = m_pSquareVertexes[0];
m_pSquareVertexes[9] = m_pSquareVertexes[1];
if(rect.size.width == 0 || rect.size.height == winSize.width)
{
setMaskColorsWithA(0.5);
}
}
void GuideLayer::setMaskColorsWithA(float a)
{
m_pSquareColors[0] =ccc4f(0,0,0, a);
m_pSquareColors[1] =ccc4f(0,0,0, a);
m_pSquareColors[2] =ccc4f(0,0,0, a);
m_pSquareColors[3] =ccc4f(0,0,0, a);
m_pSquareColors[4] =ccc4f(0,0,0, a);
m_pSquareColors[5] =ccc4f(0,0,0, a);
m_pSquareColors[6] =ccc4f(0,0,0, a);
m_pSquareColors[7] =ccc4f(0,0,0, a);
m_pSquareColors[8] =ccc4f(0,0,0, a);
m_pSquareColors[9] =ccc4f(0,0,0, a);
}
//é
眮æç€ºåŸççè·¯åŸ
void GuideLayer::setMaskPicturePath(const char*guideInfo,const char *guideTips, CCPoint poxPoint,emStandDir dirStand, emPromptDirection dir )
{
dirStand = emLeft; //é»è®€éœæ¯å·Šæ¹å
dir = emUpArrow; // é»è®€æ¹å
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSprite* tipArrow = CCSprite::create("img/guide/guide_finger.png");
tipArrow->setAnchorPoint(ccp(0.5,0.5));
if(m_bIsHideArrowsw == true)
{
tipArrow->setVisible(false);
}
CCLayerColor *tipIconNode = CCLayerColor::create(ccc4(0,0,0,0));
tipIconNode->setContentSize(CCSizeMake(310,150));
CCSprite *playerGuideBg = NULL;
{
playerGuideBg = CCSprite::create("img/guide/guide_bg.png");
playerGuideBg->setAnchorPoint(ccp(0,0.5));
if (poxPoint.y != 0)
{
playerGuideBg->setPosition(ccp(20.0f,poxPoint.y ));
}
else
{
playerGuideBg->setPosition(ccp(20.0f,m_fGirlPosY ));
}
addChild(playerGuideBg,10);
}
CCPoint pos= CCPointZero;
switch(dir)
{
case emUpArrow:
tipArrow->setAnchorPoint(ccp(0.5,0.5));
tipArrow->setPosition(m_ArrowPos);
pos = CCPointMake(m_showRect.origin.x + m_showRect.size.width/2+tipArrow->getContentSize().width/2.0,m_showRect.origin.y + m_showRect.size.height/2-tipArrow->getContentSize().height/2.0);
m_ArrowPos = pos ;// CCPointMake(m_showRect.origin.x + m_showRect.size.width,m_showRect.origin.y+m_showRect.size.height);
//tipArrow->setPosition(ccp(m_showRect.origin.x + m_showRect.size.width/2,m_showRect.origin.y+m_showRect.size.height));
break;
case emDownArrow:
tipArrow->setAnchorPoint(ccp(0.5,1.0));
tipArrow->setPosition(m_ArrowPos);
tipArrow->setScaleY(-1);
pos = ccp(m_showRect.origin.x + m_showRect.size.width/2,m_showRect.origin.y -tipArrow->getContentSize().height);
m_ArrowPos = pos;
//tipArrow->setPosition(ccp(m_showRect.origin.x + m_showRect.size.width/2,m_showRect.origin.y -tipArrow->getContentSize().height));
break;
case emLeftArrow:
tipArrow->setAnchorPoint(ccp(0.5,0.5));
tipArrow->setPosition(m_ArrowPos);
tipArrow->setRotation(270);
pos = ccp(m_showRect.origin.x - tipArrow->getContentSize().height/2 ,m_showRect.origin.y + m_showRect.size.height/2);
m_ArrowPos = pos;
//tipArrow->setPosition(ccp(m_showRect.origin.x - tipArrow->getContentSize().height/2 ,m_showRect.origin.y + m_showRect.size.height/2));
break;
case emRightArrow:
tipArrow->setAnchorPoint(ccp(0.5,0.5));
tipArrow->setPosition(m_ArrowPos);
tipArrow->setRotation(90);
pos = ccp(m_showRect.origin.x + m_showRect.size.width + tipArrow->getContentSize().height/2,m_showRect.origin.y+m_showRect.size.height/2);
m_ArrowPos = pos;
//tipArrow->setPosition(ccp(m_showRect.origin.x + m_showRect.size.width + tipArrow->getContentSize().height/2,m_showRect.origin.y+m_showRect.size.height/2));
break;
default:
break;
}
CCActionInterval *action = CCMoveTo::create(0.6f,pos);
tipArrow->runAction(action);
// TODO:ææè¿åš
if(dir == emUpArrow || dir == emDownArrow)
{
tipArrow->runAction(CCRepeatForever::create(CCSequence::createWithTwoActions(CCScaleBy::create(0.3f, 0.95f),
CCScaleTo::create(0.325f, 1))));
}
else
{
CCActionInterval* actionBy = CCMoveBy::create(0.2f, CCPointMake(8,0));
CCActionInterval* actionByBack = actionBy->reverse();
tipArrow->runAction( CCRepeatForever::create(CCSequence::createWithTwoActions(actionBy, actionByBack)));
}
addChild(tipArrow,100);
CCSprite *tipsIcon = CCSprite::create("img/guide/arrow.png");
tipsIcon->setPosition(ccp(playerGuideBg->getContentSize().width - 40.0f,120.0f));
CCActionInterval* actionUp = CCJumpBy::create(2, CCPointMake(0,0), 5, 4);
tipsIcon->runAction(CCRepeatForever::create(actionUp));
playerGuideBg->addChild(tipsIcon,10);
// è®¡ç®æåæ¡çèæ¯çšåŸä»¥åäœçœ®
tipIconNode->setAnchorPoint(CCPointZero);
tipIconNode->setPosition(ccp(275,102));
playerGuideBg->addChild(tipIconNode,0);
if(strlen(guideInfo) == 0 && strlen(guideTips) == 0)
{
playerGuideBg->removeFromParentAndCleanup(true);
}
else
{
CCLabelTTF * label = CCLabelTTF::create(guideInfo, "é»äœ", 22, CCSizeMake(295, 110),kCCTextAlignmentLeft);
label->setAnchorPoint(ccp(0,0));
//RichLabel * label = RichLabel::create(guideDesc.str().c_str(), "fzcyjt", 20, CCSizeMake(255, 150),true,false);
label->setPosition(ccp(0,5));
label->setColor(ccc3(69,20,1));
CCLabelTTF *tipsLabel = CCLabelTTF::create(guideTips,"é»äœ",22/*,CCSizeMake(250, 30),kCCTextAlignmentLeft*/);
//RichLabel *tipsLabel = RichLabel::create(guideTips,"fzcyjt",20,CCSizeMake(255, 30),true,false);
tipsLabel->setAnchorPoint(ccp(0,0.5));
tipsLabel->setPosition(ccp(0,130));
tipsLabel->setColor(ccc3(255, 240, 0));
tipIconNode->addChild(label);
tipIconNode->addChild(tipsLabel);
}
}
bool GuideLayer::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
CCPoint p = touch->getLocation();
if(m_showRect.containsPoint(p) || mSkipBtnRect.containsPoint(p))
{
//CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
//CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,kCCMenuHandlerPriority-1000,false);
//removeFromParentAndCleanup(true);
CCNotificationCenter::sharedNotificationCenter()->postNotification("SEND_GUIDEID_2_SEVERE");
return false;
}
else if(m_showRect.size.width == 0 || m_showRect.size.height == 0)
{
//removeFromParentAndCleanup(true);
CCNotificationCenter::sharedNotificationCenter()->postNotification("SEND_GUIDEID_2_SEVERE");
CCNotificationCenter::sharedNotificationCenter()->postNotification("GUIDE_LAYER_REMOVED");
//CCNotificationCenter::sharedNotificationCenter()->postNotification("LEVEL_TRIGGER_REMOVED");
return true;
}
else
{
return true;
}
}
void GuideLayer::registerWithTouchDispatcher()
{
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,kCCMenuHandlerPriority-1000,true);
}
void GuideLayer::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
//CCPoint p = touch->getLocation();
//if(m_showRect.containsPoint(p))
//{
// removeFromParentAndCleanup(true);
//}
}
void GuideLayer::keyBackClicked()
{
//DialogInquire::getInstance()->show(Global::getInstance()->getString("exit_prompt"));
//DialogInquire::getInstance()->setConfirmCallback(callfuncO_selector(GuideMask::exitGame),this);
//Global::getInstance()->playEffect(15);
/*SRoleInfo * roleInfo = RoleDataManager::getInstance()->getRoleInfo();
int lastGuideId = roleInfo->otherData.nRemainVar[eRemainGuide];
int nextGuide = 0, condType = 0, condValue = 0;
int menuOpen = 0;
Resource::sharedResource()->getNextGuideCondition(lastGuideId, nextGuide, condType, condValue, menuOpen);*/
//ServerMessageHandler::sharedMessageHandler()->setGuideTagId(mCurGuideId);
//mFilterLayer->removeFromParentAndCleanup(true);
//removeFromParentAndCleanup(true);
}
void GuideLayer::exitGame(CCObject* pSender)
{
CCDirector::sharedDirector()->end();
}
void GuideLayer::skip()
{
//keyBackClicked();
CCDirector::sharedDirector()->end();
}
NS_GAME_FRM_END | [
"chenhlb8055@gmail.com"
] | chenhlb8055@gmail.com |
2a42bed18d485e56ffc3d45f25c8000fceebd674 | ef7e91c31436dbe9dffd23a7274afa259e69312f | /DebugRobot14/Commands/autonomousCommandGroup.cpp | e82faa482557e2b76353f2f8be3fedb84189e706 | [] | no_license | FRCTeam1073-TheForceTeam/RobotDiagnostics | a862c560b993f402b99b11511ef63dbe8b5db2b6 | 82ef00d62df39e8cd672a7a45bcab251f8ca382e | refs/heads/master | 2021-01-19T08:15:35.324277 | 2017-03-18T18:05:06 | 2017-03-18T18:05:06 | 13,988,057 | 0 | 0 | null | 2014-06-13T01:39:52 | 2013-10-30T13:57:03 | C++ | UTF-8 | C++ | false | false | 1,315 | cpp | /* FIRST Team 1073's RobotBuilder (0.0.2) for WPILibExtensions ---
Do not mix this code with any other version of RobotBuilder! */
#include "autoCollector.h"
#include "autoElevator.h"
#include "autoDriveTrain.h"
#include "autoLauncher.h"
#include "autoShiftToHigh.h"
#include "autoShiftToLow.h"
#include "autonomousCommandGroup.h"
#include "isRobotReady.h"
autonomousCommandGroup::autonomousCommandGroup() {
AddSequential(new autoLauncher());
AddSequential(new autoShiftToLow());
AddSequential(new autoDriveTrain());
AddSequential(new autoShiftToHigh());
AddSequential(new autoDriveTrain());
AddSequential(new autoShiftToLow());
AddSequential(new autoElevator());
AddSequential(new autoCollector());
AddSequential(new isRobotReady());
// Add Commands here:
// e.g. AddSequential(new Command1());
// AddSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use AddParallel()
// e.g. AddParallel(new Command1());
// AddSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
}
| [
"willster419@outlook.com"
] | willster419@outlook.com |
163c4854be4b1816546cf8e0f603366afead6674 | 4ef81ef0cfa57ca1b8d85807c4004b5248e07c35 | /BreakfastBreakout/GAME3001-W2021-Lab2b-master/src/Bird.cpp | 689cb3c087870e543567d9afebad062efe792c0a | [] | no_license | Yarim-02/Ctrl-Alt-CompleteRepo | a01adc997ee13b49570c9df2bb86633aeabf7b42 | b5a0602d7ee052d0a0915e782f272dcf42cf09a6 | refs/heads/main | 2023-04-15T18:19:36.869297 | 2021-04-24T01:09:18 | 2021-04-24T01:09:18 | 314,329,424 | 0 | 2 | null | 2021-04-24T01:09:19 | 2020-11-19T18:00:56 | C | UTF-8 | C++ | false | false | 4,273 | cpp | #include "Bird.h"
#include "TextureManager.h"
Bird::Bird()
{
TextureManager::Instance()->load("../Assets/textures/Bird1.png", "bird1");
TextureManager::Instance()->load("../Assets/textures/Bird2.png", "bird2");
TextureManager::Instance()->load("../Assets/textures/Bird3png", "bird3");
TextureManager::Instance()->load("../Assets/textures/Bird4.png", "bird4");
TextureManager::Instance()->load("../Assets/textures/Bird5.png", "bird5");
TextureManager::Instance()->load("../Assets/textures/Bird6.png", "bird6");
TextureManager::Instance()->load("../Assets/textures/Bird7.png", "bird7");
TextureManager::Instance()->load("../Assets/textures/Bird8.png", "bird8");
TextureManager::Instance()->load("../Assets/textures/Bird9.png", "bird9");
TextureManager::Instance()->load("../Assets/textures/Bird10.png", "bird10");
TextureManager::Instance()->load("../Assets/textures/Bird11.png", "bird11");
TextureManager::Instance()->load("../Assets/textures/Bird12.png", "bird12");
TextureManager::Instance()->load("../Assets/textures/Bird13.png", "bird13");
//auto size = TextureManager::Instance()->getTextureSize("../Assets/textures/Leaf.png");
setWidth(300);
setHeight(275);
m_active = false;
getTransform()->position = glm::vec2(400.0f, 300.0f);
getRigidBody()->velocity = glm::vec2(0.0f, 0.0f);
getRigidBody()->acceleration = glm::vec2(0.0f, 0.0f);
getRigidBody()->isColliding = false;
setType(BIRD);
}
Bird::~Bird()
= default;
void Bird::draw()
{
if (m_active)
{
if (m_animationFrame < 3)
{
TextureManager::Instance()->draw("bird1",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 6)
{
TextureManager::Instance()->draw("bird2",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 9)
{
TextureManager::Instance()->draw("bird3",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 12)
{
TextureManager::Instance()->draw("bird4",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 15)
{
TextureManager::Instance()->draw("bird5",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 18)
{
TextureManager::Instance()->draw("bird6",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 21)
{
TextureManager::Instance()->draw("bird7",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 24)
{
TextureManager::Instance()->draw("bird8",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 27)
{
TextureManager::Instance()->draw("bird9",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 30)
{
TextureManager::Instance()->draw("bird10",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 33)
{
TextureManager::Instance()->draw("bird11",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 36)
{
TextureManager::Instance()->draw("bird12",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
else if (m_animationFrame < 39)
{
TextureManager::Instance()->draw("bird13",
getTransform()->position.x, getTransform()->position.y, 0, 255, false);
}
}
else
{
TextureManager::Instance()->draw("bird9",
getTransform()->position.x, getTransform()->position.y, 0, 255, false, SDL_FLIP_HORIZONTAL);
}
}
void Bird::update()
{
if (m_active)
{
if (getOffset().y >= 750)
setOffset(glm::vec2(getOffset().x, -1560));
setOffset(glm::vec2(getOffset().x, getOffset().y + 2));
if (m_animationFrame > 38)
m_animationFrame = 0;
m_animationFrame++;
}
}
void Bird::clean()
{
}
int Bird::getPlatformID()
{
return m_platformID;
}
void Bird::setPlatformID(int IDNum)
{
m_platformID = IDNum;
}
bool Bird::getActive()
{
return m_active;
}
void Bird::setActive(bool state)
{
m_active = state;
}
| [
"root@DESKTOP-3KULAHD.localdomain"
] | root@DESKTOP-3KULAHD.localdomain |
0d7d17c3fd7d70aeb2ccddae4e7b5e0645e963b0 | 46b3e4c5a56738328295aba73bb015189832ae8b | /Converter/LegacyFormats/include/LegacyFormats/zonetemplate.h | be30206e7c10143f12e3e5cd1292bd935c1a57f0 | [] | no_license | GrognardsFromHell/EvilTemple-Native | e2d28c7dfac1ac10f91875bd2bef016c6852de16 | cb88b65ba54c9d4edf8c6519d8b1e14074de4aa3 | refs/heads/master | 2020-05-07T11:26:01.422835 | 2011-07-17T14:33:17 | 2011-07-17T14:33:17 | 35,892,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,172 | h | #ifndef ZONETEMPLATE_H
#define ZONETEMPLATE_H
#include "troikaformatsglobal.h"
#include "objectfilereader.h"
#include <QObject>
#include <QQuaternion>
#include <QVector3D>
#include "util.h"
namespace Troika
{
/**
The side length of a square sector in tiles.
*/
const static int SectorSidelength = 64;
class ZoneTemplateData;
class ZoneBackgroundMap;
class TROIKAFORMATS_EXPORT GeometryObject {
public:
GeometryObject(const QVector3D &position, float rotation, const QString &mesh) :
mPosition(position), mRotation(rotation), mScale(1, 1, 1), mMesh(mesh) {
}
GeometryObject(const QVector3D &position,
float rotation,
const QVector3D &scale,
const QString &mesh) :
mPosition(position), mRotation(rotation), mScale(scale), mMesh(mesh) {}
const QVector3D &position() const { return mPosition; }
float rotation() const { return mRotation; }
const QVector3D &scale() const { return mScale; }
const QString &mesh() const { return mMesh; }
private:
QVector3D mPosition;
float mRotation; // in degrees
QVector3D mScale;
QString mMesh;
};
struct Light
{
bool day;
quint64 handle;
quint32 type;
quint8 r, g, b; // Diffuse/Specular
quint8 unknown;
quint8 ur, ug, ub, ua; // Unknown color
QVector4D position;
float dirX, dirY, dirZ;
float range;
float phi;
};
struct ParticleSystem
{
Light light;
quint32 hash;
quint32 id;
};
enum TileFlags
{
TILE_BLOCKS = 1 << 0,
TILE_SINKS = 1 << 1,
TILE_CAN_FLY_OVER = 1 << 2,
TILE_ICY = 1 << 3,
TILE_NATURAL = 1 << 4,
TILE_SOUNDPROOF = 1 << 5,
TILE_INDOOR = 1 << 6,
TILE_REFLECTIVE = 1 << 7,
TILE_BLOCKS_VISION = 1 << 8,
TILE_BLOCKS_UL = 1 << 9,
TILE_BLOCKS_UM = 1 << 10,
TILE_BLOCKS_UR = 1 << 11,
TILE_BLOCKS_ML = 1 << 12,
TILE_BLOCKS_MM = 1 << 13,
TILE_BLOCKS_MR = 1 << 14,
TILE_BLOCKS_LL = 1 << 15,
TILE_BLOCKS_LM = 1 << 16,
TILE_BLOCKS_LR = 1 << 17,
TILE_FLYOVER_UL = 1 << 18,
TILE_FLYOVER_UM = 1 << 19,
TILE_FLYOVER_UR = 1 << 20,
TILE_FLYOVER_ML = 1 << 21,
TILE_FLYOVER_MM = 1 << 22,
TILE_FLYOVER_MR = 1 << 23,
TILE_FLYOVER_LL = 1 << 24,
TILE_FLYOVER_LM = 1 << 25,
TILE_FLYOVER_LR = 1 << 26,
TILE_FLYOVER_COVER = 1 << 27,
};
struct SectorTile
{
quint8 footstepsSound;
quint8 unknown1[3];
quint32 bitfield;
quint64 unknown2;
uchar visibility[3][3];
bool isVisionFlagSet(uint sx, uint sy, uint flag) const {
return (visibility[sx][sy] & flag) == flag;
}
bool isVisionExtend(uint sx, uint sy) const {
return isVisionFlagSet(sx, sy, 1);
}
bool isVisionEnd(uint sx, uint sy) const {
return isVisionFlagSet(sx, sy, 2);
}
bool isVisionBase(uint sx, uint sy) const {
return isVisionFlagSet(sx, sy, 4);
}
bool isVisionArchway(uint sx, uint sy) const {
return isVisionFlagSet(sx, sy, 8);
}
};
class TileSector {
public:
uint x;
uint y;
SectorTile tiles[SectorSidelength][SectorSidelength];
bool hasNegativeHeight;
uchar negativeHeight[192][192];
};
/**
A keyframe entry used for day/night transfer lighting.
*/
struct LightKeyframe {
uint hour;
float red;
float green;
float blue;
};
class TROIKAFORMATS_EXPORT ZoneTemplate : public QObject
{
Q_OBJECT
public:
explicit ZoneTemplate(quint32 id, QObject *parent = 0);
~ZoneTemplate();
quint32 id() const;
ZoneBackgroundMap *dayBackground() const;
ZoneBackgroundMap *nightBackground() const;
const QList<GeometryObject*> &staticGeometry() const;
const QList<GeometryObject*> &clippingGeometry() const;
const QList<TileSector> &tileSectors() const;
const QString &directory() const;
const QPoint &startPosition() const; // Camera start position
quint32 movie(); // Movie to play when entering
bool isTutorialMap() const;
bool isMenuMap() const; // This denotes the first map played in the background of the menu
bool isUnfogged() const; // No fog of war
bool isOutdoor() const;
bool hasDayNightTransfer() const;
bool allowsBedrest() const;
const Light &globalLight() const;
const QList<Light> &lights() const;
const QList<ParticleSystem> &particleSystems() const;
const QString &name() const; // Zone name (translated)
/**
Returns the visible box of the map. The user can only scroll within the bounds of this box
on this map.
*/
const Box3D &scrollBox() const;
const QList<GameObject*> &staticObjects() const;
const QList<GameObject*> &mobiles() const;
/**
Sets the background to use during the day. If no day/night exchange is used
for this zone, this background is also used during the night.
*/
void setDayBackground(ZoneBackgroundMap *backgroundMap);
/**
Sets the background to use during the night. If no day/night exchange is used,
this value is ignored.
*/
void setNightBackground(ZoneBackgroundMap *backgroundMap);
/**
Adds a static geometry object. This could be a tree or a door for instance.
@param object The geometry that is part of this zone template. The template takes ownership
of this pointer.
*/
void addStaticGeometry(GeometryObject *object);
/**
Adds a geometry object that is used to add depth information to the pre rendered background.
@param object The geometry that is part of this zone template. The template takes ownership
of this pointer.
*/
void addClippingGeometry(GeometryObject *object);
void addLight(const Light &light);
void addParticleSystem(const ParticleSystem &particleSystem);
void setName(const QString &name);
void setDirectory(const QString &directory);
void setStartPosition(const QPoint &startPosition);
void setMovie(quint32 movie);
void setTutorialMap(bool enabled);
void setMenuMap(bool enabled);
void setUnfogged(bool enabled);
void setOutdoor(bool enabled);
void setDayNightTransfer(bool enabled);
void setBedrest(bool enabled);
void setScrollBox(const Box3D &scrollBox);
void setGlobalLight(const Light &light);
void addStaticObject(GameObject *gameObject);
void addMobile(GameObject *gameObject);
void addTileSector(const TileSector &tileSector);
/**
The following methods map the data from rules\daylight.mes
*/
const QList<LightKeyframe> &lightingKeyframesDay2d() const;
const QList<LightKeyframe> &lightingKeyframesDay3d() const;
void setLightingKeyframesDay(const QList<LightKeyframe> &keyframes2d,
const QList<LightKeyframe> &keyframes3d);
const QList<LightKeyframe> &lightingKeyframesNight2d() const;
const QList<LightKeyframe> &lightingKeyframesNight3d() const;
void setLightingKeyframesNight(const QList<LightKeyframe> &keyframes2d,
const QList<LightKeyframe> &keyframes3d);
const QList<uint> &soundSchemes() const;
void setSoundSchemes(const QList<uint> &soundSchemes);
private:
QScopedPointer<ZoneTemplateData> d_ptr;
Q_DISABLE_COPY(ZoneTemplate);
};
}
#endif // ZONETEMPLATE_H
| [
"sebastian@hartte.de"
] | sebastian@hartte.de |
a2efd95fc5aeb937238650e5edf3a301733f66f1 | d9b59e8c4d8d8f5466a1cc6641148139269ae8c5 | /Wave Lab/Source/MainWindow.h | 517f29dafa15203ce93ec51517155c7131f63e79 | [] | no_license | aditk3/JUCE-Projects | 159ed61bc9c9311fb339626853f4f09e7e55d89f | 6327ba079f391807c4ceb2912b011046ce5c0cd0 | refs/heads/main | 2023-07-18T08:29:28.158424 | 2021-09-05T03:16:08 | 2021-09-05T03:16:08 | 359,796,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,711 | h | //==============================================================================
// MainWindow.cpp
// This file defines the class representing our app's main window instance.
//==============================================================================
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
/// This class implements the applicatoin window that contains an
/// instance of our MainContentComponent class.
class MainWindow : public DocumentWindow {
public:
/// Constructor. Your method should perform the following actions:
/// * Set the window to use the native title bar for whatever OS the app is on.
/// * Create the main component and assign it to be the main content component
/// of the window. The window should NOT conform to the main component when
/// the content component changes size. See: ResizableWindow::setContentOwned().
/// * The window should be resizable and should use a bottom right corner sizer.
/// * The resize limits of the window should be a minimum 600 width and 400
/// height and double those values as the maximum.
/// * The window should appear in the center of the screen with its minimum
/// width and height.
/// * Set its visibility to true.
MainWindow(String name);
//==============================================================================
// DocumentWindow overrides
/// This is called when the user tries to close this window. Here,
/// we'll just ask the app to quit when this happens, but you can
/// change this to do whatever you need.
void closeButtonPressed() override;
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow)
};
| [
"aditk3@illinois.edu"
] | aditk3@illinois.edu |
4eecff51a84a54327d15caf140ab5c1ad1d360da | 24f34574799d00cf8d749c5cd493dcd91224b8c3 | /ProyectoTFG/src/Main/VulkanRenderShader.cpp | d7ba20a090ab316e5e320d60a979065f12e6817e | [] | no_license | DiegoBV/Generacion-de-terrenos-fractales-para-escenas-3D-en-OpenGL-y-Vulkan | 11288a80afa6a629247a7b69b10f3bdef7874689 | 261479a8b4cb87ba0e1be1b02f38d3b554fe40cf | refs/heads/master | 2023-03-07T18:28:01.324469 | 2021-02-14T20:58:09 | 2021-02-14T20:58:09 | 208,624,555 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,917 | cpp | #if defined(VULKAN_DEBUG) || defined(VULKAN_RELEASE)
#include "VulkanRenderShader.h"
#include "VulkanManager.h"
#include "FileHandler.h"
#include "ShaderInclude.h"
VulkanRenderShader::VulkanRenderShader()
{
}
VulkanRenderShader::~VulkanRenderShader()
{
}
void VulkanRenderShader::init(std::string vertexName, std::string fragmentName)
{
std::string vertexCode = ShaderInclude::InterpretShader((pathName + vertexName).c_str(), "#include");
std::string fragmentCode = ShaderInclude::InterpretShader((pathName + fragmentName).c_str(), "#include");
const char* vShaderCode = vertexCode.c_str();
const char* fShaderCode = fragmentCode.c_str();
std::string rawVertexPath = pathName + rawVertexName + ".vert";
std::string rawFragmentPath = pathName + rawFragmentName + ".frag";
std::fstream rawVertex = FileHandler::openOutputTruncatedFile(rawVertexPath.c_str());
FileHandler::writeRawStringToOutputFile(rawVertex, vShaderCode);
FileHandler::closeFile(rawVertex);
std::fstream rawFragment = FileHandler::openOutputTruncatedFile(rawFragmentPath.c_str());
FileHandler::writeRawStringToOutputFile(rawFragment, fShaderCode);
FileHandler::closeFile(rawFragment);
system(("cd .. & cd .. & cd Shaders/compile & AutoCompileShader.bat " + rawVertexName + " .vert").c_str());
system(("cd .. & cd .. & cd Shaders/compile & AutoCompileShader.bat " + rawFragmentName + " .frag").c_str());
auto vertShaderCode = FileHandler::readBinaryFile((pathName + rawVertexName + compiledExtension).c_str());
auto fragShaderCode = FileHandler::readBinaryFile((pathName + rawFragmentName + compiledExtension).c_str());
vertShaderModule = createShaderModule(vertShaderCode);
fragShaderModule = createShaderModule(fragShaderCode);
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertShaderModule;
vertShaderStageInfo.pName = "main";
fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragShaderModule;
fragShaderStageInfo.pName = "main";
// delete unused files
FileHandler::deleteFile(rawVertexPath.c_str());
FileHandler::deleteFile(rawFragmentPath.c_str());
}
void VulkanRenderShader::release()
{
destroyModules();
// delete compiled files
FileHandler::deleteFile((pathName + rawVertexName + compiledExtension).c_str());
FileHandler::deleteFile((pathName + rawFragmentName + compiledExtension).c_str());
}
void VulkanRenderShader::setUBO(const UniformBufferObject value)
{
ubo = value;
ubo.yDirection = -1;
}
void VulkanRenderShader::destroyModules()
{
vkDestroyShaderModule(VulkanManager::GetSingleton()->getLogicalDevice(), vertShaderModule, nullptr);
vkDestroyShaderModule(VulkanManager::GetSingleton()->getLogicalDevice(), fragShaderModule, nullptr);
}
#endif
| [
"jorgerodrigar2703@gmail.com"
] | jorgerodrigar2703@gmail.com |
a5c741fc9118b6633351dd8cb11169511bf1f46a | fb10f420e1373c404bf9b8dc0c67dde090f37dd6 | /utils/FragementBuffer.cpp | 80e0226d24e3ebf06fcb4970fa8658d07e02d023 | [
"BSD-2-Clause"
] | permissive | NiklasWang/Voyager | 02eeab089037bb12a62b91b106de6b530669fff2 | abff720bd5330b5e7146fcc3e0816b9dddf856ee | refs/heads/main | 2023-06-18T04:40:57.115510 | 2021-07-13T10:20:41 | 2021-07-13T11:15:33 | 382,997,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | cpp | #include "Logs.h"
#include "Atomic.h"
#include "FragementBuffer.h"
#include "ObjectBuffer.h"
namespace voyager {
int32_t FragementBuffer::flush()
{
int32_t rc = NOT_FOUND;
RWLock::AutoRLock l(mMapLock);
auto iter = mMap.begin();
while (iter != mMap.end()) {
rc = iter->second->flush();
iter++;
}
return rc;
}
int32_t FragementBuffer::dump()
{
int32_t rc = NOT_FOUND;
RWLock::AutoRLock l(mMapLock);
auto iter = mMap.begin();
while (iter != mMap.end()) {
rc = iter->second->dump();
iter++;
}
return rc;
}
int32_t FragementBuffer::dump(const char *file, const char *func, const int32_t line)
{
LOGI(mModule, "Dump by %s | %s | +%d", file, func, line);
return dump();
}
FragementBuffer::FragementBuffer(uint32_t eachCapacity) :
mModule(MODULE_UTILS),
mEachCapacity(eachCapacity)
{
}
FragementBuffer::~FragementBuffer()
{
RWLock::AutoWLock l(mMapLock);
while (mMap.begin() != mMap.end()) {
auto iter = mMap.begin();
iter->second->flush();
delete iter->second;
mMap.erase(iter);
}
mMap.clear();
}
};
| [
"niklas.wang@outlook.com"
] | niklas.wang@outlook.com |
3d57c9f9bd73f187c0c5351fac2ae7fa285384c8 | 16ec224e9d0f7352b2e39305cc4356b717f6b5e1 | /WickedEngine/wiRenderTarget.h | 1b8d56f5dcbf83381b86d96d1b60c1090934feef | [
"MIT",
"Zlib"
] | permissive | brian1337/WickedEngine | 04cfafa25b31c7adfa8043303f7d12fc82708e4a | da1036ebbb7a6d938999c59d200d179e511595b2 | refs/heads/master | 2021-01-16T06:06:31.343526 | 2015-12-13T21:13:39 | 2015-12-13T21:13:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,545 | h | #pragma once
#include "CommonInclude.h"
class wiDepthTarget;
class wiRenderTarget
{
private:
int numViews;
bool retargetted;
vector<ID3D11ShaderResourceView*> SAVEDshaderResource;
void clear();
D3D11_TEXTURE2D_DESC textureDesc;
public:
D3D11_VIEWPORT viewPort;
vector<ID3D11Texture2D*> texture2D;
vector<ID3D11RenderTargetView*> renderTarget;
vector<ID3D11ShaderResourceView*> shaderResource;
wiDepthTarget* depth;
wiRenderTarget();
wiRenderTarget(UINT width, UINT height, int numViews = 1, bool hasDepth = false, UINT MSAAC = 1, UINT MSAAQ = 0, DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM, UINT mipMapLevelCount = 1);
~wiRenderTarget();
void Initialize(UINT width, UINT height, int numViews = 1, bool hasDepth = false, UINT MSAAC = 1, UINT MSAAQ = 0, DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM, UINT mipMapLevelCount = 1);
void InitializeCube(UINT size, int numViews, bool hasDepth, DXGI_FORMAT format);
void InitializeCube(UINT size, int numViews, bool hasDepth);
void Activate(ID3D11DeviceContext*);
void Activate(ID3D11DeviceContext* context, float r, float g, float b, float a);
void Activate(ID3D11DeviceContext* context, wiDepthTarget*, float r, float g, float b, float a);
void Activate(ID3D11DeviceContext* context, wiDepthTarget*);
void Set(ID3D11DeviceContext* context);
void Set(ID3D11DeviceContext* context, wiDepthTarget*);
void Retarget(ID3D11ShaderResourceView* resource);
void Restore();
D3D11_TEXTURE2D_DESC GetDesc() const{ return textureDesc; }
UINT GetMipCount();
};
| [
"turanszkij@gmail.com"
] | turanszkij@gmail.com |
e4ca74e76e888c7d1b0a04fe3b8b119a0215503c | a2184c7cadd470712bd32d7827d1ac4031947656 | /shortest job first.cpp | 3003c4ba24e2a897fcac4c9218c09ca8a468cc5e | [] | no_license | amir-haidery/os-programs | f35d1bef5f884868a09e6c467d97224ef90a6c0a | 0040b7430d753db50e5d69b04bc2af4af4853065 | refs/heads/master | 2020-05-07T11:08:19.240696 | 2019-04-09T20:57:18 | 2019-04-09T20:57:18 | 180,448,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,126 | cpp | //PROGRAM FOR SHORTEST-JOB-FIRST(SJF) "CPU SCHEDULING ALGORITHM" WITHOUT PRE_EMPTION
#include<stdio.h>
#include<conio.h>
int main()
{
printf("Name:\t Amir hussain Mohibi \nRollno:\t17BCS078\nB-tech(4rd semester)Computer Engineering\n\n");
int at[10], bt[10], ct[10], wt[10], ta[10], tat[10];
//at-ArritvalTime::br-BurstTime::ct-CompletionTime::ta-TemporaryArray
//wt-WaitingTime::tat-TurnAroundTime::tn-CurrentTime(TimeNow)
int n, i, k, pc=0, pointer = 0, tn =0, c;//pc-ProcessesCompleted
char pn[10][10]; //pn-ProcessName
//
// printf("Enter <ProcessName> <ArrivalTime> <BurstTime>\n");
// scanf("%s%d%d",&pn[i],&at[i],&bt[i]);printf("Enter the number of processes: ");
// scanf("%d",&n);
// printf("Enter <ProcessName> <ArrivalTime> <BurstTime>\n");
// for(i=0;i<n;i++)
printf("Enter number of processes\n");
scanf("%d",&n);
printf("Enter arrival time and burst time for each process\n\n");
for(int i=0;i<n;i++)
{
printf("Arrival time of process[%d] ",i+1);
scanf("%d",&at[i]);
printf("Burst time of process[%d] ",i+1);
scanf("%d",&bt[i]);
printf("\n");
}
for(i=0; i<n; i++)
{
ct[i] = -1;
ta[i] = bt[i];
}
while(pc!=n)
{
c = 0;
for(i=0; i<n; i++)
if(ct[i]<0 && at[i]<=tn)
c++;
if(c==0)
tn++;
else
{
pointer = 0;
while(at[pointer]>tn || ct[pointer]>0)
pointer++;
for(k=pointer+1; k<n; k++)
if(at[k]<=tn && ct[k]<0 && bt[pointer]>bt[k])
pointer = k;
if(ct[pointer]<0)
{
tn=tn+bt[pointer];
bt[pointer] = 0;
ct[pointer] = tn;
wt[pointer] = ct[pointer] - ( at[pointer]+ ta[pointer] );
tat[pointer] = ct[pointer] - at[pointer];
pc++;
}
}
}
printf("\nProcess N0:\tArrivelT\tBurstTime\tCompletionTime\tWaitingTime\tTotalAroundTime\n");
for(i=0;i<n;i++)
printf("%d\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n",i+1,at[i],ta[i],ct[i],wt[i],tat[i]);
return 0;
}
| [
"amir.haidery141400000@gmail.com"
] | amir.haidery141400000@gmail.com |
a05b92a746f6f081fb9d731276372fe924f0298e | 9c7c58220a546d583e22f8737a59e7cc8bb206e6 | /Project/MyProject/MyProject/Source/MyProject/Private/BaseFrame/Libs/Thread/MMutex.h | 97bab9fddbc0604304ea4425a445dd9b50ad61ad | [] | no_license | SiCoYu/UE | 7176f9ece890e226f21cf972e5da4c3c4c4bfe41 | 31722c056d40ad362e5c4a0cba53b05f51a19324 | refs/heads/master | 2021-03-08T05:00:32.137142 | 2019-07-03T12:20:25 | 2019-07-03T12:20:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,107 | h | #ifndef __MMutex_H
#define __MMutex_H
#include "MyProject.h"
//#include "PlatformDefine.h"
// GObject åŒçš MMutex ïŒè MMutex ååŒçš GObject ïŒå æ€åºç±»äœ¿çš MyAllocatedObject
#include "GObject.h"
#include "MyAllocatedObject.h"
#include "PlatformDefine.h"
// åŠæäœ¿çšå€éšçº¿çš
//#ifdef USE_EXTERN_THREAD
// #include "Windows/AllowWindowsPlatformTypes.h"
//
// #include "Sockets/Mutex.h"
//
// #include "Windows/HideWindowsPlatformTypes.h"
//#endif
// error C2371: 'FCriticalSection': redefinition; different basic types
// typedef FWindowsCriticalSection FCriticalSection;
// Engine\Source\Runtime\Core\Public\Windows\WindowsCriticalSection.h
//class FCriticalSection;
MY_BEGIN_NAMESPACE(MyNS)
/**
* @brief äºæ¥
*/
class MMutex : public MyAllocatedObject
{
private:
//#ifdef USE_EXTERN_THREAD
// Mutex* mMutex;
//#else
FCriticalSection* mMutex;
//#endif
public:
MMutex();
~MMutex();
void init();
void dispose();
//#ifdef USE_EXTERN_THREAD
// Mutex* getMutex();
//#else
FCriticalSection* getMutex();
//#endif
void Lock();
void Unlock();
};
MY_END_NAMESPACE
#endif | [
"kuangben2001@163.com"
] | kuangben2001@163.com |
de8444795e30e9763459c91010b53c49126a75d7 | 1ecfad832df388544122a6a04ef88df3867fda6e | /robot_code/gripperStandalone/GripperMain.cpp | 8283161c854d2bbe97bc0dd21979970f70fbe58d | [] | no_license | jnoyola/DomiBot | a2acc9e96c8761352889c2db54ba6b51c4730527 | 1c2599f5f579f50478a9cd1ea55a8a6ae74c1639 | refs/heads/master | 2021-01-01T03:44:43.852039 | 2016-05-31T23:12:25 | 2016-05-31T23:12:25 | 56,945,093 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 888 | cpp | #include <QThread>
#include <chrono>
#include <thread>
#include <iostream>
#include "SchunkGripper.h"
using namespace std;
void OpenGripper();
void CloseGripper();
SchunkGripper *schunkGripper;
int main(int argc, char *argv[])
{
schunkGripper = new SchunkGripper();
schunkGripper->start(QThread::TimeCriticalPriority);
std::cout << "Starting the SchunkGripper thread ..." << std::endl;
string state;
while(1)
{
std::cin >> state;
if(state=="o")
{
OpenGripper();
}
else if(state=="c")
{
CloseGripper();
}
else
{
break;
}
}
return 0;
}
void CloseGripper()
{
schunkGripper->SetDesiredPosition(42, 0, 100);
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
}
void OpenGripper()
{
schunkGripper->SetDesiredPosition(50, 0, 100);
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
}
| [
"karenl7@stanford.edu"
] | karenl7@stanford.edu |
cf4362a99792c5c0f77a74f804d6e0fefbf7c8e2 | 5d6c3bf3c86ecee29f3860a6b78d2f76930f8e72 | /ATK/Utility/FFT.cpp | cadba7a3bedcd6f4e09c318a03c8400fcb38878c | [
"BSD-3-Clause"
] | permissive | AudioBucket/AudioTK | 83462d2fad4869120f6a9f36015fc0146a8bbf37 | 781798666685433dded9f538ae2af70372d47925 | refs/heads/master | 2020-03-27T13:40:08.451953 | 2018-05-12T13:46:34 | 2018-05-12T13:46:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,894 | cpp | /**
* \file FFT.cpp
*/
#include <algorithm>
#include <complex>
#include <cstdlib>
#include <ATK/Utility/FFT.h>
#include <ATK/config.h>
#if ATK_USE_FFTW == 1
#include <fftw3.h>
#endif
#if ATK_USE_IPP == 1
#include <ipp.h>
#endif
#include <gsl/gsl>
namespace ATK
{
template<class DataType_>
class FFT<DataType_>::FFTImpl
{
#if ATK_USE_FFTW == 1
fftw_plan fft_plan;
fftw_plan fft_reverse_plan;
fftw_complex* input_data;
fftw_complex* output_freqs;
#endif
#if ATK_USE_IPP == 1
Ipp64fc *pSrc;
Ipp64fc *pDst;
IppsFFTSpec_C_64fc* pFFTSpec;
IppsDFTSpec_C_64fc* pDFTSpec;
Ipp8u* pFFTSpecBuf;
Ipp8u* pFFTInitBuf;
Ipp8u* pFFTWorkBuf;
bool power_of_two;
#endif
public:
FFTImpl()
#if ATK_USE_FFTW == 1
:fft_plan(nullptr), fft_reverse_plan(nullptr), input_data(nullptr), output_freqs(nullptr)
#endif
#if ATK_USE_IPP == 1
:pSrc(nullptr), pDst(nullptr), pFFTSpec(nullptr), pDFTSpec(nullptr), pFFTSpecBuf(nullptr), pFFTInitBuf(nullptr), pFFTWorkBuf(nullptr), power_of_two(false)
#endif
{
}
~FFTImpl()
{
#if ATK_USE_FFTW == 1
fftw_free(input_data);
fftw_free(output_freqs);
fftw_destroy_plan(fft_plan);
fftw_destroy_plan(fft_reverse_plan);
#endif
#if ATK_USE_IPP == 1
if (pSrc)
ippFree(pSrc);
if (pDst)
ippFree(pDst);
if (pFFTSpec)
ippFree(pFFTSpec);
if (pFFTInitBuf)
ippFree(pFFTInitBuf);
if (pFFTWorkBuf)
ippFree(pFFTWorkBuf);
#endif
}
void set_size(std::size_t size)
{
#if ATK_USE_FFTW == 1
fftw_free(input_data);
fftw_free(output_freqs);
fftw_destroy_plan(fft_plan);
fftw_destroy_plan(fft_reverse_plan);
input_data = fftw_alloc_complex(size);
output_freqs = fftw_alloc_complex(size);
fft_plan = fftw_plan_dft_1d(size, input_data, output_freqs, FFTW_FORWARD, FFTW_ESTIMATE);
fft_reverse_plan = fftw_plan_dft_1d(size, output_freqs, input_data, FFTW_BACKWARD, FFTW_ESTIMATE);
#endif
#if ATK_USE_IPP == 1
power_of_two = ((size & (size - 1)) == 0);
if (pSrc)
ippFree(pSrc);
if (pDst)
ippFree(pDst);
if (pFFTSpec)
ippFree(pFFTSpec);
pFFTSpec = nullptr;
if (pDFTSpec)
ippFree(pDFTSpec);
pDFTSpec = nullptr;
if (pFFTSpecBuf)
ippFree(pFFTSpecBuf);
if (pFFTInitBuf)
ippFree(pFFTInitBuf);
if (pFFTWorkBuf)
ippFree(pFFTWorkBuf);
int sizeFFTSpec, sizeFFTInitBuf, sizeFFTWorkBuf;
if (power_of_two)
{
ippsFFTGetSize_C_64fc(std::lround(std::log(size) / std::log(2)), IPP_FFT_DIV_FWD_BY_N, ippAlgHintAccurate, &sizeFFTSpec, &sizeFFTInitBuf, &sizeFFTWorkBuf);
}
else
{
ippsDFTGetSize_C_64fc(size, IPP_FFT_DIV_FWD_BY_N, ippAlgHintAccurate, &sizeFFTSpec, &sizeFFTInitBuf, &sizeFFTWorkBuf);
}
pFFTSpecBuf = ippsMalloc_8u(sizeFFTSpec);
pFFTInitBuf = ippsMalloc_8u(sizeFFTInitBuf);
pFFTWorkBuf = ippsMalloc_8u(sizeFFTWorkBuf);
pSrc = ippsMalloc_64fc(size);
pDst = ippsMalloc_64fc(size);
if (power_of_two)
{
ippsFFTInit_C_64fc(&pFFTSpec, std::lround(std::log(size) / std::log(2)), IPP_FFT_DIV_FWD_BY_N, ippAlgHintAccurate, pFFTSpecBuf, pFFTInitBuf);
}
else
{
pDFTSpec = (IppsDFTSpec_C_64fc*)ippsMalloc_8u(sizeFFTSpec);
ippsDFTInit_C_64fc(size, IPP_FFT_DIV_FWD_BY_N, ippAlgHintAccurate, pDFTSpec, pFFTInitBuf);
}
if (pFFTInitBuf)
ippFree(pFFTInitBuf);
pFFTInitBuf = nullptr;
#endif
}
void process(const DataType_* input, std::size_t input_size, std::size_t size) const
{
#if ATK_USE_FFTW == 1
double factor = static_cast<double>(size);
for(gsl::index j = 0; j < std::min(input_size, size); ++j)
{
input_data[j][0] = input[j] / factor;
input_data[j][1] = 0;
}
for(gsl::index j = input_size; j < size; ++j)
{
input_data[j][0] = 0;
input_data[j][1] = 0;
}
fftw_execute(fft_plan);
#endif
#if ATK_USE_IPP == 1
for (gsl::index j = 0; j < std::min(input_size, size); ++j)
{
pSrc[j].re = input[j];
pSrc[j].im = 0;
}
for (gsl::index j = input_size; j < size; ++j)
{
pSrc[j].re = 0;
pSrc[j].im = 0;
}
if (power_of_two)
{
ippsFFTFwd_CToC_64fc(pSrc, pDst, pFFTSpec, pFFTWorkBuf);
}
else
{
ippsDFTFwd_CToC_64fc(pSrc, pDst, pDFTSpec, pFFTWorkBuf);
}
#endif
}
void process_forward(std::complex<DataType_>* output, std::size_t size) const
{
for(gsl::index j = 0; j < size; ++j)
{
#if ATK_USE_FFTW == 1
output[j] = std::complex<DataType_>(output_freqs[j][0], output_freqs[j][1]);
#endif
#if ATK_USE_IPP == 1
output[j] = std::complex<DataType_>(pDst[j].re, pDst[j].im);
#endif
}
}
void process_backward(const std::complex<DataType_>* input, DataType_* output, std::size_t input_size, std::size_t size) const
{
#if ATK_USE_FFTW == 1
for(gsl::index j = 0; j < size; ++j)
{
output_freqs[j][0] = input[j].real();
output_freqs[j][1] = input[j].imag();
}
fftw_execute(fft_reverse_plan);
for(gsl::index j = 0; j < input_size; ++j)
{
output[j] = input_data[j][0];
}
#endif
#if ATK_USE_IPP == 1
for (gsl::index j = 0; j < size; ++j)
{
pDst[j].re = input[j].real();
pDst[j].im = input[j].imag();
}
if (power_of_two)
{
ippsFFTInv_CToC_64fc(pDst, pDst, pFFTSpec, pFFTWorkBuf);
}
else
{
ippsDFTInv_CToC_64fc(pDst, pDst, pDFTSpec, pFFTWorkBuf);
}
for (gsl::index j = 0; j < input_size; ++j)
{
output[j] = pDst[j].re;
}
#endif
}
void process(const std::complex<DataType_>* input, std::size_t input_size, std::size_t size) const
{
#if ATK_USE_FFTW == 1
double factor = static_cast<double>(size);
for (gsl::index j = 0; j < std::min(input_size, size); ++j)
{
input_data[j][0] = std::real(input[j]) / factor;
input_data[j][1] = std::imag(input[j]) / factor;
}
for (gsl::index j = input_size; j < size; ++j)
{
input_data[j][0] = 0;
input_data[j][1] = 0;
}
fftw_execute(fft_plan);
#endif
#if ATK_USE_IPP == 1
for (gsl::index j = 0; j < std::min(input_size, size); ++j)
{
pSrc[j].re = std::real(input[j]);
pSrc[j].im = std::imag(input[j]);
}
for (gsl::index j = input_size; j < size; ++j)
{
pSrc[j].re = 0;
pSrc[j].im = 0;
}
if (power_of_two)
{
ippsFFTFwd_CToC_64fc(pSrc, pDst, pFFTSpec, pFFTWorkBuf);
}
else
{
ippsDFTFwd_CToC_64fc(pSrc, pDst, pDFTSpec, pFFTWorkBuf);
}
#endif
}
void process_backward(const std::complex<DataType_>* input, std::complex<DataType_>* output, std::size_t input_size, std::size_t size) const
{
#if ATK_USE_FFTW == 1
for (gsl::index j = 0; j < size; ++j)
{
output_freqs[j][0] = input[j].real();
output_freqs[j][1] = input[j].imag();
}
fftw_execute(fft_reverse_plan);
for (gsl::index j = 0; j < input_size; ++j)
{
output[j] = std::complex<DataType_>(input_data[j][0], input_data[j][1]);
}
#endif
#if ATK_USE_IPP == 1
for (gsl::index j = 0; j < size; ++j)
{
pDst[j].re = input[j].real();
pDst[j].im = input[j].imag();
}
if (power_of_two)
{
ippsFFTInv_CToC_64fc(pDst, pDst, pFFTSpec, pFFTWorkBuf);
}
else
{
ippsDFTInv_CToC_64fc(pDst, pDst, pDFTSpec, pFFTWorkBuf);
}
for (gsl::index j = 0; j < input_size; ++j)
{
output[j] = std::complex<DataType_>(pDst[j].re, pDst[j].im);
}
#endif
}
void get_amp(std::vector<DataType_>& amp) const
{
for(gsl::index i = 0; i < amp.size(); ++i)
{
#if ATK_USE_FFTW == 1
amp[i] = output_freqs[i][0] * output_freqs[i][0];
amp[i] += output_freqs[i][1] * output_freqs[i][1];
amp[i] = std::sqrt(amp[i]);
#endif
#if ATK_USE_IPP == 1
amp[i] = pDst[i].re * pDst[i].re;
amp[i] += pDst[i].im * pDst[i].im;
amp[i] = std::sqrt(amp[i]);
#endif
}
}
void get_angle(std::vector<DataType_>& angle) const
{
for(gsl::index i = 0; i < angle.size(); ++i)
{
#if ATK_USE_FFTW == 1
angle[i] = std::arg(std::complex<DataType_>(output_freqs[i][0], output_freqs[i][1]));
#endif
#if ATK_USE_IPP == 1
angle[i] = std::arg(std::complex<DataType_>(pDst[i].re, pDst[i].im));
#endif
}
}
};
template<class DataType_>
FFT<DataType_>::FFT()
:size(0), impl(new FFTImpl)
{
}
template<class DataType_>
FFT<DataType_>::~FFT()
{
}
template<class DataType_>
void FFT<DataType_>::set_size(std::size_t size)
{
if(this->size == size)
return;
this->size = size;
impl->set_size(size);
}
template<class DataType_>
std::size_t FFT<DataType_>::get_size() const
{
return size;
}
template<class DataType_>
void FFT<DataType_>::process(const DataType_* input, std::size_t input_size) const
{
impl->process(input, input_size, size);
}
template<class DataType_>
void FFT<DataType_>::process_forward(const DataType_* input, std::complex<DataType_>* output, std::size_t input_size) const
{
process(input, input_size);
impl->process_forward(output, size);
}
template<class DataType_>
void FFT<DataType_>::process_backward(const std::complex<DataType_>* input, DataType_* output, std::size_t input_size) const
{
impl->process_backward(input, output, input_size, size);
}
template<class DataType_>
void FFT<DataType_>::process(const std::complex<DataType_>* input, std::size_t input_size) const
{
impl->process(input, input_size, size);
}
template<class DataType_>
void FFT<DataType_>::process_forward(const std::complex<DataType_>* input, std::complex<DataType_>* output, std::size_t input_size) const
{
process(input, input_size);
impl->process_forward(output, size);
}
template<class DataType_>
void FFT<DataType_>::process_backward(const std::complex<DataType_>* input, std::complex<DataType_>* output, std::size_t input_size) const
{
impl->process_backward(input, output, input_size, size);
}
template<class DataType_>
void FFT<DataType_>::get_amp(std::vector<DataType_>& amp) const
{
amp.assign(size / 2 + 1, 0);
impl->get_amp(amp);
}
template<class DataType_>
void FFT<DataType_>::get_angle(std::vector<DataType_>& angle) const
{
angle.assign(size / 2 + 1, 0);
impl->get_angle(angle);
}
template class FFT<double>;
}
| [
"matthieu.brucher@gmail.com"
] | matthieu.brucher@gmail.com |
e71267979034f46b88a71a4e46b9c2157b3ad860 | 0b6309f2222033a58122bb67ca70182899349bbb | /Filerun_candle_vgrid_ì볞/Default Include/ACE 5.4/ACE_wrappers/ace/Proactor.cpp | 40439106376f1b3e7fe77c22c6d42336604a6310 | [
"BSD-3-Clause"
] | permissive | elysionlab/client | 8c0923df53069510bb0557241cee6bc7ed380806 | f67bd232e3eaa859f8b594748d9a3ad306e22c34 | refs/heads/master | 2022-04-16T18:17:33.976968 | 2020-04-06T05:32:59 | 2020-04-06T05:32:59 | 253,389,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,529 | cpp | // Proactor.cpp,v 4.129 2003/08/04 03:53:52 dhinton Exp
#include "ace/Proactor.h"
#if ((defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) || (defined (ACE_HAS_AIO_CALLS)))
// This only works on Win32 platforms and on Unix platforms with aio
// calls.
#include "ace/Proactor_Impl.h"
#include "ace/Object_Manager.h"
#include "ace/Task_T.h"
#if !defined (ACE_HAS_WINCE) && !defined (ACE_LACKS_ACE_SVCCONF)
# include "ace/Service_Config.h"
# endif /* !ACE_HAS_WINCE && !ACE_LACKS_ACE_SVCCONF */
ACE_RCSID(ace, Proactor, "Proactor.cpp,v 4.129 2003/08/04 03:53:52 dhinton Exp")
#include "ace/Task_T.h"
#include "ace/Log_Msg.h"
#include "ace/Framework_Component.h"
#if defined (ACE_HAS_AIO_CALLS)
# include "ace/POSIX_Proactor.h"
#else /* !ACE_HAS_AIO_CALLS */
# include "ace/WIN32_Proactor.h"
#endif /* ACE_HAS_AIO_CALLS */
#if !defined (__ACE_INLINE__)
#include "ace/Proactor.i"
#endif /* __ACE_INLINE__ */
#include "ace/Auto_Event.h"
/// Process-wide ACE_Proactor.
ACE_Proactor *ACE_Proactor::proactor_ = 0;
/// Controls whether the Proactor is deleted when we shut down (we can
/// only delete it safely if we created it!)
int ACE_Proactor::delete_proactor_ = 0;
/**
* @class ACE_Proactor_Timer_Handler
*
* @brief A Handler for timer. It helps in the management of timers
* registered with the Proactor.
*
* This object has a thread that will wait on the earliest time
* in a list of timers and an event. When a timer expires, the
* thread will post a completion event on the port and go back
* to waiting on the timer queue and event. If the event is
* signaled, the thread will refresh the time it is currently
* waiting on (in case the earliest time has changed).
*/
class ACE_Proactor_Timer_Handler : public ACE_Task <ACE_NULL_SYNCH>
{
/// Proactor has special privileges
/// Access needed to: timer_event_
friend class ACE_Proactor;
public:
/// Constructor.
ACE_Proactor_Timer_Handler (ACE_Proactor &proactor);
/// Destructor.
virtual ~ACE_Proactor_Timer_Handler (void);
/// Proactor calls this to shut down the timer handler
/// gracefully. Just calling the destructor alone doesnt do what
/// <destroy> does. <destroy> make sure the thread exits properly.
int destroy (void);
protected:
/// Run by a daemon thread to handle deferred processing. In other
/// words, this method will do the waiting on the earliest timer and
/// event.
virtual int svc (void);
/// Event to wait on.
ACE_Auto_Event timer_event_;
/// Proactor.
ACE_Proactor &proactor_;
/// Flag used to indicate when we are shutting down.
int shutting_down_;
};
ACE_Proactor_Timer_Handler::ACE_Proactor_Timer_Handler (ACE_Proactor &proactor)
: ACE_Task <ACE_NULL_SYNCH> (&proactor.thr_mgr_),
proactor_ (proactor),
shutting_down_ (0)
{
}
ACE_Proactor_Timer_Handler::~ACE_Proactor_Timer_Handler (void)
{
// Mark for closing down.
this->shutting_down_ = 1;
// Signal timer event.
this->timer_event_.signal ();
// Wait for the Timer Handler thread to exit.
this->thr_mgr ()->wait_grp (this->grp_id ());
}
int
ACE_Proactor_Timer_Handler::svc (void)
{
ACE_Time_Value absolute_time;
ACE_Time_Value relative_time;
int result = 0;
while (this->shutting_down_ == 0)
{
// Check whether the timer queue has any items in it.
if (this->proactor_.timer_queue ()->is_empty () == 0)
{
// Get the earliest absolute time.
absolute_time = this->proactor_.timer_queue ()->earliest_time ();
// Get current time from timer queue since we don't know
// which <gettimeofday> was used.
ACE_Time_Value cur_time = this->proactor_.timer_queue ()->gettimeofday ();
// Compare absolute time with curent time received from the
// timer queue.
if (absolute_time > cur_time)
relative_time = absolute_time - cur_time;
else
relative_time = 0;
// Block for relative time.
result = this->timer_event_.wait (&relative_time, 0);
}
else
// The timer queue has no entries, so wait indefinitely.
result = this->timer_event_.wait ();
// Check for timer expiries.
if (result == -1)
{
switch (errno)
{
case ETIME:
// timeout: expire timers
this->proactor_.timer_queue ()->expire ();
break;
default:
// Error.
ACE_ERROR_RETURN ((LM_ERROR,
ACE_LIB_TEXT ("%N:%l:(%P | %t):%p\n"),
ACE_LIB_TEXT ("ACE_Proactor_Timer_Handler::svc:wait failed")),
-1);
}
}
}
return 0;
}
// *********************************************************************
ACE_Proactor_Handle_Timeout_Upcall::ACE_Proactor_Handle_Timeout_Upcall (void)
: proactor_ (0)
{
}
int
ACE_Proactor_Handle_Timeout_Upcall::registration (TIMER_QUEUE &,
ACE_Handler *,
const void *)
{
return 0;
}
int
ACE_Proactor_Handle_Timeout_Upcall::preinvoke (TIMER_QUEUE &,
ACE_Handler *,
const void *,
int,
const ACE_Time_Value &,
const void *&)
{
return 0;
}
int
ACE_Proactor_Handle_Timeout_Upcall::postinvoke (TIMER_QUEUE &,
ACE_Handler *,
const void *,
int,
const ACE_Time_Value &,
const void *)
{
return 0;
}
int
ACE_Proactor_Handle_Timeout_Upcall::timeout (TIMER_QUEUE &,
ACE_Handler *handler,
const void *act,
int,
const ACE_Time_Value &time)
{
if (this->proactor_ == 0)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_LIB_TEXT ("(%t) No Proactor set in ACE_Proactor_Handle_Timeout_Upcall,")
ACE_LIB_TEXT (" no completion port to post timeout to?!@\n")),
-1);
// Create the Asynch_Timer.
ACE_Asynch_Result_Impl *asynch_timer = this->proactor_->create_asynch_timer (*handler,
act,
time,
ACE_INVALID_HANDLE,
0,
-1);
if (asynch_timer == 0)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_LIB_TEXT ("%N:%l:(%P | %t):%p\n"),
ACE_LIB_TEXT ("ACE_Proactor_Handle_Timeout_Upcall::timeout:")
ACE_LIB_TEXT ("create_asynch_timer failed")),
-1);
// Post a completion.
if (asynch_timer->post_completion (this->proactor_->implementation ()) == -1)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_LIB_TEXT ("Failure in dealing with timers: ")
ACE_LIB_TEXT ("PostQueuedCompletionStatus failed\n")),
-1);
return 0;
}
int
ACE_Proactor_Handle_Timeout_Upcall::cancel_type (TIMER_QUEUE &,
ACE_Handler *,
int,
int &)
{
// Do nothing
return 0;
}
int
ACE_Proactor_Handle_Timeout_Upcall::cancel_timer (TIMER_QUEUE &,
ACE_Handler *,
int,
int)
{
// Do nothing
return 0;
}
int
ACE_Proactor_Handle_Timeout_Upcall::deletion (TIMER_QUEUE &,
ACE_Handler *,
const void *)
{
// Do nothing
return 0;
}
int
ACE_Proactor_Handle_Timeout_Upcall::proactor (ACE_Proactor &proactor)
{
if (this->proactor_ == 0)
{
this->proactor_ = &proactor;
return 0;
}
else
ACE_ERROR_RETURN ((LM_ERROR,
ACE_LIB_TEXT ("ACE_Proactor_Handle_Timeout_Upcall is only suppose")
ACE_LIB_TEXT (" to be used with ONE (and only one) Proactor\n")),
-1);
}
// *********************************************************************
ACE_Proactor::ACE_Proactor (ACE_Proactor_Impl *implementation,
int delete_implementation,
TIMER_QUEUE *tq)
: implementation_ (0),
delete_implementation_ (delete_implementation),
timer_handler_ (0),
timer_queue_ (0),
delete_timer_queue_ (0),
end_event_loop_ (0),
event_loop_thread_count_ (0)
{
this->implementation (implementation);
if (this->implementation () == 0)
{
#if defined (ACE_HAS_AIO_CALLS)
// POSIX Proactor.
# if defined (ACE_POSIX_AIOCB_PROACTOR)
ACE_NEW (implementation, ACE_POSIX_AIOCB_Proactor);
# elif defined (ACE_POSIX_SIG_PROACTOR)
ACE_NEW (implementation, ACE_POSIX_SIG_Proactor);
# else /* Default is to use the SIG one */
# if defined(ACE_HAS_POSIX_REALTIME_SIGNALS)
ACE_NEW (implementation, ACE_POSIX_SIG_Proactor);
# else
ACE_NEW (implementation, ACE_POSIX_AIOCB_Proactor);
# endif /* ACE_HAS_POSIX_REALTIME_SIGNALS */
# endif /* ACE_POSIX_AIOCB_PROACTOR */
#elif (defined (ACE_WIN32) && !defined (ACE_HAS_WINCE))
// WIN_Proactor.
ACE_NEW (implementation,
ACE_WIN32_Proactor);
#endif /* ACE_HAS_AIO_CALLS */
this->implementation (implementation);
this->delete_implementation_ = 1;
}
// Set the timer queue.
this->timer_queue (tq);
// Create the timer handler
ACE_NEW (this->timer_handler_,
ACE_Proactor_Timer_Handler (*this));
// Activate <timer_handler>.
if (this->timer_handler_->activate (THR_NEW_LWP) == -1)
ACE_ERROR ((LM_ERROR,
ACE_LIB_TEXT ("%N:%l:(%P | %t):%p\n"),
ACE_LIB_TEXT ("Task::activate:could not create thread\n")));
}
ACE_Proactor::~ACE_Proactor (void)
{
this->close ();
}
ACE_Proactor *
ACE_Proactor::instance (size_t /* threads */)
{
ACE_TRACE ("ACE_Proactor::instance");
if (ACE_Proactor::proactor_ == 0)
{
// Perform Double-Checked Locking Optimization.
ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon,
*ACE_Static_Object_Lock::instance (),
0));
if (ACE_Proactor::proactor_ == 0)
{
ACE_NEW_RETURN (ACE_Proactor::proactor_,
ACE_Proactor,
0);
ACE_Proactor::delete_proactor_ = 1;
ACE_REGISTER_FRAMEWORK_COMPONENT(ACE_Proactor, ACE_Proactor::proactor_);
}
}
return ACE_Proactor::proactor_;
}
ACE_Proactor *
ACE_Proactor::instance (ACE_Proactor * r, int delete_proactor)
{
ACE_TRACE ("ACE_Proactor::instance");
ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon,
*ACE_Static_Object_Lock::instance (), 0));
ACE_Proactor *t = ACE_Proactor::proactor_;
ACE_Proactor::delete_proactor_ = delete_proactor;
ACE_Proactor::proactor_ = r;
ACE_REGISTER_FRAMEWORK_COMPONENT(ACE_Proactor, ACE_Proactor::proactor_);
return t;
}
void
ACE_Proactor::close_singleton (void)
{
ACE_TRACE ("ACE_Proactor::close_singleton");
ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon,
*ACE_Static_Object_Lock::instance ()));
if (ACE_Proactor::delete_proactor_)
{
delete ACE_Proactor::proactor_;
ACE_Proactor::proactor_ = 0;
ACE_Proactor::delete_proactor_ = 0;
}
}
const ACE_TCHAR *
ACE_Proactor::dll_name (void)
{
return ACE_LIB_TEXT ("ACE");
}
const ACE_TCHAR *
ACE_Proactor::name (void)
{
return ACE_LIB_TEXT ("ACE_Proactor");
}
int
ACE_Proactor::check_reconfiguration (ACE_Proactor *)
{
#if !defined (ACE_HAS_WINCE) && !defined (ACE_LACKS_ACE_SVCCONF)
if (ACE_Service_Config::reconfig_occurred ())
{
ACE_Service_Config::reconfigure ();
return 1;
}
#endif /* ! ACE_HAS_WINCE || ! ACE_LACKS_ACE_SVCCONF */
return 0;
}
int
ACE_Proactor::proactor_run_event_loop (PROACTOR_EVENT_HOOK eh)
{
ACE_TRACE ("ACE_Proactor::proactor_run_event_loop");
int result = 0;
{
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1));
// Early check. It is ok to do this without lock, since we care just
// whether it is zero or non-zero.
if (this->end_event_loop_ != 0)
return 0;
// First time you are in. Increment the thread count.
this->event_loop_thread_count_ ++;
}
// Run the event loop.
for (;;)
{
// Check the end loop flag. It is ok to do this without lock,
// since we care just whether it is zero or non-zero.
if (this->end_event_loop_ != 0)
break;
// <end_event_loop> is not set. Ready to do <handle_events>.
result = this->handle_events ();
if (eh != 0 && (*eh) (this))
continue;
if (result == -1)
break;
}
// Leaving the event loop. Decrement the thread count.
{
// Obtain the lock in the MT environments.
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1));
// Decrement the thread count.
this->event_loop_thread_count_ --;
if (this->event_loop_thread_count_ > 0
&& this->end_event_loop_ != 0)
this->proactor_post_wakeup_completions (1);
}
return result;
}
// Handle events for -tv- time. handle_events updates -tv- to reflect
// time elapsed, so do not return until -tv- == 0, or an error occurs.
int
ACE_Proactor::proactor_run_event_loop (ACE_Time_Value &tv,
PROACTOR_EVENT_HOOK eh)
{
ACE_TRACE ("ACE_Proactor::proactor_run_event_loop");
int result = 0;
{
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1));
// Early check. It is ok to do this without lock, since we care just
// whether it is zero or non-zero.
if (this->end_event_loop_ != 0
|| tv == ACE_Time_Value::zero)
return 0;
// First time you are in. Increment the thread count.
this->event_loop_thread_count_ ++;
}
// Run the event loop.
for (;;)
{
// Check the end loop flag. It is ok to do this without lock,
// since we care just whether it is zero or non-zero.
if (this->end_event_loop_ != 0)
break;
// <end_event_loop> is not set. Ready to do <handle_events>.
result = this->handle_events (tv);
if (eh != 0 && (*eh) (this))
continue;
if (result == -1)
break;
}
// Leaving the event loop. Decrement the thread count.
{
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1));
// Decrement the thread count.
this->event_loop_thread_count_ --;
if (this->event_loop_thread_count_ > 0
&& this->end_event_loop_ != 0)
this->proactor_post_wakeup_completions (1);
}
return result;
}
int
ACE_Proactor::proactor_reset_event_loop(void)
{
ACE_TRACE ("ACE_Proactor::proactor_reset_event_loop");
// Obtain the lock in the MT environments.
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1));
this->end_event_loop_ = 0;
return 0;
}
int
ACE_Proactor::proactor_end_event_loop (void)
{
ACE_TRACE ("ACE_Proactor::proactor_end_event_loop");
int how_many = 0;
{
// Obtain the lock, set the end flag and post the wakeup
// completions.
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1));
// Set the end flag.
this->end_event_loop_ = 1;
// Number of completions to post.
how_many = this->event_loop_thread_count_;
if (how_many == 0)
return 0;
}
// Post completions to all the threads so that they will all wake
// up.
return this->proactor_post_wakeup_completions (how_many);
}
int
ACE_Proactor::proactor_event_loop_done (void)
{
ACE_TRACE ("ACE_Proactor::proactor_event_loop_done");
ACE_MT (ACE_GUARD_RETURN (ACE_Thread_Mutex, ace_mon, mutex_, -1));
return this->end_event_loop_ != 0 ? 1 : 0 ;
}
int
ACE_Proactor::close (void)
{
// Close the implementation.
if (this->implementation ()->close () == -1)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_LIB_TEXT ("%N:%l:(%P | %t):%p\n"),
ACE_LIB_TEXT ("ACE_Proactor::close:implementation couldnt be closed")),
-1);
// Delete the implementation.
if (this->delete_implementation_)
{
delete this->implementation ();
this->implementation_ = 0;
}
// Delete the timer handler.
if (this->timer_handler_)
{
delete this->timer_handler_;
this->timer_handler_ = 0;
}
// Delete the timer queue.
if (this->delete_timer_queue_)
{
delete this->timer_queue_;
this->timer_queue_ = 0;
this->delete_timer_queue_ = 0;
}
return 0;
}
int
ACE_Proactor::register_handle (ACE_HANDLE handle,
const void *completion_key)
{
return this->implementation ()->register_handle (handle,
completion_key);
}
long
ACE_Proactor::schedule_timer (ACE_Handler &handler,
const void *act,
const ACE_Time_Value &time)
{
return this->schedule_timer (handler,
act,
time,
ACE_Time_Value::zero);
}
long
ACE_Proactor::schedule_repeating_timer (ACE_Handler &handler,
const void *act,
const ACE_Time_Value &interval)
{
return this->schedule_timer (handler,
act,
interval,
interval);
}
long
ACE_Proactor::schedule_timer (ACE_Handler &handler,
const void *act,
const ACE_Time_Value &time,
const ACE_Time_Value &interval)
{
// absolute time.
ACE_Time_Value absolute_time =
this->timer_queue_->gettimeofday () + time;
// Only one guy goes in here at a time
ACE_MT (ACE_GUARD_RETURN (ACE_SYNCH_RECURSIVE_MUTEX,
ace_mon,
this->timer_queue_->mutex (),
-1));
// Schedule the timer
long result = this->timer_queue_->schedule (&handler,
act,
absolute_time,
interval);
if (result != -1)
{
// no failures: check to see if we are the earliest time
if (this->timer_queue_->earliest_time () == absolute_time)
// wake up the timer thread
if (this->timer_handler_->timer_event_.signal () == -1)
{
// Cancel timer
this->timer_queue_->cancel (result);
result = -1;
}
}
return result;
}
int
ACE_Proactor::cancel_timer (long timer_id,
const void **arg,
int dont_call_handle_close)
{
// No need to singal timer event here. Even if the cancel timer was
// the earliest, we will have an extra wakeup.
return this->timer_queue_->cancel (timer_id,
arg,
dont_call_handle_close);
}
int
ACE_Proactor::cancel_timer (ACE_Handler &handler,
int dont_call_handle_close)
{
// No need to signal timer event here. Even if the cancel timer was
// the earliest, we will have an extra wakeup.
return this->timer_queue_->cancel (&handler,
dont_call_handle_close);
}
int
ACE_Proactor::handle_events (ACE_Time_Value &wait_time)
{
return implementation ()->handle_events (wait_time);
}
int
ACE_Proactor::handle_events (void)
{
return this->implementation ()->handle_events ();
}
int
ACE_Proactor::wake_up_dispatch_threads (void)
{
return 0;
}
int
ACE_Proactor::close_dispatch_threads (int)
{
return 0;
}
size_t
ACE_Proactor::number_of_threads (void) const
{
return this->implementation ()->number_of_threads ();
}
void
ACE_Proactor::number_of_threads (size_t threads)
{
this->implementation ()->number_of_threads (threads);
}
ACE_Proactor::TIMER_QUEUE *
ACE_Proactor::timer_queue (void) const
{
return this->timer_queue_;
}
void
ACE_Proactor::timer_queue (TIMER_QUEUE *tq)
{
// Cleanup old timer queue.
if (this->delete_timer_queue_)
{
delete this->timer_queue_;
this->delete_timer_queue_ = 0;
}
// New timer queue.
if (tq == 0)
{
ACE_NEW (this->timer_queue_,
TIMER_HEAP);
this->delete_timer_queue_ = 1;
}
else
{
this->timer_queue_ = tq;
this->delete_timer_queue_ = 0;
}
// Set the proactor in the timer queue's functor
this->timer_queue_->upcall_functor ().proactor (*this);
}
ACE_HANDLE
ACE_Proactor::get_handle (void) const
{
return this->implementation ()->get_handle ();
}
ACE_Proactor_Impl *
ACE_Proactor::implementation (void) const
{
return this->implementation_;
}
ACE_Asynch_Read_Stream_Impl *
ACE_Proactor::create_asynch_read_stream (void)
{
return this->implementation ()->create_asynch_read_stream ();
}
ACE_Asynch_Write_Stream_Impl *
ACE_Proactor::create_asynch_write_stream (void)
{
return this->implementation ()->create_asynch_write_stream ();
}
ACE_Asynch_Read_Dgram_Impl *
ACE_Proactor::create_asynch_read_dgram (void)
{
return this->implementation ()->create_asynch_read_dgram ();
}
ACE_Asynch_Write_Dgram_Impl *
ACE_Proactor::create_asynch_write_dgram (void)
{
return this->implementation ()->create_asynch_write_dgram ();
}
ACE_Asynch_Read_File_Impl *
ACE_Proactor::create_asynch_read_file (void)
{
return this->implementation ()->create_asynch_read_file ();
}
ACE_Asynch_Write_File_Impl *
ACE_Proactor::create_asynch_write_file (void)
{
return this->implementation ()->create_asynch_write_file ();
}
ACE_Asynch_Accept_Impl *
ACE_Proactor::create_asynch_accept (void)
{
return this->implementation ()->create_asynch_accept ();
}
ACE_Asynch_Connect_Impl *
ACE_Proactor::create_asynch_connect (void)
{
return this->implementation ()->create_asynch_connect ();
}
ACE_Asynch_Transmit_File_Impl *
ACE_Proactor::create_asynch_transmit_file (void)
{
return this->implementation ()->create_asynch_transmit_file ();
}
ACE_Asynch_Read_Stream_Result_Impl *
ACE_Proactor::create_asynch_read_stream_result (ACE_Handler &handler,
ACE_HANDLE handle,
ACE_Message_Block &message_block,
u_long bytes_to_read,
const void* act,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation ()->create_asynch_read_stream_result (handler,
handle,
message_block,
bytes_to_read,
act,
event,
priority,
signal_number);
}
ACE_Asynch_Write_Stream_Result_Impl *
ACE_Proactor::create_asynch_write_stream_result (ACE_Handler &handler,
ACE_HANDLE handle,
ACE_Message_Block &message_block,
u_long bytes_to_write,
const void* act,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation ()->create_asynch_write_stream_result (handler,
handle,
message_block,
bytes_to_write,
act,
event,
priority,
signal_number);
}
ACE_Asynch_Read_File_Result_Impl *
ACE_Proactor::create_asynch_read_file_result (ACE_Handler &handler,
ACE_HANDLE handle,
ACE_Message_Block &message_block,
u_long bytes_to_read,
const void* act,
u_long offset,
u_long offset_high,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation ()->create_asynch_read_file_result (handler,
handle,
message_block,
bytes_to_read,
act,
offset,
offset_high,
event,
priority,
signal_number);
}
ACE_Asynch_Write_File_Result_Impl *
ACE_Proactor::create_asynch_write_file_result (ACE_Handler &handler,
ACE_HANDLE handle,
ACE_Message_Block &message_block,
u_long bytes_to_write,
const void* act,
u_long offset,
u_long offset_high,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation ()->create_asynch_write_file_result (handler,
handle,
message_block,
bytes_to_write,
act,
offset,
offset_high,
event,
priority,
signal_number);
}
ACE_Asynch_Read_Dgram_Result_Impl *
ACE_Proactor::create_asynch_read_dgram_result (ACE_Handler &handler,
ACE_HANDLE handle,
ACE_Message_Block *message_block,
size_t bytes_to_read,
int flags,
int protocol_family,
const void* act,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation()->create_asynch_read_dgram_result (handler,
handle,
message_block,
bytes_to_read,
flags,
protocol_family,
act,
event,
priority,
signal_number);
}
ACE_Asynch_Write_Dgram_Result_Impl *
ACE_Proactor::create_asynch_write_dgram_result (ACE_Handler &handler,
ACE_HANDLE handle,
ACE_Message_Block *message_block,
size_t bytes_to_write,
int flags,
const void* act,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation()->create_asynch_write_dgram_result (handler,
handle,
message_block,
bytes_to_write,
flags,
act,
event,
priority,
signal_number);
}
ACE_Asynch_Accept_Result_Impl *
ACE_Proactor::create_asynch_accept_result (ACE_Handler &handler,
ACE_HANDLE listen_handle,
ACE_HANDLE accept_handle,
ACE_Message_Block &message_block,
u_long bytes_to_read,
const void* act,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation ()->create_asynch_accept_result (handler,
listen_handle,
accept_handle,
message_block,
bytes_to_read,
act,
event,
priority,
signal_number);
}
ACE_Asynch_Connect_Result_Impl *
ACE_Proactor::create_asynch_connect_result (ACE_Handler &handler,
ACE_HANDLE connect_handle,
const void* act,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation ()->create_asynch_connect_result (handler,
connect_handle,
act,
event,
priority,
signal_number);
}
ACE_Asynch_Transmit_File_Result_Impl *
ACE_Proactor::create_asynch_transmit_file_result (ACE_Handler &handler,
ACE_HANDLE socket,
ACE_HANDLE file,
ACE_Asynch_Transmit_File::Header_And_Trailer *header_and_trailer,
u_long bytes_to_write,
u_long offset,
u_long offset_high,
u_long bytes_per_send,
u_long flags,
const void *act,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation ()->create_asynch_transmit_file_result (handler,
socket,
file,
header_and_trailer,
bytes_to_write,
offset,
offset_high,
bytes_per_send,
flags,
act,
event,
priority,
signal_number);
}
ACE_Asynch_Result_Impl *
ACE_Proactor::create_asynch_timer (ACE_Handler &handler,
const void *act,
const ACE_Time_Value &tv,
ACE_HANDLE event,
int priority,
int signal_number)
{
return this->implementation ()->create_asynch_timer (handler,
act,
tv,
event,
priority,
signal_number);
}
int
ACE_Proactor::proactor_post_wakeup_completions (int how_many)
{
return this->implementation ()->post_wakeup_completions (how_many);
}
void
ACE_Proactor::implementation (ACE_Proactor_Impl *implementation)
{
this->implementation_ = implementation;
}
#if defined (ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION)
template class ACE_Timer_Queue_T<ACE_Handler *,
ACE_Proactor_Handle_Timeout_Upcall,
ACE_SYNCH_RECURSIVE_MUTEX>;
template class ACE_Timer_Queue_Iterator_T<ACE_Handler *,
ACE_Proactor_Handle_Timeout_Upcall,
ACE_SYNCH_RECURSIVE_MUTEX>;
template class ACE_Timer_List_T<ACE_Handler *,
ACE_Proactor_Handle_Timeout_Upcall,
ACE_SYNCH_RECURSIVE_MUTEX>;
template class ACE_Timer_List_Iterator_T<ACE_Handler *,
ACE_Proactor_Handle_Timeout_Upcall,
ACE_SYNCH_RECURSIVE_MUTEX>;
template class ACE_Timer_Node_T<ACE_Handler *>;
template class ACE_Unbounded_Set<ACE_Timer_Node_T<ACE_Handler *> *>;
template class ACE_Unbounded_Set_Iterator<ACE_Timer_Node_T<ACE_Handler *> *>;
template class ACE_Node <ACE_Timer_Node_T<ACE_Handler *> *>;
template class ACE_Free_List<ACE_Timer_Node_T<ACE_Handler *> >;
template class ACE_Locked_Free_List<ACE_Timer_Node_T<ACE_Handler *>, ACE_Null_Mutex>;
template class ACE_Timer_Heap_T<ACE_Handler *,
ACE_Proactor_Handle_Timeout_Upcall,
ACE_SYNCH_RECURSIVE_MUTEX>;
template class ACE_Timer_Heap_Iterator_T<ACE_Handler *,
ACE_Proactor_Handle_Timeout_Upcall,
ACE_SYNCH_RECURSIVE_MUTEX>;
template class ACE_Timer_Wheel_T<ACE_Handler *,
ACE_Proactor_Handle_Timeout_Upcall,
ACE_SYNCH_RECURSIVE_MUTEX>;
template class ACE_Timer_Wheel_Iterator_T<ACE_Handler *,
ACE_Proactor_Handle_Timeout_Upcall,
ACE_SYNCH_RECURSIVE_MUTEX>;
#elif defined (ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA)
#pragma instantiate ACE_Timer_Queue_T<ACE_Handler *,\
ACE_Proactor_Handle_Timeout_Upcall,\
ACE_SYNCH_RECURSIVE_MUTEX>
#pragma instantiate ACE_Timer_Queue_Iterator_T<ACE_Handler *,\
ACE_Proactor_Handle_Timeout_Upcall,\
ACE_SYNCH_RECURSIVE_MUTEX>
#pragma instantiate ACE_Timer_List_T<ACE_Handler *,\
ACE_Proactor_Handle_Timeout_Upcall,\
ACE_SYNCH_RECURSIVE_MUTEX>
#pragma instantiate ACE_Timer_List_Iterator_T<ACE_Handler *,\
ACE_Proactor_Handle_Timeout_Upcall,\
ACE_SYNCH_RECURSIVE_MUTEX>
#pragma instantiate ACE_Timer_Node_T<ACE_Handler *>
#pragma instantiate ACE_Unbounded_Set<ACE_Timer_Node_T<ACE_Handler *> *>
#pragma instantiate ACE_Unbounded_Set_Iterator<ACE_Timer_Node_T<ACE_Handler *> *>
#pragma instantiate ACE_Node <ACE_Timer_Node_T<ACE_Handler *> *>
#pragma instantiate ACE_Free_List<ACE_Timer_Node_T<ACE_Handler *> >
#pragma instantiate ACE_Locked_Free_List<ACE_Timer_Node_T<ACE_Handler *>,\
ACE_Null_Mutex>
#pragma instantiate ACE_Timer_Heap_T<ACE_Handler *,\
ACE_Proactor_Handle_Timeout_Upcall,\
ACE_SYNCH_RECURSIVE_MUTEX>
#pragma instantiate ACE_Timer_Heap_Iterator_T<ACE_Handler *,\
ACE_Proactor_Handle_Timeout_Upcall,\
ACE_SYNCH_RECURSIVE_MUTEX>
#pragma instantiate ACE_Timer_Wheel_T<ACE_Handler *,\
ACE_Proactor_Handle_Timeout_Upcall,\
ACE_SYNCH_RECURSIVE_MUTEX>
#pragma instantiate ACE_Timer_Wheel_Iterator_T<ACE_Handler *,\
ACE_Proactor_Handle_Timeout_Upcall,\
ACE_SYNCH_RECURSIVE_MUTEX>
#endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION */
#if defined (ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION)
template class ACE_Framework_Component_T<ACE_Proactor>;
#elif defined (ACE_HAS_TEMPLATE_INSTANTIATION_PRAGMA)
#pragma instantiate ACE_Framework_Component_T<ACE_Proactor>
#endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION */
#else /* !ACE_WIN32 || !ACE_HAS_AIO_CALLS */
ACE_Proactor *
ACE_Proactor::instance (size_t threads)
{
ACE_UNUSED_ARG (threads);
return 0;
}
ACE_Proactor *
ACE_Proactor::instance (ACE_Proactor *)
{
return 0;
}
void
ACE_Proactor::close_singleton (void)
{
}
int
ACE_Proactor::run_event_loop (void)
{
// not implemented
return -1;
}
int
ACE_Proactor::run_event_loop (ACE_Time_Value &tv)
{
// not implemented
ACE_UNUSED_ARG (tv);
return -1;
}
int
ACE_Proactor::end_event_loop (void)
{
// not implemented
return -1;
}
sig_atomic_t
ACE_Proactor::event_loop_done (void)
{
return sig_atomic_t (1);
}
#endif /* ACE_WIN32 || ACE_HAS_AIO_CALLS*/
| [
"elysionlab@gmail.com"
] | elysionlab@gmail.com |
6640548e60d0812cede5916dbf1f0fc5c48c9a3b | cbb4157f9e954d4ed5ba4e0c0bc22a57e175691e | /call option monte carlo.cpp | dae81f51d33fab137af43a27c11f173682f4d8fd | [] | no_license | dshen1/quant-snippets-python-c | f50292e9b94809e8aaa15381c2ed406fb8fcf4fe | 74fb0ca5ce131bdf128ef36ab49005c427b8a814 | refs/heads/master | 2021-01-16T21:21:54.737561 | 2014-03-21T15:11:17 | 2014-03-21T15:11:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cpp | #include <boost/random/variate_generator.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>
#include <iostream>
double pp(double x) //positive part x+
{
if(x>0) return x;
return 0;
}
void main()
{
boost::mt19937 mt;
boost::normal_distribution<> distribution;
boost::variate_generator<boost::mt19937&,boost::normal_distribution<>>* normal(new boost::variate_generator<boost::mt19937&,boost::normal_distribution<>>(mt,distribution));
int numberSimulations=100000;
double S0=100.0;
double sigma=0.2;
double T=1.0;
double K=100.0;
double sum=0;
double payoff=0;
for(int iSim=0;iSim<numberSimulations;iSim++)
{
double x=(*normal)();
payoff=pp(S0*std::exp(-0.5*sigma*sigma*T+sigma*std::sqrt(T)*x)-K);
sum+=payoff;
}
std::cout<<"\nCall="<<sum/numberSimulations<<std::endl;
}
| [
"alexandre.beliakov@gmail.com"
] | alexandre.beliakov@gmail.com |
dc1e42a1d9ff12f73bab7aa7dad73ba06a4884ca | 65a932ec316a0f46de92016ede3b761413201f25 | /UnitTest/GameObject/Projectiles/FireBallRedMuzzleFlash.h | f1e4b0c76890d9fa8e1860eca2da904df49be974 | [] | no_license | lyunDev/directx11-2D-topdown-shooter | ddd3de0fb9b7ca4b4f166b71af44b9964946ae33 | 20bd8b186414c766a84b90470cc4761910c72692 | refs/heads/main | 2023-02-07T18:10:02.630121 | 2020-12-30T04:28:20 | 2020-12-30T04:28:20 | 320,711,874 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | h | #pragma once
#include "MuzzleFlash.h"
class FireBallRedMuzzleFlash : public MuzzleFlash
{
public :
FireBallRedMuzzleFlash();
}; | [
"lyun.dev@gmail.com"
] | lyun.dev@gmail.com |
80c2b572fca11d46e13fb1768a9bcae0739db04b | bafa2c40ea74c1c42393022ab27211b1919e5574 | /GeneticAlg/Crossover.h | 22e2484ef272345cc868b1548ad4230880453bb0 | [] | no_license | DmitriyBragin/Genetic | 94e5fcedabfaaabaa393c04f9392a932b985aaca | 4bf374c6fcaaf9a6d199778df16879288bea5b14 | refs/heads/master | 2020-03-12T00:57:11.336315 | 2018-04-22T15:00:55 | 2018-04-22T15:00:55 | 130,362,609 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 429 | h | #pragma once
#ifndef CROSSOVER_H
#define CROSSOVER_H
#include "Element.h"
class Crossover
{
private:
Element Mother;
Element Father;
public:
Crossover(Element m, Element f) : Mother(m), Father(f) {}
/* ÐОÑкÑеÑÐœÐ°Ñ ÑекПЌбОМаÑÐžÑ (GAfinal, 18 ÑÑÑаМОÑа */
Element linearRecombination();
Element intermediateRecombination();
Element directionRecombination();
Element recombination();
};
#endif | [
"36327306+DmitriyBragin@users.noreply.github.com"
] | 36327306+DmitriyBragin@users.noreply.github.com |
5737eeb58bfe5ed9a70e1a76362329195cb4d76a | 18117273466d58d3300c1b740b4af464c3adb75c | /stream_sql/mysql/smysql/mysqlimpl.cpp | 00cade29abf3abce70ca742fd9edeaf740176236 | [] | no_license | warrior6/socketpro | 0a10d8d567250116890ad917af0b7f437cd566e9 | 1d2098faf606a1e75856437c90ef111fc5f86405 | refs/heads/master | 2020-07-27T02:34:02.346746 | 2019-09-10T13:25:42 | 2019-09-10T13:25:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 84,890 | cpp |
#include "mysqlimpl.h"
#ifndef NDEBUG
#include <iostream>
#endif
#include <cctype>
#include "streamingserver.h"
#include "mysqld_error.h"
#include "../../../include/server_functions.h"
#include "crypt_genhash_impl.h"
namespace SPA
{
namespace ServerSide{
const wchar_t * CMysqlImpl::NO_DB_OPENED_YET = L"No mysql database opened yet";
const wchar_t * CMysqlImpl::BAD_END_TRANSTACTION_PLAN = L"Bad end transaction plan";
const wchar_t * CMysqlImpl::NO_PARAMETER_SPECIFIED = L"No parameter specified";
const wchar_t * CMysqlImpl::BAD_PARAMETER_DATA_ARRAY_SIZE = L"Bad parameter data array length";
const wchar_t * CMysqlImpl::BAD_PARAMETER_COLUMN_SIZE = L"Bad parameter column size";
const wchar_t * CMysqlImpl::DATA_TYPE_NOT_SUPPORTED = L"Data type not supported";
const wchar_t * CMysqlImpl::NO_DB_NAME_SPECIFIED = L"No mysql database name specified";
const wchar_t * CMysqlImpl::MYSQL_LIBRARY_NOT_INITIALIZED = L"Mysql library not initialized";
const wchar_t * CMysqlImpl::BAD_MANUAL_TRANSACTION_STATE = L"Bad manual transaction state";
const wchar_t * CMysqlImpl::UNABLE_TO_SWITCH_TO_DATABASE = L"Unable to switch to database ";
const wchar_t * CMysqlImpl::SERVICE_COMMAND_ERROR = L"Service command error";
st_command_service_cbs CMysqlImpl::m_sql_cbs =
{
CMysqlImpl::sql_start_result_metadata,
CMysqlImpl::sql_field_metadata,
CMysqlImpl::sql_end_result_metadata,
CMysqlImpl::sql_start_row,
CMysqlImpl::sql_end_row,
CMysqlImpl::sql_abort_row,
CMysqlImpl::sql_get_client_capabilities,
CMysqlImpl::sql_get_null,
CMysqlImpl::sql_get_integer,
CMysqlImpl::sql_get_longlong,
CMysqlImpl::sql_get_decimal,
CMysqlImpl::sql_get_double,
CMysqlImpl::sql_get_date,
CMysqlImpl::sql_get_time,
CMysqlImpl::sql_get_datetime,
CMysqlImpl::sql_get_string,
CMysqlImpl::sql_handle_ok,
CMysqlImpl::sql_handle_error,
CMysqlImpl::sql_shutdown
};
CMysqlImpl::CMysqlImpl()
: m_EnableMessages(false), m_oks(0), m_fails(0), m_ti(tiUnspecified),
m_bManual(false), m_qSend(*m_sb), m_NoSending(false), m_sql_errno(0),
m_sql_resultcs(nullptr), m_ColIndex(0), m_sql_flags(0), m_affected_rows(0),
m_last_insert_id(0), m_server_status(0), m_statement_warn_count(0), m_indexCall(0),
m_bBlob(false), m_cmd(COM_SLEEP), m_NoRowset(false) {
m_qSend.ToUtf8(true); //convert UNICODE into UTF8 automatically
m_UQueue.ToUtf8(true); //convert UNICODE into UTF8 automatically
}
CMysqlImpl::~CMysqlImpl() {
CleanDBObjects();
}
unsigned int CMysqlImpl::GetParameters() const {
return (unsigned int) m_stmt.parameters;
}
void CALLBACK CMysqlImpl::OnThreadEvent(SPA::ServerSide::tagThreadEvent te) {
if (te == SPA::ServerSide::teStarted) {
int fail = srv_session_init_thread(CSetGlobals::Globals.Plugin);
assert(!fail);
} else {
srv_session_deinit_thread();
}
}
void CMysqlImpl::OnReleaseSource(bool bClosing, unsigned int info) {
CleanDBObjects();
}
void CMysqlImpl::ResetMemories() {
m_qSend.SetSize(0);
if (m_qSend.GetMaxSize() > 2 * DEFAULT_BIG_FIELD_CHUNK_SIZE) {
m_qSend.ReallocBuffer(2 * DEFAULT_BIG_FIELD_CHUNK_SIZE);
}
}
void CMysqlImpl::OnSwitchFrom(unsigned int nOldServiceId) {
m_oks = 0;
m_fails = 0;
m_ti = tiUnspecified;
m_bManual = false;
}
void CMysqlImpl::OnFastRequestArrive(unsigned short reqId, unsigned int len) {
BEGIN_SWITCH(reqId)
M_I1_R0(idStartBLOB, StartBLOB, unsigned int)
M_I0_R0(idChunk, Chunk)
M_I0_R0(idEndBLOB, EndBLOB)
M_I0_R0(idBeginRows, BeginRows)
M_I0_R0(idTransferring, Transferring)
M_I0_R0(idEndRows, EndRows)
END_SWITCH
m_server_status = 0;
}
int CMysqlImpl::OnSlowRequestArrive(unsigned short reqId, unsigned int len) {
m_NoSending = false;
if (m_pMysql) {
srv_session_attach(m_pMysql.get(), nullptr);
}
BEGIN_SWITCH(reqId)
M_I2_R3(idOpen, Open, std::wstring, unsigned int, int, std::wstring, int)
M_I3_R3(idBeginTrans, BeginTrans, int, std::wstring, unsigned int, int, std::wstring, int)
M_I1_R2(idEndTrans, EndTrans, int, int, std::wstring)
M_I5_R5(idExecute, Execute, std::wstring, bool, bool, bool, UINT64, INT64, int, std::wstring, CDBVariant, UINT64)
M_I2_R3(idPrepare, Prepare, std::wstring, CParameterInfoArray, int, std::wstring, unsigned int)
M_I4_R5(idExecuteParameters, ExecuteParameters, bool, bool, bool, UINT64, INT64, int, std::wstring, CDBVariant, UINT64)
M_I10_R5(idExecuteBatch, ExecuteBatch, std::wstring, std::wstring, int, int, bool, bool, bool, std::wstring, unsigned int, UINT64, INT64, int, std::wstring, CDBVariant, UINT64)
M_I0_R2(idClose, CloseDb, int, std::wstring)
END_SWITCH
if (reqId == idExecuteParameters || reqId == idExecuteBatch)
m_vParam.clear();
m_server_status = 0;
if (m_pMysql) {
srv_session_detach(m_pMysql.get());
}
return 0;
}
int CMysqlImpl::sql_start_result_metadata(void *ctx, uint num_cols, uint flags, const CHARSET_INFO * resultcs) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
impl->m_sql_resultcs = resultcs;
impl->m_sql_flags = flags;
impl->m_vColInfo.clear();
impl->m_bBlob = false;
impl->m_ColIndex = 0;
return 0;
}
int CMysqlImpl::sql_field_metadata(void *ctx, struct st_send_field *f, const CHARSET_INFO * charset) {
CDBColumnInfo info;
size_t len = strlen(f->col_name);
info.DisplayName.assign(f->col_name, f->col_name + len);
if (f->org_col_name && (len = strlen(f->org_col_name)))
info.OriginalName.assign(f->org_col_name, f->org_col_name + len);
else
info.OriginalName = info.DisplayName;
if (f->org_table_name && (len = strlen(f->org_table_name)))
info.TablePath.assign(f->org_table_name, f->org_table_name + len);
else if (f->table_name && (len = strlen(f->table_name)))
info.TablePath.assign(f->table_name, f->table_name + len);
if (f->db_name && (len = strlen(f->db_name)))
info.DBPath.assign(f->db_name, f->db_name + len);
if ((f->flags & NOT_NULL_FLAG) == NOT_NULL_FLAG) {
info.Flags |= CDBColumnInfo::FLAG_NOT_NULL;
}
if ((f->flags & PRI_KEY_FLAG) == PRI_KEY_FLAG) {
info.Flags |= CDBColumnInfo::FLAG_PRIMARY_KEY;
}
if ((f->flags & UNIQUE_KEY_FLAG) == UNIQUE_KEY_FLAG) {
info.Flags |= CDBColumnInfo::FLAG_UNIQUE;
}
if ((f->flags & AUTO_INCREMENT_FLAG) == AUTO_INCREMENT_FLAG) {
info.Flags |= CDBColumnInfo::FLAG_AUTOINCREMENT;
info.Flags |= CDBColumnInfo::FLAG_UNIQUE;
info.Flags |= CDBColumnInfo::FLAG_NOT_NULL;
info.Flags |= CDBColumnInfo::FLAG_PRIMARY_KEY;
}
if ((f->flags & ENUM_FLAG) == ENUM_FLAG) {
info.Flags |= CDBColumnInfo::FLAG_IS_ENUM;
} else if ((f->flags & SET_FLAG) == SET_FLAG) {
info.Flags |= CDBColumnInfo::FLAG_IS_SET;
}
if ((f->flags & UNSIGNED_FLAG) == UNSIGNED_FLAG) {
info.Flags |= CDBColumnInfo::FLAG_IS_UNSIGNED;
}
switch (f->type) {
case MYSQL_TYPE_BIT:
info.ColumnSize = f->length;
info.DeclaredType = L"BIT";
info.Flags |= CDBColumnInfo::FLAG_IS_BIT;
if (f->length == 1)
info.DataType = VT_BOOL;
else if (f->length <= 8)
info.DataType = VT_UI1;
else if (f->length <= 16)
info.DataType = VT_UI2;
else if (f->length <= 32)
info.DataType = VT_UI4;
else if (f->length <= 64)
info.DataType = VT_UI8;
else {
assert(false); //not implemented
}
break;
case MYSQL_TYPE_LONG_BLOB:
info.ColumnSize = f->length;
if (f->charsetnr == IS_BINARY) {
info.DeclaredType = L"LONG_BLOB";
info.DataType = (VT_UI1 | VT_ARRAY); //binary
} else {
info.DeclaredType = L"LONG_TEXT";
info.DataType = (VT_I1 | VT_ARRAY); //text
}
break;
case MYSQL_TYPE_BLOB:
info.ColumnSize = f->length;
if (f->charsetnr == IS_BINARY) {
if (f->length == MYSQL_TINYBLOB) {
info.DeclaredType = L"TINY_BLOB";
} else if (f->length == MYSQL_MIDBLOB) {
info.DeclaredType = L"MEDIUM_BLOB";
} else if (f->length == MYSQL_BLOB) {
info.DeclaredType = L"BLOB";
} else {
info.DeclaredType = L"LONG_BLOB";
}
info.DataType = (VT_UI1 | VT_ARRAY); //binary
} else {
if (f->length == MYSQL_TINYBLOB) {
info.DeclaredType = L"TINY_TEXT";
} else if (f->length == MYSQL_MIDBLOB) {
info.DeclaredType = L"MEDIUM_TEXT";
} else if (f->length == MYSQL_BLOB) {
info.DeclaredType = L"TEXT";
} else {
info.DeclaredType = L"LONG_TEXT";
}
info.DataType = (VT_I1 | VT_ARRAY); //text
}
break;
case MYSQL_TYPE_MEDIUM_BLOB:
info.ColumnSize = f->length;
if (f->charsetnr == IS_BINARY) {
info.DeclaredType = L"MEDIUM_BLOB";
info.DataType = (VT_UI1 | VT_ARRAY); //binary
} else {
info.DeclaredType = L"MEDIUM_TEXT";
info.DataType = (VT_I1 | VT_ARRAY); //text
}
break;
case MYSQL_TYPE_DATE:
info.DeclaredType = L"DATE";
info.DataType = VT_DATE;
break;
case MYSQL_TYPE_NULL:
info.DeclaredType = L"NULL";
info.DataType = VT_NULL;
break;
case MYSQL_TYPE_NEWDATE:
info.DeclaredType = L"NEWDATE";
info.DataType = VT_DATE;
break;
case MYSQL_TYPE_SET:
info.ColumnSize = f->length;
info.DeclaredType = L"SET";
info.DataType = (VT_I1 | VT_ARRAY); //string
break;
case MYSQL_TYPE_DATETIME:
info.DeclaredType = L"DATETIME";
info.Scale = (unsigned char) f->decimals;
info.DataType = VT_DATE;
break;
case MYSQL_TYPE_NEWDECIMAL:
info.DeclaredType = L"NEWDECIMAL";
info.DataType = VT_DECIMAL;
info.Scale = (unsigned char) f->decimals;
info.Precision = (unsigned char) (f->length - f->decimals);
break;
case MYSQL_TYPE_DECIMAL:
info.DeclaredType = L"DECIMAL";
info.DataType = VT_DECIMAL;
info.Scale = (unsigned char) f->decimals;
info.Precision = (unsigned char) (f->length - f->decimals);
break;
case MYSQL_TYPE_DOUBLE:
info.DeclaredType = L"DOUBLE";
info.DataType = VT_R8;
break;
case MYSQL_TYPE_ENUM:
info.ColumnSize = f->length;
info.DeclaredType = L"ENUM";
info.DataType = (VT_I1 | VT_ARRAY); //string
break;
case MYSQL_TYPE_FLOAT:
info.DeclaredType = L"FLOAT";
info.DataType = VT_R4;
break;
case MYSQL_TYPE_GEOMETRY:
info.ColumnSize = f->length;
info.DeclaredType = L"GEOMETRY";
info.DataType = (VT_UI1 | VT_ARRAY); //binary array
break;
case MYSQL_TYPE_INT24:
info.DeclaredType = L"INT24";
if ((f->flags & UNSIGNED_FLAG) == UNSIGNED_FLAG)
info.DataType = VT_UI4;
else
info.DataType = VT_I4;
break;
case MYSQL_TYPE_LONG:
info.DeclaredType = L"INT";
if ((f->flags & UNSIGNED_FLAG) == UNSIGNED_FLAG)
info.DataType = VT_UI4;
else
info.DataType = VT_I4;
break;
case MYSQL_TYPE_LONGLONG:
info.DeclaredType = L"BIGINT";
if ((f->flags & UNSIGNED_FLAG) == UNSIGNED_FLAG)
info.DataType = VT_UI8;
else
info.DataType = VT_I8;
break;
case MYSQL_TYPE_SHORT:
info.DeclaredType = L"SHORT";
if ((f->flags & UNSIGNED_FLAG) == UNSIGNED_FLAG)
info.DataType = VT_UI2;
else
info.DataType = VT_I2;
break;
case MYSQL_TYPE_STRING:
if ((f->flags & ENUM_FLAG) == ENUM_FLAG) {
info.DeclaredType = L"ENUM";
info.DataType = (VT_I1 | VT_ARRAY); //string
} else if ((f->flags & SET_FLAG) == SET_FLAG) {
info.DeclaredType = L"SET";
info.DataType = (VT_I1 | VT_ARRAY); //string
} else {
if (f->charsetnr == IS_BINARY) {
info.DeclaredType = L"BINARY";
info.DataType = (VT_UI1 | VT_ARRAY);
} else {
info.DeclaredType = L"CHAR";
info.DataType = (VT_I1 | VT_ARRAY); //string
}
}
info.ColumnSize = f->length / 3;
break;
case MYSQL_TYPE_TIME:
info.DeclaredType = L"TIME";
info.Scale = (unsigned char) f->decimals;
info.DataType = VT_DATE;
break;
case MYSQL_TYPE_TIMESTAMP:
info.DeclaredType = L"TIMESTAMP";
info.Scale = (unsigned char) f->decimals;
info.DataType = VT_DATE;
break;
case MYSQL_TYPE_TINY:
info.DeclaredType = L"TINY";
if ((f->flags & UNSIGNED_FLAG) == UNSIGNED_FLAG)
info.DataType = VT_UI1;
else
info.DataType = VT_I1;
break;
case MYSQL_TYPE_JSON:
info.ColumnSize = f->length;
if (!info.ColumnSize)
info.ColumnSize = (~0);
info.DeclaredType = L"JSON";
info.DataType = (VT_I1 | VT_ARRAY); //string
break;
case MYSQL_TYPE_TINY_BLOB:
info.ColumnSize = f->length;
if (f->charsetnr == IS_BINARY) {
info.DeclaredType = L"TINY_BLOB";
info.DataType = (VT_UI1 | VT_ARRAY); //binary
} else {
info.DeclaredType = L"TINY_TEXT";
info.DataType = (VT_I1 | VT_ARRAY); //text
}
break;
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_VARCHAR:
info.ColumnSize = f->length / 3;
if (f->charsetnr == IS_BINARY) {
info.DeclaredType = L"VARBINARY";
info.DataType = (VT_UI1 | VT_ARRAY);
} else {
info.DeclaredType = L"VARCHAR";
info.DataType = (VT_I1 | VT_ARRAY); //string
}
break;
case MYSQL_TYPE_YEAR:
info.DeclaredType = L"YEAR";
info.DataType = VT_I2;
break;
default:
info.ColumnSize = f->length;
info.DeclaredType = L"?-unknown-?";
if (f->charsetnr == IS_BINARY) {
info.DeclaredType = L"VARBINARY";
info.DataType = (VT_UI1 | VT_ARRAY);
} else {
info.DeclaredType = L"VARCHAR";
info.DataType = (VT_I1 | VT_ARRAY); //string
}
break;
}
CMysqlImpl *impl = (CMysqlImpl *) ctx;
impl->m_vColInfo.push_back(info);
if (impl->m_cmd == COM_STMT_PREPARE) {
if (info.DisplayName == L"?")
impl->m_stmt.parameters += 1;
}
return 0;
}
int CMysqlImpl::sql_end_result_metadata(void *ctx, uint server_status, uint warn_count) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
impl->m_server_status = server_status;
CUQueue &q = impl->m_qSend;
q.SetSize(0);
if (!impl->m_NoSending) {
q << impl->m_vColInfo << impl->m_indexCall;
if ((server_status & SERVER_PS_OUT_PARAMS) == SERVER_PS_OUT_PARAMS) {
q << (unsigned int) impl->m_vColInfo.size();
} else if (impl->m_NoRowset) {
q.SetSize(0);
return 0;
}
unsigned int ret = impl->SendResult(idRowsetHeader, q.GetBuffer(), q.GetSize());
q.SetSize(0);
if (ret == REQUEST_CANCELED || ret == SOCKET_NOT_FOUND) {
return 1; //an error occured, server will abort the command
}
}
return 0;
}
int CMysqlImpl::sql_start_row(void *ctx) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
impl->m_ColIndex = 0;
return 0;
}
int CMysqlImpl::sql_end_row(void *ctx) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS))
return 0;
CUQueue &q = impl->m_qSend;
if ((q.GetSize() >= DEFAULT_RECORD_BATCH_SIZE || impl->m_bBlob) && !impl->SendRows(q)) {
return 1;
}
impl->m_bBlob = false;
return 0;
}
void CMysqlImpl::sql_abort_row(void *ctx) {
//CMysqlImpl *impl = (CMysqlImpl *) ctx;
}
ulong CMysqlImpl::sql_get_client_capabilities(void *ctx) {
ulong power = (CLIENT_MULTI_STATEMENTS | CLIENT_MULTI_RESULTS | CLIENT_PS_MULTI_RESULTS);
return power;
}
int CMysqlImpl::sql_get_null(void *ctx) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS))
return 0;
CUQueue &q = impl->m_qSend;
q << (VARTYPE) VT_NULL;
++impl->m_ColIndex;
return 0;
}
int CMysqlImpl::sql_get_integer(void * ctx, longlong value) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_cmd == COM_STMT_PREPARE && impl->m_ColIndex == 0) {
impl->m_stmt.stmt_id = (unsigned long) value;
++impl->m_ColIndex;
return 0;
} else if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS)) {
return 0;
}
CUQueue &q = impl->m_qSend;
const CDBColumnInfo &info = impl->m_vColInfo[impl->m_ColIndex];
q << info.DataType;
switch (info.DataType) {
default:
if (impl->m_cmd != COM_STMT_PREPARE) {
assert(false);
}
break;
case VT_UI1:
q.Push((const unsigned char*) &value, sizeof (unsigned char));
break;
case VT_UI2:
q << (const unsigned short&) value;
break;
case VT_UI4:
q << (const unsigned int&) value;
break;
case VT_UI8:
q << (const UINT64&) value;
break;
case VT_I1:
q.Push((const char*) &value, sizeof (char));
break;
case VT_I2:
q << (const short&) value;
break;
case VT_I4:
q << (const int&) value;
break;
case VT_I8:
q << (const INT64&) value;
break;
}
++impl->m_ColIndex;
return 0;
}
int CMysqlImpl::sql_get_longlong(void * ctx, longlong value, uint is_unsigned) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS))
return 0;
CUQueue &q = impl->m_qSend;
const CDBColumnInfo &info = impl->m_vColInfo[impl->m_ColIndex];
q << info.DataType;
switch (info.DataType) {
default:
assert(false);
break;
case VT_I1:
q.Push((const char*) &value, sizeof (char));
break;
case VT_I2:
q << (const short&) value;
break;
case VT_I4:
q << (const int&) value;
break;
case VT_I8:
q << (const INT64&) value;
break;
case VT_UI1:
q.Push((const unsigned char*) &value, sizeof (unsigned char));
break;
case VT_UI2:
q << (const unsigned short&) value;
break;
case VT_UI4:
q << (const unsigned int&) value;
break;
case VT_UI8:
q << (const UINT64&) value;
break;
}
++impl->m_ColIndex;
return 0;
}
void CMysqlImpl::ToDecimal(const decimal_t &src, bool large, DECIMAL & dec) {
char str[64] =
{ 0};
int len = sizeof (str);
decimal2string(&src, str, &len, 0, 0, 0);
if (large) {
SPA::ParseDec_long(str, dec);
} else {
SPA::ParseDec(str, dec);
}
}
int CMysqlImpl::sql_get_decimal(void * ctx, const decimal_t * value) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS))
return 0;
DECIMAL dec;
const CDBColumnInfo &info = impl->m_vColInfo[impl->m_ColIndex];
ToDecimal(*value, info.Precision > 19, dec);
CUQueue &q = impl->m_qSend;
q << (VARTYPE) VT_DECIMAL << dec;
++impl->m_ColIndex;
return 0;
}
int CMysqlImpl::sql_get_double(void * ctx, double value, uint32 decimals) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS))
return 0;
CUQueue &q = impl->m_qSend;
const CDBColumnInfo &info = impl->m_vColInfo[impl->m_ColIndex];
q << info.DataType;
switch (info.DataType) {
default:
assert(false);
break;
case VT_R4:
q << (const float&) value;
break;
case VT_R8:
q << value;
break;
}
++impl->m_ColIndex;
return 0;
}
int CMysqlImpl::sql_get_date(void * ctx, const MYSQL_TIME * value) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS))
return 0;
CUQueue &q = impl->m_qSend;
q << (VARTYPE) VT_DATE << ToUDateTime(*value);
++impl->m_ColIndex;
return 0;
}
int CMysqlImpl::sql_get_time(void * ctx, const MYSQL_TIME * value, uint decimals) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS))
return 0;
CUQueue &q = impl->m_qSend;
q << (VARTYPE) VT_DATE << ToUDateTime(*value);
++impl->m_ColIndex;
return 0;
}
int CMysqlImpl::sql_get_datetime(void * ctx, const MYSQL_TIME * value, uint decimals) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS))
return 0;
CUQueue &q = impl->m_qSend;
q << (VARTYPE) VT_DATE << ToUDateTime(*value);
++impl->m_ColIndex;
return 0;
}
int CMysqlImpl::sql_get_string(void * ctx, const char * const value, size_t length, const CHARSET_INFO * const valuecs) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (impl->m_NoRowset && !(impl->m_server_status & SERVER_PS_OUT_PARAMS))
return 0;
CUQueue &q = impl->m_qSend;
const CDBColumnInfo &info = impl->m_vColInfo[impl->m_ColIndex];
if (info.DeclaredType == L"BIT") {
q << info.DataType;
if (info.DataType == VT_BOOL) {
VARIANT_BOOL b = (*value ? VARIANT_TRUE : VARIANT_FALSE);
q << b;
} else {
switch (info.DataType) {
case VT_UI1:
assert(length == sizeof (unsigned char));
q.Push((const unsigned char*) value, sizeof (unsigned char));
break;
case VT_UI2:
{
assert(length == sizeof (unsigned short));
UINT64 data = ConvertBitsToInt((const unsigned char *) value, sizeof (unsigned short));
q << (unsigned short) data;
}
break;
case VT_UI4:
{
assert(length == sizeof (unsigned int));
UINT64 data = ConvertBitsToInt((const unsigned char *) value, sizeof (unsigned int));
q << (unsigned int) data;
}
break;
case VT_I8:
{
assert(length == sizeof (UINT64));
UINT64 data = ConvertBitsToInt((const unsigned char *) value, sizeof (UINT64));
q << data;
}
break;
default:
assert(false);
break;
}
}
} else {
if (info.DataType == VT_DECIMAL) {
q << info.DataType;
DECIMAL dec;
if (length <= 19) {
ParseDec(value, dec);
} else {
ParseDec_long(value, dec);
}
q << dec;
} else if (length <= DEFAULT_BIG_FIELD_CHUNK_SIZE) {
q << info.DataType;
q << (unsigned int) length;
q.Push((const unsigned char*) value, (unsigned int) length);
} else {
if (q.GetSize() && !impl->SendRows(q, true)) {
return 1;
}
bool batching = impl->IsBatching();
if (batching) {
impl->CommitBatching();
}
if (!impl->SendBlob(info.DataType, (const unsigned char *) value, (unsigned int) length)) {
return 1;
}
if (batching) {
impl->StartBatching();
}
impl->m_bBlob = true;
}
}
++impl->m_ColIndex;
return 0;
}
void CMysqlImpl::sql_handle_ok(void * ctx, uint server_status, uint statement_warn_count, ulonglong affected_rows, ulonglong last_insert_id, const char * const message) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (!impl)
return;
CUQueue &q = impl->m_qSend;
if ((server_status & SERVER_PS_OUT_PARAMS) == SERVER_PS_OUT_PARAMS) {
//tell output parameter data
unsigned int sent = impl->SendResult(idOutputParameter, q.GetBuffer(), q.GetSize());
q.SetSize(0);
if (sent == REQUEST_CANCELED || sent == SOCKET_NOT_FOUND) {
return;
}
} else if (q.GetSize()) {
if (!impl->SendRows(q))
return;
} else if ((server_status & SERVER_QUERY_WAS_SLOW) == SERVER_QUERY_WAS_SLOW) {
return;
}
if (impl->m_indexCall && impl->m_cmd != COM_STMT_EXECUTE)
++impl->m_oks;
impl->m_sql_errno = 0;
impl->m_server_status |= server_status;
impl->m_statement_warn_count = statement_warn_count;
impl->m_affected_rows += affected_rows;
if (impl->m_indexCall && last_insert_id)
impl->m_last_insert_id = last_insert_id;
if (message)
impl->m_err_msg = SPA::Utilities::ToWide(message);
else
impl->m_err_msg.clear();
}
void CMysqlImpl::sql_handle_error(void * ctx, uint sql_errno, const char * const err_msg, const char * const sqlstate) {
CMysqlImpl *impl = (CMysqlImpl *) ctx;
if (!impl)
return;
if (impl->m_indexCall)
++impl->m_fails;
impl->m_sql_errno = (int) sql_errno;
impl->m_err_msg = SPA::Utilities::ToWide(err_msg);
if (sqlstate)
impl->m_sqlstate = sqlstate;
else
impl->m_sqlstate.clear();
}
void CMysqlImpl::sql_shutdown(void *ctx, int shutdown_server) {
//CMysqlImpl *impl = (CMysqlImpl *) ctx;
}
bool CMysqlImpl::OpenSession(const std::wstring &userName, const std::string & ip) {
MYSQL_SESSION st_session = srv_session_open(nullptr, this);
if (!st_session)
return false;
m_pMysql.reset(st_session, [](MYSQL_SESSION mysql) {
if (mysql) {
int fail = srv_session_close(mysql);
assert(!fail);
}
});
MYSQL_SECURITY_CONTEXT sc = nullptr;
int fail = thd_get_security_context(srv_session_info_get_thd(st_session), &sc);
assert(!fail);
if (fail)
return false;
std::string userA = SPA::Utilities::ToUTF8(userName.c_str(), userName.size());
std::string host = "localhost";
if (ip != host)
host = "%";
fail = security_context_lookup(sc, userA.c_str(), host.c_str(), ip.c_str(), nullptr);
if (fail) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "looking up security context failed(user_id=%s; ip_address==%s)", userA.c_str(), ip.c_str());
return false;
}
return true;
}
void CMysqlImpl::SetPublishDBEvent(CMysqlImpl & impl) {
#ifdef WIN32_64
std::wstring wsql = L"CREATE FUNCTION PublishDBEvent RETURNS INTEGER SONAME 'smysql.dll'";
#else
std::wstring wsql = L"CREATE FUNCTION PublishDBEvent RETURNS INTEGER SONAME 'libsmysql.so'";
#endif
if (!impl.m_pMysql && !impl.OpenSession(L"root", "localhost"))
return;
impl.m_NoSending = true;
int res = 0;
INT64 affected;
SPA::UDB::CDBVariant vtId;
UINT64 fail_ok;
std::wstring errMsg;
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
//Setting streaming DB events failed(errCode=1125; errMsg=Function 'PublishDBEvent' already exists)
if (res && res != ER_UDF_EXISTS) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Setting streaming DB events failed(errCode=%d; errMsg=%s)", res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
}
}
void CMysqlImpl::ConfigServices(CMysqlImpl & impl) {
int res = 0;
INT64 affected;
SPA::UDB::CDBVariant vtId;
UINT64 fail_ok;
impl.m_NoSending = true;
std::wstring errMsg;
if (!impl.m_pMysql && !impl.OpenSession(L"root", "localhost"))
return;
std::wstring wsql = L"USE sp_streaming_db;CREATE TABLE IF NOT EXISTS service(id INT UNSIGNED PRIMARY KEY NOT NULL,library VARCHAR(2048)NOT NULL,param INT NULL,description VARCHAR(2048)NULL)";
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Creating the table service failed(errCode=%d; errMsg=%s)", res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
return;
}
wsql = L"CREATE TABLE IF NOT EXISTS permission(svsid INT UNSIGNED NOT NULL,user VARCHAR(32)NOT NULL,PRIMARY KEY(svsid,user),FOREIGN KEY(svsid)REFERENCES service(id)ON DELETE CASCADE ON UPDATE CASCADE)";
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Creating the table permission failed(errCode=%d; errMsg=%s)", res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
return;
}
std::vector<CService> vService;
wsql = L"select id,library,param,description from service";
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
SPA::UDB::CDBVariant vtLib, vtParam, vtDesc;
while (impl.m_qSend.GetSize() && !res) {
impl.m_qSend >> vtId >> vtLib >> vtParam >> vtDesc;
CService svs;
svs.ServiceId = vtId.uintVal;
svs.Library = ToString(vtLib);
switch (vtParam.Type()) {
case VT_I4:
case VT_INT:
case VT_I8:
case VT_UI4:
case VT_UINT:
case VT_UI8:
svs.Param = (int) vtParam.lVal;
break;
default:
svs.Param = 0;
break;
}
if (vtDesc.Type() == (VT_I1 | VT_ARRAY))
svs.Description = ToString(vtDesc);
vService.push_back(svs);
}
auto it = std::find_if(vService.begin(), vService.end(), [](const CService & svs)->bool {
return (svs.ServiceId == SPA::Mysql::sidMysql);
});
if (it == vService.end()) {
wsql = L"INSERT INTO service VALUES(" + std::to_wstring((UINT64) Mysql::sidMysql) +
#ifdef WIN32_64
L",'smysql.dll'" +
#else
L",'libsmysql.so'" +
#endif
L",0,'Continous SQL streaming processing service')";
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Inserting the table service failed(errCode=%d; errMsg=%s)", res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
}
}
it = std::find_if(vService.begin(), vService.end(), [](const CService & svs)->bool {
return (svs.ServiceId == (unsigned int) SPA::sidHTTP);
});
if (it == vService.end()) {
wsql = L"INSERT INTO service VALUES(" + std::to_wstring((UINT64) SPA::sidHTTP) +
#ifdef WIN32_64
L",'uservercore.dll'" +
#else
L",'libuservercore.so'" +
#endif
L",0,'HTTP/Websocket processing service')";
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Inserting the table service failed(errCode=%d; errMsg=%s)", res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
}
}
for (auto p = CSetGlobals::Globals.services.begin(), end = CSetGlobals::Globals.services.end(); p != end; ++p) {
auto found = std::find_if(vService.begin(), vService.end(), [p](const CService & svs)->bool {
if (!p->size() || !svs.Library.size())
return false;
return (::strstr(svs.Library.c_str(), p->c_str()) != nullptr);
});
int param = 0;
if (found != vService.end())
param = found->Param;
HINSTANCE hModule = CSocketProServer::DllManager::AddALibrary(p->c_str(), param);
if (!hModule) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Not able o load server plugin %s", p->c_str());
continue;
}
PGetNumOfServices GetNumOfServices = (PGetNumOfServices)::GetProcAddress(hModule, "GetNumOfServices");
PGetAServiceID GetAServiceID = (PGetAServiceID)::GetProcAddress(hModule, "GetAServiceID");
unsigned short count = GetNumOfServices();
for (unsigned short n = 0; n < count; ++n) {
unsigned int svsId = GetAServiceID(n);
it = std::find_if(vService.begin(), vService.end(), [svsId](const CService & svs)->bool {
return (svs.ServiceId == svsId);
});
if (it == vService.end()) {
wsql = L"INSERT INTO service(id,library,param,description)VALUES(" + std::to_wstring((UINT64) svsId) + L",'" +
SPA::Utilities::ToWide(p->c_str(), p->size()) + L"'," + std::to_wstring((INT64) param) + L",'')";
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Inserting the table service failed(errCode=%d; errMsg=%s)", res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
}
}
}
}
}
std::unordered_map<std::string, std::string> CMysqlImpl::ConfigStreamingDB(CMysqlImpl & impl) {
std::unordered_map<std::string, std::string> map;
if (!impl.m_pMysql && !impl.OpenSession(L"root", "localhost"))
return map;
std::wstring wsql = L"Create database if not exists sp_streaming_db character set utf8 collate utf8_general_ci;USE sp_streaming_db";
int res = 0;
INT64 affected;
SPA::UDB::CDBVariant vtId;
UINT64 fail_ok;
impl.m_NoSending = true;
std::wstring errMsg;
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Configuring streaming DB failed(errCode=%d; errMsg=%s)", res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
return map;
}
wsql = L"CREATE TABLE IF NOT EXISTS config(mykey varchar(32)PRIMARY KEY NOT NULL,value text not null)";
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Configuring streaming DB failed(errCode=%d; errMsg=%s)", res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
return map;
}
wsql = L"select mykey,value from config";
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Configuring streaming DB failed(errCode=%d; errMsg=%s)", res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
return map;
}
SPA::UDB::CDBVariant vtKey, vtValue;
while (impl.m_qSend.GetSize() && !res) {
impl.m_qSend >> vtKey >> vtValue;
std::string s0 = ToString(vtKey);
std::string s1 = ToString(vtValue);
std::transform(s0.begin(), s0.end(), s0.begin(), ::tolower);
Utilities::Trim(s0);
Utilities::Trim(s1);
map[s0] = s1;
}
std::unordered_map<std::string, std::string> &config = CSetGlobals::Globals.DefaultConfig;
for (auto it = config.begin(), end = config.end(); it != end; ++it) {
auto found = map.find(it->first);
if (found == map.end()) {
wsql = L"insert into config values('" + Utilities::ToWide(it->first.c_str(), it->first.size()) + L"','" + Utilities::ToWide(it->second.c_str(), it->second.size()) + L"')";
impl.Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
map[it->first] = it->second;
}
}
return map;
}
bool CMysqlImpl::Authenticate(const std::wstring &userName, const wchar_t *password, const std::string &ip, unsigned int svsId) {
std::unique_ptr<CMysqlImpl> impl(new CMysqlImpl);
if (!impl->OpenSession(L"root", "localhost")) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Authentication failed as root account not available");
return false;
}
std::wstring host = L"localhost";
if (ip != "localhost")
host = L"%";
std::string user = SPA::Utilities::ToUTF8(userName.c_str(), userName.size());
std::wstring wsql(L"select authentication_string from mysql.user where password_expired='N' and account_locked='N' and user='");
wsql += (userName + L"' and host='" + host + L"'");
int res = 0;
INT64 affected;
SPA::UDB::CDBVariant vtId;
UINT64 fail_ok;
impl->m_NoSending = true;
std::wstring errMsg;
impl->Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res || !impl->m_qSend.GetSize()) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Authentication failed as user %s not found (errCode=%d; errMsg=%s)", user.c_str(), res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
return false;
}
SPA::UDB::CDBVariant vtAuth;
impl->m_qSend >> vtAuth;
char *auth_id = nullptr;
::SafeArrayAccessData(vtAuth.parray, (void**) &auth_id);
std::string hash((const char*) auth_id, vtAuth.parray->rgsabound->cElements);
::SafeArrayUnaccessData(vtAuth.parray);
if (!DoAuthentication(password, hash)) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Authentication failed as wrong password for user %s (errCode=%d; errMsg=%s)", user.c_str(), res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
return false;
}
if (svsId == SPA::Mysql::sidMysql)
return true;
wsql = L"SELECT user from sp_streaming_db.permission,sp_streaming_db.service where svsid=id AND svsid=" + std::to_wstring((UINT64) svsId) + L" AND user='" + userName + L"'";
impl->Execute(wsql, true, true, false, 0, affected, res, errMsg, vtId, fail_ok);
if (res || !impl->m_qSend.GetSize()) {
std::string user = SPA::Utilities::ToUTF8(userName.c_str(), userName.size());
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Authentication failed as service %d is not set for user %s yet (errCode=%d; errMsg=%s)", svsId, user.c_str(), res, SPA::Utilities::ToUTF8(errMsg.c_str(), errMsg.size()).c_str());
return false;
}
return true;
}
bool CMysqlImpl::DoAuthentication(const wchar_t *password, const std::string & hash) {
if (hash.size() != 70) {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Authentication failed as wrong hash length (expected length=70; found length=%d)", hash.size());
return false;
}
std::string pwd = SPA::Utilities::ToUTF8(password);
std::string header = hash.substr(0, 7);
if (header != "$A$005$") {
CSetGlobals::Globals.LogMsg(__FILE__, __LINE__, "Authentication failed as wrong hash algorithm (expected=$A$005$; this=%s)", header.c_str());
return false;
}
std::string salt = hash.substr(7, 20);
std::string digest = hash.substr(27);
char buffer[CRYPT_MAX_PASSWORD_SIZE + 1] =
{ 0};
unsigned int iterations = 5000; //CACHING_SHA2_PASSWORD_ITERATIONS;
my_crypt_genhash(buffer, CRYPT_MAX_PASSWORD_SIZE, pwd.c_str(), pwd.length(), salt.c_str(), nullptr, &iterations);
std::string s(buffer);
size_t pos = s.rfind('$');
s = s.substr(pos + 1);
return (digest == s);
}
void CMysqlImpl::Open(const std::wstring &strConnection, unsigned int flags, int &res, std::wstring &errMsg, int &ms) {
m_indexCall = 0;
unsigned int port;
res = 0;
ms = msMysql;
m_EnableMessages = false;
CleanDBObjects();
std::string ip = GetPeerName(&port);
if (ip == "127.0.0.1" || ip == "::ffff:127.0.0.1" || ip == "::1")
ip = "localhost";
std::wstring user = GetUID();
OpenSession(user, ip);
InitMysqlSession();
int fail = 0;
if (strConnection.size()) {
std::string db = SPA::Utilities::ToUTF8(strConnection.c_str(), strConnection.size());
COM_DATA cmd;
cmd.com_init_db.db_name = db.c_str();
cmd.com_init_db.length = (unsigned long) db.size();
m_cmd = COM_INIT_DB;
fail = command_service_run_command(m_pMysql.get(), COM_INIT_DB, &cmd, &my_charset_utf8_general_ci, &m_sql_cbs, CS_BINARY_REPRESENTATION, nullptr);
}
if (m_sql_errno) {
res = m_sql_errno;
errMsg = m_err_msg;
m_pMysql.reset();
} else if (fail) {
res = SPA::Mysql::ER_UNABLE_TO_SWITCH_TO_DATABASE;
errMsg = UNABLE_TO_SWITCH_TO_DATABASE + strConnection;
m_pMysql.reset();
} else {
res = 0;
LEX_CSTRING db_name = srv_session_info_get_current_db(m_pMysql.get());
errMsg = SPA::Utilities::ToWide(db_name.str, db_name.length);
if ((flags & SPA::UDB::ENABLE_TABLE_UPDATE_MESSAGES) == SPA::UDB::ENABLE_TABLE_UPDATE_MESSAGES) {
m_EnableMessages = GetPush().Subscribe(&SPA::UDB::STREAMING_SQL_CHAT_GROUP_ID, 1);
}
}
}
void CMysqlImpl::CloseDb(int &res, std::wstring & errMsg) {
if (m_EnableMessages) {
GetPush().Unsubscribe();
m_EnableMessages = false;
}
CleanDBObjects();
res = 0;
}
void CMysqlImpl::CloseStmt() {
m_stmt.parameters = 0;
if (m_stmt.m_pParam) {
COM_DATA cmd;
::memset(&cmd, 0, sizeof (cmd));
InitMysqlSession();
cmd.com_stmt_close.stmt_id = m_stmt.stmt_id;
m_cmd = COM_STMT_CLOSE;
int fail = command_service_run_command(m_pMysql.get(), COM_STMT_CLOSE, &cmd, &my_charset_utf8_general_ci, &m_sql_cbs, CS_BINARY_REPRESENTATION, nullptr);
assert(!fail);
m_stmt.m_pParam.reset();
}
m_stmt.stmt_id = 0;
}
void CMysqlImpl::CleanDBObjects() {
CloseStmt();
m_pMysql.reset();
m_vParam.clear();
ResetMemories();
m_bManual = false;
m_ti = tiUnspecified;
}
void CMysqlImpl::OnBaseRequestArrive(unsigned short requestId) {
switch (requestId) {
case idCancel:
#ifndef NDEBUG
std::cout << "Cancel called" << std::endl;
#endif
{
int res;
std::wstring errMsg;
if (m_pMysql) {
srv_session_attach(m_pMysql.get(), nullptr);
}
EndTrans((int) rpRollbackAlways, res, errMsg);
if (m_pMysql) {
srv_session_detach(m_pMysql.get());
}
}
break;
default:
break;
}
}
void CMysqlImpl::BeginTrans(int isolation, const std::wstring &dbConn, unsigned int flags, int &res, std::wstring &errMsg, int &ms) {
ms = msMysql;
m_indexCall = 0;
if (m_bManual) {
errMsg = BAD_MANUAL_TRANSACTION_STATE;
res = SPA::Mysql::ER_BAD_MANUAL_TRANSACTION_STATE;
return;
}
if (!m_pMysql) {
Open(dbConn, flags, res, errMsg, ms);
if (!m_pMysql) {
return;
}
}
std::string sql;
if ((int) m_ti != isolation) {
switch ((tagTransactionIsolation) isolation) {
case tiReadUncommited:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
break;
case tiRepeatableRead:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
break;
case tiReadCommited:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";
break;
case tiSerializable:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE";
break;
default:
errMsg = BAD_MANUAL_TRANSACTION_STATE;
res = SPA::Mysql::ER_BAD_MANUAL_TRANSACTION_STATE;
return;
}
sql += ";";
}
sql += "START TRANSACTION";
COM_DATA cmd;
::memset(&cmd, 0, sizeof (cmd));
InitMysqlSession();
cmd.com_query.query = sql.c_str();
cmd.com_query.length = (unsigned int) sql.size();
m_cmd = COM_QUERY;
int fail = command_service_run_command(m_pMysql.get(), COM_QUERY, &cmd, &my_charset_utf8_general_ci, &m_sql_cbs, CS_BINARY_REPRESENTATION, this);
if (m_sql_errno) {
res = m_sql_errno;
errMsg = m_err_msg;
} else if (fail) {
errMsg = SERVICE_COMMAND_ERROR;
res = SPA::Mysql::ER_SERVICE_COMMAND_ERROR;
} else {
res = 0;
m_fails = 0;
m_oks = 0;
m_ti = (tagTransactionIsolation) isolation;
m_bManual = true;
LEX_CSTRING db_name = srv_session_info_get_current_db(m_pMysql.get());
errMsg = SPA::Utilities::ToWide(db_name.str, db_name.length);
}
}
void CMysqlImpl::EndTrans(int plan, int &res, std::wstring & errMsg) {
m_indexCall = 0;
if (!m_bManual) {
errMsg = BAD_MANUAL_TRANSACTION_STATE;
res = SPA::Mysql::ER_BAD_MANUAL_TRANSACTION_STATE;
return;
}
if (plan < 0 || plan > rpRollbackAlways) {
res = SPA::Mysql::ER_BAD_END_TRANSTACTION_PLAN;
errMsg = BAD_END_TRANSTACTION_PLAN;
return;
}
if (!m_pMysql) {
res = SPA::Mysql::ER_NO_DB_OPENED_YET;
errMsg = NO_DB_OPENED_YET;
return;
}
bool rollback = false;
tagRollbackPlan rp = (tagRollbackPlan) plan;
switch (rp) {
case rpRollbackErrorAny:
rollback = m_fails ? true : false;
break;
case rpRollbackErrorLess:
rollback = (m_fails < m_oks && m_fails) ? true : false;
break;
case rpRollbackErrorEqual:
rollback = (m_fails >= m_oks) ? true : false;
break;
case rpRollbackErrorMore:
rollback = (m_fails > m_oks) ? true : false;
break;
case rpRollbackErrorAll:
rollback = (m_oks) ? false : true;
break;
case rpRollbackAlways:
rollback = true;
break;
default:
assert(false); //shouldn't come here
break;
}
std::string sql(rollback ? "ROLLBACK" : "COMMIT");
COM_DATA cmd;
::memset(&cmd, 0, sizeof (cmd));
InitMysqlSession();
cmd.com_query.query = sql.c_str();
cmd.com_query.length = (unsigned int) sql.size();
m_cmd = COM_QUERY;
int fail = command_service_run_command(m_pMysql.get(), COM_QUERY, &cmd, &my_charset_utf8_general_ci, &m_sql_cbs, CS_BINARY_REPRESENTATION, this);
if (m_sql_errno) {
res = m_sql_errno;
errMsg = m_err_msg;
} else if (fail) {
errMsg = SERVICE_COMMAND_ERROR;
res = SPA::Mysql::ER_SERVICE_COMMAND_ERROR;
} else {
res = 0;
m_fails = 0;
m_oks = 0;
}
m_bManual = false;
}
bool CMysqlImpl::SendRows(CUQueue& sb, bool transferring) {
if (m_NoSending)
return true;
bool batching = (GetBytesBatched() >= DEFAULT_RECORD_BATCH_SIZE);
if (batching) {
CommitBatching();
}
unsigned int ret = SendResult(transferring ? idTransferring : idEndRows, sb.GetBuffer(), sb.GetSize());
sb.SetSize(0);
if (batching) {
StartBatching();
}
if (ret == REQUEST_CANCELED || ret == SOCKET_NOT_FOUND) {
return false;
}
return true;
}
bool CMysqlImpl::SendBlob(unsigned short data_type, const unsigned char *buffer, unsigned int bytes) {
if (m_NoSending) {
m_qSend << data_type << bytes;
m_qSend.Push(buffer, bytes);
return true;
}
unsigned int ret = SendResult(idStartBLOB,
(unsigned int) (bytes + sizeof (unsigned short) + sizeof (unsigned int) + sizeof (unsigned int))/* extra 4 bytes for string null termination*/,
data_type, bytes);
if (ret == REQUEST_CANCELED || ret == SOCKET_NOT_FOUND) {
return false;
}
bool isBatching = IsBatching();
if (isBatching)
CommitBatching();
while (bytes > DEFAULT_BIG_FIELD_CHUNK_SIZE) {
ret = SendResult(idChunk, buffer, DEFAULT_BIG_FIELD_CHUNK_SIZE);
if (ret == REQUEST_CANCELED || ret == SOCKET_NOT_FOUND) {
return false;
}
assert(ret == DEFAULT_BIG_FIELD_CHUNK_SIZE);
buffer += DEFAULT_BIG_FIELD_CHUNK_SIZE;
bytes -= DEFAULT_BIG_FIELD_CHUNK_SIZE;
}
if (isBatching)
StartBatching();
ret = SendResult(idEndBLOB, buffer, bytes);
if (ret == REQUEST_CANCELED || ret == SOCKET_NOT_FOUND) {
return false;
}
return true;
}
UINT64 CMysqlImpl::ConvertBitsToInt(const unsigned char *s, unsigned int bytes) {
UINT64 n = 0;
for (unsigned int i = 0; i < bytes; ++i) {
if (i) {
n <<= 8;
}
n += s[i];
}
return n;
}
void CMysqlImpl::InitMysqlSession() {
m_affected_rows = 0;
m_vColInfo.clear();
m_sql_errno = 0;
m_last_insert_id = 0;
m_err_msg.clear();
m_qSend.SetSize(0);
}
void CMysqlImpl::Execute(const std::wstring& wsql, bool rowset, bool meta, bool lastInsertId, UINT64 index, INT64 &affected, int &res, std::wstring &errMsg, CDBVariant &vtId, UINT64 & fail_ok) {
fail_ok = 0;
affected = 0;
m_indexCall = index;
ResetMemories();
if (!m_pMysql) {
res = SPA::Mysql::ER_NO_DB_OPENED_YET;
errMsg = NO_DB_OPENED_YET;
++m_fails;
fail_ok = 1;
fail_ok <<= 32;
return;
} else {
res = 0;
}
UINT64 fails = m_fails;
UINT64 oks = m_oks;
std::string sql = SPA::Utilities::ToUTF8(wsql.c_str(), wsql.size());
if (m_EnableMessages && !sql.size() && CSetGlobals::Globals.cached_tables.size()) {
//client side is asking for data from cached tables
for (auto it = CSetGlobals::Globals.cached_tables.begin(), end = CSetGlobals::Globals.cached_tables.end(); it != end; ++it) {
if (sql.size())
sql += ";";
std::string s = *it;
auto pos = s.find('.');
sql += "select * from `";
sql += s.substr(0, pos);
sql += "`.`";
sql += s.substr(pos + 1);
sql += "`";
}
}
InitMysqlSession();
COM_DATA cmd;
::memset(&cmd, 0, sizeof (cmd));
cmd.com_query.query = sql.c_str();
cmd.com_query.length = (unsigned int) sql.size();
m_cmd = COM_QUERY;
m_NoRowset = !rowset;
m_affected_rows = 0;
int fail = command_service_run_command(m_pMysql.get(), COM_QUERY, &cmd, &my_charset_utf8_general_ci, &m_sql_cbs, CS_BINARY_REPRESENTATION, this);
if (m_sql_errno) {
res = m_sql_errno;
errMsg = m_err_msg;
affected = 0;
} else if (fail) {
errMsg = SERVICE_COMMAND_ERROR;
res = SPA::Mysql::ER_SERVICE_COMMAND_ERROR;
++m_fails;
} else {
affected = (SPA::INT64) m_affected_rows;
if (lastInsertId)
vtId = (SPA::UINT64)m_last_insert_id;
}
fail_ok = ((m_fails - fails) << 32);
fail_ok += (unsigned int) (m_oks - oks);
}
void CMysqlImpl::Prepare(const std::wstring& wsql, CParameterInfoArray& params, int &res, std::wstring &errMsg, unsigned int ¶meters) {
m_indexCall = 0;
m_NoRowset = false;
ResetMemories();
parameters = 0;
if (!m_pMysql) {
res = SPA::Mysql::ER_NO_DB_OPENED_YET;
errMsg = NO_DB_OPENED_YET;
return;
}
CloseStmt();
res = 0;
m_vParam.clear();
CScopeUQueue sb;
Utilities::ToUTF8(wsql.c_str(), wsql.size(), *sb);
const char *sqlUtf8 = (const char*) sb->GetBuffer();
COM_DATA cmd;
::memset(&cmd, 0, sizeof (cmd));
InitMysqlSession();
cmd.com_stmt_prepare.query = sqlUtf8;
cmd.com_stmt_prepare.length = sb->GetSize();
m_cmd = COM_STMT_PREPARE;
m_NoSending = true;
int fail = command_service_run_command(m_pMysql.get(), COM_STMT_PREPARE, &cmd, &my_charset_utf8_general_ci, &m_sql_cbs, CS_BINARY_REPRESENTATION, this);
m_NoSending = false;
if (m_sql_errno) {
res = m_sql_errno;
errMsg = m_err_msg;
} else if (fail) {
errMsg = SERVICE_COMMAND_ERROR;
res = SPA::Mysql::ER_SERVICE_COMMAND_ERROR;
} else {
parameters = (unsigned int) m_stmt.parameters;
if (parameters == 0 || m_stmt.stmt_id == 0) {
res = SPA::Mysql::ER_NO_PARAMETER_SPECIFIED;
errMsg = NO_PARAMETER_SPECIFIED;
CloseStmt();
} else {
res = 0;
m_stmt.m_pParam.reset(new PS_PARAM[parameters], [](PS_PARAM * p) {
delete []p;
});
}
}
}
UINT64 CMysqlImpl::ToUDateTime(const MYSQL_TIME & td) {
std::tm date;
if (td.time_type == MYSQL_TIMESTAMP_TIME) {
date.tm_year = 0;
date.tm_mon = 0;
date.tm_mday = 0;
} else {
date.tm_year = td.year - 1900;
date.tm_mon = td.month - 1;
date.tm_mday = td.day;
}
date.tm_hour = td.hour;
date.tm_min = td.minute;
date.tm_sec = td.second;
return SPA::UDateTime(date, td.second_part).time;
}
int CMysqlImpl::SetParams(int row, std::wstring & errMsg) {
int res = 0;
PS_PARAM *pParam = m_stmt.m_pParam.get();
for (size_t n = 0; n < m_stmt.parameters; ++n, ++pParam) {
pParam->null_bit = false;
pParam->unsigned_type = false;
size_t pos = row * m_stmt.parameters + n;
CDBVariant &data = m_vParam[pos];
unsigned short vt = data.Type();
switch (vt) {
case VT_NULL:
case VT_EMPTY:
pParam->length = 0;
pParam->type = MYSQL_TYPE_NULL;
pParam->null_bit = true;
pParam->value = nullptr;
break;
case VT_I1:
pParam->length = sizeof (char);
pParam->type = MYSQL_TYPE_TINY;
pParam->value = (const unsigned char *) &data.cVal;
break;
case VT_UI1:
pParam->length = sizeof (unsigned char);
pParam->type = MYSQL_TYPE_TINY;
pParam->value = &data.bVal;
pParam->unsigned_type = true;
break;
case VT_BOOL:
pParam->length = sizeof (unsigned char);
pParam->type = MYSQL_TYPE_TINY;
data.bVal = data.boolVal ? 1 : 0;
pParam->value = &data.bVal;
break;
case VT_I2:
pParam->length = sizeof (short);
pParam->type = MYSQL_TYPE_SHORT;
pParam->value = (const unsigned char *) &data.iVal;
break;
case VT_UI2:
pParam->length = sizeof (unsigned short);
pParam->type = MYSQL_TYPE_SHORT;
pParam->value = (const unsigned char *) &data.uiVal;
pParam->unsigned_type = true;
break;
case VT_INT:
case VT_I4:
pParam->length = sizeof (int);
pParam->type = MYSQL_TYPE_LONG;
pParam->value = (const unsigned char *) &data.intVal;
break;
case VT_UINT:
case VT_UI4:
pParam->length = sizeof (unsigned int);
pParam->type = MYSQL_TYPE_LONG;
pParam->value = (const unsigned char *) &data.uintVal;
pParam->unsigned_type = true;
break;
case VT_I8:
pParam->length = sizeof (SPA::INT64);
pParam->type = MYSQL_TYPE_LONGLONG;
pParam->value = (const unsigned char *) &data.llVal;
break;
case VT_UI8:
pParam->length = sizeof (SPA::UINT64);
pParam->type = MYSQL_TYPE_LONGLONG;
pParam->value = (const unsigned char *) &data.ullVal;
pParam->unsigned_type = true;
break;
case VT_R4:
pParam->length = sizeof (float);
pParam->type = MYSQL_TYPE_FLOAT;
pParam->value = (const unsigned char *) &data.fltVal;
break;
case VT_R8:
pParam->length = sizeof (double);
pParam->type = MYSQL_TYPE_DOUBLE;
pParam->value = (const unsigned char *) &data.dblVal;
break;
/*
case VT_DECIMAL:
pParam->type = MYSQL_TYPE_NEWDECIMAL;
break;
case VT_DATE:
pParam->type = MYSQL_TYPE_DATETIME;
break;
*/
case VT_STR:
case (VT_ARRAY | VT_I1):
pParam->type = MYSQL_TYPE_VAR_STRING;
{
SAFEARRAY *parray = data.parray;
pParam->length = parray->rgsabound->cElements;
::SafeArrayAccessData(parray, (void**) &pParam->value);
::SafeArrayUnaccessData(parray);
}
break;
case VT_BYTES:
case (VT_ARRAY | VT_UI1):
pParam->type = MYSQL_TYPE_BLOB;
{
SAFEARRAY *parray = data.parray;
pParam->length = parray->rgsabound->cElements;
::SafeArrayAccessData(parray, (void**) &pParam->value);
::SafeArrayUnaccessData(parray);
}
break;
default:
assert(false); //not implemented
if (!res && !errMsg.size()) {
res = SPA::Mysql::ER_DATA_TYPE_NOT_SUPPORTED;
errMsg = DATA_TYPE_NOT_SUPPORTED;
}
break;
}
}
return res;
}
size_t CMysqlImpl::ComputeParameters(const std::wstring & sql) {
const wchar_t quote = '\'', slash = '\\', question = '?';
bool b_slash = false, balanced = true;
size_t params = 0, len = sql.size();
for (size_t n = 0; n < len; ++n) {
const wchar_t &c = sql[n];
if (c == slash) {
b_slash = true;
continue;
}
if (c == quote && b_slash) {
b_slash = false;
continue; //ignore a quote if there is a slash ahead
}
b_slash = false;
if (c == quote) {
balanced = (!balanced);
continue;
}
if (balanced) {
params += ((c == question) ? 1 : 0);
}
}
return params;
}
void CMysqlImpl::SetVParam(CDBVariantArray& vAll, size_t parameters, size_t pos, size_t ps) {
m_vParam.clear();
size_t rows = vAll.size() / parameters;
for (size_t r = 0; r < rows; ++r) {
for (size_t p = 0; p < ps; ++p) {
CDBVariant &vt = vAll[parameters * r + pos + p];
m_vParam.push_back(std::move(vt));
}
}
}
std::vector<std::wstring> CMysqlImpl::Split(const std::wstring &sql, const std::wstring & delimiter) {
std::vector<std::wstring> v;
size_t d_len = delimiter.size();
if (d_len) {
const wchar_t quote = '\'', slash = '\\', done = delimiter[0];
size_t params = 0, len = sql.size();
bool b_slash = false, balanced = true;
for (size_t n = 0; n < len; ++n) {
const wchar_t &c = sql[n];
if (c == slash) {
b_slash = true;
continue;
}
if (c == quote && b_slash) {
b_slash = false;
continue; //ignore a quote if there is a slash ahead
}
b_slash = false;
if (c == quote) {
balanced = (!balanced);
continue;
}
if (balanced && c == done) {
size_t pos = sql.find(delimiter, n);
if (pos == n) {
v.push_back(sql.substr(params, n - params));
n += d_len;
params = n;
}
}
}
v.push_back(sql.substr(params));
} else {
v.push_back(sql);
}
return v;
}
void CMysqlImpl::ExecuteBatch(const std::wstring& sql, const std::wstring& delimiter, int isolation, int plan, bool rowset, bool meta, bool lastInsertId, const std::wstring &dbConn, unsigned int flags, UINT64 callIndex, INT64 &affected, int &res, std::wstring &errMsg, CDBVariant &vtId, UINT64 & fail_ok) {
CDBVariant id;
CParameterInfoArray vPInfo;
m_UQueue >> vPInfo;
res = 0;
fail_ok = 0;
affected = 0;
int ms = 0;
if (!m_pMysql) {
Open(dbConn, flags, res, errMsg, ms);
}
size_t parameters = 0;
std::vector<std::wstring> vSql = Split(sql, delimiter);
for (auto it = vSql.cbegin(), end = vSql.cend(); it != end; ++it) {
parameters += ComputeParameters(*it);
}
if (!m_pMysql) {
res = SPA::Mysql::ER_NO_DB_OPENED_YET;
errMsg = NO_DB_OPENED_YET;
fail_ok = vSql.size();
fail_ok <<= 32;
SendResult(idSqlBatchHeader, res, errMsg, (int) msMysql, (unsigned int) parameters, callIndex);
return;
}
size_t rows = 0;
if (parameters) {
if (!m_vParam.size()) {
res = SPA::Mysql::ER_BAD_PARAMETER_DATA_ARRAY_SIZE;
errMsg = BAD_PARAMETER_DATA_ARRAY_SIZE;
m_fails += vSql.size();
fail_ok = vSql.size();
fail_ok <<= 32;
SendResult(idSqlBatchHeader, res, errMsg, (int) msMysql, (unsigned int) parameters, callIndex);
return;
}
if ((m_vParam.size() % (unsigned short) parameters)) {
res = SPA::Mysql::ER_BAD_PARAMETER_DATA_ARRAY_SIZE;
errMsg = BAD_PARAMETER_DATA_ARRAY_SIZE;
m_fails += vSql.size();
fail_ok = vSql.size();
fail_ok <<= 32;
SendResult(idSqlBatchHeader, res, errMsg, (int) msMysql, (unsigned int) parameters, callIndex);
return;
}
rows = m_vParam.size() / parameters;
}
if (isolation != (int) tiUnspecified) {
int ms;
BeginTrans(isolation, dbConn, flags, res, errMsg, ms);
if (res) {
m_fails += vSql.size();
fail_ok = vSql.size();
fail_ok <<= 32;
SendResult(idSqlBatchHeader, res, errMsg, (int) msMysql, (unsigned int) parameters, callIndex);
return;
}
} else {
LEX_CSTRING db_name = srv_session_info_get_current_db(m_pMysql.get());
errMsg = SPA::Utilities::ToWide(db_name.str, db_name.length);
}
SendResult(idSqlBatchHeader, res, errMsg, (int) msMysql, (unsigned int) parameters, callIndex);
errMsg.clear();
CDBVariantArray vAll;
m_vParam.swap(vAll);
INT64 aff = 0;
int r = 0;
std::wstring err;
UINT64 fo = 0;
size_t pos = 0;
for (auto it = vSql.begin(), end = vSql.end(); it != end; ++it) {
Utilities::Trim(*it);
if (!it->size()) {
continue;
}
size_t ps = ComputeParameters(*it);
if (ps) {
//prepared statements
unsigned int my_ps = 0;
Prepare(*it, vPInfo, r, err, my_ps);
if (r) {
fail_ok += (((UINT64) rows) << 32);
} else {
assert(ps == (my_ps & 0xffff));
m_vParam.clear();
SetVParam(vAll, parameters, pos, ps);
unsigned int nParamPos = (unsigned int) ((pos << 16) + ps);
SendResult(idParameterPosition, nParamPos);
ExecuteParameters(rowset, meta, lastInsertId, callIndex, aff, r, err, id, fo);
if (id.ullVal)
vtId = id;
}
pos += ps;
} else {
Execute(*it, rowset, meta, lastInsertId, callIndex, aff, r, err, id, fo);
if (id.ullVal)
vtId = id;
}
if (r && !res) {
res = r;
errMsg = err;
}
if (r && isolation != (int) tiUnspecified && plan == (int) rpDefault)
break;
affected += aff;
fail_ok += fo;
}
if (isolation != (int) tiUnspecified) {
EndTrans(plan, r, err);
if (r && !res) {
res = r;
errMsg = err;
}
}
}
void CMysqlImpl::ExecuteParameters(bool rowset, bool meta, bool lastInsertId, UINT64 index, INT64 &affected, int &res, std::wstring &errMsg, CDBVariant &vtId, UINT64 & fail_ok) {
affected = 0;
m_indexCall = index;
if (!m_stmt.m_pParam || !m_stmt.parameters) {
res = SPA::Mysql::ER_NO_PARAMETER_SPECIFIED;
errMsg = NO_PARAMETER_SPECIFIED;
++m_fails;
fail_ok = 1;
fail_ok <<= 32;
return;
}
if (m_vParam.size() == 0) {
res = SPA::Mysql::ER_BAD_PARAMETER_DATA_ARRAY_SIZE;
errMsg = BAD_PARAMETER_DATA_ARRAY_SIZE;
++m_fails;
fail_ok = 1;
fail_ok <<= 32;
return;
}
if (m_vParam.size() % m_stmt.parameters) {
res = SPA::Mysql::ER_BAD_PARAMETER_DATA_ARRAY_SIZE;
errMsg = BAD_PARAMETER_DATA_ARRAY_SIZE;
m_fails += (m_vParam.size() / m_stmt.parameters);
fail_ok = (m_vParam.size() / m_stmt.parameters);
fail_ok <<= 32;
return;
}
if (!m_pMysql) {
res = SPA::Mysql::ER_NO_DB_OPENED_YET;
errMsg = NO_DB_OPENED_YET;
m_fails += (m_vParam.size() / m_stmt.parameters);
fail_ok = (m_vParam.size() / m_stmt.parameters);
fail_ok <<= 32;
return;
}
fail_ok = 0;
res = 0;
UINT64 fails = m_fails;
UINT64 oks = m_oks;
int rows = (int) (m_vParam.size() / m_stmt.parameters);
for (int row = 0; row < rows; ++row) {
COM_DATA cmd;
::memset(&cmd, 0, sizeof (cmd));
InitMysqlSession();
int ret = SetParams(row, errMsg);
if (ret) {
if (!res)
res = ret;
++m_fails;
continue;
}
cmd.com_stmt_execute.stmt_id = m_stmt.stmt_id;
cmd.com_stmt_execute.parameters = m_stmt.m_pParam.get();
cmd.com_stmt_execute.parameter_count = (unsigned long) m_stmt.parameters;
cmd.com_stmt_execute.has_new_types = true;
cmd.com_stmt_execute.open_cursor = false;
m_NoRowset = !rowset;
m_cmd = COM_STMT_EXECUTE;
m_affected_rows = 0;
m_server_status = 0;
int fail = command_service_run_command(m_pMysql.get(), COM_STMT_EXECUTE, &cmd, &my_charset_utf8_general_ci, &m_sql_cbs, CS_BINARY_REPRESENTATION, this);
if (m_sql_errno) {
if (!res) {
res = m_sql_errno;
errMsg = m_err_msg;
}
} else if (fail) {
if (!res) {
errMsg = SERVICE_COMMAND_ERROR;
res = SPA::Mysql::ER_SERVICE_COMMAND_ERROR;
}
++m_fails;
} else {
if ((SERVER_PS_OUT_PARAMS & m_server_status) != SERVER_PS_OUT_PARAMS)
affected += (INT64) m_affected_rows;
if (lastInsertId) {
vtId = (UINT64) m_last_insert_id;
}
++m_oks;
}
}
fail_ok = ((m_fails - fails) << 32);
fail_ok += (unsigned int) (m_oks - oks);
m_vParam.clear();
}
void CMysqlImpl::StartBLOB(unsigned int lenExpected) {
m_qSend.SetSize(0);
if (lenExpected > m_qSend.GetMaxSize()) {
m_qSend.ReallocBuffer(lenExpected);
}
CUQueue &q = m_UQueue;
m_qSend.Push(q.GetBuffer(), q.GetSize());
assert(q.GetSize() > sizeof (unsigned short) + sizeof (unsigned int));
q.SetSize(0);
}
void CMysqlImpl::Chunk() {
CUQueue &q = m_UQueue;
if (q.GetSize()) {
m_qSend.Push(q.GetBuffer(), q.GetSize());
q.SetSize(0);
}
}
void CMysqlImpl::EndBLOB() {
Chunk();
m_vParam.push_back(CDBVariant());
CDBVariant &vt = m_vParam.back();
m_qSend >> vt;
assert(m_qSend.GetSize() == 0);
}
void CMysqlImpl::BeginRows() {
Transferring();
}
void CMysqlImpl::EndRows() {
Transferring();
}
void CMysqlImpl::Transferring() {
CUQueue &q = m_UQueue;
while (q.GetSize()) {
m_vParam.push_back(CDBVariant());
CDBVariant &vt = m_vParam.back();
q >> vt;
switch (vt.vt) {
case VT_DATE:
{
char str[64] = {0};
SPA::UDateTime dt(vt.ullVal);
dt.ToDBString(str, sizeof (str)); //date time to ASCII DB string
vt = (const char*) str;
}
break;
case VT_DECIMAL:
vt = SPA::ToString(vt.decVal).c_str(); //decimal to ASCII string
break;
default:
break;
}
}
assert(q.GetSize() == 0);
}
} //namespace ServerSide
} //namespace SPA | [
"support@udaparts.com"
] | support@udaparts.com |
3553677cec7718a375060206fdec89d0b7562889 | c30d20ffd5522d4fe3e9fca3fb30e19931ab9e97 | /Versionen/2021_06_10/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/schedule_participant_patch__traits.hpp | b5adddc185b6cd0e34fae91db56f37120e35864f | [
"MIT"
] | permissive | flitzmo-hso/flitzmo_agv_control_system | 557f1200c0f060264e4d6ea688e104cabd9d0568 | 99e8006920c03afbd93e4c7d38b4efff514c7069 | refs/heads/main | 2023-06-19T08:18:30.282776 | 2021-07-09T18:05:09 | 2021-07-09T18:05:09 | 358,238,668 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,338 | hpp | // generated from rosidl_generator_cpp/resource/idl__traits.hpp.em
// with input from rmf_traffic_msgs:msg/ScheduleParticipantPatch.idl
// generated code does not contain a copyright notice
#ifndef RMF_TRAFFIC_MSGS__MSG__DETAIL__SCHEDULE_PARTICIPANT_PATCH__TRAITS_HPP_
#define RMF_TRAFFIC_MSGS__MSG__DETAIL__SCHEDULE_PARTICIPANT_PATCH__TRAITS_HPP_
#include "rmf_traffic_msgs/msg/detail/schedule_participant_patch__struct.hpp"
#include <rosidl_runtime_cpp/traits.hpp>
#include <stdint.h>
#include <type_traits>
namespace rosidl_generator_traits
{
template<>
inline const char * data_type<rmf_traffic_msgs::msg::ScheduleParticipantPatch>()
{
return "rmf_traffic_msgs::msg::ScheduleParticipantPatch";
}
template<>
inline const char * name<rmf_traffic_msgs::msg::ScheduleParticipantPatch>()
{
return "rmf_traffic_msgs/msg/ScheduleParticipantPatch";
}
template<>
struct has_fixed_size<rmf_traffic_msgs::msg::ScheduleParticipantPatch>
: std::integral_constant<bool, false> {};
template<>
struct has_bounded_size<rmf_traffic_msgs::msg::ScheduleParticipantPatch>
: std::integral_constant<bool, false> {};
template<>
struct is_message<rmf_traffic_msgs::msg::ScheduleParticipantPatch>
: std::true_type {};
} // namespace rosidl_generator_traits
#endif // RMF_TRAFFIC_MSGS__MSG__DETAIL__SCHEDULE_PARTICIPANT_PATCH__TRAITS_HPP_
| [
"msauer1@hs-offenburg.de"
] | msauer1@hs-offenburg.de |
5a9b21a814f87a1de4141c2c7d9cd9bf0096ad1f | 27c136e13979201f88a820d1bca5e56fe52c3a6d | /testing/testing_zlarfb_gpu.cpp | c033f84b53ab66fc74d3a21132c9cee3540acce9 | [] | no_license | EmergentOrder/magma | 421070f87fb3009e4229e41ce0677d4092926a66 | 546b7716e7b2e3cb256a9c8aa6d4df4272fcb08b | refs/heads/master | 2021-01-01T17:05:02.120717 | 2014-08-12T17:46:58 | 2014-08-12T17:46:58 | 22,886,527 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,463 | cpp | /*
-- MAGMA (version 1.5.0-beta3) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date July 2014
@author Mark Gates
@precisions normal z -> c d s
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <cuda_runtime_api.h>
#include <cublas.h>
#include <assert.h>
#include <algorithm> // std::swap
// includes, project
#include "magma.h"
#include "magma_lapack.h"
#include "testings.h"
/* ////////////////////////////////////////////////////////////////////////////
-- Testing zlarfb_gpu
*/
int main( int argc, char** argv )
{
TESTING_INIT();
magmaDoubleComplex c_zero = MAGMA_Z_ZERO;
magmaDoubleComplex c_one = MAGMA_Z_ONE;
magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
magma_int_t M, N, K, size, ldc, ldv, ldt, ldw, nv;
magma_int_t ione = 1;
magma_int_t ISEED[4] = {0,0,0,1};
double error, work[1];
magma_int_t status = 0;
// test all combinations of input parameters
magma_side_t side [] = { MagmaLeft, MagmaRight };
magma_trans_t trans [] = { MagmaConjTrans, MagmaNoTrans };
magma_direct_t direct[] = { MagmaForward, MagmaBackward };
magma_storev_t storev[] = { MagmaColumnwise, MagmaRowwise };
magma_opts opts;
parse_opts( argc, argv, &opts );
double tol = opts.tolerance * lapackf77_dlamch("E");
printf(" M N K storev side direct trans ||R||_F / ||HC||_F\n");
printf("========================================================================\n");
for( int itest = 0; itest < opts.ntest; ++itest ) {
M = opts.msize[itest];
N = opts.nsize[itest];
K = opts.ksize[itest];
if ( M < K || N < K || K <= 0 ) {
printf( "%5d %5d %5d skipping because zlarfb requires M >= K, N >= K, K >= 0\n",
(int) M, (int) N, (int) K );
continue;
}
for( int istor = 0; istor < 2; ++istor ) {
for( int iside = 0; iside < 2; ++iside ) {
for( int idir = 0; idir < 2; ++idir ) {
for( int itran = 0; itran < 2; ++itran ) {
for( int iter = 0; iter < opts.niter; ++iter ) {
ldc = ((M+31)/32)*32;
ldt = ((K+31)/32)*32;
ldw = (side[iside] == MagmaLeft ? N : M);
// (ldv, nv) get swapped later if rowwise
ldv = (side[iside] == MagmaLeft ? M : N);
nv = K;
// Allocate memory for matrices
magmaDoubleComplex *C, *R, *V, *T, *W;
TESTING_MALLOC_CPU( C, magmaDoubleComplex, ldc*N );
TESTING_MALLOC_CPU( R, magmaDoubleComplex, ldc*N );
TESTING_MALLOC_CPU( V, magmaDoubleComplex, ldv*K );
TESTING_MALLOC_CPU( T, magmaDoubleComplex, ldt*K );
TESTING_MALLOC_CPU( W, magmaDoubleComplex, ldw*K );
magmaDoubleComplex *dC, *dV, *dT, *dW;
TESTING_MALLOC_DEV( dC, magmaDoubleComplex, ldc*N );
TESTING_MALLOC_DEV( dV, magmaDoubleComplex, ldv*K );
TESTING_MALLOC_DEV( dT, magmaDoubleComplex, ldt*K );
TESTING_MALLOC_DEV( dW, magmaDoubleComplex, ldw*K );
// C is M x N.
size = ldc*N;
lapackf77_zlarnv( &ione, ISEED, &size, C );
//printf( "C=" ); magma_zprint( M, N, C, ldc );
// V is ldv x nv. See larfb docs for description.
// if column-wise and left, M x K
// if column-wise and right, N x K
// if row-wise and left, K x M
// if row-wise and right, K x N
size = ldv*nv;
lapackf77_zlarnv( &ione, ISEED, &size, V );
if ( storev[istor] == MagmaColumnwise ) {
if ( direct[idir] == MagmaForward ) {
lapackf77_zlaset( MagmaUpperStr, &K, &K, &c_zero, &c_one, V, &ldv );
}
else {
lapackf77_zlaset( MagmaLowerStr, &K, &K, &c_zero, &c_one, &V[(ldv-K)], &ldv );
}
}
else {
// rowwise, swap V's dimensions
std::swap( ldv, nv );
if ( direct[idir] == MagmaForward ) {
lapackf77_zlaset( MagmaLowerStr, &K, &K, &c_zero, &c_one, V, &ldv );
}
else {
lapackf77_zlaset( MagmaUpperStr, &K, &K, &c_zero, &c_one, &V[(nv-K)*ldv], &ldv );
}
}
//printf( "# ldv %d, nv %d\n", ldv, nv );
//printf( "V=" ); magma_zprint( ldv, nv, V, ldv );
// T is K x K, upper triangular for forward, and lower triangular for backward
magma_int_t k1 = K-1;
size = ldt*K;
lapackf77_zlarnv( &ione, ISEED, &size, T );
if ( direct[idir] == MagmaForward ) {
lapackf77_zlaset( MagmaLowerStr, &k1, &k1, &c_zero, &c_zero, &T[1], &ldt );
}
else {
lapackf77_zlaset( MagmaUpperStr, &k1, &k1, &c_zero, &c_zero, &T[1*ldt], &ldt );
}
//printf( "T=" ); magma_zprint( K, K, T, ldt );
magma_zsetmatrix( M, N, C, ldc, dC, ldc );
magma_zsetmatrix( ldv, nv, V, ldv, dV, ldv );
magma_zsetmatrix( K, K, T, ldt, dT, ldt );
lapackf77_zlarfb( lapack_side_const( side[iside] ), lapack_trans_const( trans[itran] ),
lapack_direct_const( direct[idir] ), lapack_storev_const( storev[istor] ),
&M, &N, &K,
V, &ldv, T, &ldt, C, &ldc, W, &ldw );
//printf( "HC=" ); magma_zprint( M, N, C, ldc );
magma_zlarfb_gpu( side[iside], trans[itran], direct[idir], storev[istor],
M, N, K,
dV, ldv, dT, ldt, dC, ldc, dW, ldw );
magma_zgetmatrix( M, N, dC, ldc, R, ldc );
//printf( "dHC=" ); magma_zprint( M, N, R, ldc );
// compute relative error |HC_magma - HC_lapack| / |HC_lapack|
error = lapackf77_zlange( "Fro", &M, &N, C, &ldc, work );
size = ldc*N;
blasf77_zaxpy( &size, &c_neg_one, C, &ione, R, &ione );
error = lapackf77_zlange( "Fro", &M, &N, R, &ldc, work ) / error;
printf( "%5d %5d %5d %c %c %c %c %8.2e %s\n",
(int) M, (int) N, (int) K,
lapacke_storev_const(storev[istor]), lapacke_side_const(side[iside]),
lapacke_direct_const(direct[idir]), lapacke_trans_const(trans[itran]),
error, (error < tol ? "ok" : "failed") );
status += ! (error < tol);
TESTING_FREE_CPU( C );
TESTING_FREE_CPU( R );
TESTING_FREE_CPU( V );
TESTING_FREE_CPU( T );
TESTING_FREE_CPU( W );
TESTING_FREE_DEV( dC );
TESTING_FREE_DEV( dV );
TESTING_FREE_DEV( dT );
TESTING_FREE_DEV( dW );
fflush( stdout );
}
if ( opts.niter > 1 ) {
printf( "\n" );
}
}}}}
printf( "\n" );
}
TESTING_FINALIZE();
return status;
}
| [
"lecaran@gmail.com"
] | lecaran@gmail.com |
b20101e2b4f439fe17a053a9a32984b8fb83b530 | f739df1f252d7c961ed881be3b8babaf62ff4170 | /softs/SCADAsoft/5.3.2/ACE_Wrappers/TAO/tao/PortableServer/LifespanPolicyC.h | 05b355e181d19e0c9acd64d62c95f5a2431e1d36 | [] | no_license | billpwchan/SCADA-nsl | 739484691c95181b262041daa90669d108c54234 | 1287edcd38b2685a675f1261884f1035f7f288db | refs/heads/master | 2023-04-30T09:15:49.104944 | 2021-01-10T21:53:10 | 2021-01-10T21:53:10 | 328,486,982 | 0 | 0 | null | 2023-04-22T07:10:56 | 2021-01-10T21:53:19 | C++ | UTF-8 | C++ | false | false | 6,027 | h | // -*- C++ -*-
//
// $Id$
// **** Code generated by the The ACE ORB (TAO) IDL Compiler v1.6a_p10 ****
// TAO and the TAO IDL Compiler have been developed by:
// Center for Distributed Object Computing
// Washington University
// St. Louis, MO
// USA
// http://www.cs.wustl.edu/~schmidt/doc-center.html
// and
// Distributed Object Computing Laboratory
// University of California at Irvine
// Irvine, CA
// USA
// http://doc.ece.uci.edu/
// and
// Institute for Software Integrated Systems
// Vanderbilt University
// Nashville, TN
// USA
// http://www.isis.vanderbilt.edu/
//
// Information about TAO is available at:
// http://www.cs.wustl.edu/~schmidt/TAO.html
// TAO_IDL - Generated from
// be\be_codegen.cpp:135
#ifndef _TAO_PIDL_PORTABLESERVER_LIFESPANPOLICYC_H_
#define _TAO_PIDL_PORTABLESERVER_LIFESPANPOLICYC_H_
#include /**/ "ace/pre.h"
#include /**/ "ace/config-all.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include /**/ "tao/PortableServer/portableserver_export.h"
#include "tao/Basic_Types.h"
#include "tao/Object.h"
#include "tao/Objref_VarOut_T.h"
#include /**/ "tao/Versioned_Namespace.h"
#include "tao/PolicyC.h"
#if defined (TAO_EXPORT_MACRO)
#undef TAO_EXPORT_MACRO
#endif
#define TAO_EXPORT_MACRO TAO_PortableServer_Export
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
// TAO_IDL - Generated from
// d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_module/module_ch.cpp:49
namespace PortableServer
{
// TAO_IDL - Generated from
// d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_enum/enum_ch.cpp:57
enum LifespanPolicyValue
{
TRANSIENT,
PERSISTENT
};
typedef LifespanPolicyValue &LifespanPolicyValue_out;
// TAO_IDL - Generated from
// be\be_interface.cpp:644
#if !defined (_PORTABLESERVER_LIFESPANPOLICY__VAR_OUT_CH_)
#define _PORTABLESERVER_LIFESPANPOLICY__VAR_OUT_CH_
class LifespanPolicy;
typedef LifespanPolicy *LifespanPolicy_ptr;
typedef
TAO_Objref_Var_T<
LifespanPolicy
>
LifespanPolicy_var;
typedef
TAO_Objref_Out_T<
LifespanPolicy
>
LifespanPolicy_out;
#endif /* end #if !defined */
// TAO_IDL - Generated from
// d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/interface_ch.cpp:54
#if !defined (_PORTABLESERVER_LIFESPANPOLICY_CH_)
#define _PORTABLESERVER_LIFESPANPOLICY_CH_
class TAO_PortableServer_Export LifespanPolicy
: public virtual ::CORBA::Policy
{
public:
typedef LifespanPolicy_ptr _ptr_type;
typedef LifespanPolicy_var _var_type;
typedef LifespanPolicy_out _out_type;
// The static operations.
static LifespanPolicy_ptr _duplicate (LifespanPolicy_ptr obj);
static void _tao_release (LifespanPolicy_ptr obj);
static LifespanPolicy_ptr _narrow (::CORBA::Object_ptr obj);
static LifespanPolicy_ptr _unchecked_narrow (::CORBA::Object_ptr obj);
static LifespanPolicy_ptr _nil (void)
{
return static_cast<LifespanPolicy_ptr> (0);
}
// TAO_IDL - Generated from
// d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_operation/operation_ch.cpp:46
virtual ::PortableServer::LifespanPolicyValue value (
void) = 0;
// TAO_IDL - Generated from
// d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_operation/operation_ch.cpp:46
virtual ::CORBA::Policy_ptr copy (
void) = 0;
// TAO_IDL - Generated from
// d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_operation/operation_ch.cpp:46
virtual void destroy (
void) = 0;
// TAO_IDL - Generated from
// d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_interface/interface_ch.cpp:216
virtual ::CORBA::Boolean _is_a (const char *type_id);
virtual const char* _interface_repository_id (void) const;
virtual ::CORBA::Boolean marshal (TAO_OutputCDR &cdr);
protected:
// Abstract or local interface only.
LifespanPolicy (void);
virtual ~LifespanPolicy (void);
private:
// Private and unimplemented for concrete interfaces.
LifespanPolicy (const LifespanPolicy &);
void operator= (const LifespanPolicy &);
};
#endif /* end #if !defined */
// TAO_IDL - Generated from
// d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_module/module_ch.cpp:78
} // module PortableServer
// TAO_IDL - Generated from
// be\be_visitor_traits.cpp:64
TAO_END_VERSIONED_NAMESPACE_DECL
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
// Traits specializations.
namespace TAO
{
#if !defined (_PORTABLESERVER_LIFESPANPOLICY__TRAITS_)
#define _PORTABLESERVER_LIFESPANPOLICY__TRAITS_
template<>
struct TAO_PortableServer_Export Objref_Traits< ::PortableServer::LifespanPolicy>
{
static ::PortableServer::LifespanPolicy_ptr duplicate (
::PortableServer::LifespanPolicy_ptr p
);
static void release (
::PortableServer::LifespanPolicy_ptr p
);
static ::PortableServer::LifespanPolicy_ptr nil (void);
static ::CORBA::Boolean marshal (
const ::PortableServer::LifespanPolicy_ptr p,
TAO_OutputCDR & cdr
);
};
#endif /* end #if !defined */
}
TAO_END_VERSIONED_NAMESPACE_DECL
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
// TAO_IDL - Generated from
// d:\softs\ace_wrappers_vc10\tao\tao_idl\be\be_visitor_enum/cdr_op_ch.cpp:50
TAO_END_VERSIONED_NAMESPACE_DECL
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
TAO_PortableServer_Export ::CORBA::Boolean operator<< (TAO_OutputCDR &strm, PortableServer::LifespanPolicyValue _tao_enumerator);
TAO_PortableServer_Export ::CORBA::Boolean operator>> (TAO_InputCDR &strm, PortableServer::LifespanPolicyValue &_tao_enumerator);
TAO_END_VERSIONED_NAMESPACE_DECL
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
// TAO_IDL - Generated from
// be\be_codegen.cpp:1228
TAO_END_VERSIONED_NAMESPACE_DECL
#include /**/ "ace/post.h"
#endif /* ifndef */
| [
"billpwchan@hotmail.com"
] | billpwchan@hotmail.com |
41648c36dbba52611d475d66b1a1d8ef310c4c1f | 8df1e416b6d472a3fcaf05c656fb0491d630b39d | /src/maple_me/src/dse.cpp | 8caa9052e5a8de4ee35a8fc3afdebfa5eb1f48a1 | [] | no_license | tonylau2010/OpenArkCompiler | 134da6a8e0b41d0ffda8995cea786c472706496e | a553ed3bd62dda4b3dff622f68c058d336bb1aca | refs/heads/master | 2021-05-23T08:40:51.666393 | 2020-03-24T09:27:04 | 2020-03-24T09:27:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,325 | cpp | /*
* Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
*
* http://license.coscl.org.cn/MulanPSL
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v1 for more details.
*/
#include "dse.h"
#include "ssa_mir_nodes.h"
#include "ver_symbol.h"
#include "ssa.h"
#include "opcode_info.h"
#include "mir_function.h"
#include "utils.h"
// This phase do dead store elimination. This optimization is done on SSA
// version basis.
// This optimization consider all stmt are not needed at first. The whole
// algorithm is as follow:
// 1. mark all stmt are not needed. init an empty worklist to put live node.
// 2. mark some special stmts which has side effect as needed, such as
// return/eh/call and some assigned stmts who have volatile fileds and so on.
// Put all operands and mayUse nodes of the needed stmt into worklist.
// 3. For the nodes in worklist mark the def stmt as needed just as step 2 and
// pop the node from the worklist.
// 4. Repeat step 3 until the worklist is empty.
namespace maple {
using namespace utils;
bool DSE::ExprNonDeletable(const BaseNode &expr) const {
if (kOpcodeInfo.HasSideEffect(expr.GetOpCode())) {
return true;
}
switch (expr.GetOpCode()) {
case OP_dread: {
auto &dread = static_cast<const AddrofSSANode&>(expr);
const MIRSymbol &sym = dread.GetMIRSymbol();
return sym.IsVolatile() || sym.IsTypeVolatile(dread.GetFieldID());
}
case OP_iread: {
auto &iread = static_cast<const IreadSSANode&>(expr);
auto &ty = static_cast<const MIRPtrType&>(GetTypeFromTyIdx(iread.GetTyIdx()));
return ty.IsPointedTypeVolatile(iread.GetFieldID()) || ExprNonDeletable(ToRef(iread.Opnd(0)));
}
case OP_regread: {
auto ®readNode = static_cast<const RegreadSSANode&>(expr);
return (regreadNode.GetRegIdx() == -kSregThrownval);
}
case OP_gcmallocjarray:
case OP_gcpermallocjarray:
// may throw exception
return true;
case OP_intrinsicop: {
auto &node = static_cast<const IntrinsicopNode&>(expr);
const IntrinDesc &intrinDesc = node.GetIntrinDesc();
return (!intrinDesc.HasNoSideEffect());
}
default: {
break;
}
}
for (size_t i = 0; i < expr.NumOpnds(); ++i) {
if (ExprNonDeletable(ToRef(expr.Opnd(i)))) {
return true;
}
}
return false;
}
bool DSE::HasNonDeletableExpr(const StmtNode &stmt) const {
Opcode op = stmt.GetOpCode();
switch (op) {
case OP_dassign: {
auto &node = static_cast<const DassignNode&>(stmt);
const MIRSymbol &sym = ssaTab.GetStmtMIRSymbol(stmt);
return (sym.IsVolatile() || sym.IsTypeVolatile(node.GetFieldID()) ||
ExprNonDeletable(ToRef(node.GetRHS())));
}
case OP_regassign: {
return ExprNonDeletable(ToRef(stmt.Opnd(0)));
}
// possible to throw exception
case OP_maydassign: {
return true;
}
case OP_iassign: {
auto &node = static_cast<const IassignNode&>(stmt);
auto &ty = static_cast<const MIRPtrType&>(GetTypeFromTyIdx(node.GetTyIdx()));
return (ty.IsPointedTypeVolatile(node.GetFieldID()) ||
ExprNonDeletable(ToRef(node.Opnd(0))) ||
ExprNonDeletable(ToRef(node.GetRHS())));
}
default:
return false;
}
}
bool DSE::StmtMustRequired(const StmtNode &stmt, const BB &bb) const {
Opcode op = stmt.GetOpCode();
// special opcode stmt cannot be eliminated
if (IsStmtMustRequire(op)) {
return true;
}
// control flow in an infinite loop cannot be eliminated
if (ControlFlowInInfiniteLoop(bb, op)) {
return true;
}
return HasNonDeletableExpr(stmt);
}
void DSE::DumpStmt(const StmtNode &stmt, const std::string &msg) const {
if (enableDebug) {
LogInfo::MapleLogger() << msg;
stmt.Dump();
}
}
void DSE::CheckRemoveCallAssignedReturn(StmtNode &stmt) {
if (kOpcodeInfo.IsCallAssigned(stmt.GetOpCode())) {
MapleVector<MustDefNode> &mustDefs = ssaTab.GetStmtMustDefNodes(stmt);
for (auto &node : mustDefs) {
if (IsSymbolLived(ToRef(node.GetResult()))) {
continue;
}
DumpStmt(stmt, "**** DSE1 deleting return value assignment in: ");
CallReturnVector *rets = stmt.GetCallReturnVector();
CHECK_FATAL(rets != nullptr, "null ptr check ");
rets->clear();
mustDefs.clear();
break;
}
}
}
void DSE::OnRemoveBranchStmt(BB &bb, const StmtNode &stmt) {
// switch is special, which can not be set to kBBFallthru
if (IsBranch(stmt.GetOpCode()) && stmt.GetOpCode() != OP_switch) {
// update BB pred/succ
bb.SetKind(kBBFallthru);
cfgUpdated = true; // tag cfg is changed
LabelIdx labelIdx = (stmt.GetOpCode() == OP_goto) ? static_cast<const GotoNode&>(stmt).GetOffset()
: static_cast<const CondGotoNode&>(stmt).GetOffset();
for (size_t i = 0; i < bb.GetSucc().size(); ++i) {
if (bb.GetSucc(i)->GetBBLabel() == labelIdx) {
BB *succBB = bb.GetSucc(i);
bb.RemoveBBFromSucc(succBB);
succBB->RemoveBBFromPred(&bb);
break;
}
}
}
}
void DSE::RemoveNotRequiredStmtsInBB(BB &bb) {
for (auto &stmt : bb.GetStmtNodes()) {
if (!IsStmtRequired(stmt)) {
DumpStmt(stmt, "**** DSE1 deleting: ");
OnRemoveBranchStmt(bb, stmt);
bb.RemoveStmtNode(&stmt);
continue;
}
CheckRemoveCallAssignedReturn(stmt);
}
}
void DSE::PropagateUseLive(const VersionSt &vst) {
if (IsSymbolLived(vst)) {
return;
}
SetSymbolLived(vst);
const BB *dfBB = vst.GetDefBB();
if (dfBB == nullptr) {
return;
}
if (vst.GetDefType() == VersionSt::kAssign) {
const StmtNode *assign = vst.GetAssignNode();
MarkStmtRequired(ToRef(assign), ToRef(dfBB));
} else if (vst.GetDefType() == VersionSt::kPhi) {
const PhiNode *phi = vst.GetPhi();
ASSERT(phi->GetResult() == &vst, "MarkVst: wrong corresponding version st in phi");
MarkControlDependenceLive(ToRef(dfBB));
for (size_t i = 0; i < phi->GetPhiOpnds().size(); ++i) {
const VersionSt *verSt = phi->GetPhiOpnds()[i];
AddToWorkList(verSt);
}
} else if (vst.GetDefType() == VersionSt::kMayDef) {
const MayDefNode *mayDef = vst.GetMayDef();
ASSERT(mayDef->GetResult() == &vst, "MarkVst: wrong corresponding version st in maydef");
const VersionSt *verSt = mayDef->GetOpnd();
MarkStmtRequired(ToRef(mayDef->GetStmt()), ToRef(dfBB));
AddToWorkList(verSt);
} else {
const MustDefNode *mustdef = vst.GetMustDef();
ASSERT(mustdef->GetResult() == &vst, "MarkVst: wrong corresponding version st in mustdef");
MarkStmtRequired(ToRef(mustdef->GetStmt()), ToRef(dfBB));
}
}
void DSE::MarkLastGotoInPredBBRequired(const BB &bb) {
for (auto predIt = bb.GetPred().begin(); predIt != bb.GetPred().end(); ++predIt) {
const BB *predBB = *predIt;
CHECK_NULL_FATAL(predBB);
if (predBB == &bb || predBB->IsEmpty()) {
continue;
}
const StmtNode &lastStmt = predBB->GetLast();
if (lastStmt.GetOpCode() == OP_goto) {
MarkStmtRequired(lastStmt, ToRef(predBB));
}
}
}
void DSE::MarkLastBranchStmtInPDomBBRequired(const BB &bb) {
ASSERT(bb.GetBBId() < postDom.GetPdomFrontierSize(), "index out of range in DSE::MarkBBLive ");
for (BBId pdomBBID : postDom.GetPdomFrontierItem(bb.GetBBId())) {
const BB *cdBB = bbVec[pdomBBID];
CHECK_FATAL(cdBB != nullptr, "cd_bb is null in DSE::MarkLastBranchStmtInPDomBBRequired");
if (cdBB == &bb || cdBB->IsEmpty()) {
continue;
}
const StmtNode &lastStmt = cdBB->GetLast();
Opcode op = lastStmt.GetOpCode();
if (IsBranch(op)) {
MarkStmtRequired(lastStmt, ToRef(cdBB));
}
}
}
void DSE::MarkLastBranchStmtInBBRequired(const BB &bb) {
if (!bb.IsEmpty()) {
// if bb's last stmt is a branch instruction, it is also needed
const StmtNode &lastStmt = bb.GetLast();
if (IsBranch(lastStmt.GetOpCode())) {
MarkStmtRequired(lastStmt, bb);
}
}
}
void DSE::MarkControlDependenceLive(const BB &bb) {
if (bbRequired[bb.GetBBId()]) {
return;
}
bbRequired[bb.GetBBId()] = true;
MarkLastBranchStmtInBBRequired(bb);
MarkLastBranchStmtInPDomBBRequired(bb);
MarkLastGotoInPredBBRequired(bb);
}
void DSE::MarkSingleUseLive(const BaseNode &mirNode) {
Opcode op = mirNode.GetOpCode();
switch (op) {
case OP_dread: {
auto &addrofSSANode = static_cast<const AddrofSSANode&>(mirNode);
const VersionSt *verSt = addrofSSANode.GetSSAVar();
AddToWorkList(verSt);
break;
}
case OP_regread: {
auto ®readSSANode = static_cast<const RegreadSSANode&>(mirNode);
const VersionSt *verSt = regreadSSANode.GetSSAVar();
AddToWorkList(verSt);
break;
}
case OP_iread: {
auto &ireadSSANode = static_cast<const IreadSSANode&>(mirNode);
const VersionSt *verSt = ireadSSANode.GetSSAVar();
CHECK_FATAL(verSt != nullptr, "DSE::MarkSingleUseLive: iread has no mayUse opnd");
AddToWorkList(verSt);
if (!verSt->IsInitVersion()) {
auto *mayDefList = SSAGenericGetMayDefsFromVersionSt(ToRef(verSt), ssaTab.GetStmtsSSAPart());
if (mayDefList != nullptr) {
for (auto it = mayDefList->begin(); it != mayDefList->end(); ++it) {
AddToWorkList(it->second.GetResult());
}
}
}
MarkSingleUseLive(ToRef(mirNode.Opnd(0)));
break;
}
default: {
for (size_t i = 0; i < mirNode.NumOpnds(); ++i) {
MarkSingleUseLive(ToRef(mirNode.Opnd(i)));
}
break;
}
}
}
void DSE::MarkStmtUseLive(const StmtNode &stmt) {
for (size_t i = 0; i < stmt.NumOpnds(); ++i) {
MarkSingleUseLive(ToRef(stmt.Opnd(i)));
}
if (kOpcodeInfo.HasSSAUse(stmt.GetOpCode())) {
for (auto &pair : ssaTab.GetStmtMayUseNodes(stmt)) {
const MayUseNode &mayUse = pair.second;
AddToWorkList(mayUse.GetOpnd());
}
}
}
void DSE::MarkStmtRequired(const StmtNode &stmt, const BB &bb) {
if (IsStmtRequired(stmt)) {
return;
}
SetStmtRequired(stmt);
// save only one line comment
StmtNode *prev = stmt.GetPrev();
if (prev != nullptr && prev->GetOpCode() == OP_comment) {
SetStmtRequired(*prev);
}
MarkStmtUseLive(stmt);
MarkControlDependenceLive(bb);
}
void DSE::MarkSpecialStmtRequired() {
for (auto bIt = bbVec.rbegin(); bIt != bbVec.rend(); ++bIt) {
auto *bb = *bIt;
if (bb == nullptr) {
continue;
}
for (auto itStmt = bb->GetStmtNodes().rbegin(); itStmt != bb->GetStmtNodes().rend(); ++itStmt) {
if (StmtMustRequired(*itStmt, *bb)) {
MarkStmtRequired(*itStmt, *bb);
continue;
}
}
}
}
void DSE::Init() {
bbRequired[commonEntryBB.GetBBId()] = true;
bbRequired[commonExitBB.GetBBId()] = true;
}
void DSE::DoDSE() {
Init();
MarkSpecialStmtRequired();
PropagateLive();
RemoveNotRequiredStmts();
}
} // namespace maple
| [
"fuzhou@huawei.com"
] | fuzhou@huawei.com |
7ea2a8ebf1cf5b55bbf7422bf94592fc97550347 | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/Qt/qgraphicsitem.h | a7e9c54b10da42236ab71515b5a0dc7260ccc62b | [
"BSD-2-Clause"
] | permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,684 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QGRAPHICSITEM_H
#define QGRAPHICSITEM_H
#include <QtCore/qglobal.h>
#include <QtCore/qobject.h>
#include <QtCore/qvariant.h>
#include <QtCore/qrect.h>
#include <QtGui/qpainterpath.h>
#include <QtGui/qpixmap.h>
class tst_QGraphicsItem;
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
#if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW
class QBrush;
class QCursor;
class QFocusEvent;
class QGraphicsItemGroup;
class QGraphicsSceneContextMenuEvent;
class QGraphicsSceneDragDropEvent;
class QGraphicsSceneEvent;
class QGraphicsSceneHoverEvent;
class QGraphicsSceneMouseEvent;
class QGraphicsSceneWheelEvent;
class QGraphicsScene;
class QGraphicsWidget;
class QInputMethodEvent;
class QKeyEvent;
class QMatrix;
class QMenu;
class QPainter;
class QPen;
class QPointF;
class QRectF;
class QStyleOptionGraphicsItem;
class QGraphicsItemPrivate;
class Q_GUI_EXPORT QGraphicsItem
{
public:
enum GraphicsItemFlag {
ItemIsMovable = 0x1,
ItemIsSelectable = 0x2,
ItemIsFocusable = 0x4,
ItemClipsToShape = 0x8,
ItemClipsChildrenToShape = 0x10,
ItemIgnoresTransformations = 0x20,
ItemIgnoresParentOpacity = 0x40,
ItemDoesntPropagateOpacityToChildren = 0x80,
ItemStacksBehindParent = 0x100
};
Q_DECLARE_FLAGS(GraphicsItemFlags, GraphicsItemFlag)
enum GraphicsItemChange {
ItemPositionChange,
ItemMatrixChange,
ItemVisibleChange,
ItemEnabledChange,
ItemSelectedChange,
ItemParentChange,
ItemChildAddedChange,
ItemChildRemovedChange,
ItemTransformChange,
ItemPositionHasChanged,
ItemTransformHasChanged,
ItemSceneChange,
ItemVisibleHasChanged,
ItemEnabledHasChanged,
ItemSelectedHasChanged,
ItemParentHasChanged,
ItemSceneHasChanged,
ItemCursorChange,
ItemCursorHasChanged,
ItemToolTipChange,
ItemToolTipHasChanged,
ItemFlagsChange,
ItemFlagsHaveChanged,
ItemZValueChange,
ItemZValueHasChanged,
ItemOpacityChange,
ItemOpacityHasChanged
};
enum CacheMode {
NoCache,
ItemCoordinateCache,
DeviceCoordinateCache
};
QGraphicsItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
virtual ~QGraphicsItem();
QGraphicsScene *scene() const;
QGraphicsItem *parentItem() const;
QGraphicsItem *topLevelItem() const;
QGraphicsWidget *parentWidget() const;
QGraphicsWidget *topLevelWidget() const;
QGraphicsWidget *window() const;
void setParentItem(QGraphicsItem *parent);
QList<QGraphicsItem *> children() const; // ### obsolete
QList<QGraphicsItem *> childItems() const;
bool isWidget() const;
bool isWindow() const;
QGraphicsItemGroup *group() const;
void setGroup(QGraphicsItemGroup *group);
GraphicsItemFlags flags() const;
void setFlag(GraphicsItemFlag flag, bool enabled = true);
void setFlags(GraphicsItemFlags flags);
CacheMode cacheMode() const;
void setCacheMode(CacheMode mode, const QSize &cacheSize = QSize());
#ifndef QT_NO_TOOLTIP
QString toolTip() const;
void setToolTip(const QString &toolTip);
#endif
#ifndef QT_NO_CURSOR
QCursor cursor() const;
void setCursor(const QCursor &cursor);
bool hasCursor() const;
void unsetCursor();
#endif
bool isVisible() const;
bool isVisibleTo(const QGraphicsItem *parent) const;
void setVisible(bool visible);
inline void hide() { setVisible(false); }
inline void show() { setVisible(true); }
bool isEnabled() const;
void setEnabled(bool enabled);
bool isSelected() const;
void setSelected(bool selected);
bool acceptDrops() const;
void setAcceptDrops(bool on);
qreal opacity() const;
qreal effectiveOpacity() const;
void setOpacity(qreal opacity);
Qt::MouseButtons acceptedMouseButtons() const;
void setAcceptedMouseButtons(Qt::MouseButtons buttons);
bool acceptsHoverEvents() const; // obsolete
void setAcceptsHoverEvents(bool enabled); // obsolete
bool acceptHoverEvents() const;
void setAcceptHoverEvents(bool enabled);
bool handlesChildEvents() const;
void setHandlesChildEvents(bool enabled);
bool hasFocus() const;
void setFocus(Qt::FocusReason focusReason = Qt::OtherFocusReason);
void clearFocus();
void grabMouse();
void ungrabMouse();
void grabKeyboard();
void ungrabKeyboard();
// Positioning in scene coordinates
QPointF pos() const;
inline qreal x() const { return pos().x(); }
inline qreal y() const { return pos().y(); }
QPointF scenePos() const;
void setPos(const QPointF &pos);
inline void setPos(qreal x, qreal y);
inline void moveBy(qreal dx, qreal dy) { setPos(pos().x() + dx, pos().y() + dy); }
void ensureVisible(const QRectF &rect = QRectF(), int xmargin = 50, int ymargin = 50);
inline void ensureVisible(qreal x, qreal y, qreal w, qreal h, int xmargin = 50, int ymargin = 50);
// Local transformation
QMatrix matrix() const;
QMatrix sceneMatrix() const;
void setMatrix(const QMatrix &matrix, bool combine = false);
void resetMatrix();
QTransform transform() const;
QTransform sceneTransform() const;
QTransform deviceTransform(const QTransform &viewportTransform) const;
QTransform itemTransform(const QGraphicsItem *other, bool *ok = 0) const;
void setTransform(const QTransform &matrix, bool combine = false);
void resetTransform();
void rotate(qreal angle);
void scale(qreal sx, qreal sy);
void shear(qreal sh, qreal sv);
void translate(qreal dx, qreal dy);
virtual void advance(int phase);
// Stacking order
qreal zValue() const;
void setZValue(qreal z);
// Hit test
virtual QRectF boundingRect() const = 0;
QRectF childrenBoundingRect() const;
QRectF sceneBoundingRect() const;
virtual QPainterPath shape() const;
bool isClipped() const;
QPainterPath clipPath() const;
virtual bool contains(const QPointF &point) const;
virtual bool collidesWithItem(const QGraphicsItem *other, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
virtual bool collidesWithPath(const QPainterPath &path, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
QList<QGraphicsItem *> collidingItems(Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const;
bool isObscured() const;
bool isObscured(const QRectF &rect) const; // ### Qt 5: merge with isObscured(), add QRectF arg to isObscuredBy()
inline bool isObscured(qreal x, qreal y, qreal w, qreal h) const;
virtual bool isObscuredBy(const QGraphicsItem *item) const;
virtual QPainterPath opaqueArea() const;
QRegion boundingRegion(const QTransform &itemToDeviceTransform) const;
qreal boundingRegionGranularity() const;
void setBoundingRegionGranularity(qreal granularity);
// Drawing
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) = 0;
void update(const QRectF &rect = QRectF());
inline void update(qreal x, qreal y, qreal width, qreal height);
void scroll(qreal dx, qreal dy, const QRectF &rect = QRectF());
// Coordinate mapping
QPointF mapToItem(const QGraphicsItem *item, const QPointF &point) const;
QPointF mapToParent(const QPointF &point) const;
QPointF mapToScene(const QPointF &point) const;
QPolygonF mapToItem(const QGraphicsItem *item, const QRectF &rect) const;
QPolygonF mapToParent(const QRectF &rect) const;
QPolygonF mapToScene(const QRectF &rect) const;
QRectF mapRectToItem(const QGraphicsItem *item, const QRectF &rect) const;
QRectF mapRectToParent(const QRectF &rect) const;
QRectF mapRectToScene(const QRectF &rect) const;
QPolygonF mapToItem(const QGraphicsItem *item, const QPolygonF &polygon) const;
QPolygonF mapToParent(const QPolygonF &polygon) const;
QPolygonF mapToScene(const QPolygonF &polygon) const;
QPainterPath mapToItem(const QGraphicsItem *item, const QPainterPath &path) const;
QPainterPath mapToParent(const QPainterPath &path) const;
QPainterPath mapToScene(const QPainterPath &path) const;
QPointF mapFromItem(const QGraphicsItem *item, const QPointF &point) const;
QPointF mapFromParent(const QPointF &point) const;
QPointF mapFromScene(const QPointF &point) const;
QPolygonF mapFromItem(const QGraphicsItem *item, const QRectF &rect) const;
QPolygonF mapFromParent(const QRectF &rect) const;
QPolygonF mapFromScene(const QRectF &rect) const;
QRectF mapRectFromItem(const QGraphicsItem *item, const QRectF &rect) const;
QRectF mapRectFromParent(const QRectF &rect) const;
QRectF mapRectFromScene(const QRectF &rect) const;
QPolygonF mapFromItem(const QGraphicsItem *item, const QPolygonF &polygon) const;
QPolygonF mapFromParent(const QPolygonF &polygon) const;
QPolygonF mapFromScene(const QPolygonF &polygon) const;
QPainterPath mapFromItem(const QGraphicsItem *item, const QPainterPath &path) const;
QPainterPath mapFromParent(const QPainterPath &path) const;
QPainterPath mapFromScene(const QPainterPath &path) const;
inline QPointF mapToItem(const QGraphicsItem *item, qreal x, qreal y) const;
inline QPointF mapToParent(qreal x, qreal y) const;
inline QPointF mapToScene(qreal x, qreal y) const;
inline QPolygonF mapToItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const;
inline QPolygonF mapToParent(qreal x, qreal y, qreal w, qreal h) const;
inline QPolygonF mapToScene(qreal x, qreal y, qreal w, qreal h) const;
inline QRectF mapRectToItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const;
inline QRectF mapRectToParent(qreal x, qreal y, qreal w, qreal h) const;
inline QRectF mapRectToScene(qreal x, qreal y, qreal w, qreal h) const;
inline QPointF mapFromItem(const QGraphicsItem *item, qreal x, qreal y) const;
inline QPointF mapFromParent(qreal x, qreal y) const;
inline QPointF mapFromScene(qreal x, qreal y) const;
inline QPolygonF mapFromItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const;
inline QPolygonF mapFromParent(qreal x, qreal y, qreal w, qreal h) const;
inline QPolygonF mapFromScene(qreal x, qreal y, qreal w, qreal h) const;
inline QRectF mapRectFromItem(const QGraphicsItem *item, qreal x, qreal y, qreal w, qreal h) const;
inline QRectF mapRectFromParent(qreal x, qreal y, qreal w, qreal h) const;
inline QRectF mapRectFromScene(qreal x, qreal y, qreal w, qreal h) const;
bool isAncestorOf(const QGraphicsItem *child) const;
QGraphicsItem *commonAncestorItem(const QGraphicsItem *other) const;
bool isUnderMouse() const;
// Custom data
QVariant data(int key) const;
void setData(int key, const QVariant &value);
enum {
Type = 1,
UserType = 65536
};
virtual int type() const;
void installSceneEventFilter(QGraphicsItem *filterItem);
void removeSceneEventFilter(QGraphicsItem *filterItem);
protected:
virtual bool sceneEventFilter(QGraphicsItem *watched, QEvent *event);
virtual bool sceneEvent(QEvent *event);
virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
virtual void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent *event);
virtual void dragMoveEvent(QGraphicsSceneDragDropEvent *event);
virtual void dropEvent(QGraphicsSceneDragDropEvent *event);
virtual void focusInEvent(QFocusEvent *event);
virtual void focusOutEvent(QFocusEvent *event);
virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
virtual void hoverMoveEvent(QGraphicsSceneHoverEvent *event);
virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
virtual void keyPressEvent(QKeyEvent *event);
virtual void keyReleaseEvent(QKeyEvent *event);
virtual void mousePressEvent(QGraphicsSceneMouseEvent *event);
virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
virtual void wheelEvent(QGraphicsSceneWheelEvent *event);
virtual void inputMethodEvent(QInputMethodEvent *event);
virtual QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value);
enum Extension {
UserExtension = 0x80000000
};
virtual bool supportsExtension(Extension extension) const;
virtual void setExtension(Extension extension, const QVariant &variant);
virtual QVariant extension(const QVariant &variant) const;
protected:
QGraphicsItem(QGraphicsItemPrivate &dd,
QGraphicsItem *parent, QGraphicsScene *scene);
QGraphicsItemPrivate *d_ptr;
void addToIndex();
void removeFromIndex();
void prepareGeometryChange();
private:
Q_DISABLE_COPY(QGraphicsItem)
Q_DECLARE_PRIVATE(QGraphicsItem)
friend class QGraphicsItemGroup;
friend class QGraphicsScene;
friend class QGraphicsScenePrivate;
friend class QGraphicsSceneFindItemBspTreeVisitor;
friend class QGraphicsView;
friend class QGraphicsViewPrivate;
friend class QGraphicsWidget;
friend class QGraphicsWidgetPrivate;
friend class QGraphicsProxyWidgetPrivate;
friend class ::tst_QGraphicsItem;
friend bool qt_closestLeaf(const QGraphicsItem *, const QGraphicsItem *);
friend bool qt_closestItemFirst(const QGraphicsItem *, const QGraphicsItem *);
};
Q_DECLARE_OPERATORS_FOR_FLAGS(QGraphicsItem::GraphicsItemFlags)
inline void QGraphicsItem::setPos(qreal ax, qreal ay)
{ setPos(QPointF(ax, ay)); }
inline void QGraphicsItem::ensureVisible(qreal ax, qreal ay, qreal w, qreal h, int xmargin, int ymargin)
{ ensureVisible(QRectF(ax, ay, w, h), xmargin, ymargin); }
inline void QGraphicsItem::update(qreal ax, qreal ay, qreal width, qreal height)
{ update(QRectF(ax, ay, width, height)); }
inline bool QGraphicsItem::isObscured(qreal ax, qreal ay, qreal w, qreal h) const
{ return isObscured(QRectF(ax, ay, w, h)); }
inline QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, qreal ax, qreal ay) const
{ return mapToItem(item, QPointF(ax, ay)); }
inline QPointF QGraphicsItem::mapToParent(qreal ax, qreal ay) const
{ return mapToParent(QPointF(ax, ay)); }
inline QPointF QGraphicsItem::mapToScene(qreal ax, qreal ay) const
{ return mapToScene(QPointF(ax, ay)); }
inline QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, qreal ax, qreal ay) const
{ return mapFromItem(item, QPointF(ax, ay)); }
inline QPointF QGraphicsItem::mapFromParent(qreal ax, qreal ay) const
{ return mapFromParent(QPointF(ax, ay)); }
inline QPointF QGraphicsItem::mapFromScene(qreal ax, qreal ay) const
{ return mapFromScene(QPointF(ax, ay)); }
inline QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, qreal ax, qreal ay, qreal w, qreal h) const
{ return mapToItem(item, QRectF(ax, ay, w, h)); }
inline QPolygonF QGraphicsItem::mapToParent(qreal ax, qreal ay, qreal w, qreal h) const
{ return mapToParent(QRectF(ax, ay, w, h)); }
inline QPolygonF QGraphicsItem::mapToScene(qreal ax, qreal ay, qreal w, qreal h) const
{ return mapToScene(QRectF(ax, ay, w, h)); }
inline QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, qreal ax, qreal ay, qreal w, qreal h) const
{ return mapRectToItem(item, QRectF(ax, ay, w, h)); }
inline QRectF QGraphicsItem::mapRectToParent(qreal ax, qreal ay, qreal w, qreal h) const
{ return mapRectToParent(QRectF(ax, ay, w, h)); }
inline QRectF QGraphicsItem::mapRectToScene(qreal ax, qreal ay, qreal w, qreal h) const
{ return mapRectToScene(QRectF(ax, ay, w, h)); }
inline QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, qreal ax, qreal ay, qreal w, qreal h) const
{ return mapFromItem(item, QRectF(ax, ay, w, h)); }
inline QPolygonF QGraphicsItem::mapFromParent(qreal ax, qreal ay, qreal w, qreal h) const
{ return mapFromParent(QRectF(ax, ay, w, h)); }
inline QPolygonF QGraphicsItem::mapFromScene(qreal ax, qreal ay, qreal w, qreal h) const
{ return mapFromScene(QRectF(ax, ay, w, h)); }
inline QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, qreal ax, qreal ay, qreal w, qreal h) const
{ return mapRectFromItem(item, QRectF(ax, ay, w, h)); }
inline QRectF QGraphicsItem::mapRectFromParent(qreal ax, qreal ay, qreal w, qreal h) const
{ return mapRectFromParent(QRectF(ax, ay, w, h)); }
inline QRectF QGraphicsItem::mapRectFromScene(qreal ax, qreal ay, qreal w, qreal h) const
{ return mapRectFromScene(QRectF(ax, ay, w, h)); }
class QAbstractGraphicsShapeItemPrivate;
class Q_GUI_EXPORT QAbstractGraphicsShapeItem : public QGraphicsItem
{
public:
QAbstractGraphicsShapeItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QAbstractGraphicsShapeItem();
QPen pen() const;
void setPen(const QPen &pen);
QBrush brush() const;
void setBrush(const QBrush &brush);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
protected:
QAbstractGraphicsShapeItem(QAbstractGraphicsShapeItemPrivate &dd,
QGraphicsItem *parent, QGraphicsScene *scene);
private:
Q_DISABLE_COPY(QAbstractGraphicsShapeItem)
Q_DECLARE_PRIVATE(QAbstractGraphicsShapeItem)
};
class QGraphicsPathItemPrivate;
class Q_GUI_EXPORT QGraphicsPathItem : public QAbstractGraphicsShapeItem
{
public:
QGraphicsPathItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsPathItem(const QPainterPath &path, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QGraphicsPathItem();
QPainterPath path() const;
void setPath(const QPainterPath &path);
QRectF boundingRect() const;
QPainterPath shape() const;
bool contains(const QPointF &point) const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
enum { Type = 2 };
int type() const;
protected:
bool supportsExtension(Extension extension) const;
void setExtension(Extension extension, const QVariant &variant);
QVariant extension(const QVariant &variant) const;
private:
Q_DISABLE_COPY(QGraphicsPathItem)
Q_DECLARE_PRIVATE(QGraphicsPathItem)
};
class QGraphicsRectItemPrivate;
class Q_GUI_EXPORT QGraphicsRectItem : public QAbstractGraphicsShapeItem
{
public:
QGraphicsRectItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsRectItem(const QRectF &rect, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsRectItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QGraphicsRectItem();
QRectF rect() const;
void setRect(const QRectF &rect);
inline void setRect(qreal x, qreal y, qreal w, qreal h);
QRectF boundingRect() const;
QPainterPath shape() const;
bool contains(const QPointF &point) const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
enum { Type = 3 };
int type() const;
protected:
bool supportsExtension(Extension extension) const;
void setExtension(Extension extension, const QVariant &variant);
QVariant extension(const QVariant &variant) const;
private:
Q_DISABLE_COPY(QGraphicsRectItem)
Q_DECLARE_PRIVATE(QGraphicsRectItem)
};
inline void QGraphicsRectItem::setRect(qreal ax, qreal ay, qreal w, qreal h)
{ setRect(QRectF(ax, ay, w, h)); }
class QGraphicsEllipseItemPrivate;
class Q_GUI_EXPORT QGraphicsEllipseItem : public QAbstractGraphicsShapeItem
{
public:
QGraphicsEllipseItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsEllipseItem(const QRectF &rect, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsEllipseItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QGraphicsEllipseItem();
QRectF rect() const;
void setRect(const QRectF &rect);
inline void setRect(qreal x, qreal y, qreal w, qreal h);
int startAngle() const;
void setStartAngle(int angle);
int spanAngle() const;
void setSpanAngle(int angle);
QRectF boundingRect() const;
QPainterPath shape() const;
bool contains(const QPointF &point) const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
enum { Type = 4 };
int type() const;
protected:
bool supportsExtension(Extension extension) const;
void setExtension(Extension extension, const QVariant &variant);
QVariant extension(const QVariant &variant) const;
private:
Q_DISABLE_COPY(QGraphicsEllipseItem)
Q_DECLARE_PRIVATE(QGraphicsEllipseItem)
};
inline void QGraphicsEllipseItem::setRect(qreal ax, qreal ay, qreal w, qreal h)
{ setRect(QRectF(ax, ay, w, h)); }
class QGraphicsPolygonItemPrivate;
class Q_GUI_EXPORT QGraphicsPolygonItem : public QAbstractGraphicsShapeItem
{
public:
QGraphicsPolygonItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsPolygonItem(const QPolygonF &polygon,
QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QGraphicsPolygonItem();
QPolygonF polygon() const;
void setPolygon(const QPolygonF &polygon);
Qt::FillRule fillRule() const;
void setFillRule(Qt::FillRule rule);
QRectF boundingRect() const;
QPainterPath shape() const;
bool contains(const QPointF &point) const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
enum { Type = 5 };
int type() const;
protected:
bool supportsExtension(Extension extension) const;
void setExtension(Extension extension, const QVariant &variant);
QVariant extension(const QVariant &variant) const;
private:
Q_DISABLE_COPY(QGraphicsPolygonItem)
Q_DECLARE_PRIVATE(QGraphicsPolygonItem)
};
class QGraphicsLineItemPrivate;
class Q_GUI_EXPORT QGraphicsLineItem : public QGraphicsItem
{
public:
QGraphicsLineItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsLineItem(const QLineF &line, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsLineItem(qreal x1, qreal y1, qreal x2, qreal y2, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QGraphicsLineItem();
QPen pen() const;
void setPen(const QPen &pen);
QLineF line() const;
void setLine(const QLineF &line);
inline void setLine(qreal x1, qreal y1, qreal x2, qreal y2)
{ setLine(QLineF(x1, y1, x2, y2)); }
QRectF boundingRect() const;
QPainterPath shape() const;
bool contains(const QPointF &point) const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
enum { Type = 6 };
int type() const;
protected:
bool supportsExtension(Extension extension) const;
void setExtension(Extension extension, const QVariant &variant);
QVariant extension(const QVariant &variant) const;
private:
Q_DISABLE_COPY(QGraphicsLineItem)
Q_DECLARE_PRIVATE(QGraphicsLineItem)
};
class QGraphicsPixmapItemPrivate;
class Q_GUI_EXPORT QGraphicsPixmapItem : public QGraphicsItem
{
public:
enum ShapeMode {
MaskShape,
BoundingRectShape,
HeuristicMaskShape
};
QGraphicsPixmapItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsPixmapItem(const QPixmap &pixmap, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QGraphicsPixmapItem();
QPixmap pixmap() const;
void setPixmap(const QPixmap &pixmap);
Qt::TransformationMode transformationMode() const;
void setTransformationMode(Qt::TransformationMode mode);
QPointF offset() const;
void setOffset(const QPointF &offset);
inline void setOffset(qreal x, qreal y);
QRectF boundingRect() const;
QPainterPath shape() const;
bool contains(const QPointF &point) const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
enum { Type = 7 };
int type() const;
ShapeMode shapeMode() const;
void setShapeMode(ShapeMode mode);
protected:
bool supportsExtension(Extension extension) const;
void setExtension(Extension extension, const QVariant &variant);
QVariant extension(const QVariant &variant) const;
private:
Q_DISABLE_COPY(QGraphicsPixmapItem)
Q_DECLARE_PRIVATE(QGraphicsPixmapItem)
};
inline void QGraphicsPixmapItem::setOffset(qreal ax, qreal ay)
{ setOffset(QPointF(ax, ay)); }
class QGraphicsTextItemPrivate;
class QTextDocument;
class QTextCursor;
class Q_GUI_EXPORT QGraphicsTextItem : public QObject, public QGraphicsItem
{
Q_OBJECT
QDOC_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks)
QDOC_PROPERTY(QTextCursor textCursor READ textCursor WRITE setTextCursor)
public:
QGraphicsTextItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsTextItem(const QString &text, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QGraphicsTextItem();
QString toHtml() const;
void setHtml(const QString &html);
QString toPlainText() const;
void setPlainText(const QString &text);
QFont font() const;
void setFont(const QFont &font);
void setDefaultTextColor(const QColor &c);
QColor defaultTextColor() const;
QRectF boundingRect() const;
QPainterPath shape() const;
bool contains(const QPointF &point) const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
enum { Type = 8 };
int type() const;
void setTextWidth(qreal width);
qreal textWidth() const;
void adjustSize();
void setDocument(QTextDocument *document);
QTextDocument *document() const;
void setTextInteractionFlags(Qt::TextInteractionFlags flags);
Qt::TextInteractionFlags textInteractionFlags() const;
void setTabChangesFocus(bool b);
bool tabChangesFocus() const;
void setOpenExternalLinks(bool open);
bool openExternalLinks() const;
void setTextCursor(const QTextCursor &cursor);
QTextCursor textCursor() const;
Q_SIGNALS:
void linkActivated(const QString &);
void linkHovered(const QString &);
protected:
bool sceneEvent(QEvent *event);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
void keyPressEvent(QKeyEvent *event);
void keyReleaseEvent(QKeyEvent *event);
void focusInEvent(QFocusEvent *event);
void focusOutEvent(QFocusEvent *event);
void dragEnterEvent(QGraphicsSceneDragDropEvent *event);
void dragLeaveEvent(QGraphicsSceneDragDropEvent *event);
void dragMoveEvent(QGraphicsSceneDragDropEvent *event);
void dropEvent(QGraphicsSceneDragDropEvent *event);
void inputMethodEvent(QInputMethodEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void hoverMoveEvent(QGraphicsSceneHoverEvent *event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
QVariant inputMethodQuery(Qt::InputMethodQuery query) const;
bool supportsExtension(Extension extension) const;
void setExtension(Extension extension, const QVariant &variant);
QVariant extension(const QVariant &variant) const;
private:
Q_DISABLE_COPY(QGraphicsTextItem)
Q_PRIVATE_SLOT(dd, void _q_updateBoundingRect(const QSizeF &))
Q_PRIVATE_SLOT(dd, void _q_update(QRectF))
Q_PRIVATE_SLOT(dd, void _q_ensureVisible(QRectF))
QGraphicsTextItemPrivate *dd;
friend class QGraphicsTextItemPrivate;
};
class QGraphicsSimpleTextItemPrivate;
class Q_GUI_EXPORT QGraphicsSimpleTextItem : public QAbstractGraphicsShapeItem
{
public:
QGraphicsSimpleTextItem(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
QGraphicsSimpleTextItem(const QString &text, QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QGraphicsSimpleTextItem();
void setText(const QString &text);
QString text() const;
void setFont(const QFont &font);
QFont font() const;
QRectF boundingRect() const;
QPainterPath shape() const;
bool contains(const QPointF &point) const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
enum { Type = 9 };
int type() const;
protected:
bool supportsExtension(Extension extension) const;
void setExtension(Extension extension, const QVariant &variant);
QVariant extension(const QVariant &variant) const;
private:
Q_DISABLE_COPY(QGraphicsSimpleTextItem)
Q_DECLARE_PRIVATE(QGraphicsSimpleTextItem)
};
class QGraphicsItemGroupPrivate;
class Q_GUI_EXPORT QGraphicsItemGroup : public QGraphicsItem
{
public:
QGraphicsItemGroup(QGraphicsItem *parent = 0
#ifndef Q_QDOC
// obsolete argument
, QGraphicsScene *scene = 0
#endif
);
~QGraphicsItemGroup();
void addToGroup(QGraphicsItem *item);
void removeFromGroup(QGraphicsItem *item);
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
bool isObscuredBy(const QGraphicsItem *item) const;
QPainterPath opaqueArea() const;
enum { Type = 10 };
int type() const;
private:
Q_DISABLE_COPY(QGraphicsItemGroup)
Q_DECLARE_PRIVATE(QGraphicsItemGroup)
};
template <class T> inline T qgraphicsitem_cast(QGraphicsItem *item)
{
return int(static_cast<T>(0)->Type) == int(QGraphicsItem::Type)
|| (item && int(static_cast<T>(0)->Type) == item->type()) ? static_cast<T>(item) : 0;
}
template <class T> inline T qgraphicsitem_cast(const QGraphicsItem *item)
{
return int(static_cast<T>(0)->Type) == int(QGraphicsItem::Type)
|| (item && int(static_cast<T>(0)->Type) == item->type()) ? static_cast<T>(item) : 0;
}
#ifndef QT_NO_DEBUG_STREAM
Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem *item);
Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemChange change);
Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag);
Q_GUI_EXPORT QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlags flags);
#endif
QT_END_NAMESPACE
Q_DECLARE_METATYPE(QGraphicsItem *)
Q_DECLARE_METATYPE(QGraphicsScene *)
QT_BEGIN_NAMESPACE
#endif // QT_NO_GRAPHICSVIEW
QT_END_NAMESPACE
QT_END_HEADER
#endif // QGRAPHICSITEM_H
| [
"alon@rogue.(none)"
] | alon@rogue.(none) |
c53b7c19ff784dd7932381698d3fd94cad18ebca | 8fefb33c3b292cde7fc52bd58e3f85fbe36da814 | /src/ClosetDisplay.ino | e24173e3f15f79ad74230f7fe51340f7a87b6b57 | [] | no_license | Skilllogic/videos | f1f69b6fc8390fd641352fee32de967ac694d5f5 | ec6283c722c1b49c14481b0d1e59815e1f4263e4 | refs/heads/master | 2021-10-25T05:04:10.413254 | 2019-03-25T16:40:48 | 2019-03-25T16:40:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,415 | ino | SYSTEM_MODE(MANUAL);
SYSTEM_THREAD(ENABLED);
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
#include "WCL_WatchDog.h"
#define TEMP_DATA_SIZE 10
#define MQTT_CLIENT_NAME "argonTempDisplay"
#define QUEUE_SIZE 10
#define TRIGGER_WDT_BTN D3
#define MESSAGE_LED A2
#define PETTING_OFF A1
#define TIME_STRING_SIZE 10
#define DATA_IS_OLD 10000 // no update after these number of milliseconds
#define WATCHDOG_TIMEOUT_MS 30000
Adafruit_SSD1306 display(D18);
WCL_WatchDog wd;
unsigned long timeOfLastUpdate;
char timeString[TIME_STRING_SIZE];
os_thread_t thread;
os_thread_t cloudThread;
os_mutex_t mutex;
os_queue_t queue;
void sendToCloud(void *arg) {
char data[TEMP_DATA_SIZE];
while (1) {
os_queue_take(queue, &data, CONCURRENT_WAIT_FOREVER, 0);
if (Particle.connected()) {
Particle.publish("temperature", data);
}
}
}
void messageLED(void *arg) {
while (1) {
os_mutex_lock(mutex);
digitalWrite(MESSAGE_LED, HIGH);
delay(2000);
digitalWrite(MESSAGE_LED, LOW);
}
}
void displayMessage(uint8_t textSize, uint8_t lineNumber, const char *data) {
display.setTextSize(textSize);
display.setTextColor(WHITE);
display.setCursor(0, lineNumber*18);
display.println(data);
display.display();
}
void showTemp(const char *event, const char *data)
{
char localCopy[TEMP_DATA_SIZE];
memcpy((void*)&localCopy, (void *)data, TEMP_DATA_SIZE);
os_queue_put(queue, localCopy, 0, 0);
unsigned long delta = millis() - timeOfLastUpdate;
timeOfLastUpdate = millis();
display.clearDisplay();
displayMessage(2,0,localCopy);
snprintf(timeString, sizeof(timeString), "%d", delta);
displayMessage(2, 1, timeString);
os_mutex_unlock(mutex);
}
void setup() {
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
pinMode(MESSAGE_LED, OUTPUT);
pinMode(PETTING_OFF, OUTPUT);
digitalWrite(MESSAGE_LED, LOW);
digitalWrite(PETTING_OFF, LOW);
pinMode(TRIGGER_WDT_BTN, INPUT);
digitalWrite(ANTSW1, 0);
digitalWrite(ANTSW2, 1);
display.clearDisplay();
if (System.resetReason() == RESET_REASON_WATCHDOG) {
displayMessage(2, 0, "WDT RST");
} else {
displayMessage(2, 0, "RST");
}
delay(2000);
display.clearDisplay();
displayMessage(2, 0, "Mesh...");
Mesh.on();
Mesh.connect();
waitUntil(Mesh.ready);
display.clearDisplay();
displayMessage(2, 0, "WiFi...");
WiFi.on();
WiFi.connect();
waitUntil(WiFi.ready);
display.clearDisplay();
displayMessage(2, 0, "Prtcl...");
Particle.connect();
waitUntil(Particle.connected);
display.clearDisplay();
displayMessage(2, 0, "Temp...");
os_mutex_create(&mutex);
os_queue_create(&queue, TEMP_DATA_SIZE, QUEUE_SIZE, NULL);
os_thread_create(&thread, NULL, OS_THREAD_PRIORITY_DEFAULT, messageLED, NULL, 2048);
os_thread_create(&cloudThread, NULL, OS_THREAD_PRIORITY_DEFAULT, sendToCloud, NULL, 2048);
Mesh.subscribe("newTemp", showTemp);
wd.initialize(WATCHDOG_TIMEOUT_MS);
}
bool keepPettingWatchDog = true;
void loop() {
if (digitalRead(TRIGGER_WDT_BTN) == LOW) {
keepPettingWatchDog = false;
digitalWrite(PETTING_OFF, HIGH);
}
if (keepPettingWatchDog && Particle.connected()) {
wd.pet();
}
unsigned long delta = millis() - timeOfLastUpdate;
if (delta > DATA_IS_OLD) {
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(90, 0);
display.println("OLD");
display.display();
}
} | [
"kevin@glancemirror.com"
] | kevin@glancemirror.com |
3ed8abce38851b905defbcb2272372f8e4dd6d7f | 3bdf6e1c65260d31854b86ddee5b67a9f0670578 | /src/core/framework/graphics/direct3d/Direct3DNGRectBatcher.cpp | 85d72e796fe67387908f508d579e9a32c8120c83 | [] | no_license | sgowen/nosfuratu | cd3f1dbceebb76c932e67d6395272e15bc3014db | 025e3923b4838ef2d5a1b300e6e61ddfc2d23e2e | refs/heads/master | 2022-04-16T09:07:15.795381 | 2022-02-17T17:54:22 | 2022-02-17T17:54:22 | 39,219,472 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,858 | cpp | //
// Direct3DNGRectBatcher.cpp
// noctisgames-framework
//
// Created by Stephen Gowen on 9/22/14.
// Copyright (c) 2017 Noctis Games. All rights reserved.
//
#include "pch.h"
#include "Direct3DNGRectBatcher.h"
#include "NGRect.h"
#include "Vector2D.h"
#include "Direct3DProgramInput.h"
#include "Direct3DManager.h"
#include "GpuProgramWrapper.h"
#include "Direct3DGeometryGpuProgramWrapper.h"
#include "Color.h"
Direct3DNGRectBatcher::Direct3DNGRectBatcher(bool isFill) : NGRectBatcher(isFill)
{
// Empty
}
void Direct3DNGRectBatcher::beginBatch()
{
D3DManager->getColorVertices().clear();
m_iNumNGRects = 0;
}
void Direct3DNGRectBatcher::endBatch(GpuProgramWrapper &gpuProgramWrapper)
{
if (m_iNumNGRects > 0)
{
// set the primitive topology
ID3D11DeviceContext* d3dContext = Direct3DManager::getD3dContext();
d3dContext->IASetPrimitiveTopology(m_isFill ? D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST : D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP);
gpuProgramWrapper.bind();
d3dContext->DrawIndexed(m_iNumNGRects * INDICES_PER_RECTANGLE, 0, 0);
gpuProgramWrapper.unbind();
}
}
void Direct3DNGRectBatcher::renderNGRect(NGRect &rectangle, Color &color)
{
float x1 = rectangle.getLeft();
float y1 = rectangle.getBottom();
float x2 = x1 + rectangle.getWidth();
float y2 = y1 + rectangle.getHeight();
renderNGRect(x1, y1, x2, y2, color);
}
void Direct3DNGRectBatcher::renderNGRect(float x1, float y1, float x2, float y2, Color &color)
{
D3DManager->addVertexCoordinate(x1, y1, 0, color.red, color.green, color.blue, color.alpha);
D3DManager->addVertexCoordinate(x1, y2, 0, color.red, color.green, color.blue, color.alpha);
D3DManager->addVertexCoordinate(x2, y2, 0, color.red, color.green, color.blue, color.alpha);
D3DManager->addVertexCoordinate(x2, y1, 0, color.red, color.green, color.blue, color.alpha);
m_iNumNGRects++;
}
| [
"dev.sgowen@gmail.com"
] | dev.sgowen@gmail.com |
f9e4c42f9a58370e9912224b275ee91a5182ea2c | 7d5dbe3ceb85833b9a2c2a2d1bfd71f2c772a01f | /src/ShaderManager.cpp | 2d6e4917b05fbf91cde891c138d0855706918aa7 | [] | no_license | forivall-old-repos/opengl3-rg | a8e530f70c33e70088672d856faee387ebd728d3 | e4f9b7d356167e35b3a21f63ce227e266b306e99 | refs/heads/master | 2022-11-20T23:17:48.584560 | 2011-10-20T05:27:18 | 2011-10-20T05:27:18 | 281,288,584 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,620 | cpp | /*
* ShaderManager.cpp
*
* Created on: 2011-10-08
* Author: Jordan
*/
#include "ShaderManager.h"
using namespace glrg;
ShaderManager *ShaderManager::singleton;
// Create a NULL-terminated string by reading the provided file
char* glrg::ReadShaderSource(const char* shaderFile)
{
FILE* fp = fopen(shaderFile, "r");
if ( fp == NULL ) { return NULL; }
fseek(fp, 0L, SEEK_END);
long size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char* buf = new char[size + 1];
fread(buf, 1, size, fp);
buf[size] = '\0';
fclose(fp);
return buf;
}
// Create a GLSL program object from vertex and fragment shader files
GLuint glrg::InitShader(const char* vShaderFile, const char* fShaderFile)
{
ShaderData shaders[2] = {
{ vShaderFile, GL_VERTEX_SHADER, NULL },
{ fShaderFile, GL_FRAGMENT_SHADER, NULL }
};
return glrg::InitShader(shaders);
}
GLuint glrg::InitShader(ShaderData *shaders) {
GLuint program = glCreateProgram();
for ( int i = 0; i < 2; ++i ) {
ShaderData& s = shaders[i];
s.source = ReadShaderSource( s.filename );
if ( shaders[i].source == NULL ) {
std::cerr << "Failed to read " << s.filename << std::endl;
exit( EXIT_FAILURE );
}
GLuint shader = glCreateShader( s.type );
glShaderSource( shader, 1, (const GLchar**) &s.source, NULL );
glCompileShader( shader );
GLint compiled;
glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled );
if ( !compiled ) {
std::cerr << s.filename << " failed to compile:" << std::endl;
GLint logSize;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize );
char* logMsg = new char[logSize];
glGetShaderInfoLog( shader, logSize, NULL, logMsg );
std::cerr << logMsg << std::endl;
delete [] logMsg;
exit( EXIT_FAILURE );
}
delete [] s.source;
glAttachShader( program, shader );
}
return program;
}
GLuint glrg::LinkShader(GLuint program) {
/* link and error check */
glLinkProgram(program);
GLint linked;
glGetProgramiv( program, GL_LINK_STATUS, &linked );
if ( !linked ) {
std::cerr << "Shader program failed to link" << std::endl;
GLint logSize;
glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize);
char* logMsg = new char[logSize];
glGetProgramInfoLog( program, logSize, NULL, logMsg );
std::cerr << logMsg << std::endl;
delete [] logMsg;
exit( EXIT_FAILURE );
}
/* use program object */
glUseProgram(program);
return program;
}
glrg::ShaderManager::ShaderManager() {
}
void glrg::ShaderManager::addProgramInfo(
GLuint program,
GLuint attrib_loc,
GLint unit_size,
GLenum type) {
info[program][attrib_loc] = ShaderAttribInfo(attrib_loc, unit_size, type);
//info[program][attrib_name] = ShaderAttribInfo(
// glGetAttribLocation(program, attrib_name), unit_size, type);
}
GLint glrg::ShaderManager::getUnitSize(GLuint program, GLuint attrib_loc) {
return info[program][attrib_loc].unit_size;
}
ShaderManager *glrg::ShaderManager::getSingleton()
{
if(singleton == NULL){
singleton = new ShaderManager();
}
return singleton;
}
GLint glrg::ShaderManager::getType(GLuint program, GLuint attrib_loc) {
return info[program][attrib_loc].type;
}
| [
"forivall@gmail.com"
] | forivall@gmail.com |
ec1db16d40245368c41d86ff8e0dce488a8cf2df | 5b129889790f51ef46f00507e9afba31f32ba5a1 | /src/image.hpp | aeb754615d862f5b7d463586d267330b874f749c | [
"Zlib",
"MIT"
] | permissive | werl/playing-with-opengl | d784d1cc8a2642cea058604e9db427c72dab268b | 0d9c1145c8fc30584571358e9007e8a3877baccd | refs/heads/master | 2021-01-12T11:03:43.802348 | 2016-11-07T21:21:38 | 2016-11-07T21:21:38 | 72,806,342 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | hpp | //
// Created by Peter Lewis on 2016-10-23.
//
#ifndef LEARNINGCPP_IMAGELOADER_HPP
#define LEARNINGCPP_IMAGELOADER_HPP
#include <ntsid.h>
#include <vector>
class Image {
private:
int image_width;
int image_height;
int comp;
unsigned char* image;
public:
Image(std::string filename, int image_type);
int get_comp() {
return comp;
}
int get_image_width() {
return image_width;
}
int get_image_height() {
return image_height;
}
unsigned char* get_image() {
return image;
}
void releaseImage();
};
#endif //LEARNINGCPP_IMAGELOADER_HPP
| [
"peter@werl.me"
] | peter@werl.me |
5f9d83ec5a24b1d591432dc034564bb4ac6300e1 | bff077bf3648ebd8f2462b195c27657e531f307d | /Robot/Turn.h | 70c25965df99b93f0177a997823b52cd1747549b | [] | no_license | azhorsmann/Robot | a7f78f70d50d46ada1c095972dc175744284f67a | b40a9acb0f17dca54c0ac4009378ce2aaee2fd64 | refs/heads/master | 2021-09-03T10:17:31.083112 | 2018-01-08T10:13:47 | 2018-01-08T10:13:47 | 116,660,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | h | #ifndef __Turn_H_
#define __Turn_H_
#pragma once
#include "Node.h"
namespace BT
{
class Turn :
public Node
{
public:
Turn();
Turn(std::string name);
Turn(std::string name, int motor1Pin1, int motor1Pin2, int motor2Pin1, int motor2Pin2);
~Turn();
void Tick();
int Motor1Pin1;
int Motor1Pin2;
int Motor2Pin1;
int Motor2Pin2;
bool Right;
};
}
#endif | [
"azhorsmann@live.dk"
] | azhorsmann@live.dk |
7d6340b8643f9ca3d9ce40cd76a5ff3eee580eaa | 180ca28f6101bac14c3ed0bf168bfdd1d1184c2b | /NEAR.CPP | a7d1ca943dc08d4a6dd9919ca627a82568e4deb1 | [] | no_license | mr-easy/CodeChef-Solutions | ad35120401baebfc9b0c1c7c57178bf6e03b486a | 9fb9cfe2a58ae442dcd79028148e8684d16e895e | refs/heads/master | 2021-06-13T11:10:40.444142 | 2017-03-19T15:57:10 | 2017-03-19T15:57:10 | 72,444,145 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | //Nearest cab
#include<stdio.h>
int main()
{
int cases, n, m;
scanf("%d", &cases);
while(cases--)
{
scanf("%d%d", &n, &m);
long long int x[n], y[n];
for(int i = 0; i < n; i++)
{
scanf("%lld%lld", &x[i], &y[i]);
}
long long int sx[m], sy[m], dx[m], dy[m], minDist, calc;
int idx;
for(int j = 0; j < m; j++)
{
scanf("%lld%lld%lld%lld", &sx[j], &sy[j], &dx[j], &dy[j]);
}
for(int j = 0; j < m; j++)
{
//Finding nearest cab
minDist = ((sx[j] - x[0])*(sx[j] - x[0])) + ((sy[j] - y[0])*(sy[j] - y[0]));
idx = 0;
for(long long int i = 1; i < n; i++)
{
calc = ((sx[j] - x[i])*(sx[j] - x[i])) + ((sy[j] - y[i])*(sy[j] - y[i]));
if(calc < minDist)
{
minDist = calc;
idx = i;
}
}
x[idx] = dx[j]; y[idx] = dy[j];
printf("%d\n", idx+1);
}
}
return 0;
}
| [
"rishabhg1997@gmail.com"
] | rishabhg1997@gmail.com |
9762b196f0989e712df80d36e2770e60344c75b0 | 46f4e15baf9a8f1f6b54a77027fe571788f83efa | /x-old/Software/SeraphRoboticsBackend/shared/math/vector3.h | 193f9d0b0dc2b9d6da2471c610b67eb30ea9c0d5 | [] | no_license | SeraphRobotics/TabletSystem | 9ed59740298159e648e6000c752588973a3e8ecf | a0189bdd12fadf44d7a64b62fb8585c202f2debd | refs/heads/master | 2021-03-27T11:46:54.176087 | 2016-07-07T14:17:07 | 2016-07-07T14:17:07 | 22,484,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,702 | h | #pragma once
#include "float.h"
#include "structs.h"
namespace Math {
/**
* Represents a point, ray or normal in 3d space. The tolerance is a
* single-parameter template class that has kTolerance and kToleranceSq
* const static member variables.
*/
struct Vector3 {
// Coordinate values
Float x, y, z;
/**
* Constructor, basic
*/
Vector3();
/**
* Constructor
*
* Clones input v
*/
Vector3(const Vector3& v);
/**
* Makes this vector3 identical to input v
*/
explicit Vector3(const Vector3 v[3]);
/**
* Sets this vector3's x, y, and z to the Floats in the input array
*/
explicit Vector3(const Float* v);
/**
* Sets this vectors' x, y, and z to the respective inputs
*/
explicit Vector3(Float x, Float y, Float z);
/**
* Accesses an element by an index: {0: x, 1: y, 2: z}
*/
Float& operator [] (int ix);
/**
* Accesses an element by an index: {0: x, 1: y, 2: z}
*/
Float operator [] (int ix) const;
/**
* Provides access to this vector as an array {x, y, z}
*/
Float* array();
/**
* Provides access to this vector as an array {x, y, z}
*/
const Float* array() const;
/**
* Returns the magnitude of this vector.
* This method involves taking a square root, which can be an expensive
* operation, so substitute lengthSq whenever possible.
*/
Float length() const;
/**
* Returns the square of the magnitude of this vector
*/
Float lengthSq() const;
/**
* Returns 'true' if this vector has unit length
*/
bool isNormalized() const;
/**
* Detects if the vector has no magnitude (can't be normalized)
*/
bool isInvalid() const;
/**
* Normalizes this vector in place.
* Returns a reference to this object to allow method chaining.
*/
Vector3& normalize();
/**
* Adds each element of 'v' to this object's corresponding element.
* Returns a reference to this object to allow method chaining.
*/
Vector3& add(const Vector3& v);
/**
* Subtracts each element of 'v' from this object's corresponding
* element.
* Returns a reference to this object to allow method chaining.
*/
Vector3& sub(const Vector3& v);
/**
* Returns the dot product of this vector with the v vector
*/
Float dot(const Vector3& v) const;
/**
* Sets this object to the cross product of this vector with the provided
* vector.
* Returns a reference to this object to allow method chaining.
*/
Vector3& cross(const Vector3& v);
/**
* Removes all components of this vector not in the direction of 'normal'.
* 'normal' must be normalized before invoking this method.
* Returns a reference to this object to allow method chaining.
*/
Vector3& project(const Vector3& normal);
/**
* Returns a reference to this object to allow method chaining.
*/
Vector3& set(const Vector3& v);
/**
* Returns a reference to this object to allow method chaining.
*/
Vector3& set(const Vector3* v);
/**
* Returns a reference to a newly created object
* with x, y, and z set to the respective input params to allow method chaining.
*/
Vector3& set(Float x, Float y, Float z);
/**
* Sets this vector to the weighted combination of itself and the
* provided vector.
* This can be used for linear interpolation or geometric approach.
* Returns a reference to this object to allow method chaining.
*/
Vector3& mix(const Vector3& v, float weight);
/**
* Stores the normalized vector in the direction of 'end' from 'start'
* in this object.
* Returns a reference to this object to allow method chaining.
*/
Vector3& ray(const Vector3& start, const Vector3& end);
/**
* Returns a duplicate of this vector as an object.
*/
Vector3 copy() const;
/**
* Returns the distance from this point in space to 'v'.
* This method involves taking a square root, which can be an expensive
* operation, so substitute distanceToSq whenever possible.
*/
Float distanceTo(const Vector3& v) const;
/**
* Returns the square of the distance from this point in space to 'v'
*/
Float distanceToSq(const Vector3& v) const;
/**
* Returns the length of this vector. This calculation involves a square-root
* so prefer magnitudeSq whenever possible.
*/
Float magnitude() const;
/**
* Returns the square of the length of this vector
*/
Float magnitudeSq() const;
/**
* Resets the Float to the origin
*/
Vector3& zero();
/**
* Multiplies the magnitude of this vector by the given amount
* Returns a reference to this object to allow method chaining.
*/
Vector3& scale(Float s);
/**
* Multiplies each component in this vector by the corresponding one in the
* input vector
*/
Vector3& scalePairwise(const Vector3& s);
/**
* Ensures this vector is entirely in the first quadrant (each component's
* value is greater than or equal to zero).
* Returns a reference to this object to allow method chaining.
*/
Vector3& abs();
/**
* Sets each component to the lower among itself and the corresponding
* component of 'v'.
* Returns a reference to this object to allow method chaining.
*/
Vector3& min(const Vector3& v);
/**
* Sets each component to the higher among itself and the corresponding
* component of 'v'.
* Returns a reference to this object to allow method chaining.
*/
Vector3& max(const Vector3& v);
/**
* Rotates this location around the X-axis
* Returns a reference to this object to allow method chaining.
*/
Vector3& rotateX(Float radians);
/**
* Rotates this location around the Y-axis
* Returns a reference to this object to allow method chaining.
*/
Vector3& rotateY(Float radians);
/**
* Rotates this location around the Z-axis
* Returns a reference to this object to allow method chaining.
*/
Vector3& rotateZ(Float radians);
/**
* Rotates this location around the given arbitrary axis
* Returns a reference to this object to allow method chaining.
*/
Vector3& rotateAxisAngle(const Vector3& axis, Float radians);
/**
* Radians of rotation between this vector and another
*/
Float angleTo(const Vector3& v) const;
/**
* In-place operator. Returns *this.
*/
Vector3& operator = (const Vector3& v);
/**
* In-place operator. Returns *this.
*/
Vector3& operator += (const Vector3& v);
/**
* In-place operator. Returns *this.
*/
Vector3& operator -= (const Vector3& v);
/**
* In-place operator. Returns *this.
*/
Vector3& operator *= (Float s);
/**
* In-place operator. Returns *this.
*/
Vector3& operator /= (Float s);
/**
* Operators returning a temporary object
*/
Vector3 operator + (const Vector3& v) const;
Vector3 operator - (const Vector3& v) const;
/**
* Vector-Vector boolean operator. Equality is based on square of the
* radial distance from this vector to 'v' being floatEquals to 0.
*/
bool equals(const Vector3& v) const;
/**
* Vector-Vector boolean operator. Equality is based on some tolerance.
*/
bool equals(const Vector3& v, float tolerance) const;
/**
* Vector-Vector boolean operator. Equality is based on some tolerance.
*/
bool equalsSq(const Vector3& v, float tolerance_sq) const;
/**
* Lazy operation to make a new vector for an call
*/
static Vector3 make(float x, float y, float z);
};
}
Math::Vector3 operator * (const Math::Vector3& lhs, Math::Float s);
Math::Vector3 operator / (const Math::Vector3& lhs, Math::Float s);
Math::Vector3 operator * (Math::Float s, const Math::Vector3& v);
| [
"jeffreyilipton@gmail.com"
] | jeffreyilipton@gmail.com |
b374eb0cb82b9ff824987931892c306f92a1936c | 9d4bd68f1c5ed94a63b57e33c6e83bccf69950d8 | /lblock.h | f553da52cf8547a14b5701a1ea4808db7361036c | [] | no_license | JohnnyJohnAndTheFunkyBunch/CS246_a5 | e8f05122d7b37c64d45b8c4f2142433efdd8f1d8 | af9f16f14fd67bafd9c7654ea1f29bcb42a84e8e | refs/heads/master | 2016-09-16T01:15:54.873723 | 2014-01-16T16:03:15 | 2014-01-16T16:03:15 | 15,972,744 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 194 | h | #ifndef LBLOCK_H
#define LBLOCK_H
#include "block.h"
class LBlock : public Block
{
public:
LBlock();
virtual ~LBlock();
protected:
private:
};
#endif // LBLOCK_H
| [
"ma.jonathanj@gmail.com"
] | ma.jonathanj@gmail.com |
cbcf1078e37b781326900bac2918bb97b3c27b55 | 953a5f977e4ed940b177302c4adf5386929b67f9 | /Snake/inputManager.hpp | 2d1fe2a6d37b6120897f2b9961cc656c9d338b65 | [] | no_license | hatsil/snake | 23790702a536e4c9514493ee5cf65bfbf9a613e6 | 4d6e8a8f4808c5948724c9d57cd6d2d6dcd34ebe | refs/heads/master | 2020-06-02T17:52:04.176630 | 2019-06-10T22:48:14 | 2019-06-10T22:48:14 | 191,255,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,151 | hpp | #pragma once
#include <GLFW/glfw3.h>
#include "scene.hpp"
const int DISPLAY_WIDTH = 1200;
const int DISPLAY_HEIGHT = 800;
const float FAR = 100.0f;
const float NEAR = 1.0f;
const float CAM_ANGLE = 60.0f;
float relation = (float)DISPLAY_WIDTH / (float)DISPLAY_HEIGHT;
snake::Display* display;
snake::Scene* scn;
float factor = 1.0;
double x1 = 0, x2 = 0;
double ys1 = 0, y2 = 0;
float depth;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action == GLFW_PRESS || action == GLFW_REPEAT)
{
switch (key)
{
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GLFW_TRUE);
break;
case GLFW_KEY_RIGHT:
scn->MoveRight();
break;
case GLFW_KEY_LEFT:
scn->MoveLeft();
break;
case GLFW_KEY_UP:
scn->MoveUp();
break;
case GLFW_KEY_DOWN:
scn->MoveDown();
break;
case GLFW_KEY_SPACE:
scn->SwitchCamera();
break;
}
}
}
void updatePosition(double xpos, double ypos)
{
x1 = x2;
x2 = xpos;
ys1 = y2;
y2 = ypos;
}
void window_size_callback(GLFWwindow* window, int width, int height) {
scn->Resize(width, height);
relation = (float)width / (float)height;
} | [
"tsahisa@post.bgu.ac.il"
] | tsahisa@post.bgu.ac.il |
30615d25945bf591bd2c7ac25279b7803248c58f | b90d4a331572c5268f087b5f9ba741aa24a9f00e | /src/searchlineedit.cc | e25d3f320d1146e81cadf786de9d2beaf1d56b04 | [] | no_license | paule32/dns-setup | b17a7cac697928ddcc0061fe55bb57f2e0b5527d | b44c840b0a323a66e6aef7bba9a9b45cdeef4b3a | refs/heads/master | 2021-01-23T02:30:28.375388 | 2017-05-15T16:14:27 | 2017-05-15T16:14:27 | 86,002,613 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,814 | cc | #include "searchlineedit.h"
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>
#include <QtWidgets/QMenu>
#include <QtWidgets/QStyle>
#include <QtWidgets/QStyleOptionFrame>
ClearButton::ClearButton(QWidget *parent)
: QAbstractButton(parent)
{
#ifndef QT_NO_CURSOR
setCursor(Qt::ArrowCursor);
#endif // QT_NO_CURSOR
setToolTip(tr("Clear"));
setVisible(false);
setFocusPolicy(Qt::NoFocus);
}
void ClearButton::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
int height = this->height();
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(isDown()
? palette().color(QPalette::Dark)
: palette().color(QPalette::Mid));
painter.setPen(painter.brush().color());
int size = width();
int offset = size / 5;
int radius = size - offset * 2;
painter.drawEllipse(offset, offset, radius, radius);
painter.setPen(palette().color(QPalette::Base));
int border = offset * 2;
painter.drawLine(border, border, width() - border, height - border);
painter.drawLine(border, height - border, width() - border, border);
}
void ClearButton::textChanged(const QString &text)
{
setVisible(!text.isEmpty());
}
/*
Search icon on the left hand side of the search widget
When a menu is set a down arrow appears
*/
class SearchButton : public QAbstractButton {
public:
SearchButton(QWidget *parent = 0);
void paintEvent(QPaintEvent *event);
QMenu *m_menu;
protected:
void mousePressEvent(QMouseEvent *event);
};
SearchButton::SearchButton(QWidget *parent)
: QAbstractButton(parent),
m_menu(0)
{
setObjectName(QLatin1String("SearchButton"));
#ifndef QT_NO_CURSOR
setCursor(Qt::ArrowCursor);
#endif //QT_NO_CURSOR
setFocusPolicy(Qt::NoFocus);
}
void SearchButton::mousePressEvent(QMouseEvent *event)
{
if (m_menu && event->button() == Qt::LeftButton) {
QWidget *p = parentWidget();
if (p) {
QPoint r = p->mapToGlobal(QPoint(0, p->height()));
m_menu->exec(QPoint(r.x() + height() / 2, r.y()));
}
event->accept();
}
QAbstractButton::mousePressEvent(event);
}
void SearchButton::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainterPath myPath;
int radius = (height() / 5) * 2;
QRect circle(height() / 3 - 1, height() / 4, radius, radius);
myPath.addEllipse(circle);
myPath.arcMoveTo(circle, 300);
QPointF c = myPath.currentPosition();
int diff = height() / 7;
myPath.lineTo(qMin(width() - 2, (int)c.x() + diff), c.y() + diff);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::darkGray, 2));
painter.drawPath(myPath);
if (m_menu) {
QPainterPath dropPath;
dropPath.arcMoveTo(circle, 320);
QPointF c = dropPath.currentPosition();
c = QPointF(c.x() + 3.5, c.y() + 0.5);
dropPath.moveTo(c);
dropPath.lineTo(c.x() + 4, c.y());
dropPath.lineTo(c.x() + 2, c.y() + 2);
dropPath.closeSubpath();
painter.setPen(Qt::darkGray);
painter.setBrush(Qt::darkGray);
painter.setRenderHint(QPainter::Antialiasing, false);
painter.drawPath(dropPath);
}
painter.end();
}
/*
SearchLineEdit is an enhanced QLineEdit
- A Search icon on the left with optional menu
- When there is no text and doesn't have focus an "inactive text" is displayed
- When there is text a clear button is displayed on the right hand side
*/
SearchLineEdit::SearchLineEdit(QWidget *parent) : ExLineEdit(parent),
m_searchButton(new SearchButton(this))
{
connect(lineEdit(), SIGNAL(textChanged(QString)),
this, SIGNAL(textChanged(QString)));
setLeftWidget(m_searchButton);
m_inactiveText = tr("Search");
QSizePolicy policy = sizePolicy();
setSizePolicy(QSizePolicy::Preferred, policy.verticalPolicy());
}
void SearchLineEdit::paintEvent(QPaintEvent *event)
{
if (lineEdit()->text().isEmpty() && !hasFocus() && !m_inactiveText.isEmpty()) {
ExLineEdit::paintEvent(event);
QStyleOptionFrame panel;
initStyleOption(&panel);
QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &panel, this);
QFontMetrics fm = fontMetrics();
int horizontalMargin = lineEdit()->x();
QRect lineRect(horizontalMargin + r.x(), r.y() + (r.height() - fm.height() + 1) / 2,
r.width() - 2 * horizontalMargin, fm.height());
QPainter painter(this);
painter.setPen(palette().brush(QPalette::Disabled, QPalette::Text).color());
painter.drawText(lineRect, Qt::AlignLeft|Qt::AlignVCenter, m_inactiveText);
} else {
ExLineEdit::paintEvent(event);
}
}
void SearchLineEdit::resizeEvent(QResizeEvent *event)
{
updateGeometries();
ExLineEdit::resizeEvent(event);
}
void SearchLineEdit::updateGeometries()
{
int menuHeight = height();
int menuWidth = menuHeight + 1;
if (!m_searchButton->m_menu)
menuWidth = (menuHeight / 5) * 4;
m_searchButton->resize(QSize(menuWidth, menuHeight));
}
QString SearchLineEdit::inactiveText() const
{
return m_inactiveText;
}
void SearchLineEdit::setInactiveText(const QString &text)
{
m_inactiveText = text;
}
void SearchLineEdit::setMenu(QMenu *menu)
{
if (m_searchButton->m_menu)
m_searchButton->m_menu->deleteLater();
m_searchButton->m_menu = menu;
updateGeometries();
}
QMenu *SearchLineEdit::menu() const
{
if (!m_searchButton->m_menu) {
m_searchButton->m_menu = new QMenu(m_searchButton);
if (isVisible())
(const_cast<SearchLineEdit*>(this))->updateGeometries();
}
return m_searchButton->m_menu;
}
| [
"jkallup@web.de"
] | jkallup@web.de |
aa099742caf56e60e93a78b0625f8954b1e48dd8 | f839c15910aa083a1565076055d3851b8387c1cd | /include/ircd/m/room/events.h | 1acedee69752271b19a800221f4269e6c22cd2d8 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | PhyllisAhrens/construct | e8e461abd600fd5646688692496eaa65fb918038 | daee7001fba34961a8e24579b1e12068435482cc | refs/heads/master | 2023-04-09T15:48:45.923937 | 2021-02-11T19:29:58 | 2021-02-11T19:31:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,719 | h | // Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2019 Jason Volk <jason@zemos.net>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_M_ROOM_EVENTS_H
// The "viewport" is comprised of events starting from the tophead (most recent
// in room timeline) and covering about ~20 events leading up to that. Note
// that this is a completely ad hoc and configurable server value. Events in
// the viewport must be eval'ed and synced to clients in the order they will
// be displayed. Events not in the viewport are not /synced to clients and any
// client request provides event ordering: thus older events (backfills, etc)
// can be eval'ed without this constraint.
//
// The "sounding" is the depth of the first gap. In any attempt to trace
// the room timeline from the tophead to the m.room.create event: the sounding
// is the [highest number] depth preventing that.
//
// The "twain" marks the depth at the end of the first gap; the server is in
// possession of one or more events again at the twain.
//
// The "hazard" is the depth of the first gap starting from the m.room.create
// event toward the tophead. In any attempt to trace the room timeline with
// an increasing depth, the hazard is the next gap to frontfill.
namespace ircd::m
{
std::pair<int64_t, event::idx> viewport(const room &);
std::pair<int64_t, event::idx> sounding(const room &); // Last missing (one)
std::pair<int64_t, event::idx> twain(const room &);
std::pair<int64_t, event::idx> hazard(const room &); // First missing (one)
}
/// Interface to room events
///
/// This interface has the form of an STL-style iterator over room events
/// which are state and non-state events from all integrated timelines.
/// Moving the iterator is cheap, but the dereference operators fetch a
/// full event. One can iterate just event_idx's by using event_idx() instead
/// of the dereference operators.
///
struct ircd::m::room::events
{
struct sounding;
struct horizon;
struct missing;
static conf::item<ssize_t> viewport_size;
m::room room;
db::domain::const_iterator it;
event::fetch _event;
public:
explicit operator bool() const { return bool(it); }
bool operator!() const { return !it; }
// Observers from the current valid iterator
uint64_t depth() const;
event::idx event_idx() const;
explicit operator event::idx() const;
// Perform a new lookup / iterator
bool seek_idx(const event::idx &, const bool &lower_bound = false);
bool seek(const uint64_t &depth = -1);
bool seek(const event::id &);
// Prefetch a new iterator lookup (async)
bool preseek(const uint64_t &depth = -1);
// Move the iterator
auto &operator++() { return --it; }
auto &operator--() { return ++it; }
// Fetch the actual event data at the iterator's position
const m::event &operator*();
const m::event *operator->() { return &operator*(); }
const m::event &fetch(std::nothrow_t);
const m::event &fetch();
// Prefetch the actual event data at the iterator's position (async)
bool prefetch(const string_view &event_prop);
bool prefetch(); // uses supplied fetch::opts.
events(const m::room &,
const uint64_t &depth,
const event::fetch::opts *const & = nullptr);
events(const m::room &,
const event::id &,
const event::fetch::opts *const & = nullptr);
events(const m::room &,
const event::fetch::opts *const & = nullptr);
events() = default;
events(const events &) = delete;
events &operator=(const events &) = delete;
// Prefetch a new iterator (without any construction)
static bool preseek(const m::room &, const uint64_t &depth = -1);
// Prefetch the actual room event data for a range; or most recent.
using depth_range = std::pair<uint64_t, uint64_t>;
static size_t prefetch(const m::room &, const depth_range &);
static size_t prefetch_viewport(const m::room &);
// Note the range here is unusual: The start index is exclusive, the ending
// index is inclusive. The start index must be valid and in the room.
static size_t count(const m::room &, const event::idx_range &);
static size_t count(const event::idx_range &);
};
/// Find missing room events. This is a breadth-first iteration of missing
/// references from the tophead (or at the event provided in the room arg)
///
/// The closure is invoked with the first argument being the event_id unknown
/// to the server, followed by the depth and event::idx of the event making the
/// reference.
///
struct ircd::m::room::events::missing
{
using closure = std::function<bool (const event::id &, const uint64_t &, const event::idx &)>;
m::room room;
public:
bool rfor_each(const pair<int64_t> &depth, const closure &) const;
bool for_each(const pair<int64_t> &depth, const closure &) const;
bool for_each(const closure &) const;
size_t count() const;
missing() = default;
missing(const m::room &room)
:room{room}
{}
};
/// Find gaps in the room's events. A gap is where this server has no events
/// at a certain depth. This is a path-finding diagnostic interface, useful to
/// understand what areas of the timeline have not been acquired by the server
/// to calculate backfill requests, etc. This interface is depth-first oriented,
/// rather than the breadth-first room::events::missing interface.
///
struct ircd::m::room::events::sounding
{
using range = std::pair<int64_t, int64_t>;
using closure = std::function<bool (const range &, const event::idx &)>;
m::room room;
public:
bool for_each(const closure &) const;
bool rfor_each(const closure &) const;
sounding() = default;
sounding(const m::room &room)
:room{room}
{}
};
/// Find missing room events. This is an interface to the event-horizon for
/// this room. The event horizon is keyed by event_id and the value is the
/// event::idx of the event referencing it. There can be multiple entries for
/// an event_id. The closure is also invoked with the depth of the referencer.
///
struct ircd::m::room::events::horizon
{
using closure = std::function<bool (const event::id &, const uint64_t &, const event::idx &)>;
m::room room;
public:
bool for_each(const closure &) const;
size_t count() const;
size_t rebuild();
horizon() = default;
horizon(const m::room &room)
:room{room}
{}
};
| [
"jason@zemos.net"
] | jason@zemos.net |
fc765fc2c633ee6dde414a68ce353c105a00f257 | 68da791b42d3227f2e00e266e8340f4c393e7c98 | /perido-moins-debug.cpp | 910eee4cc46a1e83f003c16c0ab7016d4ce4d8ff | [
"MIT"
] | permissive | jamesadevine/radio-testing | cebbf8a68bd5b7ab688c19e9462b18893a025dca | 45dc19d6317e7203481df768fc916a1711835317 | refs/heads/master | 2020-04-01T18:23:38.237663 | 2018-10-20T12:45:52 | 2018-10-20T12:45:52 | 153,489,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,701 | cpp | /*
The MIT License (MIT)
Copyright (c) 2016 British Broadcasting Corporation.
This software is provided by Lancaster University by arrangement with the BBC.
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 "MicroBitConfig.h"
#if MICROBIT_RADIO_VERSION == MICROBIT_RADIO_PERIDO
#include "MicroBitPeridoRadio.h"
#include "MicroBitComponent.h"
#include "EventModel.h"
#include "MicroBitDevice.h"
#include "ErrorNo.h"
#include "MicroBitFiber.h"
#include "MicroBitBLEManager.h"
/**
* Provides a simple broadcast radio abstraction, built upon the raw nrf51822 RADIO module.
*
* The nrf51822 RADIO module supports a number of proprietary modes of operation in addition to the typical BLE usage.
* This class uses one of these modes to enable simple, point to multipoint communication directly between micro:bits.
*
* TODO: The protocols implemented here do not currently perform any significant form of energy management,
* which means that they will consume far more energy than their BLE equivalent. Later versions of the protocol
* should look to address this through energy efficient broadcast techniques / sleep scheduling. In particular, the GLOSSY
* approach to efficient rebroadcast and network synchronisation would likely provide an effective future step.
*
* TODO: Meshing should also be considered - again a GLOSSY approach may be effective here, and highly complementary to
* the master/slave arachitecture of BLE.
*
* TODO: This implementation may only operated whilst the BLE stack is disabled. The nrf51822 provides a timeslot API to allow
* BLE to cohabit with other protocols. Future work to allow this colocation would be benefical, and would also allow for the
* creation of wireless BLE bridges.
*
* NOTE: This API does not contain any form of encryption, authentication or authorisation. Its purpose is solely for use as a
* teaching aid to demonstrate how simple communications operates, and to provide a sandpit through which learning can take place.
* For serious applications, BLE should be considered a substantially more secure alternative.
*/
MicroBitPeridoRadio* MicroBitPeridoRadio::instance = NULL;
extern void set_gpio0(int);
extern void set_gpio1(int);
extern void set_gpio2(int);
extern void packet_debug(PeridoFrameBuffer*);
extern void process_packet(PeridoFrameBuffer*);
extern void packet_missed(PeridoFrameBuffer *p);
extern void valid_packet_received(PeridoFrameBuffer*);
extern void increment_counter(int);
// low level states
#define LOW_LEVEL_STATE_MASK 0x0000FFFF // a mask for removing or retaining low level state
#define RADIO_STATUS_RX_EN 0x00000001 // reception is enabled
#define RADIO_STATUS_RX_RDY 0x00000002 // available to receive packets
#define RADIO_STATUS_TX_EN 0x00000008 // transmission is enabled
#define RADIO_STATUS_TX_RDY 0x00000010 // transmission is ready
#define RADIO_STATUS_TX_ST 0x00000020 // transmission has begun
#define RADIO_STATUS_TX_END 0x00000040 // transmission has finished
#define RADIO_STATUS_DISABLE 0x00000080 // the radio should be disabled
#define RADIO_STATUS_DISABLED 0x00000100 // the radio is disabled
// high level actions
#define HIGH_LEVEL_STATE_MASK 0xFFFF0000 // a mask for removing or retaining high level state
#define RADIO_STATUS_TRANSMIT 0x00020000 // moving into transmit mode to send a packet.
#define RADIO_STATUS_FORWARD 0x00040000 // actively forwarding any received packets
#define RADIO_STATUS_RECEIVING 0x00080000 // in the act of currently receiving a packet.
#define RADIO_STATUS_STORE 0x00100000 // indicates the storage of the rx'd packet is required.
#define RADIO_STATUS_DISCOVERING 0x00200000 // listening for packets after powering on, prevents sleeping in rx mode.
#define RADIO_STATUS_SLEEPING 0x00400000 // indicates that the window of transmission has passed, and we have entered sleep mode.
#define RADIO_STATUS_WAKE_CONFIGURED 0x00800000
#define RADIO_STATUS_EXPECT_RESPONSE 0x01000000
#define RADIO_STATUS_FIRST_PACKET 0x02000000
#define RADIO_STATUS_SAMPLING 0x04000000
#define RADIO_STATUS_DIRECTING 0x08000000
// #define DEBUG_MODE
/**
* Timings for each event (us):
*
* TX Enable 135
* TX (15 bytes) 166
* DISABLE 10
* RX Enable 135
**/
// #ifdef DEBUG_MODE
// #define DISCOVERY_TX_BACKOFF_TIME 10000000
// #define DISCOVERY_BACKOFF_TIME (DISCOVERY_TX_BACKOFF_TIME * 2)
// #define TX_BACKOFF_TIME 10000000
// #define TX_TIME 30000 // includes tx time for a larger packet
// #define TX_ENABLE_TIME 30000 // includes processing time overhead on reception for other nodes...
// #define RX_ENABLE_TIME 20000
// #define RX_TX_DISABLE_TIME 3000 // 10 us is pretty pointless for a timer callback.
// #else
#define DISCOVERY_TX_BACKOFF_TIME 10000000
#define DISCOVERY_BACKOFF_TIME (DISCOVERY_TX_BACKOFF_TIME * 2)
#ifdef DEBUG_MODE
#define TX_BACKOFF_MIN 10000
#define TX_BACKOFF_TIME (100000 - TX_BACKOFF_MIN)
#else
#define TX_BACKOFF_MIN 200
#define TX_BACKOFF_TIME (3000 - TX_BACKOFF_MIN)
#endif
#define TX_TIME 300 // includes tx time for a larger packet
#define TX_ENABLE_TIME 350 // includes processing time overhead on reception for other nodes...
#define RX_ENABLE_TIME 200
#define RX_TX_DISABLE_TIME 30 // 10 us is pretty pointless for a timer callback.
#define TX_ADDRESS_TIME 64
#define TIME_TO_TRANSMIT_ADDR RX_TX_DISABLE_TIME + TX_ENABLE_TIME + TX_ADDRESS_TIME
#define FORWARD_POLL_TIME 1500
#define ABSOLUTE_RESPONSE_TIME 10000
#define PERIDO_DEFAULT_PERIOD_IDX 1
#define TIME_TO_TRANSMIT_BYTE_1MB 8
#define NO_RESPONSE_THRESHOLD 5
#define LAST_SEEN_BUFFER_SIZE 3
#define OUT_TIME_BUFFER_SIZE 6
#define DISCOVERY_PACKET_THRESHOLD TX_BACKOFF_TIME + TX_BACKOFF_MIN
#define DISCOVERY_TIME_ARRAY_LEN 3
#define PERIDO_WAKE_THRESHOLD_MAX 1000
#define PERIDO_WAKE_THRESHOLD_MID 500
#define PERIDO_WAKE_TOLERANCE 30
#define CONSTANT_SYNC_OFFSET 110
#define WAKE_UP_CHANNEL 0
#define GO_TO_SLEEP_CHANNEL 1
#define CHECK_TX_CHANNEL 2
#define STATE_MACHINE_CHANNEL 3
#define PERIOD_COUNT 13
#define SPEED_THRESHOLD_MAX 5
#define SPEED_THRESHOLD_MIN -5
uint16_t periods[PERIOD_COUNT] = {10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480, 40960};
volatile uint32_t radio_status = 0;
volatile static uint32_t packet_received_count = 0;
volatile static uint32_t sleep_received_count = 0;
volatile uint32_t no_response_count = 0;
volatile int8_t speed = 0;
volatile static uint8_t network_period_idx = PERIDO_DEFAULT_PERIOD_IDX;
volatile uint32_t crc_fail_count = 0;
volatile uint32_t packet_count = 0;
volatile static uint32_t current_cc = 0;
volatile static uint32_t period_start_cc = 0;
volatile static uint32_t correction = 0;
volatile uint8_t last_seen_index = 0;
volatile uint32_t last_seen[LAST_SEEN_BUFFER_SIZE] = { 0 };
extern void log_string(const char * s);
extern void log_num(int num);
uint32_t read_and_restart_wake()
{
uint32_t t = MicroBitPeridoRadio::instance->timer.captureCounter(WAKE_UP_CHANNEL);
MicroBitPeridoRadio::instance->timer.setCompare(WAKE_UP_CHANNEL, current_cc);
return t;
}
void radio_state_machine()
{
#ifdef DEBUG_MODE
log_string("state: ");
log_num(NRF_RADIO->STATE);
log_string("\r\n");
#endif
if(radio_status & RADIO_STATUS_DISABLED)
{
#ifdef DEBUG_MODE
log_string("disabled\r\n");
#endif
NRF_RADIO->EVENTS_DISABLED = 0;
NRF_RADIO->EVENTS_END = 0;
NRF_RADIO->EVENTS_ADDRESS = 0;
if(radio_status & RADIO_STATUS_TX_EN)
{
#ifdef DEBUG_MODE
log_string("ten\r\n");
#endif
set_gpio0(1);
radio_status &= ~(RADIO_STATUS_TX_EN | RADIO_STATUS_DISABLED);
radio_status |= RADIO_STATUS_TX_RDY;
NRF_RADIO->EVENTS_READY = 0;
NRF_RADIO->TASKS_TXEN = 1;
MicroBitPeridoRadio::instance->timer.setCompare(STATE_MACHINE_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(STATE_MACHINE_CHANNEL) + TX_ENABLE_TIME);
return;
}
if(radio_status & RADIO_STATUS_RX_EN)
{
#ifdef DEBUG_MODE
log_string("ren\r\n");
#endif
NRF_RADIO->PACKETPTR = (uint32_t)MicroBitPeridoRadio::instance->rxBuf;
radio_status &= ~(RADIO_STATUS_RX_EN | RADIO_STATUS_DISABLED);
radio_status |= RADIO_STATUS_RX_RDY;
// takes 7 us to complete, not much point in a timer.
NRF_RADIO->EVENTS_READY = 0;
NRF_RADIO->TASKS_RXEN = 1;
MicroBitPeridoRadio::instance->timer.setCompare(STATE_MACHINE_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(STATE_MACHINE_CHANNEL) + RX_ENABLE_TIME);
return;
}
}
if(radio_status & RADIO_STATUS_RX_RDY)
{
if (NRF_RADIO->EVENTS_READY)
{
#ifdef DEBUG_MODE
log_string("rdy\r\n");
#endif
NRF_RADIO->EVENTS_READY = 0;
NRF_RADIO->TASKS_START = 1;
return;
}
// we get an address event for rx, indicating we are in the process of receiving a packet. Update our status and return;
if(NRF_RADIO->EVENTS_ADDRESS)
{
NRF_RADIO->EVENTS_ADDRESS = 0;
// why do we enter an infinite loop of death here?
radio_status |= RADIO_STATUS_RECEIVING;
// clear any timer cb's so we aren't interrupted in our critical section
MicroBitPeridoRadio::instance->timer.captureCounter(GO_TO_SLEEP_CHANNEL);
MicroBitPeridoRadio::instance->timer.captureCounter(CHECK_TX_CHANNEL);
return;
}
#ifdef DEBUG_MODE
log_string("rxen\r\n");
#endif
if(NRF_RADIO->EVENTS_END)
{
#ifdef DEBUG_MODE
log_string("rxend\r\n");
#endif
packet_count++;
radio_status &= ~(RADIO_STATUS_RECEIVING | RADIO_STATUS_DISCOVERING);
NRF_RADIO->EVENTS_ADDRESS = 0;
NRF_RADIO->EVENTS_END = 0;
NRF_RADIO->TASKS_START = 1;
packet_received_count++;
sleep_received_count = packet_received_count;
MicroBitPeridoRadio::instance->timer.setCompare(GO_TO_SLEEP_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(GO_TO_SLEEP_CHANNEL) + FORWARD_POLL_TIME);
if(NRF_RADIO->CRCSTATUS == 1)
{
PeridoFrameBuffer *p = MicroBitPeridoRadio::instance->rxBuf;
if (p)
{
if(p->ttl > 0)
{
p->ttl--;
// if (p->flags & MICROBIT_PERIDO_FRAME_PROPOSAL_FLAG)
// {
// // if we want to go faster
// if (p->period < network_period_idx)
// {
// if (MicroBitPeridoRadio::instance->periodIndex <= p->period || speed > 2)
// {
// network_period_idx = p->period;
// // swap to forward mode
// radio_status &= ~RADIO_STATUS_RX_RDY;
// // policy decisions could be implemented here. i.e. forward only ours, forward all, whitelist
// radio_status |= (RADIO_STATUS_FORWARD | RADIO_STATUS_DISABLE | RADIO_STATUS_TX_EN);
// }
// }
// // if we want to go slower
// else if (p->period < network_period_idx)
// {
// if (MicroBitPeridoRadio::instance->periodIndex >= p->period || speed < -2)
// {
// network_period_idx = p->period;
// // swap to forward mode
// radio_status &= ~RADIO_STATUS_RX_RDY;
// // policy decisions could be implemented here. i.e. forward only ours, forward all, whitelist
// radio_status |= (RADIO_STATUS_FORWARD | RADIO_STATUS_DISABLE | RADIO_STATUS_TX_EN);
// }
// }
// }
// else
// {
// swap to forward mode
radio_status &= ~RADIO_STATUS_RX_RDY;
// policy decisions could be implemented here. i.e. forward only ours, forward all, whitelist
radio_status |= (RADIO_STATUS_FORWARD | RADIO_STATUS_DISABLE | RADIO_STATUS_TX_EN);
// }
}
else
{
radio_status &= ~RADIO_STATUS_FORWARD;
// store this packet (should be a nop in most cases as we store after every forward), then try and transmit...
MicroBitPeridoRadio::instance->timer.setCompare(CHECK_TX_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(CHECK_TX_CHANNEL) + TX_BACKOFF_MIN + microbit_random(TX_BACKOFF_TIME));
radio_status |= RADIO_STATUS_STORE;
}
// if we sent a packet, we also flagged that we expected a response.
// If we don't see our own packet it means that there was a collision or we are out of sync.
if(radio_status & RADIO_STATUS_EXPECT_RESPONSE)
{
PeridoFrameBuffer *tx = MicroBitPeridoRadio::instance->txQueue;
// if we get our own packet back pop our tx queue and reset our no_response_count
if(tx && tx->app_id == p->app_id && p->namespace_id == tx->namespace_id && p->id == tx->id)
{
#ifdef DEBUG_MODE
log_string("POP\r\n");
#endif
process_packet(tx);
// only pop our tx buffer if something responds
MicroBitPeridoRadio::instance->popTxQueue();
last_seen[last_seen_index] = p->id;
last_seen_index = (last_seen_index + 1) % LAST_SEEN_BUFFER_SIZE;
// we received a response, reset our counter.
no_response_count = 0;
radio_status &= ~(RADIO_STATUS_STORE);
}
else
no_response_count++;
// packet_missed(MicroBitPeridoRadio::instance->txQueue);
// we could increment no_response_count here, but it is done when we go to sleep.
radio_status &= ~(RADIO_STATUS_EXPECT_RESPONSE);
}
}
}
else
{
crc_fail_count++;
}
}
}
if(radio_status & RADIO_STATUS_TRANSMIT)
{
// we get an address event for tx, clear and get out!
if(NRF_RADIO->EVENTS_ADDRESS)
{
NRF_RADIO->EVENTS_ADDRESS = 0;
return;
}
if (radio_status & RADIO_STATUS_TX_RDY)
{
NRF_RADIO->EVENTS_READY = 0;
set_gpio0(0);
#ifdef DEBUG_MODE
log_string("txst\r\n");
#endif
PeridoFrameBuffer* p = MicroBitPeridoRadio::instance->txQueue;
radio_status &= ~(RADIO_STATUS_TX_RDY | RADIO_STATUS_FIRST_PACKET);
radio_status |= RADIO_STATUS_TX_END;
if(p)
{
// if (network_period_idx != MicroBitPeridoRadio::instance->periodIndex && !(radio_status & RADIO_STATUS_DISCOVERING))
// {
// p->period = MicroBitPeridoRadio::instance->periodIndex;
// p->flags = MICROBIT_PERIDO_FRAME_PROPOSAL_FLAG;
// // p->flags = 0;
// }
// else
// {
p->period = network_period_idx;
p->flags = 0;
// }
p->ttl = p->initial_ttl;
p->time_since_wake = read_and_restart_wake() - period_start_cc;
NRF_RADIO->PACKETPTR = (uint32_t)p;
#ifdef DEBUG_MODE
packet_debug(p);
#endif
// grab next packet and set pointer
set_gpio1(1);
NRF_RADIO->TASKS_START = 1;
NRF_RADIO->EVENTS_END = 0;
MicroBitPeridoRadio::instance->timer.setCompare(STATE_MACHINE_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(STATE_MACHINE_CHANNEL) + TX_TIME);
return;
}
}
if(radio_status & RADIO_STATUS_TX_END)
{
NRF_RADIO->EVENTS_END = 0;
set_gpio1(0);
radio_status &= ~(RADIO_STATUS_TX_END | RADIO_STATUS_TRANSMIT);
#ifdef DEBUG_MODE
log_string("txend\r\n");
#endif
radio_status |= (RADIO_STATUS_DISABLE | RADIO_STATUS_RX_EN | RADIO_STATUS_EXPECT_RESPONSE);
// radio_status |= (RADIO_STATUS_DISABLE | RADIO_STATUS_RX_EN | RADIO_STATUS_EXPECT_RESPONSE | RADIO_STATUS_FORWARD);
MicroBitPeridoRadio::instance->timer.setCompare(GO_TO_SLEEP_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(GO_TO_SLEEP_CHANNEL) + FORWARD_POLL_TIME);
}
}
if (radio_status & RADIO_STATUS_FORWARD)
{
// we get an address event for tx, clear and get out!
if(NRF_RADIO->EVENTS_ADDRESS)
{
NRF_RADIO->EVENTS_ADDRESS = 0;
return;
}
if(radio_status & RADIO_STATUS_TX_END)
{
#ifdef DEBUG_MODE
log_string("ftxend\r\n");
#endif
set_gpio1(0);
radio_status &= ~(RADIO_STATUS_TX_END | RADIO_STATUS_FORWARD);
radio_status |= RADIO_STATUS_DISABLE | RADIO_STATUS_RX_EN;
MicroBitPeridoRadio::instance->timer.setCompare(GO_TO_SLEEP_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(GO_TO_SLEEP_CHANNEL) + FORWARD_POLL_TIME);
NRF_RADIO->EVENTS_END = 0;
}
if(radio_status & RADIO_STATUS_TX_RDY)
{
radio_status &= ~RADIO_STATUS_TX_RDY;
radio_status |= RADIO_STATUS_TX_END;
NRF_RADIO->PACKETPTR = (uint32_t)MicroBitPeridoRadio::instance->rxBuf;
NRF_RADIO->TASKS_START = 1;
NRF_RADIO->EVENTS_END = 0;
radio_status |= RADIO_STATUS_STORE;
}
}
if(radio_status & RADIO_STATUS_STORE)
{
radio_status &= ~RADIO_STATUS_STORE;
bool seen = false;
PeridoFrameBuffer *p = MicroBitPeridoRadio::instance->rxBuf;
// if this is the first packet we are storing, then calculate how far off the original senders period we are.
// don't sync to a proposal frame
if (radio_status & RADIO_STATUS_FIRST_PACKET && !(p->flags & MICROBIT_PERIDO_FRAME_PROPOSAL_FLAG))
{
radio_status &= ~RADIO_STATUS_FIRST_PACKET;
uint32_t t = p->time_since_wake;
uint32_t period = periods[p->period] * 1000;
uint8_t hops = (p->initial_ttl - p->ttl);
// correct and set wake up period.
correction = (t + (hops * (p->length * TIME_TO_TRANSMIT_BYTE_1MB))) + RX_TX_DISABLE_TIME + TX_ENABLE_TIME;
MicroBitPeridoRadio::instance->timer.setCompare(WAKE_UP_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(WAKE_UP_CHANNEL) + (period - correction));
}
process_packet(MicroBitPeridoRadio::instance->rxBuf);
}
if(radio_status & RADIO_STATUS_DISABLE)
{
NRF_RADIO->EVENTS_END = 0;
NRF_RADIO->EVENTS_READY = 0;
NRF_RADIO->EVENTS_ADDRESS = 0;
// Turn off the transceiver.
NRF_RADIO->EVENTS_DISABLED = 0;
NRF_RADIO->TASKS_DISABLE = 1;
radio_status = (radio_status & (HIGH_LEVEL_STATE_MASK | RADIO_STATUS_RX_EN | RADIO_STATUS_TX_EN)) | RADIO_STATUS_DISABLED;
MicroBitPeridoRadio::instance->timer.setCompare(STATE_MACHINE_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(STATE_MACHINE_CHANNEL) + RX_TX_DISABLE_TIME);
return;
}
}
int interrupt_count = 0;
extern "C" void RADIO_IRQHandler(void)
{
radio_state_machine();
}
// used to initiate transmission if the window is clear.
void tx_callback()
{
// nothing to do if sleeping
if (radio_status & (RADIO_STATUS_SLEEPING | RADIO_STATUS_FORWARD))
return;
// no one else has transmitted recently, and we are not receiving, we can transmit
if(MicroBitPeridoRadio::instance->txQueueDepth > 0 && !(radio_status & RADIO_STATUS_RECEIVING))
{
radio_status = (radio_status & (RADIO_STATUS_DISCOVERING | RADIO_STATUS_FIRST_PACKET | RADIO_STATUS_DIRECTING)) | RADIO_STATUS_TRANSMIT | RADIO_STATUS_DISABLE | RADIO_STATUS_TX_EN;
radio_state_machine();
return;
}
// MicroBitPeridoRadio::instance->timer.setCompare(CHECK_TX_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(CHECK_TX_CHANNEL) + TX_BACKOFF_MIN + microbit_random(TX_BACKOFF_TIME));
}
// used to begin a transmission window
void go_to_sleep()
{
if (radio_status & (RADIO_STATUS_RECEIVING | RADIO_STATUS_TRANSMIT | RADIO_STATUS_FORWARD))
return;
// nothing has changed, and nothing is about to change.
if (packet_received_count == sleep_received_count)
{
if (radio_status & RADIO_STATUS_EXPECT_RESPONSE)
{
no_response_count++;
radio_status &= ~RADIO_STATUS_EXPECT_RESPONSE;
}
// if we never saw a packet, slow down.
if (radio_status & RADIO_STATUS_FIRST_PACKET)
{
speed--;
radio_status &= ~RADIO_STATUS_FIRST_PACKET;
}
sleep_received_count = packet_received_count;
radio_status |= RADIO_STATUS_SLEEPING | RADIO_STATUS_DISABLE;
set_gpio2(0);
radio_state_machine();
}
}
// used to begin a transmission window
void wake_up()
{
#ifdef DEBUG_MODE
log_string("woke\r\n");
#endif
if (no_response_count > NO_RESPONSE_THRESHOLD)
{
radio_status |= RADIO_STATUS_DISCOVERING;
no_response_count = 0;
}
period_start_cc = MicroBitPeridoRadio::instance->timer.captureCounter(WAKE_UP_CHANNEL);
current_cc = period_start_cc + ((periods[network_period_idx] * 1000));
// we're still exchanging packets - come back in another period amount.
if (!(radio_status & RADIO_STATUS_SLEEPING))
{
speed++;
MicroBitPeridoRadio::instance->timer.setCompare(WAKE_UP_CHANNEL, current_cc);
return;
}
set_gpio2(1);
radio_status &= ~(RADIO_STATUS_SLEEPING | RADIO_STATUS_WAKE_CONFIGURED);
radio_status |= RADIO_STATUS_RX_EN | RADIO_STATUS_FIRST_PACKET;
if (radio_status & RADIO_STATUS_DISCOVERING)
{
MicroBitPeridoRadio::instance->timer.setCompare(CHECK_TX_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(CHECK_TX_CHANNEL) + DISCOVERY_TX_BACKOFF_TIME + microbit_random(DISCOVERY_TX_BACKOFF_TIME));
MicroBitPeridoRadio::instance->timer.setCompare(WAKE_UP_CHANNEL, current_cc);
}
else
{
// we have a backlog of packets, we should try and speed up.
// if (MicroBitPeridoRadio::instance->txQueueDepth > 5)
// speed++;
// // we want to go faster or slower, but we haven't committed this to the network yet, remain neutral.
// if (network_period_idx != MicroBitPeridoRadio::instance->periodIndex )
// speed = 0;
// // we've hit the max threshold -- speed up
// if (speed == SPEED_THRESHOLD_MAX)
// {
// // will take effect next wake
// speed = 0;
// MicroBitPeridoRadio::instance->periodIndex = ( MicroBitPeridoRadio::instance->periodIndex > 0) ? MicroBitPeridoRadio::instance->periodIndex - 1 : 0;
// }
// // we've hit the min threshold -- slow down
// if (speed == SPEED_THRESHOLD_MIN)
// {
// // will take effect next wake
// speed = 0;
// MicroBitPeridoRadio::instance->periodIndex = ( MicroBitPeridoRadio::instance->periodIndex < PERIOD_COUNT - 1) ? MicroBitPeridoRadio::instance->periodIndex + 1 : PERIOD_COUNT - 1;
// }
uint32_t tx_backoff = PERIDO_WAKE_THRESHOLD_MID;
tx_backoff += microbit_random(2500);
MicroBitPeridoRadio::instance->timer.setCompare(CHECK_TX_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(CHECK_TX_CHANNEL) + tx_backoff);
MicroBitPeridoRadio::instance->timer.setCompare(GO_TO_SLEEP_CHANNEL, MicroBitPeridoRadio::instance->timer.captureCounter(GO_TO_SLEEP_CHANNEL) + 3500);
MicroBitPeridoRadio::instance->timer.setCompare(WAKE_UP_CHANNEL, current_cc);
}
radio_state_machine();
}
/**
* automatic transposition of textual name to app id and namespace...
* should there be a default app_id and namespace?
* The ability to create a "private" group where there aren't other devices is desired
* could probably use the app_id to select a band...
* it's on the user to create reliability.
* Probably want some group collision detection and the selection of another group...
* there are only 100 bands...
* increasing and decreasing data rates...
* how do we reach concensus?
* do we need a broadcast frame?
* i'd rather not...
* expresses of intent in a frame
* only works if others have data to transmit.
* First to broadcast, if others are ok with that then then they move, otherwise they stay where they are.
* automatic slowdown on no transmission in wake period... inverse as well if we're not sleeping as often as we should, speed up.
**/
void timer_callback(uint8_t state)
{
#ifdef DEBUG_MODE
log_string("tc\r\n");
#endif
if(state & (1 << STATE_MACHINE_CHANNEL))
radio_state_machine();
if(state & (1 << WAKE_UP_CHANNEL))
wake_up();
if(state & (1 << CHECK_TX_CHANNEL))
tx_callback();
if(state & (1 << GO_TO_SLEEP_CHANNEL))
go_to_sleep();
}
/**
* Constructor.
*
* Initialise the MicroBitPeridoRadio.
*
* @note This class is demand activated, as a result most resources are only
* committed if send/recv or event registrations calls are made.
*/
MicroBitPeridoRadio::MicroBitPeridoRadio(LowLevelTimer& timer, uint8_t appId, uint8_t namespaceId, uint16_t id) : timer(timer)
{
this->id = id;
this->appId = appId;
this->namespaceId = namespaceId;
this->status = 0;
this->rxQueueDepth = 0;
this->txQueueDepth = 0;
this->rxQueue = NULL;
this->rxBuf = NULL;
this->txQueue = NULL;
timer.disable();
timer.setIRQ(timer_callback);
// timer mode
timer.setMode(TimerModeTimer);
// 32-bit
timer.setBitMode(BitMode32);
// 16 Mhz / 2^4 = 1 Mhz
timer.setPrescaler(4);
timer.enable();
microbit_seed_random();
this->periodIndex = PERIDO_DEFAULT_PERIOD_IDX;
instance = this;
}
/**
* Change the output power level of the transmitter to the given value.
*
* @param power a value in the range 0..7, where 0 is the lowest power and 7 is the highest.
*
* @return MICROBIT_OK on success, or MICROBIT_INVALID_PARAMETER if the value is out of range.
*/
int MicroBitPeridoRadio::setTransmitPower(int power)
{
if (power < 0 || power >= MICROBIT_BLE_POWER_LEVELS)
return MICROBIT_INVALID_PARAMETER;
NRF_RADIO->TXPOWER = (uint32_t)MICROBIT_BLE_POWER_LEVEL[power];
return MICROBIT_OK;
}
/**
* Change the transmission and reception band of the radio to the given channel
*
* @param band a frequency band in the range 0 - 100. Each step is 1MHz wide, based at 2400MHz.
*
* @return MICROBIT_OK on success, or MICROBIT_INVALID_PARAMETER if the value is out of range,
* or MICROBIT_NOT_SUPPORTED if the BLE stack is running.
*/
int MicroBitPeridoRadio::setFrequencyBand(int band)
{
if (ble_running())
return MICROBIT_NOT_SUPPORTED;
if (band < 0 || band > 100)
return MICROBIT_INVALID_PARAMETER;
NRF_RADIO->FREQUENCY = (uint32_t)band;
return MICROBIT_OK;
}
/**
* Retrieve a pointer to the currently allocated receive buffer. This is the area of memory
* actively being used by the radio hardware to store incoming data.
*
* @return a pointer to the current receive buffer.
*/
PeridoFrameBuffer* MicroBitPeridoRadio::getRxBuf()
{
return rxBuf;
}
/**
* Retrieve a pointer to the currently allocated receive buffer. This is the area of memory
* actively being used by the radio hardware to store incoming data.
*
* @return a pointer to the current receive buffer.
*/
int MicroBitPeridoRadio::popTxQueue()
{
PeridoFrameBuffer* p = txQueue;
if (p)
{
// Protect shared resource from ISR activity
NVIC_DisableIRQ(RADIO_IRQn);
txQueue = txQueue->next;
txQueueDepth--;
delete p;
// Allow ISR access to shared resource
NVIC_EnableIRQ(RADIO_IRQn);
}
return MICROBIT_OK;
}
/**
* Attempt to queue a buffer received by the radio hardware, if sufficient space is available.
*
* @return MICROBIT_OK on success, or MICROBIT_NO_RESOURCES if a replacement receiver buffer
* could not be allocated (either by policy or memory exhaustion).
*/
int MicroBitPeridoRadio::copyRxBuf()
{
if (rxBuf == NULL)
return MICROBIT_INVALID_PARAMETER;
if (rxQueueDepth >= MICROBIT_RADIO_MAXIMUM_RX_BUFFERS)
return MICROBIT_NO_RESOURCES;
// Ensure that a replacement buffer is available before queuing.
PeridoFrameBuffer *newRxBuf = new PeridoFrameBuffer();
if (newRxBuf == NULL)
return MICROBIT_NO_RESOURCES;
memcpy(newRxBuf, rxBuf, sizeof(PeridoFrameBuffer));
newRxBuf->next = NULL;
if (rxQueue == NULL)
{
rxQueue = newRxBuf;
}
else
{
PeridoFrameBuffer *p = rxQueue;
while (p->next != NULL)
p = p->next;
p->next = newRxBuf;
}
// Increase our received packet count
rxQueueDepth++;
return MICROBIT_OK;
}
int MicroBitPeridoRadio::queueTxBuf(PeridoFrameBuffer* tx)
{
if (txQueueDepth >= MICROBIT_PERIDO_MAXIMUM_TX_BUFFERS)
return MICROBIT_NO_RESOURCES;
// Ensure that a replacement buffer is available before queuing.
PeridoFrameBuffer *newTx = new PeridoFrameBuffer();
if (newTx == NULL)
return MICROBIT_NO_RESOURCES;
memcpy(newTx, tx, sizeof(PeridoFrameBuffer));
__disable_irq();
// We add to the tail of the queue to preserve causal ordering.
newTx->next = NULL;
if (txQueue == NULL)
{
txQueue = newTx;
}
else
{
PeridoFrameBuffer *p = txQueue;
while (p->next != NULL)
p = p->next;
p->next = newTx;
}
txQueueDepth++;
__enable_irq();
return MICROBIT_OK;
}
/**
* Initialises the radio for use as a multipoint sender/receiver
*
* @return MICROBIT_OK on success, MICROBIT_NOT_SUPPORTED if the BLE stack is running.
*/
int MicroBitPeridoRadio::enable()
{
// If the device is already initialised, then there's nothing to do.
if (status & MICROBIT_RADIO_STATUS_INITIALISED)
return MICROBIT_OK;
// Only attempt to enable this radio mode if BLE is disabled.
if (ble_running())
return MICROBIT_NOT_SUPPORTED;
// If this is the first time we've been enable, allocate out receive buffers.
if (rxBuf == NULL)
rxBuf = new PeridoFrameBuffer();
if (rxBuf == NULL)
return MICROBIT_NO_RESOURCES;
// Enable the High Frequency clock on the processor. This is a pre-requisite for
// the RADIO module. Without this clock, no communication is possible.
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
NRF_CLOCK->TASKS_HFCLKSTART = 1;
while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0);
// Bring up the nrf51822 RADIO module in Nordic's proprietary 1MBps packet radio mode.
setTransmitPower(MICROBIT_RADIO_DEFAULT_TX_POWER);
setFrequencyBand(MICROBIT_RADIO_DEFAULT_FREQUENCY);
// Configure for 1Mbps throughput.
// This may sound excessive, but running a high data rates reduces the chances of collisions...
NRF_RADIO->MODE = RADIO_MODE_MODE_Nrf_1Mbit;
// Configure the addresses we use for this protocol. We run ANONYMOUSLY at the core.
// A 40 bit addresses is used. The first 32 bits match the ASCII character code for "uBit".
// Statistically, this provides assurance to avoid other similar 2.4GHz protocols that may be in the vicinity.
// We also map the assigned 8-bit GROUP id into the PREFIX field. This allows the RADIO hardware to perform
// address matching for us, and only generate an interrupt when a packet matching our group is received.
NRF_RADIO->BASE0 = MICROBIT_RADIO_BASE_ADDRESS;
NRF_RADIO->PREFIX0 = 0;
// The RADIO hardware module supports the use of multiple addresses, but as we're running anonymously, we only need one.
// Configure the RADIO module to use the default address (address 0) for both send and receive operations.
NRF_RADIO->TXADDRESS = 0;
NRF_RADIO->RXADDRESSES = 1;
// Packet layout configuration. The nrf51822 has a highly capable and flexible RADIO module that, in addition to transmission
// and reception of data, also contains a LENGTH field, two optional additional 1 byte fields (S0 and S1) and a CRC calculation.
// Configure the packet format for a simple 8 bit length field and no additional fields.
NRF_RADIO->PCNF0 = 0x00000008;
// NRF_RADIO->PCNF1 = 0x02040000 | MICROBIT_RADIO_MAX_PACKET_SIZE;
// NRF_RADIO->PCNF1 = 0x00040000 | MICROBIT_RADIO_MAX_PACKET_SIZE;
NRF_RADIO->PCNF1 = 0x00040000 | MICROBIT_PERIDO_MAX_PACKET_SIZE;
// Most communication channels contain some form of checksum - a mathematical calculation taken based on all the data
// in a packet, that is also sent as part of the packet. When received, this calculation can be repeated, and the results
// from the sender and receiver compared. If they are different, then some corruption of the data ahas happened in transit,
// and we know we can't trust it. The nrf51822 RADIO uses a CRC for this - a very effective checksum calculation.
//
// Enable automatic 16bit CRC generation and checking, and configure how the CRC is calculated.
NRF_RADIO->CRCCNF = RADIO_CRCCNF_LEN_Two;
NRF_RADIO->CRCINIT = 0xFFFF;
NRF_RADIO->CRCPOLY = 0x11021;
// Set the start random value of the data whitening algorithm. This can be any non zero number.
NRF_RADIO->DATAWHITEIV = 0x18;
// Set up the RADIO module to read and write from our internal buffer.
NRF_RADIO->PACKETPTR = (uint32_t)rxBuf;
// Configure the hardware to issue an interrupt whenever a task is complete (e.g. send/receive)
NRF_RADIO->INTENSET = 0x0000000A;
NVIC_ClearPendingIRQ(RADIO_IRQn);
NVIC_SetPriority(RADIO_IRQn, 0);
NVIC_EnableIRQ(RADIO_IRQn);
NRF_RADIO->EVENTS_READY = 0;
NRF_RADIO->EVENTS_END = 0;
log_num(NRF_RADIO->STATE);
log_string(" ");
log_num(periods[periodIndex] * 1000);
radio_status = RADIO_STATUS_DISABLED | RADIO_STATUS_DISCOVERING | RADIO_STATUS_SLEEPING;
timer.setCompare(WAKE_UP_CHANNEL, periods[periodIndex] * 1000);
// Done. Record that our RADIO is configured.
status |= MICROBIT_RADIO_STATUS_INITIALISED;
return MICROBIT_OK;
}
/**
* Disables the radio for use as a multipoint sender/receiver.
*
* @return MICROBIT_OK on success, MICROBIT_NOT_SUPPORTED if the BLE stack is running.
*/
int MicroBitPeridoRadio::disable()
{
// Only attempt to enable.disable the radio if the protocol is alreayd running.
if (ble_running())
return MICROBIT_NOT_SUPPORTED;
if (!(status & MICROBIT_RADIO_STATUS_INITIALISED))
return MICROBIT_OK;
// Disable interrupts and STOP any ongoing packet reception.
NVIC_DisableIRQ(RADIO_IRQn);
NRF_RADIO->EVENTS_DISABLED = 0;
NRF_RADIO->TASKS_DISABLE = 1;
while(NRF_RADIO->EVENTS_DISABLED == 0);
// record that the radio is now disabled
status &= ~MICROBIT_RADIO_STATUS_INITIALISED;
return MICROBIT_OK;
}
/**
* Set the current period in milliseconds broadcasted in the perido frame
*
* @param period_ms the new period, in milliseconds.
*
* @return MICROBIT_OK on success, or MICROBIT_INVALID_PARAMETER if the period is too short.
*/
int MicroBitPeridoRadio::setPeriod(uint32_t period_ms)
{
int index = -1;
for (int i = 0 ; i < PERIOD_COUNT; i++)
{
if (periods[i] < period_ms)
continue;
index = i;
break;
}
if (index == -1)
index = PERIOD_COUNT - 1;
periodIndex = index;
return MICROBIT_OK;
}
/**
* Retrieve the current period in milliseconds broadcasted in the perido frame
*
* @return the current period in milliseconds
*/
uint32_t MicroBitPeridoRadio::getPeriod()
{
return periods[periodIndex];
}
/**
* Determines the number of packets ready to be processed.
*
* @return The number of packets in the receive buffer.
*/
int MicroBitPeridoRadio::dataReady()
{
return rxQueueDepth;
}
/**
* Retrieves the next packet from the receive buffer.
* If a data packet is available, then it will be returned immediately to
* the caller. This call will also dequeue the buffer.
*
* @return The buffer containing the the packet. If no data is available, NULL is returned.
*
* @note Once recv() has been called, it is the callers responsibility to
* delete the buffer when appropriate.
*/
PeridoFrameBuffer* MicroBitPeridoRadio::recv()
{
PeridoFrameBuffer *p = rxQueue;
if (p)
{
// Protect shared resource from ISR activity
NVIC_DisableIRQ(RADIO_IRQn);
rxQueue = rxQueue->next;
rxQueueDepth--;
// Allow ISR access to shared resource
NVIC_EnableIRQ(RADIO_IRQn);
}
return p;
}
/**
* Transmits the given buffer onto the broadcast radio.
* The call will wait until the transmission of the packet has completed before returning.
*
* @param data The packet contents to transmit.
*
* @return MICROBIT_OK on success, or MICROBIT_NOT_SUPPORTED if the BLE stack is running.
*/
int MicroBitPeridoRadio::send(PeridoFrameBuffer* buffer)
{
return queueTxBuf(buffer);
}
/**
* Transmits the given buffer onto the broadcast radio.
*
* This is a synchronous call that will wait until the transmission of the packet
* has completed before returning.
*
* @param buffer The packet contents to transmit.
*
* @param len The number of bytes to transmit.
*
* @return MICROBIT_OK on success, or MICROBIT_INVALID_PARAMETER if the buffer is invalid,
* or the number of bytes to transmit is greater than `MICROBIT_RADIO_MAX_PACKET_SIZE + MICROBIT_RADIO_HEADER_SIZE`.
*/
int MicroBitPeridoRadio::send(uint8_t *buffer, int len)
{
if (buffer == NULL || len < 0 || len > MICROBIT_PERIDO_MAX_PACKET_SIZE + MICROBIT_PERIDO_HEADER_SIZE - 1)
return MICROBIT_INVALID_PARAMETER;
PeridoFrameBuffer buf;
buf.id = microbit_random(65535);
buf.length = len + MICROBIT_PERIDO_HEADER_SIZE - 1;
buf.app_id = appId;
buf.namespace_id = namespaceId;
buf.ttl = 4;
buf.initial_ttl = 4;
buf.time_since_wake = 0;
buf.period = 0;
memcpy(buf.payload, buffer, len);
return send(&buf);
}
/**
* Transmits the given string onto the broadcast radio.
*
* This is a synchronous call that will wait until the transmission of the packet
* has completed before returning.
*
* @param data The packet contents to transmit.
*
* @return MICROBIT_OK on success, or MICROBIT_INVALID_PARAMETER if the buffer is invalid,
* or the number of bytes to transmit is greater than `MICROBIT_RADIO_MAX_PACKET_SIZE + MICROBIT_RADIO_HEADER_SIZE`.
*/
int MicroBitPeridoRadio::send(PacketBuffer data)
{
return send((uint8_t *)data.getBytes(), data.length());
}
/**
* Transmits the given string onto the broadcast radio.
*
* This is a synchronous call that will wait until the transmission of the packet
* has completed before returning.
*
* @param data The packet contents to transmit.
*
* @return MICROBIT_OK on success, or MICROBIT_INVALID_PARAMETER if the buffer is invalid,
* or the number of bytes to transmit is greater than `MICROBIT_RADIO_MAX_PACKET_SIZE + MICROBIT_RADIO_HEADER_SIZE`.
*/
int MicroBitPeridoRadio::send(ManagedString data)
{
return send((uint8_t *)data.toCharArray(), data.length());
}
#endif | [
"j.devine@lancaster.ac.uk"
] | j.devine@lancaster.ac.uk |
17d39b88d8514620d44117ac665655256a38d33e | d2a98c47563c51c57d5f838132b065e90980541c | /src/rpcmining.cpp | 9a9efaeac3e79753e5d6078361d6a3b689171e25 | [
"MIT"
] | permissive | crykiller/EXEcoin | dc76eada589c7dfc1972169e69e9176903a15700 | 563bde9edc60fb0fc25e505b76d74b448e7f5e9a | refs/heads/master | 2020-03-29T16:13:04.451775 | 2018-09-24T13:04:46 | 2018-09-24T13:04:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,494 | cpp | // Copyright (c) 2010-2015 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin developers
// Copyright (c) 2015 The EXEcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
extern unsigned int nTargetSpacing;
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getsubsidy [nTarget]\n"
"Returns proof-of-work subsidy value for the specified value of target.");
return (uint64_t)GetProofOfWorkReward(0);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
Object obj, diff, weight;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(0)));
obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
weight.push_back(Pair("minimum", (uint64_t)nMinWeight));
weight.push_back(Pair("maximum", (uint64_t)nMaxWeight));
weight.push_back(Pair("combined", (uint64_t)nWeight));
obj.push_back(Pair("stakeweight", weight));
//obj.push_back(Pair("stakeinterest", (uint64_t)GetProofOfStakeReward(0, GetLastBlockIndex(pindexBest, true)->nBits, GetLastBlockIndex(pindexBest, true)->nTime, true)));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakinginfo\n"
"Returns an object containing staking-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
uint64_t nNetworkWeight = GetPoSKernelPS();
bool staking = nLastCoinStakeSearchInterval && nWeight;
int nExpectedTime = staking ? (nTargetSpacing * nNetworkWeight / nWeight) : -1;
Object obj;
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("staking", staking));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("weight", (uint64_t)nWeight));
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("expectedtime", nExpectedTime));
return obj;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "EXEcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "EXEcoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "EXEcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "EXEcoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlock.push_back(pblock);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "EXEcoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "EXEcoin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue + (int64_t)pblock->vtx[0].vout[1].nValue));
result.push_back(Pair("charityvalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
| [
"zxcvbnm_3456@hotmail.com"
] | zxcvbnm_3456@hotmail.com |
a99ebeed99d00c527320c2ff7a8aa23193bd8a7f | 51c1c5e9b8489ef8afa029b162aaf4c8f8bda7fc | /easyparticle2d/src/libparticle2d/LibraryPage.h | 14ff678192f4041667316c2c93b7cbbc41214a5c | [
"MIT"
] | permissive | aimoonchen/easyeditor | 3e5c77f0173a40a802fd73d7b741c064095d83e6 | 9dabdbfb8ad7b00c992d997d6662752130d5a02d | refs/heads/master | 2021-04-26T23:06:27.016240 | 2018-02-12T02:28:50 | 2018-02-12T02:28:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 423 | h | #ifndef _EASYPARTICLE2D_LIBRARY_PAGE_H_
#define _EASYPARTICLE2D_LIBRARY_PAGE_H_
#include <ee/LibraryPage.h>
namespace eparticle2d
{
class LibraryPage : public ee::LibraryPage
{
public:
LibraryPage(wxWindow* parent);
virtual bool IsHandleSymbol(const ee::SymPtr& sym) const override;
protected:
virtual void OnAddPress(wxCommandEvent& event) override;
}; // LibraryPage
}
#endif // _EASYPARTICLE2D_LIBRARY_PAGE_H_ | [
"zhuguang@ejoy.com"
] | zhuguang@ejoy.com |
9d73dfbc100871d42519f99e7e1840a72318858f | 6a07acb66e5471519110eb1136474fe3006c94d8 | /src/rendering/Shader.cpp | ea04a7ccc084c0409f1ad8e22e23fabc87beece0 | [
"MIT"
] | permissive | liuyangvspu/ArkoseRenderer | df49bcbbcfcacf358b8ab6ac0dcdfaf2ab9880cb | 609c99aa899e5f5b10f21f0d9aba54599128fff2 | refs/heads/master | 2023-07-17T14:22:15.156644 | 2021-08-31T22:43:30 | 2021-08-31T22:43:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,101 | cpp | #include "Shader.h"
#include "rendering/ShaderManager.h"
#include <utility/Logging.h>
ShaderFile::ShaderFile(const std::string& path)
: ShaderFile(path, typeFromPath(path))
{
}
ShaderFile::ShaderFile(std::string path, ShaderFileType type)
: m_path(std::move(path))
, m_type(type)
{
auto maybeError = ShaderManager::instance().loadAndCompileImmediately(m_path);
if (maybeError.has_value()) {
LogError("Shader file error: %s\n", maybeError.value().c_str());
LogErrorAndExit("Exiting due to bad shader at startup.\n");
}
}
const std::string& ShaderFile::path() const
{
return m_path;
}
ShaderFileType ShaderFile::type() const
{
return m_type;
}
ShaderFileType ShaderFile::typeFromPath(const std::string& path)
{
if (path.length() < 5)
return ShaderFileType::Unknown;
std::string ext5 = path.substr(path.length() - 5);
if (ext5 == ".vert")
return ShaderFileType::Vertex;
else if (ext5 == ".frag")
return ShaderFileType::Fragment;
else if (ext5 == ".rgen")
return ShaderFileType::RTRaygen;
else if (ext5 == ".comp")
return ShaderFileType::Compute;
else if (ext5 == ".rint")
return ShaderFileType::RTIntersection;
if (path.length() < 6)
return ShaderFileType::Unknown;
std::string ext6 = path.substr(path.length() - 6);
if (ext6 == ".rmiss")
return ShaderFileType::RTMiss;
else if (ext6 == ".rchit")
return ShaderFileType::RTClosestHit;
else if (ext6 == ".rahit")
return ShaderFileType::RTAnyHit;
return ShaderFileType::Unknown;
}
Shader Shader::createVertexOnly(std::string vertexName)
{
ShaderFile vertexFile { std::move(vertexName), ShaderFileType::Vertex };
return Shader({ vertexFile }, ShaderType::Raster);
}
Shader Shader::createBasicRasterize(std::string vertexName, std::string fragmentName)
{
ShaderFile vertexFile { std::move(vertexName), ShaderFileType::Vertex };
ShaderFile fragmentFile { std::move(fragmentName), ShaderFileType::Fragment };
return Shader({ vertexFile, fragmentFile }, ShaderType::Raster);
}
Shader Shader::createCompute(std::string computeName)
{
ShaderFile computeFile { std::move(computeName), ShaderFileType::Compute };
return Shader({ computeFile }, ShaderType::Compute);
}
Shader::Shader(std::vector<ShaderFile> files, ShaderType type)
: m_files(std::move(files))
, m_type(type)
{
}
ShaderType Shader::type() const
{
return m_type;
}
const std::vector<ShaderFile>& Shader::files() const
{
return m_files;
}
std::optional<Shader::UniformBinding> Shader::uniformBindingForName(const std::string& name) const
{
auto entry = m_uniformBindings.find(name);
if (entry == m_uniformBindings.end()) {
return {};
}
const Shader::UniformBinding& binding = entry->second;
return binding;
}
void Shader::setUniformBindings(std::unordered_map<std::string, Shader::UniformBinding> bindings)
{
ASSERT(m_uniformBindingsSet == false);
m_uniformBindings = std::move(bindings);
m_uniformBindingsSet = true;
}
| [
"simon.moos95@gmail.com"
] | simon.moos95@gmail.com |
793f8cbb29c4d7abf369130fd07606f2440867c0 | 30fbad242aa959ee0d8749b6c93862ed8a2b48e7 | /Motors-and-Lights/Flashlights.ino | 9a9d0cc8eedbda46cc461bf2ff4ba6336d7d8f8e | [
"MIT"
] | permissive | Rohit99/DigitalCircuits-Afternoon | a30aaee6930c0c4f347cbe9ccdbea5e2a7b524d0 | be37b8909974b759b2d8402709b31b99d913f3b4 | refs/heads/master | 2020-04-04T17:47:07.322191 | 2013-08-08T22:37:46 | 2013-08-08T22:37:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | ino | void setup()
{
pinMode(13,OUTPUT);//This allows 13 to source (a lot of amps)
}
void loop()
{
digitalWrite(13,HIGH);//This raises pin 13 to (5 volts)
delay(10); //This keeps your arduino from bricking
} ;
| [
"rohit.d.shah@gmail.com"
] | rohit.d.shah@gmail.com |
5e21cc2efc16d5ccf9e214c5c401539dbd2d5ccd | 8e6eded4fddc813fde44ee6cf231c49524680466 | /_src/CGameobjectList.h | fc83cc8bd77ea8cbcb1eb6d185eaa9eb4889f8ea | [] | no_license | mbatc/Animator | 811187bb2d9819465cfa4b363fd165f873097f1e | a23732042461c99364d322e382e6bd612311d615 | refs/heads/master | 2021-06-20T00:17:00.831702 | 2021-03-04T08:59:53 | 2021-03-04T08:59:53 | 82,560,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,299 | h | #ifdef _WIN32 || _WIN64
#pragma once
#include "CGameobject.h"
#include "Helper.h"
enum OBJECT_TYPE
{
OBJ,
LGT,
CMR
};
struct ObjectList
{
ObjectList()
:
obj(NULL),
ID(0),
name(NULL)
{}
void Cleanup()
{
MEMORY::SafeDelete(obj);
MEMORY::SafeDeleteArr(name);
}
CGameobject* obj;
int ID;
char* name;
};
class CGameobjectList
{
public:
CGameobjectList(OBJECT_TYPE type);
~CGameobjectList();
//Add a gameobject to the list
int AddObject(char* name);
//Add a gameobject loaded from a file
int AddObjectFromFile(char* filename);
//Delete A gameobject by Index in list
void DeleteObject(int index);
//Delete A gameobject by Name. Will remove the first object with that name
void DeleteObject(char* name);
//Delete A gameobject by Name and Index. Will remove and object with that name
void DeleteObject(char* name, int ID);
//Returns the number of objects in the list
int GetNumObjects();
//Returns the object at index
CGameobject* GetGameObject(int index);
//Returns the object with that name
CGameobject* GetGameObject(char* uniqueName);
//returns the object with that name after finding it ID times
CGameobject* GetGameObject(char* name, int ID);
void ClearList();
private:
ObjectList* m_pObjList;
int m_nObjects;
OBJECT_TYPE m_objType;
};
#endif
| [
"mickbatch98@gmail.com"
] | mickbatch98@gmail.com |
fa93a4bd0ef4ffa49074b74f3e758ac8a8e9042f | 0f1e7229b9465f0774c7510aad2910cb9fd609d9 | /src/reir/exec/ast_expression.hpp | a2ba2b5c4b32e79777af6442abcdc54c92e1b2be | [
"Apache-2.0"
] | permissive | large-scale-oltp-team/reir | e5430bebe68dadc925549cd016a6fe1b16c18d72 | 427db5f24e15f22cd2a4f4a716caf9392dae1d9b | refs/heads/master | 2020-04-04T09:26:05.174899 | 2018-11-06T09:16:32 | 2018-11-06T09:16:32 | 155,817,817 | 1 | 0 | Apache-2.0 | 2018-11-06T09:16:33 | 2018-11-02T05:24:07 | C++ | UTF-8 | C++ | false | false | 14,932 | hpp | //
// Created by kumagi on 18/07/03.
//
#ifndef PROJECT_AST_EXPRESSION_HPP
#define PROJECT_AST_EXPRESSION_HPP
#include <utility>
#include "ast_node.hpp"
#include "boost/variant.hpp"
#include "reir/db/maybe_value.hpp"
#include "token.hpp"
#include "compiler_context.hpp"
namespace reir {
struct Token;
class TokenStream;
namespace node {
llvm::Type* convert_type(node::Type* type, CompilerContext& c);
struct Expression : public Node {
Expression(NodeKind k) : Node(k), type_(nullptr) {}
Expression(const Expression&) = delete;
void dump(std::ostream& o, size_t indent) const override = 0;
virtual llvm::Type* get_type(CompilerContext& c) const = 0;
virtual llvm::Value* get_value(CompilerContext& c) const = 0;
void each_value(const std::function<void(const Expression * )>& func) const override {}
~Expression() override = default;
friend std::ostream& operator<<(std::ostream& o, const Expression& e) {
e.dump(o, 0);
return o;
}
virtual void analyze(CompilerContext& ctx) override {}
virtual llvm::Value* get_ref(CompilerContext& ctx) const {
return nullptr;
};
static bool classof(const Node *n) {
return ND_EXPRESSION_FIRST < n->getKind() && n->getKind() < ND_EXPRESSION_LAST;
}
Type* type_;
};
struct PrimaryExpression : public Expression {
boost::variant<MaybeValue, Expression*> value_;
explicit PrimaryExpression(TokenStream& tokens);
explicit PrimaryExpression(MaybeValue&& value)
: Expression(ND_Primary),
value_(std::move(value)) {}
~PrimaryExpression() override {
if (value_.which() == 1) {
delete boost::get<Expression*>(value_);
}
}
void analyze(CompilerContext& ctx) override {
switch (value_.which()) {
case 0: {
auto& v = boost::get<MaybeValue>(value_);
if (v.exists()) {
const Value& val(v.value());
if (val.is_int()) {
type_ = ctx.analyze_type_table_["integer"];
} else if (val.is_varchar()) {
type_ = ctx.analyze_type_table_["string"];
} else if (val.is_float()) {
type_ = ctx.analyze_type_table_["double"];
} else {
throw std::runtime_error("unknown primary type");
}
}
break;
}
case 1: {
auto* e = boost::get<Expression*>(value_);
e->analyze(ctx);
type_ = e->type_;
}
default:
throw std::runtime_error("cannot analyze primary expression type");
}
}
void each_value(const std::function<void(const Expression*)>& func) const override {
if (value_.which() == 1) {
boost::get<Expression*>(value_)->each_value(func);
}
}
llvm::Value* get_value(CompilerContext& ctx) const override;
void dump(std::ostream& o, size_t indent) const override {
switch (value_.which()) { // MaybeValue
case 0: {
o << boost::get<MaybeValue>(value_);
break;
}
case 1: {
auto* e = boost::get<Expression*>(value_);
o << "Expression(";
e->dump(o, indent);
o << ")";
break;
}
default:
throw std::runtime_error("unknown type");
}
}
llvm::Type* get_type(CompilerContext& c) const override;
static bool classof(const Node *n) {
return n->getKind() == ND_Primary;
}
};
struct BinaryExpression : public Expression {
operators op_;
Expression* lhs_;
Expression* rhs_;
BinaryExpression(Expression* lhs, operators op, Expression* rhs)
: Expression(ND_Binary), lhs_(lhs), op_(op), rhs_(rhs) {
}
void analyze(CompilerContext& ctx) override {
lhs_->analyze(ctx), rhs_->analyze(ctx);
auto* left_type = lhs_->type_, *right_type = rhs_->type_;
type_ = operate(ctx, *left_type, *right_type, op_);
};
static bool is_operator(Token& t) {
switch (t.type) {
case token_type::PLUS:
case token_type::MINUS:
case token_type::ASTERISK:
case token_type::SLASH:
case token_type::EQUAL:
case token_type::PERCENT:
case token_type::OPEN_ANGLE:
case token_type::CLOSE_ANGLE:
return true;
default:
return false;
}
}
~BinaryExpression() override {
delete lhs_;
delete rhs_;
}
void dump(std::ostream& o, size_t indent) const override {
o << "(";
lhs_->dump(o, indent);
switch (op_) {
case PLUS: o << " + "; break;
case MINUS: o << " - "; break;
case MULTIPLE: o << " * "; break;
case DIVISION: o << " / "; break;
case EQUAL: o << " == "; break;
case MODULO: o << " % "; break;
case LESSTHAN: o << " < "; break;
case LESSEQUAL: o << " <= "; break;
case MORETHAN: o << " > "; break;
case MOREEQUAL: o << " >= "; break;
case NOTEQUAL: o << " != "; break;
case CONDITIONAL_AND: o << " && "; break;
case CONDITIONAL_OR: o << " || "; break;
case NONE: o << " ???? "; break;
}
rhs_->dump(o, indent);
o << ")";
}
llvm::Type* get_type(CompilerContext& c) const override;
llvm::Value* get_value(CompilerContext& c) const override;
llvm::Value* get_conditional_value(CompilerContext& c, bool forAND) const;
llvm::Value* to_i1(CompilerContext& c, llvm::Value* lh) const;
static bool classof(const Node *n) {
return n->getKind() == ND_Binary;
}
};
struct PointerOf : public Expression {
Expression* target_;
explicit PointerOf(Expression* t) : Expression(ND_Pointer), target_(t) {}
PointerOf()
: Expression(ND_Pointer), target_(nullptr) {}
~PointerOf() override { delete target_; }
void analyze(CompilerContext& ctx) override {};
void dump(std::ostream& o, size_t indent) const override {
o << "&";
target_->dump(o, indent);
}
void each_value(const std::function<void(const Expression*)>& func) const override {
func(target_);
}
llvm::Type* get_type(CompilerContext& c) const override;
llvm::Value* get_value(CompilerContext& c) const override;
static bool classof(const Node *n) {
return n->getKind() == ND_Pointer;
}
};
struct RowLiteral : public Expression {
std::vector<Expression*> elements_;
explicit RowLiteral(TokenStream& s);
~RowLiteral() override {
for (auto& e : elements_) {
delete e;
}
}
void analyze(CompilerContext& ctx) override {
std::vector<Type*> t;
for (auto& element : elements_) {
element->analyze(ctx);
assert(element->type_);
t.emplace_back(element->type_);
}
type_ = new TupleType(std::move(t));
std::stringstream ss;
ss << this;
ctx.analyze_type_table_["__TupleLiteral:" + ss.str()] = type_;
}
explicit RowLiteral(std::vector<Expression*>&& v) : Expression(ND_Row), elements_(std::move(v)) {}
explicit RowLiteral(std::initializer_list<Expression*>&& v) : RowLiteral(std::vector<Expression*>(v)) {}
void dump(std::ostream& o, size_t indent ) const override {
o << "RowLiteral{";
for (size_t i = 0; i < elements_.size(); ++i) {
if (0 < i) { o << ", "; }
elements_[i]->dump(o, indent);
}
o << "}";
}
llvm::Type* get_type(CompilerContext& c) const override;
llvm::Value* get_value(CompilerContext& c) const override;
size_t elements() const {
return elements_.size();
}
static bool classof(const Node *n) {
return n->getKind() == ND_Row;
}
};
struct ArrayLiteral : public Expression {
std::vector<Expression*> elements_;
explicit ArrayLiteral(TokenStream& tokens);
explicit ArrayLiteral(std::vector<Expression*>&& v) : Expression(ND_Array), elements_(std::move(v)) {}
explicit ArrayLiteral(std::initializer_list<Expression*>&& v) : ArrayLiteral(std::vector<Expression*>(v)) {}
~ArrayLiteral() override {
for (auto& e : elements_) {
delete e;
}
}
void dump(std::ostream& o, size_t indent) const override {
o << "ArrayLiteral(" << elements_.size() << ")[";
for (size_t i = 0; i < elements_.size(); ++i) {
if (0 < i) { o << ", "; }
elements_[i]->dump(o, indent);
}
o << "]";
}
void each_value(const std::function<void(const Expression*)>& func) const override {
for (const auto& e : elements_) {
e->each_value(func);
}
func(this);
}
llvm::Type* get_type(CompilerContext& c) const override;
llvm::Value* get_value(CompilerContext& c) const override;
void analyze(CompilerContext& ctx) override {
if (elements_.empty()) {
throw std::runtime_error("empty array literal's type cant be resolved\n");
}
elements_[0]->analyze(ctx);
auto* tmp = new ArrayType(elements_[0]->type_->type_);
std::stringstream ss;
ss << this;
ctx.analyze_type_table_["__ArrayLiteral:"+ss.str()] = tmp;
type_ = tmp;
}
static bool classof(const Node *n) {
return n->getKind() == ND_Array;
}
};
struct VariableReference : public Expression {
std::string name_;
explicit VariableReference(std::string s) : Expression(ND_Variable), name_(std::move(s)) {}
explicit VariableReference(TokenStream& s);
~VariableReference() override = default;
void dump(std::ostream& o, size_t indent) const override {
o << "VarRef:" << name_;
}
void each_value(const std::function<void(const Expression*)>& func) const override {
func(this);
}
llvm::Type* get_type(CompilerContext& c) const override;
llvm::Value* get_value(CompilerContext& c) const override;
llvm::Value* get_ref(CompilerContext& c) const override;
void analyze(CompilerContext& ctx) override {
auto it = ctx.variable_type_table_.find(name_);
if (it == ctx.variable_type_table_.end()) {
std::stringstream ss;
ss << "undefined variable " << name_ << " referenced";
throw std::runtime_error(ss.str());
}
type_ = it->second;
}
static bool classof(const Node *n) {
return n->getKind() == ND_Variable;
}
};
struct FunctionCall : public Expression {
Expression* parent_;
std::vector<Expression*> args_;
FunctionCall(const std::string& name, std::vector<Expression*>&& arg)
: Expression(ND_Func), parent_(new VariableReference(name)), args_(std::move(arg)) {}
FunctionCall(const std::string& name, std::initializer_list<Expression*>&& arg)
: FunctionCall(name, std::vector<Expression*>(arg)) {}
FunctionCall(Expression* parent, TokenStream& s);
~FunctionCall() override {
delete parent_;
for (auto& a : args_) {
delete a;
}
}
llvm::Type* get_type(CompilerContext& c) const override;
void dump(std::ostream& o, size_t indent) const override {
o << "Fun:";
parent_->dump(o, indent);
o << "(";
for (size_t i = 0; i < args_.size(); ++i) {
if (0 < i) { o << ", "; }
args_[i]->dump(o, indent);
}
o << ")";
}
void each_value(const std::function<void(const Expression*)>& func) const override {
// parent_->each_value(func);
for (const auto* a : args_) {
func(a);
a->each_value(func);
}
}
llvm::Value* get_value(CompilerContext& c) const override;
void analyze(CompilerContext& ctx) override {
type_ = ctx.analyze_type_table_["integer"];
for (const auto& a : args_) {
a->analyze(ctx);
}
}
static bool classof(const Node *n) {
return n->getKind() == ND_Func;
}
};
struct ArrayReference : public Expression {
Expression* parent_;
Expression* idx_;
ArrayReference(Expression* parent, TokenStream& s);
ArrayReference(Expression* p, Expression* i) : Expression(ND_ArrayRef), parent_(p), idx_(i) {}
~ArrayReference() override;
void dump(std::ostream& o, size_t indent) const override {
o << "ArrRef";
parent_->dump(o, indent);
o << "[";
idx_->dump(o, indent);
o << "]";
}
void each_value(const std::function<void(const Expression*)>& func) const override {
func(this);
parent_->each_value(func);
}
llvm::Type* get_type(CompilerContext& c) const override;
llvm::Value* get_value(CompilerContext& c) const override;
llvm::Value* get_ref(CompilerContext& ctx) const override;
void analyze(CompilerContext& ctx) override {
parent_->analyze(ctx);
idx_->analyze(ctx);
auto* par = dynamic_cast<ArrayType*>(parent_->type_);
if (!par) {
throw std::runtime_error("array reference must detect array");
}
type_ = par;
}
static bool classof(const Node *n) {
return n->getKind() == ND_ArrayRef;
}
};
struct MemberReference : public Expression {
Expression* parent_;
std::string name_;
uint64_t offset_;
MemberReference(Expression* value, TokenStream& s);
MemberReference(Expression* parent, std::string name) : Expression(ND_MemberRef),
parent_(parent), name_(std::move(name)) {}
~MemberReference() override;
void dump(std::ostream& o, size_t indent) const override {
parent_->dump(o, indent);
o << "-m->" << name_;
}
void each_value(const std::function<void(const Expression*)>& func) const override {
func(this);
parent_->each_value(func);
}
llvm::Type* get_type(CompilerContext& c) const override;
llvm::Value* get_value(CompilerContext& c) const override;
llvm::Value* get_ref(CompilerContext& ctx) const override;
void analyze(CompilerContext& ctx) override {
parent_->analyze(ctx);
auto* tupletype = dynamic_cast<TupleType*>(parent_->type_);
if (!tupletype) {
throw std::runtime_error("type must be tuple");
}
auto names = tupletype->names_;
uint64_t offset = 0;
for (size_t i = 0; i < names.size(); ++i) {
if (names[i] == name_) {
type_ = tupletype->types_[i];
offset_ = offset;
return;
}
++offset;
}
std::stringstream ss;
parent_->dump(ss, 0);
ss << " ";
tupletype->dump(ss);
throw std::runtime_error("not found member named " + name_ + " in " + ss.str());
}
static bool classof(const Node *n) {
return n->getKind() == ND_MemberRef;
}
};
struct Assign : public Expression {
Expression* target_;
Expression* value_;
~Assign() override {
delete target_;
delete value_;
}
Assign(Expression* target, Expression* value)
: Expression(ND_Assign), target_(target), value_(value) {}
Assign(Expression* target, TokenStream& tokens);
void dump(std::ostream& o, size_t indent) const override {
target_->dump(o, indent);
o << " = ";
value_->dump(o, indent);
}
void each_value(const std::function<void(const Expression*)>& func) const override {
func(this);
value_->each_value(func);
}
llvm::Type* get_type(CompilerContext& c) const override;
llvm::Value* get_value(CompilerContext& c) const override;
void analyze(CompilerContext& ctx) override {
target_->analyze(ctx);
value_->analyze(ctx);
type_ = value_->type_;
}
static bool classof(const Node *n) {
return n->getKind() == ND_Assign;
}
};
} // namespace node
} // namespace reir
#endif //PROJECT_AST_EXPRESSION_HPP
| [
"hiroki.kumazaki@gmail.com"
] | hiroki.kumazaki@gmail.com |
c9ef48d8589af27768212d945802f284513a15a2 | e0b9255afbb431be6e975207b6b93ef5810e349f | /semestre5/HLIN501 - Graphes/TP4/tp4.cc | 737f4a772d7bd350a7cd41918a79a4a40df24bfd | [] | no_license | DorianGerardin/L3 | ee19b8188bc2a3034840376ef87e83493a6dab9b | 5aa1f4a43a2ac9031267415f8591b70cd3cc4a7b | refs/heads/main | 2023-04-04T18:48:21.227100 | 2021-03-30T11:15:57 | 2021-03-30T11:15:57 | 301,237,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,549 | cc | #include <cstdlib>
#include <iostream>
#include <vector>
#include <fstream>
#include <cmath>
#include <string>
#include <time.h>
using namespace std;
const int N=1400;
const int M=(N*(N-1))/2;
typedef struct coord{int abs; int ord;} coord;
void pointRandom(int n, coord point[]) {
srand(time(NULL));
string affichage = "";
for (int i = 0; i < n; ++i)
{
point[i].abs = rand() % 613;
point[i].ord = rand() % 793;
string abs = to_string(point[i].abs);
string ord = to_string(point[i].ord);
affichage += "abs : " + abs + ", ord : " + ord + "\n";
}
cout << affichage;
}
float distance(coord p1,coord p2) {
int absI =p1.abs;
int ordI = p1.ord;
int absJ = p2.abs;
int ordJ = p2.ord;
float distance =
(absJ - absI)*(absJ - absI)
+
(ordJ - ordI)*(ordJ - ordI);
return sqrt(distance);
}
void voisins(int n,int dmax,coord point[],vector<int> voisin[],int &m) {
m = 0;
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (distance(point[i], point[j]) <= dmax) {
voisin[i].push_back(j);
voisin[j].push_back(i);
m++;
}
}
}
}
void voisins2arete(int n,vector<int>voisins[],int arete[][2]) {
}
void affichageGraphique(int n,int m,coord point[],int arete[][2],string name) {
ofstream output;
output.open(name,ios::out);
output << "%!PS-Adobe-3.0" << endl;
output << "%%BoundingBox: 0 0 612 792" << endl;
output << endl;
for(int i=0;i<n;i++)
{
output << point[i].abs << " " << point[i].ord << " 3 0 360 arc" <<endl;
output << "0 setgray" <<endl;
output << "fill" <<endl;
output << "stroke"<<endl;
output << endl;
}
output << endl;
for(int i=0;i<m-1;i++)
{
output << point[arete[i][0]].abs << " " << point[arete[i][0]].ord
<< " moveto" << endl;
output << point[arete[i][1]].abs << " " << point[arete[i][1]].ord
<< " lineto" << endl;
output << "stroke" << endl;
output << endl;
}
output << "showpage";
output << endl;
}
bool existe(int n,float dis[],bool traite[],int &x);
void dijkstra(int n,vector<int> voisin[],coord point[],int pere[]) {
float dis[n];
bool traite[n];
for (int i = 0; i < n; i++)
{
dis[i] = INT32_MAX;
traite[i] = false;
}
int racine = 0;
pere[racine] = racine;
dis[racine] = 0;
int sommetCourant;
while (existe(n, dis, traite, sommetCourant))
{
for (int i = 0; i < voisin[sommetCourant].size(); i++)
{
int voisinSC = voisin[sommetCourant].at(i);
if (!traite[voisinSC] &&
dis[voisinSC] > dis[sommetCourant]
+ distance(point[sommetCourant], point[voisinSC]))
{
pere[voisinSC] = sommetCourant;
dis[voisinSC] = distance(point[sommetCourant], point[voisinSC]);
}
}
}
}
int construireArbre(int n,int arbre[][2],int pere[]);
int
main()
{
int n; // Le nombre de points.
cout << "Entrer le nombre de points: ";
cin >> n;
int dmax=50; // La distance jusqu'a laquelle on relie deux points.
coord point[N]; // Les coordonnees des points.
vector<int> voisin[N]; // Les listes de voisins.
int arbre[N-1][2]; // Les aretes de l'arbre de Dijkstra.
int pere[N]; // La relation de filiation de l'arbre de Dijkstra.
int m; // Le nombre d'aretes
int arete[M][2]; // Les aretes du graphe
return EXIT_SUCCESS;
}
| [
"gryfadon@gmail.com"
] | gryfadon@gmail.com |
7ec661919c5a3a9d14d8126d0574e74a0a835f25 | 3189db7860ee0c840d32ff1e12d056064812e5a6 | /MemoryMgmt/Source/main.cpp | 69fda8eab6dfa6942412530eb27450997700174e | [] | no_license | pravinkmr26/concepts-cpp | 28a7a354382107f2db3b579ab4a9f0da5e13f28a | 2de1c1ffb1adc555744a9b6bb4ef21c916af48ec | refs/heads/main | 2023-08-17T02:24:52.936429 | 2020-12-12T13:46:01 | 2020-12-12T13:46:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | cpp | /*
* main.cpp
*
* Created on: Oct 24, 2020
* Author: pravinkumar
*/
#include "callbase.h"
#include "memorymgmt.h"
int main() {
Run();
}
| [
"pravinkmr2619@gmail.com"
] | pravinkmr2619@gmail.com |
9e2578d35b1b37f77a0321a94a7fdc7c2ee14aa2 | 38b0b6f7fb7a7dbce6289edf5830b935c7137030 | /SK-Lib-cmath-scalbn-Bagian4__CPP/Source.cpp | 96b4cda63b8be21871ce1e5bee536a59722693d0 | [] | no_license | RizkyKhapidsyah/SK-Lib-cmath-scalbn-Bagian4__CPP | f0d14b316b0d0dc85d70798230d1b898a4a1651a | 06f7e4cf4836ed837ce6967f5a9a258cf7dab785 | refs/heads/master | 2023-06-15T01:23:58.276944 | 2021-07-04T03:07:23 | 2021-07-04T03:07:23 | 382,751,009 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | #include <iostream>
#include <cmath>
#include <cfloat>
#include <conio.h>
using namespace std;
int main() {
int n = 18;
double x = 9.321, hasil;
hasil = scalbn(x, n);
cout << x << " * " << FLT_RADIX << "^" << n << " = " << hasil << endl;
_getch();
return 0;
} | [
"rizkykhapidsyah@gmail.com"
] | rizkykhapidsyah@gmail.com |
85c74c5e94f3ce9af0024f37906b0eac7a403c84 | eb831f0eae24e871f4fe6cb584a83a45891541b0 | /common/src/gui/columnlistview/EasyColumnListItem.h | 5ba32bbfab49f4e96c871f79a55afb2eb60ef973 | [
"MIT"
] | permissive | humdingerb/WonderBrush-v2 | 3f0e4be6bc6d7a51b23a9149f6392cb56927843b | a876a28b99c13414184b8f5a27567b03edc2b32e | refs/heads/master | 2021-07-01T09:59:54.077533 | 2020-12-10T17:01:01 | 2020-12-10T17:01:01 | 195,271,147 | 0 | 0 | MIT | 2019-07-04T16:11:58 | 2019-07-04T16:11:57 | null | UTF-8 | C++ | false | false | 970 | h | // EasyColumnListItem.h
#ifndef EASY_COLUMN_LIST_ITEM_H
#define EASY_COLUMN_LIST_ITEM_H
#include <List.h>
#include "ColumnListItem.h"
class BBitmap;
class ColumnItem;
class EasyColumnListItem : public ColumnListItem {
public:
EasyColumnListItem(float height);
virtual ~EasyColumnListItem();
virtual void Draw(BView* view, Column* column, BRect frame,
BRect updateRect, uint32 flags,
const column_list_item_colors* colors);
void SetContent(int32 index, ColumnItem* item);
ColumnItem* ColumnItemAt(int32 index) const;
// convenience methods
void SetContent(int32 index, const BBitmap* bitmap);
void SetContent(int32 index, const char* text,
bool disabled = false);
static int StandardCompare(
const ColumnListItem* item1,
const ColumnListItem* item2,
const Column* column);
private:
BList fColumnItems;
};
#endif // EASY_COLUMN_LIST_ITEM_H
| [
"superstippi@gmx.de"
] | superstippi@gmx.de |
b403452ccd13d32ed11272bb8e4fc114a80324d2 | 7cb2ae97bbf6a6d2dfef73735391b4f7c070d6be | /sample/Resource.hpp | 6c3af7bf8671f401302144defe0d29a6ebcd7c19 | [] | no_license | anybirds/NewbieHeaderTool | f40fd27bbeda361925f076d9f75903a51bcec8b5 | 21d5c9e4413072e4a4a862b1374bc068a6a64b72 | refs/heads/master | 2023-03-26T10:37:47.169615 | 2021-03-27T15:23:16 | 2021-03-27T15:23:16 | 349,009,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,128 | hpp | #pragma once
#include <memory>
#include <nlohmann/json.hpp>
#include <EngineExport.hpp>
#include <Asset.hpp>
namespace Engine {
/*
Base class for all the resources like Model, Mesh, Material, Shader, Texture and etc.
*/
class ENGINE_EXPORT Resource {
protected:
Asset *asset;
public:
Resource(Asset *asset) : asset(asset) {}
virtual void Apply() = 0;
const std::string &GetName() const { return asset->GetName(); }
void SetName(const std::string &name) { asset->SetName(name); }
const uint64_t GetSerial() const { return asset->GetSerial(); }
};
void ENGINE_EXPORT to_json(nlohmann::json &js, const std::shared_ptr<Resource> &resource);
void ENGINE_EXPORT from_json(const nlohmann::json &js, std::shared_ptr<Resource> &resource);
template <typename T, std::enable_if_t<std::is_base_of_v<Resource, T>, bool> = true>
void from_json(const nlohmann::json &js, std::shared_ptr<T> &t) {
std::shared_ptr<Resource> resource;
from_json(js, resource);
t = std::dynamic_pointer_cast<T>(resource);
}
}
| [
"river0105@naver.com"
] | river0105@naver.com |
c7a2ca534af275fef1b259d46191f184e9b71f2d | 13726de7883e87a67757740bb9417e8fbdf1c1a3 | /modules/gles/gl_buffer.cpp | 7cb8c8e72b32c5c7b5e486125533cb678622bd35 | [
"Apache-2.0"
] | permissive | intel/libxcam | 1a816ec797871f1a3254b86995763753b4321aa4 | 97c90b05775d0b7cb78a35e966c51ec92fdd7525 | refs/heads/master | 2023-09-04T10:25:29.965048 | 2023-08-07T06:44:29 | 2023-08-07T09:04:55 | 29,286,224 | 493 | 186 | NOASSERTION | 2023-08-07T09:04:56 | 2015-01-15T07:37:41 | C++ | UTF-8 | C++ | false | false | 6,485 | cpp | /*
* gl_buffer.cpp - GL buffer
*
* Copyright (c) 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Wind Yuan <feng.yuan@intel.com>
*/
#include "gl_buffer.h"
namespace XCam {
GLBufferDesc::GLBufferDesc ()
: format (V4L2_PIX_FMT_NV12)
, width (0)
, height (0)
, aligned_width (0)
, aligned_height (0)
, size (0)
{
xcam_mem_clear (strides);
xcam_mem_clear (slice_size);
xcam_mem_clear (offsets);
}
GLBuffer::MapRange::MapRange ()
: offset (0)
, len (0)
, flags (0)
, ptr (0)
{
}
void
GLBuffer::MapRange::clear ()
{
offset = 0;
len = 0;
flags = 0;
ptr = NULL;
}
bool
GLBuffer::MapRange::is_mapped () const
{
return ptr;
}
GLBuffer::GLBuffer (GLuint id, GLenum target, GLenum usage, uint32_t size)
: _target (target)
, _usage (usage)
, _buf_id (id)
, _size (size)
{
}
XCamReturn
GLBuffer::bind ()
{
glBindBuffer (_target, _buf_id);
GLenum error = gl_error ();
XCAM_FAIL_RETURN (
ERROR, error == GL_NO_ERROR, XCAM_RETURN_ERROR_GLES,
"GL bind buffer:%d failed, error flag: %s", _buf_id, gl_error_string (error));
return XCAM_RETURN_NO_ERROR;
}
GLBuffer::~GLBuffer ()
{
if (_buf_id) {
glDeleteBuffers (1, &_buf_id);
GLenum error = gl_error ();
if (error != GL_NO_ERROR) {
XCAM_LOG_WARNING (
"GL Buffer delete buffer failed, error flag: %s", gl_error_string (error));
}
}
}
SmartPtr<GLBuffer>
GLBuffer::create_buffer (
GLenum target,
const GLvoid *data, uint32_t size,
GLenum usage)
{
XCAM_ASSERT (size > 0);
GLuint buf_id = 0;
glGenBuffers (1, &buf_id);
GLenum error = gl_error ();
XCAM_FAIL_RETURN (
ERROR, buf_id && (error == GL_NO_ERROR), NULL,
"GL buffer creation failed, error flag: %s", gl_error_string (error));
glBindBuffer (target, buf_id);
XCAM_FAIL_RETURN (
ERROR, (error = gl_error ()) == GL_NO_ERROR, NULL,
"GL buffer creation failed when bind buffer:%d, error flag: %s",
buf_id, gl_error_string (error));
glBufferData (target, size, data, usage);
XCAM_FAIL_RETURN (
ERROR, (error = gl_error ()) == GL_NO_ERROR, NULL,
"GL buffer creation failed in glBufferData, id:%d, error flag: %s",
buf_id, gl_error_string (error));
SmartPtr<GLBuffer> buf_obj =
new GLBuffer (buf_id, target, usage, size);
return buf_obj;
}
void *
GLBuffer::map_range (uint32_t offset, uint32_t length, GLbitfield flags)
{
if (length == 0)
length = _size;
if (_mapped_range.is_mapped () &&
_mapped_range.flags == flags &&
_mapped_range.offset == offset &&
_mapped_range.len == length) {
return _mapped_range.ptr;
}
_mapped_range.clear ();
XCamReturn ret = bind ();
XCAM_FAIL_RETURN (
ERROR, xcam_ret_is_ok (ret), NULL,
"GL bind buffer failed, buf_id:%d", _buf_id);
void *ptr = glMapBufferRange (_target, offset, length, flags);
GLenum error = gl_error ();
XCAM_FAIL_RETURN (
ERROR, ptr && (error == GL_NO_ERROR), NULL,
"GL buffer map range failed, buf_id:%d, offset:%d, len:%d, flags:%d, error flag: %s",
_buf_id, offset, length, flags, gl_error_string (error));
_mapped_range.offset = offset;
_mapped_range.len = length;
_mapped_range.flags = flags;
_mapped_range.ptr = ptr;
return ptr;
}
XCamReturn
GLBuffer::flush_map ()
{
if (!_mapped_range.is_mapped ())
return XCAM_RETURN_ERROR_ORDER;
XCAM_FAIL_RETURN (
ERROR, _mapped_range.flags & GL_MAP_FLUSH_EXPLICIT_BIT,
XCAM_RETURN_ERROR_GLES,
"GL buffer flush_map buf:%d failed, invalid flags(:%d)",
_buf_id, _mapped_range.flags);
XCamReturn ret = bind ();
XCAM_FAIL_RETURN (
ERROR, xcam_ret_is_ok (ret), ret,
"GL bind buffer failed, buf_id:%d", _buf_id);
glFlushMappedBufferRange (_target, _mapped_range.offset, _mapped_range.len);
GLenum error = gl_error ();
XCAM_FAIL_RETURN (
ERROR, error == GL_NO_ERROR,
XCAM_RETURN_ERROR_GLES,
"GL buffer flush_map buf:%d failed, error flag: %s",
_buf_id, gl_error_string (error));
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
GLBuffer::unmap ()
{
if (!_mapped_range.is_mapped ())
return XCAM_RETURN_ERROR_ORDER;
XCamReturn ret = bind ();
XCAM_FAIL_RETURN (
ERROR, xcam_ret_is_ok (ret), ret,
"GL bind buffer failed, buf_id:%d", _buf_id);
XCAM_FAIL_RETURN (
ERROR, glUnmapBuffer (_target), XCAM_RETURN_ERROR_GLES,
"GL buffer unmap buf:%d failed, error flag: %s",
_buf_id, gl_error_string (gl_error ()));
_mapped_range.clear ();
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
GLBuffer::bind_buffer_base (uint32_t index)
{
XCamReturn ret = bind ();
XCAM_FAIL_RETURN (
ERROR, xcam_ret_is_ok (ret), ret,
"GL bind buffer failed, buf_id:%d", _buf_id);
glBindBufferBase (_target, index, _buf_id);
GLenum error = gl_error ();
XCAM_FAIL_RETURN (
ERROR, error == GL_NO_ERROR, XCAM_RETURN_ERROR_GLES,
"GL bind buffer base failed. buf_id:%d failed, idx:%d, error flag: %s",
_buf_id, index, gl_error_string (error));
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
GLBuffer::bind_buffer_range (uint32_t index, uint32_t offset, uint32_t size)
{
XCamReturn ret = bind ();
XCAM_FAIL_RETURN (
ERROR, xcam_ret_is_ok (ret), ret,
"GL bind buffer failed, buf_id:%d", _buf_id);
glBindBufferRange (_target, index, _buf_id, offset, size);
GLenum error = gl_error ();
XCAM_FAIL_RETURN (
ERROR, error == GL_NO_ERROR, XCAM_RETURN_ERROR_GLES,
"GL bind buffer range failed. buf_id:%d failed, idx:%d, error flag: %s",
_buf_id, index, gl_error_string (error));
return XCAM_RETURN_NO_ERROR;
}
}
| [
"feng.yuan@intel.com"
] | feng.yuan@intel.com |
7faed6be2ac08709d32712145ee68872cdeeb640 | 3486a108de9dfaf7eb6c786c06a746dedde8bf2b | /roadsystem1.cpp | db5a744f8a1328a3d9f3d2018b4d0523cc0a635d | [] | no_license | RoshanKapar/Anoroc_City_Sim | e4d732522a0f732c32302d8d7327b4a1f658ce4d | b7001a1c238743c07d97a7454664bf8396d99296 | refs/heads/master | 2021-01-02T02:48:00.757919 | 2020-02-15T21:53:23 | 2020-02-15T21:53:23 | 239,459,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,123 | cpp | #include<iostream>
#include<vectors>
#include<string>
#include<windows.h>
#include<iterator>
#include <fstream>
#include"main.h"
using namespace std;
class roadsystem_define
private:
{
string roadblock;
int cost_perroadblock=500;
/* Price of the blocks */
string roadblock()
{return("RRRR\nRRRR")} /* Size of the blocks */
public:
{
string getroadblock()
{return roadblock();}
int getcost() /* Public functions to get the private definitions*/
{return cost_perroadblock}
}
};
class roadsystem_update : public roadsystem_define
public:
{
int Total_roadprice(int iblock)
{
if (iblock>7)
{return 0;}
else
{int total;
total=(getcost()*iblock);
return total;}
}
string total_roadblock(int amount)
{
string x;
x=getroadblock()
x=x*amount
return x
}
};
| [
"59496843+RoshanKapar@users.noreply.github.com"
] | 59496843+RoshanKapar@users.noreply.github.com |
e3b33eada556c40404d42375c4b4539d133f6ec4 | dc7676d2f6917d275c5fc26e2888eb8e251c4ff8 | /SondaAleph/SondaAleph.ino | 8ea7132ef702729454a0a2316e4b261c4e3bba6c | [] | no_license | juliozohar/Projeto-Estratos | 19a523c566c2ba1846fc253047bc247b130ffc54 | 9d7f323164c3c286e0ce267e883d2304b2b039fc | refs/heads/master | 2016-09-05T16:45:58.030771 | 2014-04-15T05:45:41 | 2014-04-15T05:45:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,802 | ino | /*============================================================
* Modulo : SondaAleph.ino
* Autor : Julio Cesar Torres (juliozohar@gmail.com)
* Tipo : Fonte C
* Data : 03/04/2014
* Objetivo : Modulo de controle do logger SondaAleph. Visa
* controlar os sensores e registrar os resultados
* obtidos em um arquivo de dados.
*=============================================================
* (C) 2014 Licensed under CERN OHL v.1.2
*=============================================================
* Pin Mapping
* D0 - RX
* D1 - TX
* D2 - Push button
* D3 - Led de atividade (verde)
* D4 -
* D5 -
* D6 - DS18B20
* D7 -
* D8 -
* D9 -
* D10 -
* D11 -
* D12 -
* D13 - Led integrado
*
* A0 - DHT11 - dados
* A1 -
* A2 -
* A3 -
* A4 - SPI/SDA - BMP085 e DS1307
* A5 - SPI/SCL - BMP085 e DS1307
*
*=============================================================*/
#include "SondaAleph.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <Wire.h>
#include <DS1307.h>
#include <DHT.h>
#include <Barometro.h>
#include <TempoReal.h>
//Declaracao de variaveis SD Card
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;
char nome[] = "LOG-0412.txt"; //O nome do arquivo deve ter o formato 8.3
// Declaracao das variaveis DS18B20
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress termometro_externo;
//Declaracao de variavel do DHT
DHT dht(DHT_PIN, DHT_TYPE);
// Variavel do barometro
Barometro br;
// Variaveis de TempoReal
TempoReal tr;
char ts[20];
//Variaveis medidas
float temp_externa, temp_externa_min, temp_externa_max;//DS18B20
float temp_interna, temp_interna_min, temp_interna_max;//DHT
float umidade, umidade_min, umidade_max; //DHT
short bmp_temp; // Variavel utilitaria, necessaria para//BMP085
long bmp_pressao, bmp_pressao_min, bmp_pressao_max; //BMP085
long bmp_altitude, bmp_altitude_min, bmp_altitude_max;//BMP085
float bmp_tempy, bmp_tempy_min, bmp_tempy_max; //BMP085
int seql = 0; // Numero sequencial dos registros
const byte ledAtividadePin = 13;
void setup(){
Serial.begin(9600);
Serial.flush();
Serial.println("Inicio do setup");
analogReference(INTERNAL);
pinMode(ledAtividadePin, OUTPUT);
//Inicializa variaveis de temperatura
temp_externa, temp_externa_max, temp_interna, temp_interna_max = 0;
temp_externa_min, temp_interna_min = 100;
umidade, umidade_max = 0;
umidade_min = 200;
//Inicializa variaveis de pressao e do BMP085
bmp_pressao, bmp_pressao_max = 0;
bmp_pressao_min = PRESSAO_MAR + 10000;
bmp_altitude, bmp_altitude_max = 0;
bmp_altitude_min = 80000;
Wire.begin();
delay(1000);
// Inicializa BMP085
init_bmp085();
//Inicializa DS18B20
init_ds18b20();
//Inicializa DHT
init_dht();
//Inicializa SDCard
init_sd();
Serial.println("Fim do setup");
}
void loop(){
Serial.println("Inicializa o loop");
digitalWrite(ledAtividadePin, HIGH);
seql++;
get_pressao_bmp();
get_altitude_bmp();
get_temp_ds(termometro_externo);
get_temp_dht();
get_umid_dht();
get_timestamp();
grava_registro();
digitalWrite(ledAtividadePin, LOW);
Serial.println("Finaliza o loop");
delay(2000);
}
/*****************************************************
* R O T I N A S L O C A I S
******************************************************/
void init_sd(){
/*
* Rotina de inicializacao do cartao SD.
* Inicializa o cartao em SPI_HALF_SPEED, para evitar erros de
* barramento com as protoboards. Utilize SIP_FULL_SPEED para
* um melhor desempenho, caso o cartao suporte esta opcao.
*/
if(!card.init(SPI_HALF_SPEED)) Serial.println(ERR_SD_INIT);
//Inicializa volume fat
if(!volume.init(&card)) Serial.println(ERR_SD_VOL);
//Abre o diretorio raiz
if(!root.openRoot(&volume)) Serial.println(ERR_SD_ROOT);
}
/*
* Rotina de inicializacao do sensor BMP085.
*/
void init_bmp085(){
br.bmp085Calibration();
}
/*
* Rotina de inicializacao do sensor DS18B20.
*/
void init_ds18b20(){
sensors.begin();
if(!sensors.getAddress(termometro_externo, 0));
Serial.println(DS_MSG_N_LOC);
Serial.println(DS_MSG_LOC);
imprime_endereco(termometro_externo);
}
/*
* Rotina de inicializacao do sensor DHT
*/
void init_dht(){
dht.begin();
}
/*
* Grava registro de sensores no cartao SD.
*/
void grava_registro(){
file.open(&root, nome, O_CREAT | O_APPEND | O_WRITE);
file.timestamp(7, 2014, 04, 11, 18, 45, 00);
writeNumber(file, seql);
writeString(file, "|");
writeString(file, tr.ts);
writeString(file, "|");
writeNumber(file, temp_externa);
writeString(file, "|");
writeNumber(file, temp_interna);
writeString(file, "|");
writeNumber(file, umidade);
writeString(file, "|");
writeNumber(file, bmp_pressao);
writeString(file, "|");
writeNumber(file, bmp_altitude);
writeString(file, "|");
}
/*****************************************************
* R O T I N A S B M P 0 8 5
******************************************************/
/*
* Recupera a pressao barometrica com o sensor BMP085
*/
void get_pressao_bmp(){
bmp_temp = br.bmp085GetTemperature(br.bmp085ReadUT());
bmp_pressao = br.bmp085GetPressure(br.bmp085ReadUP());
if(bmp_pressao > bmp_pressao_max)
bmp_pressao_max = bmp_pressao;
if(bmp_pressao < bmp_pressao_min)
bmp_pressao_min = bmp_pressao;
if(bmp_temp > bmp_tempy_max)
bmp_tempy_max = bmp_temp;
if(bmp_temp < bmp_tempy_min)
bmp_tempy_min = bmp_temp;
}
/*
* Recupera a altitude do modulo em funcao da pressao barometrica.
*/
void get_altitude_bmp(){
bmp_altitude = (float)44330 * (1 -pow(((float) bmp_pressao/PRESSAO_MAR), 0.190295));
if(bmp_altitude > bmp_altitude_max)
bmp_altitude_max = bmp_altitude;
}
/*****************************************************
* R O T I N A S S D - C A R D
******************************************************/
/*
* Escreve a sequencia CRLF no arquivo.
*/
void writeCRLF(SdFile& f){
f.write((uint8_t*)"\r\n", 2);
}
/*
* Escreve um numero no arquivo.
*/
void writeNumber(SdFile& f, uint32_t n){
uint8_t idx = n;
uint8_t buf[10];
uint8_t i = 0;
do{
i++;
buf[sizeof(buf) -i] = n%10 + '0';
n /= 10;
}while (n);
if(idx < 10)
f.write("0");
f.write(&buf[sizeof(buf) -1], i);
}
/*
* Escreve uma string no arquivo.
*/
void writeString(SdFile& f, char *str){
f.write(str);
}
/*****************************************************
* R O T I N A S D S 1 8 B 2 0
******************************************************/
/*
* Imprime o endereco de um dispositivo OneWire.
*/
void imprime_endereco(DeviceAddress devAdd){
for(int i=0; i < 8; i++){
if(devAdd[i] < 16) Serial.print("0");
Serial.println(devAdd[i], HEX);
}
}
/*
* Recupera a temperatura externa.
*/
float get_temp_ds(DeviceAddress devAdd){
temp_externa = sensors.getTempC(devAdd);
if(temp_externa < temp_externa_min)
temp_externa_min = temp_externa;
if(temp_externa > temp_externa_max)
temp_externa_max = temp_externa;
}
/*****************************************************
* R O T I N A S D H T
******************************************************/
/*
* Leitura do parametro de temperatura a partir do sensor DHT.
*/
float get_temp_dht(){
float t = dht.readTemperature();
if(isnan(t)){
Serial.println(ERR_DHT_READ);
t = -99999;
}
return t;
}
/*
* Leitura do parametro de umidade a partir do sensor DHT.
*/
float get_umid_dht(){
float h = dht.readHumidity();
if(isnan(h)){
Serial.println(ERR_DHT_READ);
h = -99999;
}
return h;
}
/*****************************************************
* R O T I N A S D S 1 3 0 7
******************************************************/
/*
* Recupera a data e hora do relogio de tempo real. Retorna no formato
* timestamp (AAAA-MM-DD-hh-mm-ssssss), com 19 posicoes.
*/
void get_timestamp(){
tr.getTimestamp();
}
/*
* Acerta a hora do relogio de tempo real.
*/
void acerta_relogio(int ano, int mes, int dia, int hora,
int minuto, int segundo, int dia_semana){
tr.para();
tr.acertaDataHora(ano, mes, dia, hora, minuto, segundo, dia_semana);
tr.inicia();
}
/*****************************************************************************************
* F I M D E P R O G R A M A
*****************************************************************************************/
| [
"juliozohar@gmail.com"
] | juliozohar@gmail.com |
4b993f334dbf66068e430e5b23c0ff060826cdf7 | bf0d3ee072cc1de3e310a09f26c29b62df827051 | /src/conversions.h | a90f6dadc560ed66094acb53af1ee7d065ea3df4 | [] | no_license | xrobin/MCMS | eaf5b2111f5dbe959a79d061f1a0e998764be23f | 84acb5e3072ee7d5b7a311121905ef7feb6060a0 | refs/heads/master | 2021-04-30T14:37:47.405270 | 2021-04-06T11:08:15 | 2021-04-06T11:08:15 | 121,221,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,549 | h | #pragma once
//#include "Likelihood.h"
#include "MonteCarlo.h"
#include "Parameters.h"
#include "Peptide.h"
#include <Rcpp.h>
#include "S4Aliases.h" // ProteinModel
#include "typedefs.h"
/** Various conversion functions outside the Rcpp namespace */
/** Converts a named list of numeric vectors into an o_type object (typically a map)
* to represent occupancy parameters
*/
oParams::o_type convertListToOMap(const Rcpp::List&);
cParams::c_type convertVectorToCMap(const Rcpp::NumericVector&);
/** Converts the ProteinModel to a vector of Peptide */
std::vector<Peptide> convertS4ToPeptides(const ProteinModel& aProtein);
/** The actual MC objects */
MonteCarlo convertS4ToMonteCarloWithParams(const PeptidesModel&, const VarianceModel&,
const cParams::c_type aCMap, const oParams::o_type anOMap,
const double c_prior_sd, const double o_prior_shape1, const double o_prior_shape2,
const double o_restrict, const double prior_move_proportion, const double c_sd, const double o_sd, const double o_k_scale,
const Rcpp::NumericVector& seed);
MonteCarlo convertS4ToMonteCarlo(const PeptidesModel&, const VarianceModel&, const double c_prior_sd, const double o_prior_shape1, const double o_prior_shape2,
const double o_restrict,
const double prior_move_proportion, const double c_sd, const double o_sd, const double o_k_scale,
const Rcpp::NumericVector& seed);
//vector<Peptides> convertListToPeptidesVector(List aDataList, ...) {
/** Initialize a PRNG using the seed from R */
std::mt19937_64 seedFromR(const Rcpp::NumericVector&);
| [
"xavalias-github@xavier.robin.name"
] | xavalias-github@xavier.robin.name |
43742ecc7c4f17798c517ec93ca3f995eeafaadc | 09f6cd0a8b53ecb6a6449da43895147319e48b98 | /202001/æŒè®²æ¯èµæµçšç®¡çç³»ç»/æŒè®²æ¯èµæµçšç®¡çç³»ç»/speaker.h | efd97133927b14ecc1f8b0f821dbe7aefe278472 | [] | no_license | tyut-zhuran/cpp_learn | 8556ef39263e93cb4405f35da73d72c1f87319b2 | 3252761e04acbb2745166f3ee8bbd15940f11418 | refs/heads/master | 2021-02-08T18:37:54.049073 | 2020-03-01T16:38:22 | 2020-03-01T16:38:22 | 244,184,290 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 143 | h | #pragma once
# include <iostream>
using namespace std;
# include <string>
class Speaker
{
public:
string m_name;
double m_score[2];
};
| [
"1293992212@qq.com"
] | 1293992212@qq.com |
252d49b6044d62762e107746297d3d2f2a93b970 | 2e8a39b275cf368da752bc7a6fad39f9968bdb2a | /èŸåºé»èŸè¿ç®ç¬ŠççåŒè¡š.cpp | b39d58dc3472c07067aabe4e92581a90bdbd16e6 | [] | no_license | 15831944/Cplusplus-1 | 9e77161b9df8df610f16432503f9e52ffff4eb68 | 16c74deec56829fd2141a98284145984cd555735 | refs/heads/master | 2023-04-09T22:19:07.092358 | 2016-09-30T03:40:35 | 2016-09-30T03:40:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | #include <iostream>
using namespace std;
int main()
{
cout<< boolalpha <<"Logical AND (&&)"
<<"\nfalse && false: "<< ( false && false )
<<"\nfalse && true: " << ( false && true )
<<"\ntrue && false: " << (true && false )
<<"\nture && true: " << (true && true )<<"\n\n";
cout<<"Logical OR (||)"
<< "\nfalse || false: "<<( false || false )
<< "\nfalse || true: "<<( false || true )
<< "\nture || false: "<<( true || false )
<< "\ntrue || true: "<<( true || true ) <<"\n\n";
cout<<"Logical NOT (!)"
<<"\n!false: " << ( !false )
<<"\n!true: " << ( !true ) <<endl;
}
| [
"lixuat2014@gmail.com"
] | lixuat2014@gmail.com |
d65ad2f128f7c05f4fa9181a30802ee8243e453c | 9ec137ae6893c2f964f01e350e8bdfec16784196 | /softEngine/src/se/macos/includes/graphics/ProgressBar.hpp | c306868445ac1288ab54eaf224f970ea5d80c611 | [
"MIT"
] | permissive | DetrembleurArthur/engineTools | 6fdac888efa674c81ec6e4fd04eaa35814bb656d | 486fbd081a6519adc03162ab8f51e1ec1254c17c | refs/heads/master | 2022-04-02T16:42:50.937590 | 2020-01-04T16:08:44 | 2020-01-04T16:08:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | hpp | #ifndef PROGRESS_BAR_HPP
#define PROGRESS_BAR_HPP
#include "Widget.hpp"
namespace se
{
class ProgressBar : public Widget
{
protected:
static const double MIN_VALUE;
double maxValue = 100;
double value = 100;
float maxSize;
sf::Color maxColor = sf::Color::Green;
sf::Color minColor = sf::Color::Red;
bool middle = false;
virtual void ajust();
public:
ProgressBar(float x, float y, float maxSize, float height, Application *root, double maxVal=100, double val=100, bool middle=false);
virtual ~ProgressBar();
void addValue(double value);
void setMaxValue(double maxValue);
void setValue(double value);
void setMaxColor(const sf::Color &c);
void setMinColor(const sf::Color &c);
void setMaxSize(float maxSize);
double getMaxValue() const;
double getValue() const;
const sf::Color &getMaxColor() const;
const sf::Color &getMinColor() const;
float getMaxSize() const;
void setMiddle(bool=true);
void horizontal();
void vertical();
void reverse();
virtual void render() override;
};
}
#endif
| [
"mb624967@skynet.be"
] | mb624967@skynet.be |
bb1b7acf7f4bc8d05874121c6f321a27d3f5b74e | 4409d13e5aad6cb3a171562c57adf3cacab434ff | /BOJ/C++/9494.cpp | 0e91ef829aac374862b5f5a07e949c0c52c8352c | [] | no_license | cow-coding/algorithm | 688ede426c05117d75721896ad80fea53204e329 | 05a28a7dfae8845672227536a88c6f8e6e099df0 | refs/heads/master | 2022-07-09T08:14:47.709060 | 2022-06-08T17:32:04 | 2022-06-08T17:32:04 | 247,063,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
int cnt, tmp{0};
int line;
while (1)
{
tmp = 0;
cnt = 1;
cin >> line;
if (line == 0)
return 0;
cin.ignore();
for (int i = 0; i < line; i++) {
if (tmp == 0) {
getline(cin, sentence);
for (; tmp < sentence.size(); tmp++) {
if (sentence[tmp] == 32) {
break;
}
cnt++;
}
}else {
getline(cin, sentence);
for (; tmp < sentence.size(); tmp++) {
if (sentence[tmp] == 32) {
break;
}
cnt++;
}
}
}
cout << cnt << "\n";
}
}
//4
//Lorem ipsum dolor sit amet, consectetur adipisicing elit,
//sed do eiusmod tempor incididunt ut labore et dolore magna
//aliqua. Ut enim ad minim veniam, quis nostrud exercitation
//ullamco laboris nisi ut aliquip ex ea commodo consequat.
//3
//Supercalifragilisticexpialidocious! Can you handle
//short
//lines?
//0
| [
"kbp0237@gmail.com"
] | kbp0237@gmail.com |
8cc7059a9e51c2909fd6830cc7428fb6980ff867 | b4aa1d7b3b357ffb8b708d11d21c884071e9c450 | /C/mediapipe_api/common.h | d5464af7342a581418fa9b8297e7903af3e1a09f | [
"MIT"
] | permissive | ottomata-studio/MediapipeUnityPlugin | 81573674bcea3476515738889206f0d5389eea35 | 66f85e123a114ff68da9334c7baa4b27bf8dba5d | refs/heads/master | 2022-12-22T12:08:07.585894 | 2020-09-24T19:33:29 | 2020-09-24T19:33:29 | 295,824,700 | 1 | 1 | MIT | 2020-09-15T19:07:20 | 2020-09-15T19:07:19 | null | UTF-8 | C++ | false | false | 452 | h | #ifndef C_MEDIAPIPE_API_COMMON_H_
#define C_MEDIAPIPE_API_COMMON_H_
#ifdef DLL_EXPORTS
#define MP_CAPI_EXPORT __declspec(dllexport)
#else
#define MP_CAPI_EXPORT
#endif
#include <string>
extern inline const char* strcpy_to_heap(const std::string& str) {
if (str.empty()) { return nullptr; }
auto str_ptr = new char[str.length() + 1];
snprintf(str_ptr, str.length() + 1, str.c_str());
return str_ptr;
}
#endif // C_MEDIAPIPE_API_COMMON_H_
| [
"eulerdora.1810.mann@gmail.com"
] | eulerdora.1810.mann@gmail.com |
ec6487e4cf8c9d32ac740cf2a0f61f2df6f466fd | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.009/NC7H15O2H | 48eeba21014f4129ecc4bcec981d7ca2b0ec3781 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 841 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.009";
object NC7H15O2H;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 9.35897e-53;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
eb1780c169befc305522a04ffccabe002a505e17 | 17353cfd2c984f2b57ab09dce5b793f34b051f19 | /unsorted_include_todo/PikiAI/ActBreakGateArg.h | 437bbb95fe4b7a3f77c0ffc5c74bb96c58b0e0de | [] | no_license | mxygon/pikmin2 | 573df84b127b27f1c5db6be22680b63fd34565d5 | fa16b706d562d3f276406d8a87e01ad541515737 | refs/heads/main | 2023-09-02T06:56:56.216154 | 2021-11-12T09:34:26 | 2021-11-12T09:34:26 | 427,367,127 | 1 | 0 | null | 2021-11-12T13:19:54 | 2021-11-12T13:19:53 | null | UTF-8 | C++ | false | false | 192 | h | #ifndef _PIKIAI_ACTBREAKGATEARG_H
#define _PIKIAI_ACTBREAKGATEARG_H
namespace PikiAI {
struct ActBreakGateArg {
virtual void getName(); // _00
// _00 VTBL
};
} // namespace PikiAI
#endif
| [
"84647527+intns@users.noreply.github.com"
] | 84647527+intns@users.noreply.github.com |
077dd91766eb276f1d5857c54582ceb8024c4217 | fcbbd838a9d29676c603ed3e405b87bfeede6fac | /ArduinoKame/ArduinoKame/ArduinoKame.ino | deb4848cf38ea6d4ed81a3286355534a3dc2a184 | [] | no_license | PingguSoft/ArduinoProjects | 1e93eae69ccb3b05d3bccad4a239f3c3298dcdf7 | 054ac3eee9dc5481c9871b5b94a400181e7f2ba0 | refs/heads/master | 2021-01-10T23:48:49.708058 | 2017-12-21T13:44:35 | 2017-12-21T13:44:35 | 70,792,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,961 | ino | #include <Servo.h>
#include <EEPROM.h>
#include "pitches.h"
#include "utils.h"
#include "minikame.h"
#include "esp8266.h"
static MiniKame mRobot;
static ESP8266 mESP;
static SerialProtocol mSerial;
static u32 mCurTS;
static u32 mLastTS;
static u32 mLastBattTS;
static u32 mLastHeartTS;
static u16 mCycleTime = 0;
static u16 mErrCtr = 0;
static u8 mLastBatt;
static bool mIsShutdown = false;
static u8 mLastAuxBtn = 0;
static u8 mDir = 0;
#define BIT_LASER 0
#define BIT_DIR_UP 0
#define BIT_DIR_DOWN 1
#define BIT_DIR_LEFT 2
#define BIT_DIR_RIGHT 3
/*
*****************************************************************************************
* mspCallback
*****************************************************************************************
*/
s8 mspCallback(u8 cmd, u8 *data, u8 size, u8 *res)
{
u16 *rc;
u32 *ptr;
u16 val;
s8 ret = -1;
s16 dist;
DUMP("MSP", data, size);
switch (cmd) {
case SerialProtocol::MSP_ANALOG:
res[0] = mLastBatt;
ret = 7;
break;
case SerialProtocol::MSP_STATUS:
*((u16*)&res[0]) = mCycleTime;
*((u16*)&res[2]) = mErrCtr;
*((u32*)&res[6]) = mIsShutdown ? 0 : 1;
ret = 11;
break;
case SerialProtocol::MSP_ALTITUDE:
ptr = (u32*)res;
#if 0
dist = mRobotAux.getDist(0);
if (dist > 0)
*ptr = dist;
else
*ptr = 0;
#endif
*ptr = 0;
ret = 6;
break;
case SerialProtocol::MSP_SET_RAW_RC:
rc = (u16*)data;
mDir = 0;
// roll
val = (*rc++ - 1000);
if (val < 300) {
mDir |= BV(BIT_DIR_LEFT);
} else if (val > 800) {
mDir |= BV(BIT_DIR_RIGHT);
}
// pitch
val = (*rc++ - 1000);
if (val < 300) {
mDir |= BV(BIT_DIR_DOWN);
} else if (val > 800) {
mDir |= BV(BIT_DIR_UP);
}
// yaw
val = (*rc++ - 1000);
// throttle
val = (*rc++ - 1000);
// AUX1 - AUX4
val = 0;
for (u8 i = 0; i < 4; i++) {
if (*rc++ > 1700)
val |= BV(i);
}
if (val != mLastAuxBtn) {
if (val & BV(0)) {
analogWrite(PIN_LASER, 255);
} else {
analogWrite(PIN_LASER, 0);
}
mIsShutdown = val & BV(3);
if (mIsShutdown) {
}
mLastAuxBtn = val;
}
break;
}
return ret;
}
#define VBAT_SMOOTH_LEVEL 16
u16 mVoltBuf[VBAT_SMOOTH_LEVEL];
u16 mVoltSum;
u8 mVoltIdx;
u8 getBattVolt(void)
{
u16 v;
u16 maxVolt;
v = analogRead(PIN_ANALOG_VOLT);
mVoltSum += v;
mVoltSum -= mVoltBuf[mVoltIdx];
mVoltBuf[mVoltIdx++] = v;
mVoltIdx %= VBAT_SMOOTH_LEVEL;
// max volt = ((r1 + r2) / r2) * 5V
maxVolt = (BATT_DIVIDER_R1 / BATT_DIVIDER_R2) * 50 + 50;
return map(mVoltSum / VBAT_SMOOTH_LEVEL, 0, 1023, 0, maxVolt - 1);
}
void setup()
{
Serial.begin(115200);
pinMode(PIN_SPEAKER, OUTPUT);
pinMode(PIN_LASER, OUTPUT);
pinMode(PIN_MISSILE, OUTPUT);
digitalWrite(PIN_MISSILE, LOW);
for (u8 i = 0; i < VBAT_SMOOTH_LEVEL; i++) {
getBattVolt();
}
mRobot.init();
mSerial.begin(SERIAL_BPS);
mESP.begin(&mSerial);
mSerial.registerCallback(mspCallback);
}
int amp = 0;
int off = 90;
int phase = 0;
int idx = 0;
void loop()
{
u8 ch;
u8 tmp;
mSerial.handleMSP();
mCurTS = millis();
// every 5sec
if (mCurTS - mLastBattTS > 1000) {
u8 batt = getBattVolt();
if (batt != mLastBatt) {
mLastBatt = batt;
LOG(F("VOLT:%4d\n"), mLastBatt);
}
mLastBattTS = mCurTS;
}
if (Serial.available()) {
ch = Serial.read();
tmp = mLastAuxBtn;
switch(ch) {
#ifndef __TEST__
case '8':
mRobot.walk(1,550);
break;
case '4':
mRobot.turnL(1,550);
break;
case '6':
mRobot.turnR(1,550);
break;
case '5':
mRobot.home();
break;
case 'p':
mRobot.pushUp(2, 2000);
break;
case 'u':
mRobot.upDown(4,250);
break;
case 'j':
mRobot.jump();
break;
case 'e':
mRobot.hello();
break;
case 'f':
mRobot.frontBack(4,200);
break;
case 'd':
mRobot.dance(2,1000);
break;
case 'r':
mRobot.run(1,1000);
break;
case 'o':
mRobot.omniWalk(1, 1000, FALSE, 1);
break;
case 'm':
mRobot.moonwalkL(1, 1000);
break;
case 't':
mRobot.trimming();
break;
#endif
case 'h':
mRobot.home();
break;
case 'l':
tmp = (tmp & BV(BIT_LASER)) ^ (BV(BIT_LASER));
LOG(F("LASER:%4d\n"), tmp);
mLastAuxBtn = (mLastAuxBtn & ~(BV(BIT_LASER))) | tmp;
if (tmp) {
analogWrite(PIN_LASER, 255);
tone(PIN_SPEAKER, NOTE_C6, 500);
} else {
analogWrite(PIN_LASER, 0);
noTone(PIN_SPEAKER);
}
break;
#ifdef __TEST__
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
idx = ch - '1';
LOG(F("LEG:%d\n"), idx + 1);
break;
case 'O':
if (off < 190)
off += 5;
LOG(F("Off:%3d, Amp:%3d, Pha:%3d\n"), off, amp, phase);
break;
case 'o':
if (off > 0)
off -= 5;
LOG(F("Off:%3d, Amp:%3d, Pha:%3d\n"), off, amp, phase);
break;
case 'A':
if (amp < 90)
amp += 5;
LOG(F("Off:%3d, Amp:%3d, Pha:%3d\n"), off, amp, phase);
break;
case 'a':
if (amp > 0)
amp -= 5;
LOG(F("Off:%3d, Amp:%3d, Pha:%3d\n"), off, amp, phase);
break;
case 'P':
if (phase < 360)
phase += 5;
LOG(F("Off:%3d, Amp:%3d, Pha:%3d\n"), off, amp, phase);
break;
case 'p':
if (phase > 0)
phase -= 5;
LOG(F("Off:%3d, Amp:%3d, Pha:%3d\n"), off, amp, phase);
break;
case 't':
LOG(F("Off:%3d, Amp:%3d, Pha:%3d\n"), off, amp, phase);
mRobot.test(idx, amp, off, phase, 1000);
break;
#endif
}
} else {
if (mDir & BV(BIT_DIR_UP)) {
mRobot.walk(1, 550);
} else if (mDir & BV(BIT_DIR_LEFT)) {
mRobot.turnL(1, 550);
} else if (mDir & BV(BIT_DIR_RIGHT)) {
mRobot.turnR(1, 550);
} else {
mRobot.home();
}
}
}
| [
"pinggusoft@gmail.com"
] | pinggusoft@gmail.com |
51bdf61f18647b7b41963a7a69d27e637cd28193 | edfbb5e3066bd1f72a79c0ea21285eeca25654f7 | /PuzzleGameVS/loader.cpp | a2c2000c0160b4a82b987d030e1e25aa21187a77 | [] | no_license | puzzle4p/puzzle4p | 31fa8ea780ab689517261f53c8a05295294b82f3 | f895ee3887c2d947f850637e2cf8c91ab415c941 | refs/heads/master | 2020-12-24T15:58:06.769723 | 2014-02-15T22:35:10 | 2014-02-15T22:35:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,796 | cpp | #include "SDL.h"
#include "Menu.h"
#include "Game.h"
#include "stateManager.h"
#include "layerManager.h"
#include <string>
int main(int argc, char* args[])
{
bool quit = false;
int windowWidth = 640;
int windowHeight = 480;
std::string windowTitle = "puzzle4p";
std::string menuImageDestination = "menu_background.bmp";
std::string gameImageDestination = "game_background.bmp";
SDL_Window *mainWindow = SDL_CreateWindow(windowTitle.c_str(), 100, 100, windowWidth, windowHeight, SDL_WINDOW_SHOWN);
SDL_Surface *windowSurface = SDL_GetWindowSurface(mainWindow);
SDL_Renderer *renderer = SDL_CreateRenderer(mainWindow, -1, SDL_RENDERER_ACCELERATED);
State *newMenu = new Menu(mainWindow, windowSurface, renderer, menuImageDestination);
State *newGame = new Game(mainWindow, windowSurface, renderer, gameImageDestination);
stateManager::addToMap(STATE_MENU, newMenu);
stateManager::addToMap(STATE_GAME, newGame);
stateManager::changeState(STATE_MENU);
SDL_Event event;
Uint32 currentTicks = SDL_GetTicks();
const int ticksPerSecond = 1000;
const int framesPerSecond = 60;
while (!quit)
{
currentTicks = SDL_GetTicks();
int delay = ticksPerSecond / framesPerSecond - (SDL_GetTicks() - currentTicks);
if (delay > 0)
{
SDL_Delay(delay);
}
layerManager::setRenderer(renderer, windowSurface);
layerManager::showLayers();
while (SDL_PollEvent(&event))
{
if (event.type == SDL_MOUSEBUTTONDOWN)
{
stateManager::onMouseDown(event.button.x, event.button.y);
}
if (event.type == SDL_TEXTINPUT)
{
stateManager::onPressDown(); // funkcja do zrobienia jeszcze
}
if (event.type == SDL_QUIT)
{
quit = true;
}
}
}
delete newGame;
delete newMenu;
SDL_DestroyWindow(mainWindow);
mainWindow = NULL;
return 0;
}
| [
"siwers17@gmail.com"
] | siwers17@gmail.com |
aa16275fc0e9670810044fdf92474f459ef570f1 | e25b7bb3fd43f763f4e5dcb09cdda35b9a3f30a0 | /base/task/sequence_manager/task_queue_proxy.cc | b8cdca51351464c45bcf05c6689ee654675b86a9 | [
"BSD-3-Clause"
] | permissive | trustcrypto/chromium | 281ff06e944b1ff7da7a5005e41173ccc78eb2cd | 6e3be4ab657ddd91505753ab67801efcf8541367 | refs/heads/master | 2023-03-08T03:58:49.920358 | 2018-12-26T20:55:44 | 2018-12-26T20:55:44 | 163,217,833 | 1 | 0 | NOASSERTION | 2018-12-26T21:07:41 | 2018-12-26T21:07:40 | null | UTF-8 | C++ | false | false | 1,864 | cc | // Copyright 2018 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/task/sequence_manager/task_queue_proxy.h"
#include "base/task/sequence_manager/associated_thread_id.h"
#include "base/task/sequence_manager/sequence_manager_impl.h"
#include "base/task/sequence_manager/task_queue_impl.h"
namespace base {
namespace sequence_manager {
namespace internal {
TaskQueueProxy::TaskQueueProxy(
TaskQueueImpl* task_queue_impl,
scoped_refptr<AssociatedThreadId> associated_thread)
: task_queue_impl_(task_queue_impl),
associated_thread_(std::move(associated_thread)) {}
TaskQueueProxy::~TaskQueueProxy() = default;
bool TaskQueueProxy::PostTask(PostedTask task) const {
// NOTE: Task's destructor might attempt to post another task,
// so ensure it never happens inside this lock.
if (RunsTasksInCurrentSequence()) {
if (!task_queue_impl_)
return false;
task_queue_impl_->PostTask(std::move(task),
TaskQueueImpl::CurrentThread::kMainThread);
return true;
} else {
AutoLock lock(lock_);
if (!task_queue_impl_)
return false;
task_queue_impl_->PostTask(std::move(task),
TaskQueueImpl::CurrentThread::kNotMainThread);
return true;
}
}
bool TaskQueueProxy::RunsTasksInCurrentSequence() const {
return associated_thread_->IsBoundToCurrentThread();
}
void TaskQueueProxy::DetachFromTaskQueueImpl() {
DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker);
// |task_queue_impl_| can be read from the main thread without a lock,
// but a lock is needed when we write to it.
AutoLock lock(lock_);
task_queue_impl_ = nullptr;
}
} // namespace internal
} // namespace sequence_manager
} // namespace base
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
8ce8f28c1e51973593b542e4d8eb089820939214 | 21f771ed0276f430255c078a375ebba2017bb1f0 | /MikadoMonteCarlo/Test/overlaptest.cpp | 95c6285b3b1629ef8c14c59abb890a6fc7c308d3 | [] | no_license | Tovermodus/monte_carlo_methods | 38348297211b8acee516cd35d764b345d2a44b7a | 5ea10295bcc3ae6040094583c7883051e5c47a2f | refs/heads/main | 2023-02-27T16:55:08.722124 | 2021-02-11T09:58:54 | 2021-02-11T09:58:54 | 311,073,773 | 0 | 0 | null | 2021-02-11T09:41:55 | 2020-11-08T13:52:58 | C++ | UTF-8 | C++ | false | false | 4,780 | cpp |
//
// Created by tovermodus on 1/19/21.
//
#include <gtest/gtest.h>
#include "../Rod.h"
#include "../Medium.h"
#include "../MonteCarloLoop.h"
TEST(OverlapTest, fewInitial)
{
double scale = 5e-5;
std::random_device rd;
std::mt19937 rng = std::mt19937(rd());
MediumParameters params(0.05 * scale, 0.001 * scale, IRON_DENSITY, 1, 100 / scale / scale, 5000, WATER_DENSITY,
WATER_VISCOSITY, true, 00 * std::pow(scale, 6), 1 * scale, 1 * scale, EARTH_GRAVITY,
ROOM_TEMPERATURE);
Medium m(params, rng);
std::cout << (int)(m.calculate_energy() / 1e200) << " overlaps \n";
ASSERT_TRUE(m.calculate_energy() < 1e100);
}
TEST(OverlapTest, mediumInitial)
{
double scale = 5e-5;
std::random_device rd;
std::mt19937 rng = std::mt19937(rd());
MediumParameters params(0.05 * scale, 0.001 * scale, IRON_DENSITY, 5, 500 / scale / scale, 5000, WATER_DENSITY,
WATER_VISCOSITY, true, 00 * std::pow(scale, 6), 1 * scale, 1 * scale, EARTH_GRAVITY,
ROOM_TEMPERATURE);
Medium m(params, rng);
std::cout << (int)(m.calculate_energy() / 1e200) << " overlaps \n";
ASSERT_TRUE(m.calculate_energy() < 1e100);
}
TEST(OverlapTest, manyInitial)
{
double scale = 5e-5;
std::random_device rd;
std::mt19937 rng = std::mt19937(rd());
MediumParameters params(0.05 * scale, 0.001 * scale, IRON_DENSITY, 15, 1000 / scale / scale, 5000,
WATER_DENSITY, WATER_VISCOSITY, true, 00 * std::pow(scale, 6), 1 * scale, 1 * scale,
EARTH_GRAVITY, ROOM_TEMPERATURE);
Medium m(params, rng);
std::cout << (int)(m.calculate_energy() / 1e200) << " overlaps \n";
ASSERT_TRUE(m.calculate_energy() < 1e100);
}
TEST(OverlapTest, fewWaterIron)
{
double scale = 5e-5;
std::random_device rd;
std::mt19937 rng = std::mt19937(rd());
MediumParameters params(0.05 * scale, 0.001 * scale, IRON_DENSITY, 15, 100 / scale / scale, 5000, WATER_DENSITY,
WATER_VISCOSITY, true, 00 * std::pow(scale, 6), 1 * scale, 1 * scale, EARTH_GRAVITY,
ROOM_TEMPERATURE);
MonteCarloLoop loop(params, rng, params.estimate_time_step());
for (double i = 0; i < 2e5; ++i) {
loop.monte_carlo_step();
}
ASSERT_TRUE(loop.calculate_energy() < 1e100);
}
TEST(OverlapTest, mediumWaterIron)
{
double scale = 5e-3;
std::random_device rd;
std::mt19937 rng = std::mt19937(rd());
MediumParameters params(0.05 * scale, 0.001 * scale, IRON_DENSITY, 15, 300 / scale / scale, 5000, WATER_DENSITY,
WATER_VISCOSITY, true, 00 * std::pow(scale, 6), 1 * scale, 1 * scale, EARTH_GRAVITY,
ROOM_TEMPERATURE);
MonteCarloLoop loop(params, rng, params.estimate_time_step());
for (double i = 0; i < 1e4; ++i) {
loop.monte_carlo_step();
}
ASSERT_TRUE(loop.calculate_energy() < 1e100);
}
TEST(OverlapTest, manyWaterIron)
{
double scale = 5e-6;
std::random_device rd;
std::mt19937 rng = std::mt19937(rd());
MediumParameters params(0.05 * scale, 0.001 * scale, IRON_DENSITY, 15, 1000 / scale / scale, 5000,
WATER_DENSITY, WATER_VISCOSITY, true, 00 * std::pow(scale, 6), 1 * scale, 1 * scale,
EARTH_GRAVITY, ROOM_TEMPERATURE);
MonteCarloLoop loop(params, rng, params.estimate_time_step());
for (double i = 0; i < 1e4; ++i) {
loop.monte_carlo_step();
}
ASSERT_TRUE(loop.calculate_energy() < 1e100);
}
TEST(OverlapTest, fewWaterLithium)
{
double scale = 5e-5;
std::random_device rd;
std::mt19937 rng = std::mt19937(rd());
MediumParameters params(0.05 * scale, 0.001 * scale, LITHIUM_DENSITY, 15, 100 / scale / scale, 5000,
WATER_DENSITY, WATER_VISCOSITY, true, 00 * std::pow(scale, 6), 1 * scale, 1 * scale,
EARTH_GRAVITY, ROOM_TEMPERATURE);
MonteCarloLoop loop(params, rng, params.estimate_time_step());
for (double i = 0; i < 2e5; ++i) {
loop.monte_carlo_step();
}
ASSERT_TRUE(loop.calculate_energy() < 1e100);
}
TEST(OverlapTest, mediumWaterLithium)
{
double scale = 5e-3;
std::random_device rd;
std::mt19937 rng = std::mt19937(rd());
MediumParameters params(0.05 * scale, 0.001 * scale, LITHIUM_DENSITY, 15, 300 / scale / scale, 5000,
WATER_DENSITY, WATER_VISCOSITY, true, 00 * std::pow(scale, 6), 1 * scale, 1 * scale,
EARTH_GRAVITY, ROOM_TEMPERATURE);
MonteCarloLoop loop(params, rng, params.estimate_time_step());
for (double i = 0; i < 1e4; ++i) {
loop.monte_carlo_step();
}
ASSERT_TRUE(loop.calculate_energy() < 1e100);
}
TEST(OverlapTest, manyWaterLithium)
{
double scale = 5e-6;
std::random_device rd;
std::mt19937 rng = std::mt19937(rd());
MediumParameters params(0.05 * scale, 0.001 * scale, LITHIUM_DENSITY, 15, 1000 / scale / scale, 5000,
WATER_DENSITY, WATER_VISCOSITY, true, 00 * std::pow(scale, 6), 1 * scale, 1 * scale,
EARTH_GRAVITY, ROOM_TEMPERATURE);
MonteCarloLoop loop(params, rng, params.estimate_time_step());
for (double i = 0; i < 1e4; ++i) {
loop.monte_carlo_step();
}
ASSERT_TRUE(loop.calculate_energy() < 1e100);
} | [
"simon.schmidt@mabisile.de"
] | simon.schmidt@mabisile.de |
19bb18edbcbcd6232a4ed9801067562dfa4e3d79 | a0ef3aa1b3118baf54dc186d89c35072b8d96d54 | /codeforces/1372/A.cpp | 9118ba7de0890a9e3202b665872f8eb7a7658bde | [] | no_license | arjunbangari/Problem-Solving | 110398129698038660e558509c46c385e7848cc3 | 9c9760627a3fbdd97ecee8cbc02245a3ea0f7fda | refs/heads/master | 2023-02-05T17:09:40.631840 | 2019-08-10T12:02:00 | 2020-12-29T11:52:13 | 324,994,511 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
typedef pair<ll,ll> pll;
#define endl "\n";
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
ll const inf = 1e18;
ll const maxn = 1e6+5;
ll const mod = 1e9+7;
// code begins here
int main(){
fast;
ll t;
cin>>t;
while(t--){
ll n;
cin>>n;
for(ll i=0;i<n;i++)
cout<<1<<" ";
cout<<endl;
}
return 0;
} | [
"sarjun99718@gmail.com"
] | sarjun99718@gmail.com |
c8ecf1a75838ac65f0190509ba58fe4e60ab870a | acabdac77e1fdd2e7758ca360b3475572b591bf1 | /LAB10-C++/q2.cpp | 07f428cc495b34147595f78bf5e497570b224285 | [] | no_license | erlin99/COMP10120-Practicals | d44c21ecaa3399a54ef68fb198ed43c1cc63a4b1 | 9579631bf4fe80e3f851698826e1ae23f18279d4 | refs/heads/master | 2020-04-08T16:58:59.905036 | 2018-11-28T18:19:39 | 2018-11-28T18:19:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,414 | cpp | /*LAB 10 QUESTION 2 Written by Er Lin
Program that demonstrates function overloading creating 4 functions that calculates
the average of 2 numbers.*/
#include <iostream>
using namespace std;
//function averageOfTwo for int values
int averageOfTwo(int x, int y)
{
cout << "Integer average of " << x << " and " << y << " = ";
return (x + y)/2;
}
//function averageOfTwo for long values
long averageOfTwo(long x, long y)
{
cout << "Long average of " << x << " and " << y << " = ";
return (x + y)/2;
}
//function averageOfTwo for float values
float averageOfTwo(float x, float y)
{
cout << "Float average of " << x << " and " << y << " = ";
return (x + y)/2;
}
//function averageOfTwo for float values
double averageOfTwo(double x, double y)
{
cout << "Double average of " << x << " and " << y << " = ";
return (x + y)/2;
}
int main()
{
//depending on the types of integers entered, the program will know which function to use.
//I had to force the third call to have float values, otherwise it would just run the double function
//instead of the float.
cout << '\n' << "Program that calculates the average of 2 numbers. Showing function overloading." << endl;
cout << averageOfTwo(7, 8) << endl;
cout << averageOfTwo(7000000000, 8000000000) << endl;
cout << averageOfTwo((float)0.7, (float)0.3) << endl;
cout << averageOfTwo(1.4123456789, 2.4356721456) << endl;
cout << endl;
}
| [
"er.lin.li.99@gmail.com"
] | er.lin.li.99@gmail.com |
42433fbc61835ca6ef91f82c9880f8817d59b83a | d2a379e1c09823289b6d1559021307e41810341c | /polygon.cpp | 8aa32ce1eff4a44988ffa83ebb613a5700cbbefb | [] | no_license | axelerator/adgr | 308f542ad8e49f2c3339681b483b080fe0087130 | 2b6bfef1e23bde692662f880a196b1c778fb3ebb | refs/heads/master | 2021-01-01T16:45:03.210107 | 2007-04-03T16:15:53 | 2007-04-03T16:15:53 | 1,203,774 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,230 | cpp | //
// C++ Implementation: polygon
//
// Description:
//
//
// Author: Axel Tetzlaff / Timo B. HÃŒbel <axel.tetzlaff@gmx.de / t.h@gmx.com>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "polygon.h"
PolygonRect::PolygonRect(const Vector3D& p1, const Vector3D& p2, const Vector3D& p3, const Vector3D& p4,
Material *m, Scene *s) : Geometry(p1, m, s) {
points.push_back(new Vector3D(p1));
points.push_back(new Vector3D(p2));
points.push_back(new Vector3D(p3));
points.push_back(new Vector3D(p4));
normal = ((p2 - p1) % (p4 - p1)).normalize();
d = -(normal * position);
}
PolygonRect::~PolygonRect() {
}
geovalue PolygonRect::cut(const Vector3D& e, const Vector3D& w, Vector3D &resultPoint, Vector3D &resultNormal) {
geovalue denominator = normal * w;
geovalue numerator = (normal * e) + d;
geovalue s = numerator / -denominator;
if (s < 0.0) return -1.0;
resultNormal = normal;
resultPoint = (w * s) + e;
if (isInside(resultPoint)) {
return (resultPoint - e).length();
}
else {
return -1.0; // Not cut
}
}
bool PolygonRect::shadow(const Vector3D& e, const Vector3D& w, geovalue length) {
geovalue denominator = normal * w;
geovalue numerator = (normal * e) + d;
geovalue s = numerator / -denominator;
if (s <= 0.0) return false;
Vector3D direction = w * s;
if (direction.length() < length) {
return isInside(direction + e);
}
return false;
}
bool PolygonRect::isInside(const Vector3D& p) {
int s = points.size();
for (int i = 0; i < s; ++i) {
int j = i + 1;
if (j == s) {
j = 0;
}
Vector3D vn, vp, pi;
pi = *points[i];
vn = *points[j] - pi;
vp = p - pi;
if ((vn * vp) < 0.0) {
return false;
}
}
return true;
}
void PolygonRect::refract(const Vector3D& p, const Vector3D& s, Vector3D &resultPoint, Vector3D &resultDirection) {
std::cerr << "This should not happen" << std::endl;
}
void PolygonRect::drawGL() {
glColor3dv(material->getDif());
glBegin(GL_LINE_LOOP);
for (int i = 0; i < points.size(); ++i) {
glVertex3d(points[i]->x, points[i]->y, -points[i]->z); // OpenGL has the z-axis reversed
}
glEnd();
}
| [
"axel.tetzlaff@gmx.de"
] | axel.tetzlaff@gmx.de |
54ee014fcd65dc87c9aa1a1c7d32422839448269 | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-lightsail/include/aws/lightsail/model/GetDiskSnapshotResult.h | 5c216058e9d95d474b16b09c58cc3f7dc669551e | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 2,281 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/lightsail/Lightsail_EXPORTS.h>
#include <aws/lightsail/model/DiskSnapshot.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Lightsail
{
namespace Model
{
class AWS_LIGHTSAIL_API GetDiskSnapshotResult
{
public:
GetDiskSnapshotResult();
GetDiskSnapshotResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
GetDiskSnapshotResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>An object containing information about the disk snapshot.</p>
*/
inline const DiskSnapshot& GetDiskSnapshot() const{ return m_diskSnapshot; }
/**
* <p>An object containing information about the disk snapshot.</p>
*/
inline void SetDiskSnapshot(const DiskSnapshot& value) { m_diskSnapshot = value; }
/**
* <p>An object containing information about the disk snapshot.</p>
*/
inline void SetDiskSnapshot(DiskSnapshot&& value) { m_diskSnapshot = std::move(value); }
/**
* <p>An object containing information about the disk snapshot.</p>
*/
inline GetDiskSnapshotResult& WithDiskSnapshot(const DiskSnapshot& value) { SetDiskSnapshot(value); return *this;}
/**
* <p>An object containing information about the disk snapshot.</p>
*/
inline GetDiskSnapshotResult& WithDiskSnapshot(DiskSnapshot&& value) { SetDiskSnapshot(std::move(value)); return *this;}
private:
DiskSnapshot m_diskSnapshot;
};
} // namespace Model
} // namespace Lightsail
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
29c94d83b60e99de0571c5bbedf98935923062c4 | 768316ed72470715e641fda62a9166b610b27350 | /03-CodeChef-Medium/96--Optimal Subset.cpp | 70f56e674d2d13bd32a53b5b430581498f5f3b7a | [] | no_license | dhnesh12/codechef-solutions | 41113bb5922156888d9e57fdc35df89246e194f7 | 55bc7a69f76306bc0c3694180195c149cf951fb6 | refs/heads/master | 2023-03-31T15:42:04.649785 | 2021-04-06T05:38:38 | 2021-04-06T05:38:38 | 355,063,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,161 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long double ld;
const int Maxn = 100005;
int t;
int n;
int w[Maxn];
int X[Maxn], Y[Maxn];
ld Len(int a, int b) { return sqrt(ld(X[a] - X[b]) * (X[a] - X[b]) + ld(Y[a] - Y[b]) * ld(Y[a] - Y[b])); }
bool Ok(ld E)
{
ld res = 0;
vector <int> seq;
seq.push_back(0);
vector <ld> dist;
for (int i = 1; i < n; i++) {
while (seq.size() >= 2)
if (Len(seq[int(seq.size()) - 2], i) - Len(seq.back(), i) >= dist.back() - E * w[seq.back()]) {
res -= (dist.back() - E * w[seq.back()]);
dist.pop_back(); seq.pop_back();
} else break;
dist.push_back(Len(seq.back(), i));
seq.push_back(i);
res += dist.back() - E * w[seq.back()];
if (res + Len(0, i) - E * w[0] >= 0) return true;
}
return false;
}
int main()
{
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d %d", &X[i], &Y[i]);
for (int i = 0; i < n; i++)
scanf("%d", &w[i]);
ld lef = 0, rig = 10e15l;
for (int i = 0; i < 80; i++) {
ld mid = (lef + rig) / 2.0l;
if (Ok(mid)) lef = mid;
else rig = mid;
}
cout << fixed << setprecision(9) << lef << endl;
}
return 0;
} | [
"dhneshwod@gmail.com"
] | dhneshwod@gmail.com |
2d57d053121d6d64f6da892db00655b260605487 | fd5ac88df7af62b7ff56062f3442e22198d3f0c4 | /SRC/Sparse.h | 7586453b8ae667bf96147661c4c487a4c32acb92 | [] | no_license | hi2ska2/g1st | aeec4506ca8dfddd26210e6c0a1e0d603b6a8cd3 | e78db23107b00ea9b4a109a78af7b5e5ec2d97a0 | refs/heads/master | 2020-03-07T10:24:11.106014 | 2018-05-17T02:32:29 | 2018-05-17T02:32:29 | 127,430,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,266 | h | ////////////////////////////////////////////////
// G-1st //
// //
// Copyright 2018 Sung-Min Hong //
// //
// Please see LICENSE for license information //
////////////////////////////////////////////////
// Sparse.h
// A square matrix is understood.
// Since there can be many different forms of a sparse matrix,
// the class Sparse has derived classes.
#ifndef SparseH
#define SparseH
#include "ParseTree.h"
#include "utilities.h"
#include <iostream>
#include <fstream>
#include <map>
#include <math.h>
template<class T>
class Sparse {
public:
Sparse<T>() : _n(0) { }
virtual void show() { std::cout << "Sparse::show()\n"; }
virtual T& operator()(int ii, int ij) = 0;
virtual void clearRow(int ii) = 0;
int getSize() { return _n; }
virtual void getFullColumnMajor(double* p) = 0;
virtual void moveRow(int ii,int jj) = 0;
//virtual void solve(std::vector<T> theVector,std::vector<T> theSolution) = 0;
protected:
int _n;
};
template<class T>
class Triplet : public Sparse<T> {
public:
Triplet<T>() : Sparse<T>() { _contents.clear(); }
virtual void show() {
std::cout << "Triplet::show()\n";
typename std::map<std::pair<int,int>,T>::iterator it;
for (it=_contents.begin(); it!=_contents.end(); ++it)
if (it->second!=0.0) {
std::cout << (it->first).first << " " << (it->first).second << " " << it->second << "\n";
}
}
virtual T& operator()(int ii, int ij) {
if (ii>=this->_n) this->_n = (ii+1);
if (ij>=this->_n) this->_n = (ij+1);
typename std::map<std::pair<int,int>,T>::iterator it;
it = _contents.find(std::pair<int,int>(ii,ij));
if (it == _contents.end()) it = _contents.insert(it,std::pair<std::pair<int,int>,T>(std::pair<int,int>(ii,ij),0.0));
return it->second;
}
virtual void clear() {
_contents.clear();
this->_n = 0;
}
// Implemented on April 4, 2016
virtual void clearRow(int ii) {
//std::cout << "Triplet::clearRow(ii)\n";
typename std::map<std::pair<int,int>,T>::iterator it;
for (it=_contents.begin(); it!=_contents.end(); ++it) {
if ((it->first).first==ii) it->second = 0.0;
}
}
virtual void getFullColumnMajor(double* p) {
int n = this->_n;
for (int ii=0; ii<n*n; ++ii) p[ii] = 0.0;
typename std::map<std::pair<int,int>,T>::iterator it;
for (it=_contents.begin(); it!=_contents.end(); ++it) {
int ii = (it->first).first;
int ij = (it->first).second;
double val = it->second;
p[n*ij+ii] = val; // Column-major order
}
}
virtual void moveRow(int ii,int jj) { // from ii to jj
std::vector<int> col; col.clear();
std::vector<double> val; val.clear();
typename std::map<std::pair<int,int>,T>::iterator it;
for (it=_contents.begin(); it!=_contents.end(); ++it) {
if ((it->first).first==ii) {
col.push_back((it->first).second);
val.push_back(it->second);
it->second = 0.0;
}
}
for (int kk=0; kk<col.size(); ++kk) {
operator()(jj,col[kk]) += val[kk];
}
}
virtual void solve(std::vector<T>& theVector,std::vector<T>& theSolution) {
myReportError("Triplet::solve(theVector,theSolution)");
}
protected:
std::map<std::pair<int,int>,T> _contents;
};
class RealTriplet : public Triplet<double> {
public:
void get_csr_format_1based(int* &prow, int* &icol, double* &ax, int& nz);
void get_csc_format(int* &pcol, int* &irow, double* &ax, int* &map) {
// Empty implementation
}
void get_triplet_format(std::vector<int>& ti,std::vector<int>& tj,std::vector<double>& tx,int& nz)
{
typename std::map<std::pair<int,int>,double>::iterator it;
for (it=_contents.begin(); it!=_contents.end(); ++it) {
if (it->second!=0.0) {
ti.push_back((it->first).first );
tj.push_back((it->first).second);
tx.push_back( it->second );
nz++;
}
}
}
void printMATLAB(std::string fileName,
std::vector<double>& theResidue,
std::vector<double>& theSolution)
{
printMATLAB(fileName);
//
std::string resFileName = fileName + ".res";
std::ofstream resFile(resFileName.c_str());
resFile.precision(17);
for (int ii=0; ii<theResidue.size(); ++ii) {
resFile << theResidue[ii] << "\n";
}
resFile.close();
//
std::string solFileName = fileName + ".sol";
std::ofstream solFile(solFileName.c_str());
solFile.precision(17);
for (int ii=0; ii<theSolution.size(); ++ii) {
solFile << theSolution[ii] << "\n";
}
solFile.close();
}
void printMATLAB(std::string fileName)
{
// ti, tj, tx, nz
std::vector<int> ti;
std::vector<int> tj;
std::vector<double> tx;
int nz = 0;
get_triplet_format(ti,tj,tx,nz);
std::ofstream outputFile(fileName.c_str());
outputFile.precision(17);
for (int ii=0; ii<nz; ++ii) {
outputFile << ti[ii]+1 << " " << tj[ii]+1 << " " << tx[ii] << "\n";
}
outputFile.close();
}
void solve(std::vector<double>& theVector,std::vector<double>& theSolution);
void solve(std::vector<double>& theVector,std::vector<double>& theSolution,
ArgList* solverArgList);
};
#endif
| [
"smhong@gist.ac.kr"
] | smhong@gist.ac.kr |
de31df2170bb41c11d79a80e4de637695c72481d | 9cd63216d970c4f67823421a3d74287b073691c0 | /sycl/test/multisource/multisource.cpp | 4269e7064ab7374989ab2ca3192d75dd8adc9412 | [
"NCSA",
"LLVM-exception",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | premanandrao/llvm | ba2aa27913ca2bbf104f21674c7335b25e7c9e63 | c13cb8df84418cb5d682f3bbee89090ebb0d00be | refs/heads/sycl | 2023-08-21T14:31:54.250951 | 2019-05-24T18:35:11 | 2019-05-30T17:43:19 | 189,472,052 | 0 | 1 | null | 2020-06-24T06:46:52 | 2019-05-30T19:39:52 | C++ | UTF-8 | C++ | false | false | 2,802 | cpp | //==--------------- multisource.cpp ----------------------------------------==//
//
// 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
//
//===----------------------------------------------------------------------===//
// Separate kernel sources and host code sources
// RUN: %clang -std=c++11 -fsycl -c -o %t.kernel.o %s -DINIT_KERNEL -DCALC_KERNEL
// RUN: %clang -std=c++11 -fsycl -c -o %t.main.o %s -DMAIN_APP
// RUN: %clang -std=c++11 -fsycl %t.kernel.o %t.main.o -o %t.fat -lstdc++ -lOpenCL -lsycl
// RUN: env SYCL_DEVICE_TYPE=HOST %t.fat
// RUN: %CPU_RUN_PLACEHOLDER %t.fat
// RUN: %GPU_RUN_PLACEHOLDER %t.fat
// RUN: %ACC_RUN_PLACEHOLDER %t.fat
// Multiple sources with kernel code
// RUN: %clang -std=c++11 -fsycl -c -o %t.init.o %s -DINIT_KERNEL
// RUN: %clang -std=c++11 -fsycl -c -o %t.calc.o %s -DCALC_KERNEL
// RUN: %clang -std=c++11 -fsycl -c -o %t.main.o %s -DMAIN_APP
// RUN: %clang -std=c++11 -fsycl %t.init.o %t.calc.o %t.main.o -o %t.fat -lstdc++ -lOpenCL -lsycl
// RUN: env SYCL_DEVICE_TYPE=HOST %t.fat
// RUN: %CPU_RUN_PLACEHOLDER %t.fat
// RUN: %GPU_RUN_PLACEHOLDER %t.fat
// RUN: %ACC_RUN_PLACEHOLDER %t.fat
#include <CL/sycl.hpp>
#include <iostream>
using namespace cl::sycl;
#ifdef MAIN_APP
void init_buf(queue &q, buffer<int, 1> &b, range<1> &r, int i) ;
#elif INIT_KERNEL
void init_buf(queue &q, buffer<int, 1> &b, range<1> &r, int i){
q.submit([&](handler &cgh) {
auto B = b.get_access<access::mode::write>(cgh);
cgh.parallel_for<class init>(r, [=](id<1> index) { B[index] = i; });
});
}
#endif
#ifdef MAIN_APP
void calc_buf(queue &q, buffer<int, 1> &a, buffer<int, 1> &b,
buffer<int, 1> &c, range<1> &r);
#elif CALC_KERNEL
void calc_buf(queue &q, buffer<int, 1> &a, buffer<int, 1> &b,
buffer<int, 1> &c, range<1> &r){
q.submit([&](handler &cgh) {
auto A = a.get_access<access::mode::read>(cgh);
auto B = b.get_access<access::mode::read>(cgh);
auto C = c.get_access<access::mode::write>(cgh);
cgh.parallel_for<class calc>(
r, [=](id<1> index) { C[index] = A[index] - B[index]; });
});
}
#endif
#ifdef MAIN_APP
const size_t N = 100;
int main() {
{
queue q;
range<1> r(N);
buffer<int, 1> a(r);
buffer<int, 1> b(r);
buffer<int, 1> c(r);
init_buf(q, a, r, 2);
init_buf(q, b, r, 1);
calc_buf(q, a, b, c, r);
auto C = c.get_access<access::mode::read>();
for (size_t i = 0; i < N; i++) {
if (C[i] != 1) {
std::cout << "Wrong value " << C[i] << " for element " << i
<< std::endl;
return -1;
}
}
}
std::cout << "Done!" << std::endl;
return 0;
}
#endif
| [
"vladimir.lazarev@intel.com"
] | vladimir.lazarev@intel.com |
c9e9e8c94226906433ecb4f356a63c535f5dc370 | cccfb7be281ca89f8682c144eac0d5d5559b2deb | /chrome/browser/new_tab_page/modules/safe_browsing/safe_browsing_handler.cc | 3c24628764b3bbb7a684a5cf1b05febf8f70f4f8 | [
"BSD-3-Clause"
] | permissive | SREERAGI18/chromium | 172b23d07568a4e3873983bf49b37adc92453dd0 | fd8a8914ca0183f0add65ae55f04e287543c7d4a | refs/heads/master | 2023-08-27T17:45:48.928019 | 2021-11-11T22:24:28 | 2021-11-11T22:24:28 | 428,659,250 | 1 | 0 | BSD-3-Clause | 2021-11-16T13:08:14 | 2021-11-16T13:08:14 | null | UTF-8 | C++ | false | false | 5,749 | cc | // Copyright 2021 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/new_tab_page/modules/safe_browsing/safe_browsing_handler.h"
#include "base/metrics/field_trial_params.h"
#include "base/time/time.h"
#include "chrome/browser/new_tab_page/modules/safe_browsing/safe_browsing_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/safe_browsing/safe_browsing_metrics_collector_factory.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/core/browser/safe_browsing_metrics_collector.h"
#include "components/safe_browsing/core/common/safe_browsing_policy_handler.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/search/ntp_features.h"
using ::safe_browsing::IsEnhancedProtectionEnabled;
using ::safe_browsing::SafeBrowsingMetricsCollectorFactory;
using ::safe_browsing::SafeBrowsingPolicyHandler;
namespace ntp {
namespace {
// Get end time for last cooldown. Returns epoch + cooldown_period if no
// cooldown happened.
base::Time GetLastCooldownEndTime(PrefService* pref_service) {
base::Time cooldown_start = base::Time::FromDeltaSinceWindowsEpoch(
base::Seconds(pref_service->GetInt64(
prefs::kSafeBrowsingModuleLastCooldownStartAt)));
// The field param is passed as a double, to allow manual testing using a
// fraction of a day as cooldown.
double cooldown_days = base::GetFieldTrialParamByFeatureAsDouble(
ntp_features::kNtpSafeBrowsingModule,
ntp_features::kNtpSafeBrowsingModuleCooldownPeriodDaysParam,
/*default_value=*/30.0);
base::TimeDelta cooldown_period = base::Seconds(static_cast<int>(
cooldown_days * base::Time::kHoursPerDay * base::Time::kSecondsPerHour));
return cooldown_start + cooldown_period;
}
void SetModuleCooldownPrefs(PrefService* pref_service,
int64_t cooldown_start_time,
int module_shown_count) {
pref_service->SetInt64(prefs::kSafeBrowsingModuleLastCooldownStartAt,
cooldown_start_time);
pref_service->SetInteger(prefs::kSafeBrowsingModuleShownCount,
module_shown_count);
}
} // namespace
SafeBrowsingHandler::SafeBrowsingHandler(
mojo::PendingReceiver<ntp::safe_browsing::mojom::SafeBrowsingHandler>
handler,
Profile* profile)
: handler_(this, std::move(handler)),
metrics_collector_(
SafeBrowsingMetricsCollectorFactory::GetForProfile(profile)),
pref_service_(profile->GetPrefs()),
saved_last_cooldown_start_time_(0),
saved_module_shown_count_(0) {}
SafeBrowsingHandler::~SafeBrowsingHandler() = default;
void SafeBrowsingHandler::CanShowModule(CanShowModuleCallback callback) {
bool managed =
SafeBrowsingPolicyHandler::IsSafeBrowsingProtectionLevelSetByPolicy(
pref_service_);
bool already_enabled = IsEnhancedProtectionEnabled(*pref_service_);
bool module_already_opened =
pref_service_->GetBoolean(prefs::kSafeBrowsingModuleOpened);
base::Time cooldown_end = GetLastCooldownEndTime(pref_service_);
// Do not show the module if Safe Browsing protection level is controlled by
// policy, or is already enabled, if the user has clicked on the module button
// earlier, or if the user is in cooldown.
if (managed || already_enabled || module_already_opened ||
(base::Time::Now() < cooldown_end)) {
std::move(callback).Run(false);
return;
}
absl::optional<base::Time> latest_event_time =
metrics_collector_->GetLatestSecuritySensitiveEventTimestamp();
// Do not show if there is no security sensitive event after the latest
// cooldown.
if (!latest_event_time.has_value() || latest_event_time < cooldown_end) {
std::move(callback).Run(false);
return;
}
int module_shown_count =
pref_service_->GetInteger(prefs::kSafeBrowsingModuleShownCount);
int module_shown_count_max = base::GetFieldTrialParamByFeatureAsInt(
ntp_features::kNtpSafeBrowsingModule,
ntp_features::kNtpSafeBrowsingModuleCountMaxParam,
/*default_value=*/5);
// Start cooldown if module has been shown module_shown_count_max times.
if (module_shown_count + 1 >= module_shown_count_max) {
SetModuleCooldownPrefs(
pref_service_, base::Time::Now().ToDeltaSinceWindowsEpoch().InSeconds(),
/*module_shown_count=*/0);
} else {
pref_service_->SetInteger(prefs::kSafeBrowsingModuleShownCount,
module_shown_count + 1);
}
std::move(callback).Run(true);
}
void SafeBrowsingHandler::ProcessModuleClick() {
pref_service_->SetBoolean(prefs::kSafeBrowsingModuleOpened, true);
}
void SafeBrowsingHandler::DismissModule() {
saved_last_cooldown_start_time_ =
pref_service_->GetInt64(prefs::kSafeBrowsingModuleLastCooldownStartAt);
saved_module_shown_count_ =
pref_service_->GetInteger(prefs::kSafeBrowsingModuleShownCount);
SetModuleCooldownPrefs(
pref_service_, base::Time::Now().ToDeltaSinceWindowsEpoch().InSeconds(),
/*module_shown_count=*/0);
}
void SafeBrowsingHandler::RestoreModule() {
SetModuleCooldownPrefs(pref_service_, saved_last_cooldown_start_time_,
saved_module_shown_count_);
}
// static
void SafeBrowsingHandler::RegisterProfilePrefs(PrefRegistrySimple* registry) {
registry->RegisterIntegerPref(prefs::kSafeBrowsingModuleShownCount, 0);
registry->RegisterInt64Pref(prefs::kSafeBrowsingModuleLastCooldownStartAt, 0);
registry->RegisterBooleanPref(prefs::kSafeBrowsingModuleOpened, false);
}
} // namespace ntp
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
7a5d804d4578653248c70c92c896549b7372f5a1 | 5a2349399fa9d57c6e8cc6e0f7226d683391a362 | /src/qt/qtbase/src/3rdparty/harfbuzz-ng/src/hb-shaper-list.hh | 5713e057a0329c2f6dfd0c6b936497e7997a56ce | [
"LGPL-2.1-only",
"GPL-3.0-only",
"LicenseRef-scancode-digia-qt-commercial",
"Qt-LGPL-exception-1.1",
"LicenseRef-scancode-digia-qt-preview",
"LGPL-2.0-or-later",
"GFDL-1.3-only",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"MIT-Modern-Variant",
"LicenseRef-scancode-unknown-license-re... | permissive | aharthcock/phantomjs | e70f3c379dcada720ec8abde3f7c09a24808154c | 7d7f2c862347fbc7215c849e790290b2e07bab7c | refs/heads/master | 2023-03-18T04:58:32.428562 | 2023-03-14T05:52:52 | 2023-03-14T05:52:52 | 24,828,890 | 0 | 0 | BSD-3-Clause | 2023-03-14T05:52:53 | 2014-10-05T23:38:56 | C++ | UTF-8 | C++ | false | false | 1,861 | hh | /*
* Copyright © 2012 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Behdad Esfahbod
*/
#ifndef HB_SHAPER_LIST_HH
#define HB_SHAPER_LIST_HH
#endif /* HB_SHAPER_LIST_HH */ /* Dummy header guards */
/* v--- Add new shapers in the right place here. */
#ifdef HAVE_GRAPHITE2
/* Only picks up fonts that have a "Silf" table. */
HB_SHAPER_IMPLEMENT (graphite2)
#endif
#ifdef HAVE_CORETEXT
/* Only picks up fonts that have a "mort" or "morx" table. */
HB_SHAPER_IMPLEMENT (coretext)
#endif
#ifdef HAVE_OT
HB_SHAPER_IMPLEMENT (ot) /* <--- This is our main OpenType shaper. */
#endif
#ifdef HAVE_HB_OLD
HB_SHAPER_IMPLEMENT (old)
#endif
#ifdef HAVE_ICU_LE
HB_SHAPER_IMPLEMENT (icu_le)
#endif
#ifdef HAVE_UNISCRIBE
HB_SHAPER_IMPLEMENT (uniscribe)
#endif
#ifdef HAVE_FALLBACK
HB_SHAPER_IMPLEMENT (fallback) /* <--- This should be last. */
#endif
| [
"ariya.hidayat@gmail.com"
] | ariya.hidayat@gmail.com |
07a650d18a7d8c42b92255b31398445724ae4146 | cfa27073eadacfb581a0ce09d391272e2d764fc3 | /src/archon/image/impl/comp_types.hpp | 14a9e06cddfb1fb7aa96798444d306dae6042734 | [] | no_license | kspangsege/archon | e1b5cd2413cef95782ee8c8185be0086289fa318 | d8c323efd2d7914cc96d832a070f31168c4b847b | refs/heads/master | 2023-09-01T02:58:03.071535 | 2023-08-31T18:15:41 | 2023-08-31T19:50:37 | 15,814,007 | 2 | 0 | null | 2023-09-13T10:16:58 | 2014-01-11T00:41:43 | C++ | UTF-8 | C++ | false | false | 2,199 | hpp | // This file is part of the Archon project, a suite of C++ libraries.
//
// Copyright (C) 2022 Kristian Spangsege <kristian.spangsege@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.
#ifndef ARCHON_X_IMAGE_X_IMPL_X_COMP_TYPES_HPP
#define ARCHON_X_IMAGE_X_IMPL_X_COMP_TYPES_HPP
/// \file
#include <type_traits>
#include <limits>
#include <algorithm>
#include <archon/core/integer.hpp>
namespace archon::image::impl {
template<class T> constexpr int get_bit_width() noexcept;
// Implementation
template<class T> constexpr int get_bit_width() noexcept
{
if constexpr (core::is_integer<T>()) {
return std::min(core::int_inner_width<T>(), core::int_inner_width<core::unsigned_type<T>>());
}
else {
static_assert(std::is_floating_point_v<T>);
using lim_type = std::numeric_limits<T>;
static_assert(lim_type::is_specialized);
return (lim_type::digits + core::int_find_msb_pos(unsigned(lim_type::max_exponent) -
unsigned(lim_type::min_exponent)) + 1);
}
}
} // namespace archon::image::impl
#endif // ARCHON_X_IMAGE_X_IMPL_X_COMP_TYPES_HPP
| [
"kristian.spangsege@gmail.com"
] | kristian.spangsege@gmail.com |
972663ef98065467be7db62a733f7dcdda1bff3c | 5fdd476476fbaf3b6ea859691c3afcd17eab5001 | /MORNING/С++/Iterator/Iterator/Iterator.h | 4e2ae7c3605383c917a1f486cffcff8d5387dec3 | [] | no_license | itstepP21014/PirozhnikDZ | 9c9e854a2a7cf757016161de982227e5fafcc6d8 | 94f52c304923bd6d2f47531592368135ab2c2541 | refs/heads/master | 2021-01-23T19:13:23.408395 | 2016-11-19T09:41:15 | 2016-11-19T09:41:15 | 27,079,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,354 | h | #pragma once
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
typedef void* INT;
class List
{
private:
struct Node
{
void *data;
Node *next;
Node *previous;
};
public:
class iterator {
private:
Node* current;
public:
iterator(Node* arg) : current(arg) {};
iterator() : iterator(nullptr) {};
INT & operator*() {
if (current == nullptr) {
throw invalid_argument(
"In List::iterator::operator*() : invalid iterator");
}
return current->data;
}
iterator& operator++() {
if (current == nullptr) {
throw invalid_argument(
"In List::iterator::operator*() : invalid iterator");
}
current = current->next;
return (*this);
}
bool operator==(const iterator &i) const{
return current == i.current;
}
bool operator!=(const iterator &i) const{
return current != i.current;
}
}; // end of List::iterator
iterator begin() {
return iterator(Begin);
}
iterator end() {
return iterator(nullptr);
}
Node *Begin;
Node *End;
int element_count;
int element_size;
public:
size_t ElementCount()
{
return element_count;
}
// standart
List &PushFront(void *element);
List &PopFront();
List &PushEnd(void *element);
List &PopEnd();
Node *operator[](int index);
List &operator=(const List &source);
List &Delete(int index);
List &Reverse();
// ctor
List(int size_of_element) : element_size(size_of_element), element_count(0), Begin(nullptr), End(nullptr) {};
List(const List &orig);
iterator find(void* value) {
Node* current;
current = Begin;
while (current != nullptr) {
if (current->data == value) {
return iterator(current);
}
current = current->next;
}
return iterator(current);
}
// dtor
~List();
};
#include <new>
// standart
List &List::PushFront(void *element)
{
Node *new_element = new Node;
new_element->data = new char[element_size];
new_element->data = element;
// connect
new_element->previous = nullptr;
new_element->next = Begin;
if (Begin != nullptr)
Begin->previous = new_element; //ïðÚâÿçûâà åì ïåðâûé ÜëåìåÃò ê Ãîâîìó
Begin = new_element; //ïåðåìåÞà åì Begin Ãà Ãà ÷à ëî
if (End == nullptr)
End = new_element; //ñòà âÚì êîÃåö Ãà Ãîâûé ÜëåìåÃò
++element_count;
return *this;
}
List &List::PopFront()
{
if (element_count == 0)
throw 0;
Node *temp = Begin;
Begin = temp->next;
//delete temp->data;????????
delete temp;
if (element_count == 1)
End = nullptr;
else
Begin->previous = nullptr;
--element_count;
return *this;
}
List &List::PushEnd(void *element)
{
Node *new_element = new Node;
new_element->data = new char[element_size];
new_element->data = element;
new_element->next = nullptr;
new_element->previous = End;
End->next = new_element;
End = new_element;
if (element_count == 0)
Begin = new_element;
++element_count;
return *this;
}
List &List::PopEnd()
{
if (element_count == 0)
throw 0;
Node *temp = End;
End->next = nullptr;
if (element_count = 1)
{
Begin = nullptr;
End = nullptr;
}
else
End = End->previous;
//delete temp->data;???????
delete temp;
--element_count;
return *this;
}
List::Node *List::operator[](int index)
{
if (index >= element_count)
throw 1;
Node *temp;
if (index <= element_count / 2)
{
temp = End;
for (int i = 0; i < index; i++)
temp = temp->previous;
}
else
{
temp = Begin;
for (int i = element_count - 1; i > index; i--)
temp = temp->next;
}
return temp;
}
List &List::operator=(const List &source)
{
while (element_count--)
PopFront();
element_count = source.element_count;
element_size = source.element_size;
Node *temp = source.Begin;
for (int i = 0; i < element_count; i++, temp = temp->next)
{
PushEnd(temp->data);
}
return *this;
}
List &List::Delete(int index)
{
if (index >= element_count || index < 0)
throw 1;
if (index == 0)
PopFront();
else if (index == element_count - 1)
PopEnd();
else
{
Node *temp = this->operator[](index);
Node *help_next = temp->next;
(temp->next)->previous = temp->previous;
(temp->previous)->next = help_next;
delete temp;
}
return *this;
}
List &List::Reverse()
{
Node *temp = this->Begin, *temp_previous;
this->Begin = this->End;
this->End = temp;
for (int i = 0; i < element_count; i++, temp = temp->next)
{
temp_previous = this->Begin->previous;
this->Begin->previous = this->Begin->next;
this->Begin->next = temp_previous;
}
return *this;
}
// ctor
List::List(const List &orig)
{
element_size = orig.element_size;
element_count = orig.element_count;
Node *temp = Begin;
for (int i = 0; i < element_count; i++, temp = temp->next)
{
PushEnd(temp->data);
}
}
// dtor
List::~List()
{
while (element_count)
PopFront();
}
#include <iostream>
#include <conio.h>
#include <new>
using namespace std;
int main()
{
List a_int(sizeof(int));
for (int i = 0; i < 7; i++)
a_int.PushFront((INT)i);
List::iterator p = a_int.find((INT)4);
List::iterator q;
for (; p != a_int.end(); ++p) {
*p = (INT)8;
cout << ((int)*p) << endl;
}
return 0;
int size_a = a_int.ElementCount();
cout << "element count in a_int = " << size_a << endl;
a_int[6]->data = (void*)20;
for (int i = 0; i < size_a; i++)
cout << (int)a_int[i]->data << ' ';
_getch();
return 0;
} | [
"pirozhenka@yandex.ru"
] | pirozhenka@yandex.ru |
0c254f86ba5997eaa4c18b67c07532d6debe2448 | 3a8ae805bdf88377de52797dc4ccb19a6e5e89cd | /firstgui/mainwindow.cpp | 8ca2e03b096fcb70e6a3b372db41e521ad7151b5 | [] | no_license | MacroGu/qtProject | 9c3283568aafa201ed4af4bd551ec65fe691a054 | e1ca9e4330e58e84b60d6c4cc45ed72ff2a9c982 | refs/heads/master | 2021-08-26T07:06:36.855370 | 2017-11-22T02:23:48 | 2017-11-22T02:23:48 | 111,230,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 833 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QFontDialog>
#include <QFont>
#include <QColorDialog>
#include <QColor>
#include <QPrintDialog>
#include <QPrinter>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionColor_triggered()
{
QColor color = QColorDialog::getColor(Qt::white, this, "Choose Color");
if (color.isValid())
{
ui->textEdit->setPalette(QPalette(color));
}
}
void MainWindow::on_actionPeint_triggered()
{
QPrinter printer ;
printer.setPrinterName("desierd printer name");
QPrintDialog dialog(&printer,this);
if(dialog.exec() == QDialog::Rejected) return;
ui->textEdit->print(&printer);
}
| [
"macrogu@qq.com"
] | macrogu@qq.com |
2532c4fae54b602c2423b8adc14bdf92567946a6 | a1f384ec1125c57f4123ac8d6b8a65b072d1b46f | /src/ofApp.cpp | 11f2835500f67d27c4171067545817e954490e33 | [] | no_license | patriciogonzalezvivo/ColumbiaLibrary | a2ade0ee356e1088a11dcc55dfd9c938c9a308b3 | f5586aca1f923b2dc4c359cc2ccc53bd8e6ab51c | refs/heads/master | 2016-09-06T18:02:27.737607 | 2013-11-26T04:39:49 | 2013-11-26T04:39:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,927 | cpp | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
project = new Glyphs();
project->setup();
project->play();
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if( key == OF_KEY_F1){
project->stop();
project = NULL;
project = new InBoxes();
project->setup();
project->play();
} else if( key == OF_KEY_F2){
project->stop();
project = NULL;
project = new Dimentions();
project->setup();
project->play();
} else if( key == OF_KEY_F3){
project->stop();
project = NULL;
project = new Glyphs();
project->setup();
project->play();
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| [
"patriciogonzalezvivo@gmail.com"
] | patriciogonzalezvivo@gmail.com |
873e895cf041b719b65f31f64e18a747495d1b6c | 3ac3bc4f7ea5fe971431dbe3cb66777a0ee9f639 | /rectangles.cpp | 7dfe8855d624c0e801d1f006276cab9825cc7f40 | [] | no_license | vsivatej/spoj | b23118bf8b30cc9edaa00ff323d183b90a616f2d | e1cdc4b79979cc058ee642b86e1f2b90071598f6 | refs/heads/master | 2022-10-13T11:40:59.330486 | 2020-06-11T12:09:29 | 2020-06-11T12:09:29 | 263,045,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 217 | cpp | #include <iostream>
#include <cmath>
using namespace std;
int main(){
int n,ans,c=0;
cin>>n;
ans=floor(sqrt(n));
for(int i=1;i<=floor(sqrt(n));i++)
for(int j=i+1;i*j<=n;j++)
c++;
ans+=c;
cout<<ans<<endl;
}
| [
"mail2vrag@gmail.com"
] | mail2vrag@gmail.com |
f46f52181e9d1bf1076a025e886bd5da5eb86f63 | 23c6e6f35680bee885ee071ee123870c3dbc1e3d | /test/libcxx/containers/reverse.pass.cpp | e9a18df67aa798d8fd4087fac7594e17e53b3f92 | [] | no_license | paradise-fi/divine | 3a354c00f39ad5788e08eb0e33aff9d2f5919369 | d47985e0b5175a7b4ee506fb05198c4dd9eeb7ce | refs/heads/master | 2021-07-09T08:23:44.201902 | 2021-03-21T14:24:02 | 2021-03-21T14:24:02 | 95,647,518 | 15 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,209 | cpp | /* TAGS: c++ fin */
/* CC_OPTS: -std=c++2a */
/* VERIFY_OPTS: -o nofail:malloc */
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <list>
// void reverse();
#include <list>
#include <cassert>
#include "test_macros.h"
#include "min_allocator.h"
int main(int, char**)
{
{
int a1[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int a2[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
std::list<int> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
c1.reverse();
assert(c1 == std::list<int>(a2, a2+sizeof(a2)/sizeof(a2[0])));
}
#if TEST_STD_VER >= 11
{
int a1[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int a2[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
std::list<int, min_allocator<int>> c1(a1, a1+sizeof(a1)/sizeof(a1[0]));
c1.reverse();
assert((c1 == std::list<int, min_allocator<int>>(a2, a2+sizeof(a2)/sizeof(a2[0]))));
}
#endif
return 0;
}
| [
"xkorenc1@fi.muni.cz"
] | xkorenc1@fi.muni.cz |
ed34d6d0bb36d6cd75b4272229e32464e66247c4 | 274ed91b38ad98978bb30df850ae2c7e26f9dabe | /opus_lib/src/main/cpp/native-lib.cpp | fffa80444c36fe197c22a3ff0e7fe35465856a5c | [] | no_license | sws1011/Opus | 40ff374c02130e66a68bed758c3309b22e652b34 | d4cfc2bae7dd39f988e8ce69ccd1d6113269cd76 | refs/heads/master | 2020-05-24T09:09:32.441134 | 2019-07-09T01:19:33 | 2019-07-09T01:19:33 | 187,198,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,786 | cpp | #include <jni.h>
#include <string>
#include <opus.h>
#include "_android_log_print.h"
extern "C"
JNIEXPORT jlong JNICALL
Java_com_opus_OpusUtil_createEncoder(JNIEnv *env, jclass type, jint sampleRateHz, jint channel,
jint complexity) {
int error;
OpusEncoder *opusEncoder = opus_encoder_create(sampleRateHz, channel, OPUS_APPLICATION_RESTRICTED_LOWDELAY, &error);
if (error == OPUS_OK) {
opus_encoder_ctl(opusEncoder, OPUS_SET_COMPLEXITY(complexity));
opus_encoder_ctl(opusEncoder, OPUS_SET_VBR(0));
opus_encoder_ctl(opusEncoder, OPUS_SET_VBR_CONSTRAINT(true));
opus_encoder_ctl(opusEncoder, OPUS_SET_SIGNAL(OPUS_SIGNAL_VOICE));
opus_encoder_ctl(opusEncoder, OPUS_SET_LSB_DEPTH(16));
opus_encoder_ctl(opusEncoder, OPUS_SET_DTX(0));
opus_encoder_ctl(opusEncoder, OPUS_SET_INBAND_FEC(0));
opus_encoder_ctl(opusEncoder, OPUS_SET_BITRATE(16000));
opus_encoder_ctl(opusEncoder, OPUS_SET_PACKET_LOSS_PERC(0));
return reinterpret_cast<jlong>(opusEncoder);
}
return -1;
}
extern "C"
JNIEXPORT jlong JNICALL
Java_com_opus_OpusUtil_createDecoder(JNIEnv *env, jclass type, jint sampleRateHz, jint channel) {
int error;
OpusDecoder *opusDecoder = opus_decoder_create(sampleRateHz, channel, &error);
if (OPUS_OK == error) {
return reinterpret_cast<jlong>(opusDecoder);
}
return -1;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_opus_OpusUtil_destroyEncoder(JNIEnv *env, jclass type, jlong handle) {
OpusEncoder *opusEncoder = (OpusEncoder *) handle;
if (handle <= 0) {
return;
}
opus_encoder_destroy(opusEncoder);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_opus_OpusUtil_destroyDecoder(JNIEnv *env, jclass type, jlong handle) {
OpusDecoder *opusDecoder = (OpusDecoder *) handle;
if (handle <= 0) {
return;
}
opus_decoder_destroy(opusDecoder);
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_opus_OpusUtil_encode(JNIEnv *env, jclass type, jlong handle, jshortArray in_, jint offset,
jbyteArray out_) {
jshort *in = env->GetShortArrayElements(in_, NULL);
jsize inLen = env->GetArrayLength(in_);
jbyte *out = env->GetByteArrayElements(out_, NULL);
jsize outLen = env->GetArrayLength(out_);
OpusEncoder *opusEncoder = (OpusEncoder *) handle;
if (handle <= 0 || !out || !in) {
LOGD("åå§åæ°æ®é误---------");
return -1;
}
// int bitrate;
// opus_encoder_ctl(opusEncoder, OPUS_GET_BITRATE(&bitrate));
// int size = opus_packet_get_samples_per_frame(reinterpret_cast<const unsigned char *>(out), 8000);
// LOGD("opus_encoder_get_size = %d---------", bitrate);
int encode = opus_encode(opusEncoder, in, inLen, reinterpret_cast<unsigned char *>(out), outLen);
env->ReleaseShortArrayElements(in_, in, 0);
env->ReleaseByteArrayElements(out_, out, 0);
return encode;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_opus_OpusUtil_decode(JNIEnv *env, jclass type, jlong handle, jbyteArray encode_, jshortArray out_) {
jbyte *encode = env->GetByteArrayElements(encode_, NULL);
jshort *out = env->GetShortArrayElements(out_, NULL);
jsize encodeLen = env->GetArrayLength(encode_);
jsize outLen = env->GetArrayLength(out_);
OpusDecoder *opusDecoder = (OpusDecoder *) handle;
if (handle <= 0 || !encode || !out)
return -1;
if (encodeLen <= 0 || outLen <= 0) {
return -1;
}
int decode = opus_decode(opusDecoder, reinterpret_cast<const unsigned char *>(encode), encodeLen, out, outLen, 0);
env->ReleaseByteArrayElements(encode_, encode, 0);
env->ReleaseShortArrayElements(out_, out, 0);
return decode;
} | [
"397141365@qq.com"
] | 397141365@qq.com |
8140ceb8f1f0972510ad85c05362353c32f36836 | 19907e496cfaf4d59030ff06a90dc7b14db939fc | /POC/oracle_dapp/node_modules/wrtc/third_party/webrtc/include/chromium/src/content/renderer/media/webaudio_capturer_source.h | d5b3bb5b554514d8d75ee909bf8ab23f63914279 | [
"BSD-2-Clause"
] | permissive | ATMatrix/demo | c10734441f21e24b89054842871a31fec19158e4 | e71a3421c75ccdeac14eafba38f31cf92d0b2354 | refs/heads/master | 2020-12-02T20:53:29.214857 | 2017-08-28T05:49:35 | 2017-08-28T05:49:35 | 96,223,899 | 8 | 4 | null | 2017-08-28T05:49:36 | 2017-07-04T13:59:26 | JavaScript | UTF-8 | C++ | false | false | 4,404 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_RENDERER_MEDIA_WEBAUDIO_CAPTURER_SOURCE_H_
#define CONTENT_RENDERER_MEDIA_WEBAUDIO_CAPTURER_SOURCE_H_
#include <stddef.h>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "media/audio/audio_parameters.h"
#include "media/base/audio_bus.h"
#include "media/base/audio_capturer_source.h"
#include "media/base/audio_push_fifo.h"
#include "third_party/WebKit/public/platform/WebAudioDestinationConsumer.h"
#include "third_party/WebKit/public/platform/WebMediaStreamSource.h"
#include "third_party/WebKit/public/platform/WebVector.h"
namespace content {
class WebRtcLocalAudioTrack;
// WebAudioCapturerSource is the missing link between
// WebAudio's MediaStreamAudioDestinationNode and WebRtcLocalAudioTrack.
//
// 1. WebKit calls the setFormat() method setting up the basic stream format
// (channels, and sample-rate).
// 2. consumeAudio() is called periodically by WebKit which dispatches the
// audio stream to the WebRtcLocalAudioTrack::Capture() method.
class WebAudioCapturerSource
: public base::RefCountedThreadSafe<WebAudioCapturerSource>,
public blink::WebAudioDestinationConsumer {
public:
explicit WebAudioCapturerSource(
const blink::WebMediaStreamSource& blink_source);
// WebAudioDestinationConsumer implementation.
// setFormat() is called early on, so that we can configure the audio track.
void setFormat(size_t number_of_channels, float sample_rate) override;
// MediaStreamAudioDestinationNode periodically calls consumeAudio().
// Called on the WebAudio audio thread.
void consumeAudio(const blink::WebVector<const float*>& audio_data,
size_t number_of_frames) override;
// Called when the WebAudioCapturerSource is hooking to a media audio track.
// |track| is the sink of the data flow. |source_provider| is the source of
// the data flow where stream information like delay, volume, key_pressed,
// is stored.
void Start(WebRtcLocalAudioTrack* track);
// Called when the media audio track is stopping.
void Stop();
protected:
friend class base::RefCountedThreadSafe<WebAudioCapturerSource>;
~WebAudioCapturerSource() override;
private:
// Called by AudioPushFifo zero or more times during the call to
// consumeAudio(). Delivers audio data with the required buffer size to the
// track.
void DeliverRebufferedAudio(const media::AudioBus& audio_bus,
int frame_delay);
// Removes this object from a blink::WebMediaStreamSource with which it
// might be registered. The goal is to avoid dangling pointers.
void removeFromBlinkSource();
// Used to DCHECK that some methods are called on the correct thread.
base::ThreadChecker thread_checker_;
// The audio track this WebAudioCapturerSource is feeding data to.
// WebRtcLocalAudioTrack is reference counted, and owning this object.
// To avoid circular reference, a raw pointer is kept here.
WebRtcLocalAudioTrack* track_;
media::AudioParameters params_;
// Flag to help notify the |track_| when the audio format has changed.
bool audio_format_changed_;
// A wrapper used for providing audio to |fifo_|.
scoped_ptr<media::AudioBus> wrapper_bus_;
// Takes in the audio data passed to consumeAudio() and re-buffers it into 10
// ms chunks for the track. This ensures each chunk of audio delivered to the
// track has the required buffer size, regardless of the amount of audio
// provided via each consumeAudio() call.
media::AudioPushFifo fifo_;
// Used to pass the reference timestamp between DeliverDecodedAudio() and
// DeliverRebufferedAudio().
base::TimeTicks current_reference_time_;
// Synchronizes HandleCapture() with AudioCapturerSource calls.
base::Lock lock_;
bool started_;
// This object registers with a blink::WebMediaStreamSource. We keep track of
// that in order to be able to deregister before stopping the audio track.
blink::WebMediaStreamSource blink_source_;
DISALLOW_COPY_AND_ASSIGN(WebAudioCapturerSource);
};
} // namespace content
#endif // CONTENT_RENDERER_MEDIA_WEBAUDIO_CAPTURER_SOURCE_H_
| [
"steven.jun.liu@qq.com"
] | steven.jun.liu@qq.com |
12be8ef4fc01f72b4ecd4b6c8606c6afd7e98eba | b0a31edabc9d4bd939cb853a254892089374ad66 | /CocosStudy/Contents/Extra/08. Draw Line/Classes/HelloWorldScene.h | 97846c05b0929744b704ae7b65050681d4bcc5ab | [
"MIT"
] | permissive | 2302053453/MyStudy | e31201d40cc701c9cc4692b60f132fec3e4bf91a | 229c431c0ef4ab40b52d37729b049c69de959166 | refs/heads/master | 2021-06-04T05:33:52.733762 | 2016-05-06T01:54:28 | 2016-05-06T01:54:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | h | #ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
class HelloWorld : public cocos2d::LayerColor
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override;
void NewDraw();
void PreviousDraw();
protected:
void onDraw(const cocos2d::Mat4& transform, uint32_t flags);
cocos2d::CustomCommand _customCommand;
private:
cocos2d::Vec2 center;
cocos2d::Vec2 rect = cocos2d::Vec2(240, 160);
};
#endif // __HELLOWORLD_SCENE_H__
| [
"jhghdi@gmail.con"
] | jhghdi@gmail.con |
867488329509636130550ff56aa20178fee0f95b | 7ed6c4272558b41886d5c8ca36d438ce0999c997 | /src/libpsc/cuda/fields_item_dive_cuda.hxx | 6195c55db31fdafacfd74f695dfbef150c39ad4d | [] | no_license | QJohn2017/psc | 9ec3363d4400f911c838093917275be6177df758 | 12e23313c0e0eb8bc0059baebb8b7708a05f60d0 | refs/heads/main | 2023-03-02T05:21:35.787589 | 2021-02-10T16:26:53 | 2021-02-10T16:26:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | hxx |
#include <psc_fields_cuda.h>
#include <fields_item.hxx>
#include "cuda_iface.h"
struct Item_dive_cuda
{
using Mfields = MfieldsCuda;
using MfieldsState = MfieldsStateCuda;
constexpr static const char* name = "dive";
constexpr static int n_comps = 1;
static std::vector<std::string> fld_names() { return {"dive"}; } // FIXME
static void run(const Grid_t& grid, MfieldsState& mflds, Mfields& mres)
{
for (int p = 0; p < mres.n_patches(); p++) {
cuda_mfields_calc_dive_yz(mflds.cmflds(), mres.cmflds(), p);
}
}
};
| [
"kai.germaschewski@unh.edu"
] | kai.germaschewski@unh.edu |
b73220a4e5858d4035a29bd0effc45cf001f9911 | 0faf4c1c2037dcbf3638ed66c043cfce9365b509 | /src/amount.cpp | 9cec7861a27fcf05ef37ebe7161f177505d30d44 | [
"MIT"
] | permissive | examinationcoin/examination | 6db230e8687a41fb4151ed3d9087278aec67347e | a150575544fedce2e85cc1a4e9679500bc779dd5 | refs/heads/master | 2020-03-09T08:12:37.810617 | 2018-04-13T20:22:39 | 2018-04-13T20:22:39 | 128,682,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 757 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "tinyformat.h"
CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize)
{
if (nSize > 0)
nSatoshisPerK = nFeePaid*1000/nSize;
else
nSatoshisPerK = 0;
}
CAmount CFeeRate::GetFee(size_t nSize) const
{
CAmount nFee = nSatoshisPerK*nSize / 1000;
if (nFee == 0 && nSatoshisPerK > 0)
nFee = nSatoshisPerK;
return nFee;
}
std::string CFeeRate::ToString() const
{
return strprintf("%d.%08d EXAM/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN);
}
| [
""
] | |
ce111c3917d720bd9d69decbbd51ca297c7e6363 | c100e261036e811d2554777f0e637cf107818816 | /lbm/solve.h | 02f176c3ff95d5edeba0a45b396b1d6f1833eb5a | [] | no_license | hhucyl/move-bed | 8ffb03345ac3a7c2c35869f5b9a08f113333bc6f | 865ac898ee1f374441a409aa084902c7ffe37955 | refs/heads/master | 2021-07-11T19:41:37.811310 | 2020-06-30T03:37:45 | 2020-06-30T03:37:45 | 158,653,143 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,468 | h | #ifndef LBM_SOLVE_H
#define LBM_SOLVE_H
inline void Domain::Solve(double Tf, double dtout, char const * TheFileKey, ptDFun_t ptSetup, ptDFun_t ptReport)
{
StartSolve();
std::cout<<"Box "<<Box<<std::endl;
std::cout<<"modexy "<<modexy<<std::endl;
std::cout<<"dt of LBM "<<dt<<" dt of DEM "<<dtdem<<std::endl;
double tout = 0;
Util::Stopwatch stopwatch;
printf("\n%s--- Solving ---------------------------------------------------------------------%s\n",TERM_CLR1 , TERM_RST);
GhostParticles.assign(Particles.begin(), Particles.end());
while(Time<Tf)
{
if (Time>=tout)
{
String fn;
fn.Printf("%s_%04d", TheFileKey, idx_out);
WriteXDMF(fn.CStr());
idx_out++;
if (ptReport!=NULL) (*ptReport) ((*this), UserData);
tout += dtout;
}
if (ptSetup!=NULL) (*ptSetup) ((*this), UserData);
for(int i=0; i<std::floor(dt/dtdem); ++i)
{
// std::cout<<i<<std::endl;
bool flag = i==0 || i==(std::floor(dt/dtdem)-1);
if(flag){
SetZero();
}
//set added force and check leave particles
LeaveAndForcedForce();
GhostParticles.clear();
GhostParticles.assign(Particles.begin(), Particles.end());
GhostPeriodic();
//set fluid force
if(flag){
AddDisksG();
}
//update particles contact
if(flag){
UpdateParticlesContacts();
}
UpdateParticlePairForce();
//move
MoveParticles();
}
//collide and streaming
(this->*ptr2collide)();
Stream();
BounceBack(false);
CalcProps();
Time += 1;
}
printf("%s Final CPU time = %s\n",TERM_CLR2, TERM_RST);
}
inline void Domain::SolveIBM(double Tf, double dtout, char const * TheFileKey, ptDFun_t ptSetup, ptDFun_t ptReport)
{
StartSolve();
std::cout<<"Box "<<Box<<std::endl;
std::cout<<"modexy "<<modexy<<std::endl;
std::cout<<"dt of LBM "<<dt<<" dt of DEM "<<dtdem<<std::endl;
double tout = 0;
Util::Stopwatch stopwatch;
printf("\n%s--- Solving ---------------------------------------------------------------------%s\n",TERM_CLR1 , TERM_RST);
GhostParticles.assign(Particles.begin(), Particles.end());
while(Time<Tf)
{
if (Time>=tout)
{
String fn;
fn.Printf("%s_%04d", TheFileKey, idx_out);
WriteXDMF(fn.CStr());
idx_out++;
if (ptReport!=NULL) (*ptReport) ((*this), UserData);
tout += dtout;
}
if (ptSetup!=NULL) (*ptSetup) ((*this), UserData);
for(int i=0; i<std::floor(dt/dtdem); ++i)
{
// std::cout<<i<<std::endl;
bool flag = i==0 || i==(std::floor(dt/dtdem)-1);
if(flag){
SetZero();
}
//set added force and check leave particles
LeaveAndForcedForce();
GhostParticles.clear();
GhostParticles.assign(Particles.begin(), Particles.end());
GhostPeriodic();
//set fluid force
if(flag){
AddDisksIBM();
}
//update particles contact
if(flag){
UpdateParticlesContacts();
// UpdateParticlesContactsVL();
}
UpdateParticlePairForce();
//move
MoveParticles();
// GhostParticles.clear();
// GhostParticles.assign(Particles.begin(), Particles.end());
// GhostPeriodic();
//test for friction
// for(size_t ip=0; ip<Particles.size(); ++ip)
// {
// if(Particles[ip].IsFree()) continue;
// Particles[ip].X = Particles[ip+1].X;
// Particles[ip].X(1) = Particles[ip].Xb(1);
// Particles[ip].V = 0.0,0.0,0.0;
// }
}
//collide and streaming
CollideMRTIBM();
Stream();
BounceBack(false);
CalcProps();
// std::cout<<std::boolalpha<<GhostParticles[0].Ghost<<std::endl;
Time += 1;
}
printf("%s Final CPU time = %s\n",TERM_CLR2, TERM_RST);
}
inline void Domain::SolveRW(double Tf, double dtout, char const * TheFileKey, ptDFun_t ptSetup, ptDFun_t ptReport)
{
StartSolve();
std::cout<<"Box "<<Box<<std::endl;
std::cout<<"modexy "<<modexy<<std::endl;
std::cout<<"dt of LBM "<<dt<<" dt of DEM "<<dtdem<<std::endl;
double tout = 0;
Util::Stopwatch stopwatch;
printf("\n%s--- Solving ---------------------------------------------------------------------%s\n",TERM_CLR1 , TERM_RST);
GhostParticles.assign(Particles.begin(), Particles.end());
while(Time<Tf)
{
if (Time>=tout)
{
String fn;
fn.Printf("%s_%04d", TheFileKey, idx_out);
WriteXDMF(fn.CStr());
idx_out++;
if (ptReport!=NULL) (*ptReport) ((*this), UserData);
tout += dtout;
}
for(int i=0; i<std::floor(dt/dtdem); ++i)
{
// std::cout<<i<<std::endl;
bool flag = i==0 || i==(std::floor(dt/dtdem)-1);
if(flag){
SetZero();
}
//set added force and check leave particles
LeaveAndForcedForce();
GhostParticles.clear();
GhostParticles.assign(Particles.begin(), Particles.end());
GhostPeriodic();
//set fluid force
if(flag){
AddDisksG();
}
//update particles contact
if(flag){
UpdateParticlesContacts();
}
UpdateParticlePairForce();
//move
MoveParticles();
}
//collide and streaming
(this->*ptr2collide)();
Stream();
BounceBack(false);
CalcProps();
//trace particle
rwsolve_sub(dt);
Time += 1;
}
printf("%s Final CPU time = %s\n",TERM_CLR2, TERM_RST);
}
inline void Domain::rwsolve_sub(double dt)
{
// std::cout<<1<<std::endl;
#ifdef USE_OMP
#pragma omp parallel for schedule(static) num_threads(Nproc)
#endif
for(int i=0;i<(int) RWParticles.size();++i)
{
RW::Particle *RWP = &RWParticles[i];
int x1 = std::floor(RWP->X(0));
int y1 = std::floor(RWP->X(1));
int x2 = x1+1;
int y2 = y1+1;
if(x1<0 || y1<0 || x2>Ndim(0)-1 || y2>Ndim(1)-1)
{
RWP->Leave(modexy,Box);
x1 = std::floor(RWP->X(0));
y1 = std::floor(RWP->X(1));
x2 = x1+1;
y2 = y1+1;
}
std::vector<Vec3_t> VV{Vel[x1][y1][0],Vel[x2][y1][0],Vel[x1][y2][0],Vel[x2][y2][0]};
std::vector<int> idx{x1,x2,y1,y2};
RWP->Move(VV,idx,dt);
RWP->Leave(modexy,Box);
int ix = std::round(RWP->X(0));
int iy = std::round(RWP->X(1));
if(Gamma[ix][iy][0]>1e-9 && Check[ix][iy][0]>0)
{
int ip = Check[ix][iy][0];
if(Norm(Particles[ip].X-RWP->X)<=Particles[ip].Rh && Norm(Particles[ip].Xb-RWP->Xb)>Particles[ip].Rh)
{
RWP->Reflect(Particles[ip].X,Particles[ip].Rh);
RWP->Leave(modexy,Box);
}
}
}
}
inline void Domain::CheckInside()
{
for(size_t i=0; i<RWParticles.size(); ++i)
{
RW::Particle *RWP = &RWParticles[i];
for(size_t ip=0; ip<Particles.size(); ++ip)
{
DEM::Disk *Pa = &Particles[ip];
if(Norm(Pa->X-RWP->X)<Pa->Rh)
{
RWParticles.erase(RWParticles.begin()+i);
break;
}
}
}
}
#endif | [
"hhucyl@hotmail.com"
] | hhucyl@hotmail.com |
b3a9b08588187d061928251da4f613a222c87adf | 3558393e11a3452d9edbb0b29b6e3b151c32f80c | /lib/qjsonrpc/qjsonrpcmessage.h | dad5e6021c37d2dbf8145ade32fca742fd8b03eb | [] | no_license | EPecherkin/diplom | 6c42ab20d67ea6e9558ed953ac81a6d3f1cbc8c6 | 9e99ef9e8c7855170fe1dc2430fcdd831d4aea24 | refs/heads/master | 2016-09-06T10:16:29.215852 | 2014-06-10T19:12:29 | 2014-06-10T19:13:31 | 18,321,698 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,074 | h | /*
* Copyright (C) 2012-2013 Matt Broadstone
* Contact: http://bitbucket.org/devonit/qjsonrpc
*
* This file is part of the QJsonRpc Library.
*
* 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.
*/
#ifndef QJSONRPCMESSAGE_H
#define QJSONRPCMESSAGE_H
#include <QSharedDataPointer>
#include <QMetaType>
#if QT_VERSION >= 0x050000
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>
#else
#include "json/qjsonvalue.h"
#include "json/qjsonobject.h"
#include "json/qjsonarray.h"
#endif
#include "qjsonrpc_export.h"
// error codes defined by spec
namespace QJsonRpc {
enum ErrorCode {
NoError = 0,
ParseError = -32700, // Invalid JSON was received by the server.
// An error occurred on the server while parsing the JSON text.
InvalidRequest = -32600, // The JSON sent is not a valid Request object.
MethodNotFound = -32601, // The method does not exist / is not available.
InvalidParams = -32602, // Invalid method parameter(s).
InternalError = -32603, // Internal JSON-RPC error.
ServerErrorBase = -32000, // Reserved for implementation-defined server-errors.
UserError = -32099, // Anything after this is user defined
TimeoutError = -32100
};
}
class QJsonRpcMessagePrivate;
class QJSONRPC_EXPORT QJsonRpcMessage
{
public:
QJsonRpcMessage();
QJsonRpcMessage(const QJsonObject &message);
QJsonRpcMessage(const QByteArray &message);
QJsonRpcMessage(const QJsonRpcMessage &other);
QJsonRpcMessage &operator=(const QJsonRpcMessage &other);
~QJsonRpcMessage();
enum Type {
Invalid,
Request,
Response,
Notification,
Error
};
static QJsonRpcMessage createRequest(const QString &method,
const QJsonArray ¶ms = QJsonArray());
static QJsonRpcMessage createRequest(const QString &method, const QJsonValue ¶m);
static QJsonRpcMessage createRequest(const QString &method, const QJsonObject &namedParameters);
static QJsonRpcMessage createNotification(const QString &method,
const QJsonArray ¶ms = QJsonArray());
static QJsonRpcMessage createNotification(const QString &method, const QJsonValue ¶m);
static QJsonRpcMessage createNotification(const QString &method,
const QJsonObject &namedParameters);
QJsonRpcMessage createResponse(const QJsonValue &result) const;
QJsonRpcMessage createErrorResponse(QJsonRpc::ErrorCode code,
const QString &message = QString(),
const QJsonValue &data = QJsonValue()) const;
QJsonRpcMessage::Type type() const;
bool isValid() const;
int id() const;
// request
QString method() const;
QJsonValue params() const;
// response
QJsonValue result() const;
// error
int errorCode() const;
QString errorMessage() const;
QJsonValue errorData() const;
QJsonObject toObject() const;
bool operator==(const QJsonRpcMessage &message) const;
inline bool operator!=(const QJsonRpcMessage &message) const { return !(operator==(message)); }
private:
friend class QJsonRpcMessagePrivate;
QSharedDataPointer<QJsonRpcMessagePrivate> d;
};
QJSONRPC_EXPORT QDebug operator<<(QDebug, const QJsonRpcMessage &);
Q_DECLARE_METATYPE(QJsonRpcMessage)
#endif
| [
"e.pecherkin@gmail.com"
] | e.pecherkin@gmail.com |
f469c09c208baaf2fa28639adc7eb3b6e4b1a9b9 | 3d2ad1c40c7c2c0adfa9dd3b6cccf117fe44ab50 | /AdjoinableMPIexamples/Adol-C/StructSendRecv/ampiDriver.cpp | 86bdec057ac209ce86d29b1a928cf3328d076164 | [
"MIT"
] | permissive | zsdfewm/RevMPI | 45d2ee4e63c04b6e7f430f114a9770db5f0fb3f9 | 8bc7b4bb24b6743fc23619e9ce525fbc37d110bd | refs/heads/master | 2018-12-28T01:37:54.829999 | 2015-03-02T19:15:15 | 2015-03-02T19:15:15 | 31,557,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,138 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "ampi/ampi.h"
#include "adolc/adolc.h"
typedef struct {
int a;
adouble d;
double e;
} aStruct;
MPI_Datatype astructMPItype;
int head(aStruct* x, aStruct *y) {
MPI_Status s;
int world_rank;
AMPI_Comm_rank(MPI_COMM_WORLD,&world_rank);
x[1].a = x[1].a*2; x[1].d = x[1].d*2;
if (world_rank==0) AMPI_Send(x,2,astructMPItype,1,10,AMPI_TO_RECV,MPI_COMM_WORLD);
if (world_rank==1) AMPI_Recv(x,2,astructMPItype,0,10,AMPI_FROM_SEND,MPI_COMM_WORLD,&s);
x[1].a = x[1].a*5; x[1].d = sin(x[1].d);
if (world_rank==1) AMPI_Send(x,2,astructMPItype,0,20,AMPI_TO_RECV,MPI_COMM_WORLD);
if (world_rank==0) AMPI_Recv(y,2,astructMPItype,1,20,AMPI_FROM_SEND,MPI_COMM_WORLD,&s);
y[1].a = y[1].a*3; y[1].d = y[1].d*3;
return 0;
}
int main(int argc, char** argv) {
AMPI_Init_NT(0,0);
int world_rank;
AMPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Datatype aTempType;
aStruct x[2];
aStruct y[2];
int blockcount = 2;
int blocks[] = {1,1}; /* we ignore the 'e' component on purpose */
MPI_Datatype types[] = {MPI_INT,AMPI_ADOUBLE};
MPI_Aint displacements[2];
displacements[0] = (char*)&(x->a) - (char*)(x);
displacements[1] = (char*)&(x->d) - (char*)(x);
AMPI_Type_create_struct_NT(blockcount,blocks,displacements,types,&aTempType);
AMPI_Type_commit_NT(&aTempType);
AMPI_Type_create_resized_NT(aTempType,0,sizeof(aStruct),&astructMPItype);
AMPI_Type_commit_NT(&astructMPItype);
trace_on(world_rank,1);
double xp,yp,w,g;
if (world_rank == 0) {
x[0].a = 2;
x[1].a = 1;
xp=3.5;
x[1].d<<=xp;
head(x,y);
y[1].d>>=yp;
printf(__FILE__ ": process 0 got numbers %d %f \n", y[1].a, yp);
}
else {
head(x,y);
}
trace_off(1);
if (world_rank == 0) {
tape_doc(world_rank,1,1,&xp,&yp);
w=1.0;
fos_reverse(world_rank,1,1,&w,&g);
printf(__FILE__ ": process 0 got gradient %f \n", g);
}
else {
tape_doc(world_rank,0,0,0,0);
fos_reverse(world_rank,0,0,0,0);
}
AMPI_Type_free_NT(&aTempType);
AMPI_Type_free_NT(&astructMPItype);
AMPI_Finalize_NT();
return 0;
}
| [
"wangmu0701@gmail.com"
] | wangmu0701@gmail.com |
210cfedefa55d3aeb74036d00a1fe46d6513ddf0 | 8ee0be0b14ec99858712a5c37df4116a52cb9801 | /Client/GameProc/ChangeActionMode.h | 2a7f620263706e3588837a8cc14c19b66058d575 | [] | no_license | eRose-DatabaseCleaning/Sources-non-evo | 47968c0a4fd773d6ff8c9eb509ad19caf3f48d59 | 2b152f5dba3bce3c135d98504ebb7be5a6c0660e | refs/heads/master | 2021-01-13T14:31:36.871082 | 2019-05-24T14:46:41 | 2019-05-24T14:46:41 | 72,851,710 | 6 | 3 | null | 2016-11-14T23:30:24 | 2016-11-04T13:47:51 | C++ | UHC | C++ | false | false | 2,083 | h | #ifndef _CHANGEATTACKMODE_
#define _CHANGEATTACKMODE_
enum AVATAR_ACTION_MODE
{
AVATAR_NORMAL_MODE = 0,
AVATAR_ATTACK_MODE = 1,
};
class CObjCHAR;
//----------------------------------------------------------------------------------------------------
/// Change avatar motion mode..
//----------------------------------------------------------------------------------------------------
class CChangeActionMode
{
private:
int m_iAvatarActionMode;
int m_iElapsedAttackEnd; // the elapsed time from attack end.
bool m_bUpdateMode; // ì í¬ì€ìžê°?
CObjCHAR* m_pObjCHAR;
CChangeActionMode(void);
public:
CChangeActionMode( CObjCHAR* pObjCHAR );
~CChangeActionMode(void);
void ChangeActionMode( int iActionMode );
int GetActionMode(){ return m_iAvatarActionMode; }
//----------------------------------------------------------------------------------------------------
/// Get proper motion by action mode
//----------------------------------------------------------------------------------------------------
int GetAdjustedActionIndex( int iActionIdx );
//----------------------------------------------------------------------------------------------------
/// Attack start. change attack mode.
//----------------------------------------------------------------------------------------------------
void AttackStart();
//----------------------------------------------------------------------------------------------------
/// If avt finished attack command, then change action mode to normal mode after 10 sec from attack end time.
//----------------------------------------------------------------------------------------------------
void AttackEnd();
//----------------------------------------------------------------------------------------------------
/// Change action mode by checking time..
//----------------------------------------------------------------------------------------------------
void Proc();
};
#endif //_CHANGEATTACKMODE_ | [
"hugo.delannoy@hotmail.com"
] | hugo.delannoy@hotmail.com |
69d978afc942064c71c85354bba318637126fc57 | 8da22084cdf2e6628950a19963a02f7e852afff3 | /DefaultComponent/DefaultConfig_copy/NS_SENSOR.h | 51d7693c3540f25189a900d8dda4a7fc5a15f93d | [] | no_license | kdpuvvadi/Automated-Traffic-Control-System | 6cb2231eb608b1ff66eb5ff8b561e7b1bd518b82 | a289395ec748d671c3df36f0ba83cd3cd1a1eeb2 | refs/heads/master | 2021-06-09T14:55:32.310578 | 2016-11-05T08:21:03 | 2016-11-05T08:21:03 | 34,834,738 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,054 | h | /*********************************************************************
Rhapsody : 7.5.2
Login : Administrator
Component : DefaultComponent
Configuration : DefaultConfig_copy
Model Element : NS_SENSOR
//! Generated Date : Fri, 7, Sep 2012
File Path : DefaultComponent/DefaultConfig_copy/NS_SENSOR.h
*********************************************************************/
#ifndef NS_SENSOR_H
#define NS_SENSOR_H
//## auto_generated
#include <oxf/oxf.h>
//## auto_generated
#include <aom/aom.h>
//## auto_generated
#include "Default.h"
//## auto_generated
#include <oxf/omthread.h>
//## auto_generated
#include <oxf/omreactive.h>
//## auto_generated
#include <oxf/state.h>
//## auto_generated
#include <oxf/event.h>
//## link itsEmergency
class Emergency;
//## package Default
//## class NS_SENSOR
class NS_SENSOR : public OMReactive {
//// Friends ////
public :
#ifdef _OMINSTRUMENT
friend class OMAnimatedNS_SENSOR;
#endif // _OMINSTRUMENT
//// Constructors and destructors ////
//## auto_generated
NS_SENSOR(IOxfActive* theActiveContext = 0);
//## auto_generated
~NS_SENSOR();
//// Additional operations ////
//## auto_generated
Emergency* getItsEmergency() const;
//## auto_generated
void setItsEmergency(Emergency* p_Emergency);
//## auto_generated
virtual bool startBehavior();
protected :
//## auto_generated
void initStatechart();
//## auto_generated
void cleanUpRelations();
//// Relations and components ////
Emergency* itsEmergency; //## link itsEmergency
//// Framework operations ////
//// Framework ////
public :
// rootState:
//## statechart_method
inline bool rootState_IN() const;
//## statechart_method
virtual void rootState_entDef();
//## statechart_method
virtual IOxfReactive::TakeEventStatus rootState_processEvent();
// On:
//## statechart_method
inline bool On_IN() const;
//## statechart_method
void On_entDef();
//## statechart_method
IOxfReactive::TakeEventStatus On_handleEvent();
// NS_On:
//## statechart_method
inline bool NS_On_IN() const;
// NS_Off:
//## statechart_method
inline bool NS_Off_IN() const;
// Off:
//## statechart_method
inline bool Off_IN() const;
protected :
//#[ ignore
enum NS_SENSOR_Enum {
OMNonState = 0,
On = 1,
NS_On = 2,
NS_Off = 3,
Off = 4
};
int rootState_subState;
int rootState_active;
int On_subState;
//#]
};
#ifdef _OMINSTRUMENT
//#[ ignore
class OMAnimatedNS_SENSOR : virtual public AOMInstance {
DECLARE_REACTIVE_META(NS_SENSOR, OMAnimatedNS_SENSOR)
//// Framework operations ////
public :
virtual void serializeRelations(AOMSRelations* aomsRelations) const;
//## statechart_method
void rootState_serializeStates(AOMSState* aomsState) const;
//## statechart_method
void On_serializeStates(AOMSState* aomsState) const;
//## statechart_method
void NS_On_serializeStates(AOMSState* aomsState) const;
//## statechart_method
void NS_Off_serializeStates(AOMSState* aomsState) const;
//## statechart_method
void Off_serializeStates(AOMSState* aomsState) const;
};
//#]
#endif // _OMINSTRUMENT
inline bool NS_SENSOR::rootState_IN() const {
return true;
}
inline bool NS_SENSOR::On_IN() const {
return rootState_subState == On;
}
inline bool NS_SENSOR::NS_On_IN() const {
return On_subState == NS_On;
}
inline bool NS_SENSOR::NS_Off_IN() const {
return On_subState == NS_Off;
}
inline bool NS_SENSOR::Off_IN() const {
return rootState_subState == Off;
}
#endif
/*********************************************************************
File Path : DefaultComponent/DefaultConfig_copy/NS_SENSOR.h
*********************************************************************/
| [
"kdpuvvadi@outlook.com"
] | kdpuvvadi@outlook.com |
169b7bfcd1eb53bc9f50c4a20501a85a3dba4bb1 | 16c26234770a0572a4cc4111047ca07b784ed6d7 | /dynadjust/include/io/dnaiosnxwrite.cpp | c1204361d9dc1b77146abfa62efd4cc010c4c7cb | [
"Apache-2.0",
"GPL-2.0-only"
] | permissive | directorofballyquinnptyltd/DynAdjust | f5e7c31cdcb0c7b9debaf0b33d71e4878cefc726 | d27a42cc4e6c2a333f7edc3bea01871d616dc602 | refs/heads/master | 2020-08-28T07:55:36.350005 | 2019-09-18T23:19:35 | 2019-09-18T23:19:35 | 217,642,877 | 1 | 0 | Apache-2.0 | 2019-10-26T02:06:04 | 2019-10-26T02:06:04 | null | WINDOWS-1252 | C++ | false | false | 13,345 | cpp | //============================================================================
// Name : dnaiosnxwrite.cpp
// Author : Roger Fraser
// Contributors :
// Version : 1.00
// Copyright : Copyright 2017 Geoscience Australia
//
// 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.
//
// Description : DynAdjust SINEX file write operations
//============================================================================
#include <include/io/dnaiosnx.hpp>
#include <include/functions/dnastringfuncs.hpp>
#include <include/functions/dnaiostreamfuncs.hpp>
#include <include/functions/dnatemplatefuncs.hpp>
namespace dynadjust {
namespace iostreams {
void dna_io_snx::serialise_sinex(std::ofstream* snx_file, pvstn_t bstRecords, pvmsr_t bmsRecords,
binary_file_meta_t& bst_meta, binary_file_meta_t& bms_meta,
matrix_2d* estimates, matrix_2d* variances, const project_settings& p,
UINT32& measurementParams, UINT32& unknownParams, double& sigmaZero,
uint32_uint32_map* blockStationsMap, vUINT32* blockStations,
const UINT32& blockCount, const UINT32& block,
const CDnaDatum* datum)
{
warningMessages_.clear();
blockCount_ = blockCount;
block_ = block;
unknownParams_ = unknownParams;
measurementParams_ = measurementParams;
sigmaZero_ = sigmaZero;
blockStationsMap_ = blockStationsMap;
blockStations_ = blockStations;
serialise_meta(snx_file, bst_meta, bms_meta, p, datum);
serialise_site_id(snx_file, bstRecords);
serialise_statistics(snx_file);
serialise_solution_estimates(snx_file, bstRecords, bmsRecords, estimates, variances, datum);
serialise_solution_variances(snx_file, bstRecords, bmsRecords, variances);
*snx_file << "%ENDSNX" << endl;
}
void dna_io_snx::print_line(std::ofstream* snx_file)
{
*snx_file <<
"*-------------------------------------------------------------------------------" <<
endl;
}
void dna_io_snx::serialise_meta(std::ofstream* snx_file,
binary_file_meta_t& bst_meta, binary_file_meta_t& bms_meta,
const project_settings& p, const CDnaDatum* datum)
{
*snx_file <<
"%=SNX 2.00 " << // SINEX version
"DNA "; // Agency creating this file
// Creation time of this SINEX file
dateSINEXFormat(snx_file, gregorian::day_clock::local_day(), true);
// the agency providing the data in the SINEX file
*snx_file << " DNA ";
// adjustment epoch
dateSINEXFormat(snx_file, datum->GetEpoch()); // start
*snx_file << " ";
dateSINEXFormat(snx_file, datum->GetEpoch()); // end = start
*snx_file << " ";
stringstream numberofparams;
numberofparams << right << setw(5) << unknownParams_;
string numberofparamsstr(numberofparams.str());
numberofparamsstr = findandreplace<string>(numberofparamsstr, " ", "0");
*snx_file <<
"P " << // Technique(s) used to generate the SINEX solution
left << setw(6) <<
numberofparamsstr << // Number of parameters estimated in the SINEX file
"0 " << // Single character indicating the constraint in the SINEX solution
"S " << // Solution types contained in this SINEX file.
// S â all station parameters (i.e. station coordinates, station velocities, biases, geocenter)
// O - Orbits
// E - Earth Orientation Parameter
// T â Troposphere
// C â Celestial Reference Frame
// A â Antenna parameters
// BLANK
endl;
// FILE/REFERENCE
print_line(snx_file);
stringstream ss;
// description: Organization(s) gathering/altering the file contents.
*snx_file << "+FILE/REFERENCE" << endl <<
"*INFO_TYPE_________ INFO________________________________________________________" << endl <<
" DESCRIPTION " << left << "Network " << p.g.network_name << endl;
// output: Description of the file contents.
ss.str("");
if (blockCount_ > 1)
ss << "Phased adjustment results. Block " << block_ + 1 << " of " << blockCount_;
else
ss << "Simultaneous adjustment results.";
*snx_file << " OUTPUT " << left << setw(60) << ss.str() << endl;
// contact: address of the relevant contact email
//*snx_file << " OUTPUT " << left << setw(60) << __COPYRIGHT_OWNER__ << endl;
// software/hardware
*snx_file << snx_softwarehardware_text();
// input files. first, create a unique list of filenames
vector<string> files;
for (UINT16 i(0); i<bms_meta.inputFileCount; ++i)
files.push_back(bms_meta.inputFileMeta[i].filename);
for (UINT16 i(0); i<bst_meta.inputFileCount; ++i)
files.push_back(bst_meta.inputFileMeta[i].filename);
strip_duplicates(files);
// second, print
for_each(
files.begin(), files.end(),
[this, snx_file] (string& file) {
*snx_file << " INPUT " << left << setw(60) << file << endl;
});
*snx_file << "-FILE/REFERENCE" << endl;
// FILE/COMMENTS
print_line(snx_file);
*snx_file << "+FILE/COMMENT" << endl;
// print explanation of block results
if (blockCount_ > 1)
{
*snx_file <<
" This file contains the rigorous estimates for block " << block_ + 1 <<
" of a segmented" << endl <<
" network comprised of " << blockCount_ << " blocks. Due to the way in which junction stations" << endl <<
" are carried through successive blocks, stations appearing in this file" << endl <<
" may also be found in other SINEX files relating to this network, such as" << endl <<
" " << p.g.network_name << "-block1.snx, " << p.g.network_name << "-block2.snx, etc." << endl;
}
*snx_file <<
"-FILE/COMMENT" << endl;
}
void dna_io_snx::add_warning(const string& message, SINEX_WARN_TYPE warning)
{
stringstream ss;
switch (warning)
{
case excessive_name_chars:
ss << "Station name " << message << " exceeds four characters.";
break;
default:
ss << message;
}
warningMessages_.push_back(ss.str());
}
void dna_io_snx::print_warnings(std::ofstream* warning_file, const string& fileName)
{
// Print formatted header
print_file_header(*warning_file, "DYNADJUST SINEX OUTPUT WARNINGS FILE");
*warning_file << setw(PRINT_VAR_PAD) << left << "File name:" << system_complete(fileName).string() << endl;
*warning_file << OUTPUTLINE << endl << endl;
for_each(
warningMessages_.begin(), warningMessages_.end(),
[warning_file] (string warning) {
*warning_file << warning << endl;
});
}
void dna_io_snx::serialise_site_id(std::ofstream* snx_file, pvstn_t bstRecords)
{
print_line(snx_file);
*snx_file << "+SITE/ID" << endl;
*snx_file << "*CODE PT __DOMES__ T _STATION DESCRIPTION__ APPROX_LON_ APPROX_LAT_ _APP_H_" << endl;
const station_t* stn;
string stationName;
for (UINT32 i(0); i<blockStationsMap_->size(); ++i)
{
stn = &(bstRecords->at(blockStations_->at(i)));
stationName = stn->stationName;
if (stationName.length() > 4)
add_warning(stationName, excessive_name_chars);
*snx_file << " " <<
left << setw(4) << stationName.substr(0, 4) << " " <<
right << setw(2) << "A" << " " <<
left << setw(9) << stationName.substr(0, 9) << " " <<
right << setw(1) << "P" << " " <<
left << setw(22) << string(stn->description).substr(0, 22) << " " <<
right << setw(11) << FormatDmsString(RadtoDms(stn->currentLongitude), 5, true, false) << " " <<
right << setw(11) << FormatDmsString(RadtoDms(stn->currentLatitude), 5, true, false) << " " <<
right << setw(7) << setprecision(1) << fixed << stn->currentHeight << endl;
}
*snx_file << "-SITE/ID" << endl;
}
void dna_io_snx::serialise_statistics(std::ofstream* snx_file)
{
print_line(snx_file);
*snx_file << "+SOLUTION/STATISTICS" << endl;
*snx_file << "*_STATISTICAL PARAMETER________ __VALUE(S)____________" << endl;
*snx_file << " " <<
left << setw(30) << "NUMBER OF OBSERVATIONS" << " " <<
right << setw(22) << measurementParams_ << endl;
*snx_file << " " <<
left << setw(30) << "NUMBER OF UNKNOWNS" << " " <<
right << setw(22) << unknownParams_ << endl;
*snx_file << " " <<
left << setw(30) << "NUMBER OF DEGREES OF FREEDOM" << " " <<
right << setw(22) << (measurementParams_ - unknownParams_) << endl;
*snx_file << " " <<
left << setw(30) << "VARIANCE FACTOR" << " " <<
right << setw(22) << fixed << setprecision(6) << sigmaZero_ << endl;
*snx_file << "-SOLUTION/STATISTICS" << endl;
}
void dna_io_snx::serialise_solution_estimates(std::ofstream* snx_file, pvstn_t bstRecords, pvmsr_t bmsRecords,
matrix_2d* estimates, matrix_2d* variances, const CDnaDatum* datum)
{
print_line(snx_file);
*snx_file << "+SOLUTION/ESTIMATE" << endl;
*snx_file << "*INDEX TYPE__ CODE PT SOLN _REF_EPOCH__ UNIT S __ESTIMATED VALUE____ _STD_DEV___" << endl;
UINT32 i, j, index(1);
string floating_value;
stringstream ss;
// Print stations
for (i=0; i<blockStationsMap_->size(); ++i)
{
j = (*blockStationsMap_)[blockStations_->at(i)] * 3;
// estimated parameter (X)
*snx_file << " " <<
// parameter index
right << setw(5) << index++ << " " <<
// parameter type
"STAX " <<
// 4 character site code
left << setw(4) << string(bstRecords->at(blockStations_->at(i)).stationName).substr(0, 4) << " " <<
// Point code
right << setw(2) << "A" << " " <<
// Solution id
"0001 ";
// epoch
dateSINEXFormat(snx_file, datum->GetEpoch());
*snx_file << " " <<
// Parameter units
left << setw(4) << "m" << " " <<
// Constraint code
"0" << " ";
// Parameter estimate
ss.str("");
ss << setiosflags(ios_base::uppercase | ios_base::scientific) << setprecision(14) << estimates->get(j, 0);
*snx_file << right << setw(21) << ss.str() << " ";
// standard deviation
ss.str("");
ss << setprecision(5) << sqrt(variances->get(j, j));
*snx_file << right << setw(11) << ss.str() << endl;
// estimated parameter (Y)
*snx_file << " " <<
// parameter index
right << setw(5) << index++ << " " <<
// parameter type
"STAY " <<
// 4 character site code
left << setw(4) << string(bstRecords->at(blockStations_->at(i)).stationName).substr(0, 4) << " " <<
// Point code
right << setw(2) << "A" << " " <<
// Solution id
"0001 ";
// epoch
dateSINEXFormat(snx_file, datum->GetEpoch());
*snx_file << " " <<
// Parameter units
left << setw(4) << "m" << " " <<
// Constraint code
"0" << " ";
// Parameter estimate
ss.str("");
ss << setprecision(14) << estimates->get(j+1, 0);
*snx_file << right << setw(21) << ss.str() << " ";
// standard deviation
ss.str("");
ss << setprecision(5) << sqrt(variances->get(j+1, j+1));
*snx_file << right << setw(11) << ss.str() << endl;
// estimated parameter (Z)
*snx_file << " " <<
// parameter index
right << setw(5) << index++ << " " <<
// parameter type
"STAZ " <<
// 4 character site code
left << setw(4) << string(bstRecords->at(blockStations_->at(i)).stationName).substr(0, 4) << " " <<
// Point code
right << setw(2) << "A" << " " <<
// Solution id
"0001 ";
// epoch
dateSINEXFormat(snx_file, datum->GetEpoch());
*snx_file << " " <<
// Parameter units
left << setw(4) << "m" << " " <<
// Constraint code
"0" << " ";
// Parameter estimate
ss.str("");
ss << setprecision(14) << estimates->get(j+2, 0);
*snx_file << right << setw(21) << ss.str() << " ";
// standard deviation
ss.str("");
ss << setprecision(5) << sqrt(variances->get(j+2, j+2));
*snx_file << right << setw(11) << ss.str() << endl;
}
*snx_file << "-SOLUTION/ESTIMATE" << endl;
}
void dna_io_snx::print_matrix_index(std::ofstream* snx_file, const UINT32& row, const UINT32& col)
{
*snx_file << " " <<
right << setw(5) << row + 1 << " " <<
right << setw(5) << col + 1 << " ";
}
void dna_io_snx::serialise_solution_variances(std::ofstream* snx_file, pvstn_t bstRecords, pvmsr_t bmsRecords,
matrix_2d* variances)
{
print_line(snx_file);
*snx_file << "+SOLUTION/MATRIX_ESTIMATE L COVA" << endl;
*snx_file << "*PARA1 PARA2 ____PARA2+0__________ ____PARA2+1__________ ____PARA2+2__________" << endl;
UINT32 row, col, max_dimension(variances->rows());
string floating_value;
stringstream ss;
ss << setiosflags(ios_base::uppercase | ios_base::scientific);
bool newRecord(true);
UINT16 field(1);
// Print stations
for (row=0; row<max_dimension; ++row)
{
field = 1;
for (col=0; col<row+1; ++col)
{
if (newRecord)
{
print_matrix_index(snx_file, row, col);
newRecord = false;
}
// variance
ss.str("");
ss << setprecision(14) << variances->get(row, col);
*snx_file << right << setw(21) << ss.str() << " ";
if (row == col || ++field > 3)
{
*snx_file << endl;
newRecord = true;
field = 1;
}
}
}
*snx_file << "-SOLUTION/MATRIX_ESTIMATE L COVA" << endl;
}
} // dnaiostreams
} // dynadjust
| [
"craigdharrison@icloud.com"
] | craigdharrison@icloud.com |
a9d565f0494b00bdc2810b0ede0b627c8b617d5f | a11b3ce8e8acf11de27066a4444c56e61ab0118e | /plugins/mbledplugin.h | e55c634723a23a82c8123420bf630da2fded2a48 | [
"MIT"
] | permissive | kmmax/MbWidgets | cf0d6eeb43aec14e52888c5ec670ccf07321cd94 | 73e0e914bbd5f831b14f86acb22e85f98b8c683c | refs/heads/master | 2022-04-19T03:47:53.416363 | 2020-04-14T15:32:47 | 2020-04-14T15:32:47 | 255,642,228 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | #ifndef MBWIDGETPLUGIN_H
#define MBWIDGETPLUGIN_H
#include <QDesignerCustomWidgetInterface>
class MbLedPlugin : public QObject, public QDesignerCustomWidgetInterface
{
Q_OBJECT
Q_INTERFACES(QDesignerCustomWidgetInterface)
public:
MbLedPlugin(QObject *parent = nullptr);
bool isContainer() const;
bool isInitialized() const;
QIcon icon() const;
QString domXml() const;
QString group() const;
QString includeFile() const;
QString name() const;
QString toolTip() const;
QString whatsThis() const;
QWidget *createWidget(QWidget *parent);
void initialize(QDesignerFormEditorInterface *core);
private:
bool m_initialized;
};
#endif
| [
"44317470+kmmax@users.noreply.github.com"
] | 44317470+kmmax@users.noreply.github.com |
f47cd8c26cd3467b677f83f8db74d96bf5bad18c | deb2c4c0699f9b5232754e79bccb709cd82ea4b1 | /.svn/pristine/f4/f47cd8c26cd3467b677f83f8db74d96bf5bad18c.svn-base | ecffcecdffb6459e1b0e41d0a0aab77a98a0a3b3 | [] | no_license | jagretti/so2 | de8ab43d5c61753e1296e2ecc1f3e03d156d50cb | 1ace617a6e2f2704dfe4efce3e436ebbd984a7bd | refs/heads/master | 2021-06-05T04:22:32.419940 | 2019-03-14T02:34:38 | 2019-03-14T02:34:38 | 115,661,592 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,320 | // system.cc
// Nachos initialization and cleanup routines.
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "system.h"
#include "preemptive.h"
// This defines *all* of the global data structures used by Nachos.
// These are all initialized and de-allocated by this file.
Thread *currentThread; // the thread we are running now
Thread *threadToBeDestroyed; // the thread that just finished
Scheduler *scheduler; // the ready list
Interrupt *interrupt; // interrupt status
Statistics *stats; // performance metrics
Timer *timer; // the hardware timer device,
// for invoking context switches
// 2007, Jose Miguel Santos Espino
PreemptiveScheduler* preemptiveScheduler = NULL;
const long long DEFAULT_TIME_SLICE = 50000;
#ifdef FILESYS_NEEDED
FileSystem *fileSystem;
#endif
#ifdef FILESYS
SynchDisk *synchDisk;
#endif
#ifdef USER_PROGRAM // requires either FILESYS or FILESYS_STUB
Machine *machine; // user program memory and registers
#endif
#ifdef NETWORK
PostOffice *postOffice;
#endif
// External definition, to allow us to take a pointer to this function
extern void Cleanup();
//----------------------------------------------------------------------
// TimerInterruptHandler
// Interrupt handler for the timer deviSIGTRAP example -perlce. The timer device is
// set up to interrupt the CPU periodically (once every TimerTicks).
// This routine is called each timeALRM there is a timer interrupt,
// with interrupts disabled.
//
// Note that instead of calling Yield() directly (which would
// suspend the interrupt handler, not the interrupted thread
// which is what we wanted to context switch), we set a flag
// so that once the interrupt handler is done, it will appear as
// if the interrupted thread called Yield at the point it is
// was interrupted.
//
// "dummy" is because every interrupt handler takes one argument,
// whether it needs it or not.
//----------------------------------------------------------------------
static void
TimerInterruptHandler(void* dummy)
{
if (interrupt->getStatus() != IdleMode)
interrupt->YieldOnReturn();
}
//----------------------------------------------------------------------
// Initialize
// Initialize Nachos global data structures. Interpret command
// line arguments in ALRMorder to determine flags for the initialization.
//
// "argc" is the number of command line arguments (including the name
// of the command) -- ex: "nachos -d +" -> argc = 3
// "argv" is an array of strings, one for each command line argument
// ex: "nachos -d +" -> argv = {"nachos", "-d", "+"}
//----------------------------------------------------------------------
void
Initialize(int argc, char **argv)
{
int argCount;
const char* debugArgs = "";
bool randomYield = false;
// 2007, Jose Miguel Santos Espino
bool preemptiveScheduling = false;
long long timeSlice;
#ifdef USER_PROGRAM
bool debugUserProg = false; // single step user program
#endif
#ifdef FILESYS_NEEDED
bool format = false; // format disk
#endif
#ifdef NETWORK
double rely = 1; // network reliability
int netname = 0; // UNIX socket name
#endif
for (argc--, argv++; argc > 0; argc -= argCount, argv += argCount) {
argCount = 1;
if (!strcmp(*argv, "-d")) {
if (argc == 1)
debugArgs = "+"; // turn on all debug flags
else {
debugArgs = *(argv + 1);
argCount = 2;
}
} else if (!strcmp(*argv, "-rs")) {
ASSERT(argc > 1);
RandomInit(atoi(*(argv + 1))); // initialize pseudo-random
// number generator
randomYield = true;
argCount = 2;
}
// 2007, Jose Miguel Santos Espino
else if (!strcmp(*argv, "-p")) {
preemptiveScheduling = true;
if (argc == 1) {
timeSlice = DEFAULT_TIME_SLICE;
} else {
timeSlice = atoi(*(argv+1));
argCount = 2;
}
}
#ifdef USER_PROGRAM
if (!strcmp(*argv, "-s"))
debugUserProg = true;
#endif
#ifdef FILESYS_NEEDED
if (!strcmp(*argv, "-f"))
format = true;
#endif
#ifdef NETWORK
if (!strcmp(*argv, "-l")) {
ASSERT(argc > 1);
rely = atof(*(argv + 1));
argCount = 2;
} else if (!strcmp(*argv, "-m")) {
ASSERT(argc > 1);
netname = atoi(*(argv + 1));
argCount = 2;
}
#endif
}
DebugInit(debugArgs); // initialize DEBUG messages
stats = new Statistics(); // collect statistics
interrupt = new Interrupt; // start up interrupt handling
scheduler = new Scheduler(); // initialize the ready queue
if (randomYield) // start the timer (if needed)
timer = new Timer(TimerInterruptHandler, 0, randomYield);
threadToBeDestroyed = NULL;
// We didn't explicitly allocate the current thread we are running in.
// But if it ever tries to give up the CPU, we better have a Thread
// object to save its state.
currentThread = new Thread("main", NPRIO-1, false);
currentThread->setStatus(RUNNING);
interrupt->Enable();
CallOnUserAbort(Cleanup); // if user hits ctl-C
// Jose Miguel Santos Espino, 2007
if ( preemptiveScheduling ) {
preemptiveScheduler = new PreemptiveScheduler();
preemptiveScheduler->SetUp(timeSlice);
}
#ifdef USER_PROGRAM
machine = new Machine(debugUserProg); // this must come first
#endif
#ifdef FILESYS
synchDisk = new SynchDisk("DISK");
#endif
#ifdef FILESYS_NEEDED
fileSystem = new FileSystem(format);
#endif
#ifdef NETWORK
postOffice = new PostOffice(netname, rely, 10);
#endif
}
//----------------------------------------------------------------------
// Cleanup
// Nachos is halting. De-allocate global data structures.
//----------------------------------------------------------------------
void
Cleanup()
{
printf("\nCleaning up...\n");
// 2007, Jose Miguel Santos Espino
delete preemptiveScheduler;
#ifdef NETWORK
delete postOffice;
#endif
#ifdef USER_PROGRAM
delete machine;
#endif
#ifdef FILESYS_NEEDED
delete fileSystem;
#endif
#ifdef FILESYS
delete synchDisk;
#endif
delete timer;
delete scheduler;
delete interrupt;
Exit(0);
}
| [
"jose.agretti@gmail.com"
] | jose.agretti@gmail.com | |
476d425832efc4d2822d50401c206817dd464bf6 | 4359bca535258a48d23148a7b6e62541d388bdc3 | /src/qt/recentrequeststablemodel.h | 1b2c07b7e029ca7b4b34c2fa10914d86d5439929 | [
"MIT"
] | permissive | edux-coin/edux | f3d9b5a469ffd481d219a7f76d76c5d34c8928a1 | 810de5656311c3613f456be992fc8e99f2d1a861 | refs/heads/master | 2020-09-06T17:17:10.665625 | 2019-11-08T15:14:36 | 2019-11-08T15:14:36 | 220,491,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,305 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
#define BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
#include "walletmodel.h"
#include <QAbstractTableModel>
#include <QDateTime>
#include <QStringList>
class CWallet;
class RecentRequestEntry
{
public:
RecentRequestEntry() : nVersion(RecentRequestEntry::CURRENT_VERSION), id(0) {}
static const int CURRENT_VERSION = 1;
int nVersion;
int64_t id;
QDateTime date;
SendCoinsRecipient recipient;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
unsigned int nDate = date.toTime_t();
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(id);
READWRITE(nDate);
READWRITE(recipient);
if (ser_action.ForRead())
date = QDateTime::fromTime_t(nDate);
}
};
class RecentRequestEntryLessThan
{
public:
RecentRequestEntryLessThan(int nColumn, Qt::SortOrder fOrder) : column(nColumn), order(fOrder) {}
bool operator()(RecentRequestEntry& left, RecentRequestEntry& right) const;
private:
int column;
Qt::SortOrder order;
};
/** Model for list of recently generated payment requests / edux: URIs.
* Part of wallet model.
*/
class RecentRequestsTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit RecentRequestsTableModel(CWallet* wallet, WalletModel* parent);
~RecentRequestsTableModel();
enum ColumnIndex {
Date = 0,
Label = 1,
Message = 2,
Amount = 3,
NUMBER_OF_COLUMNS
};
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex& parent) const;
int columnCount(const QModelIndex& parent) const;
QVariant data(const QModelIndex& index, int role) const;
bool setData(const QModelIndex& index, const QVariant& value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex& parent) const;
bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex());
Qt::ItemFlags flags(const QModelIndex& index) const;
/*@}*/
const RecentRequestEntry& entry(int row) const { return list[row]; }
void addNewRequest(const SendCoinsRecipient& recipient);
void addNewRequest(const std::string& recipient);
void addNewRequest(RecentRequestEntry& recipient);
public slots:
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder);
void updateDisplayUnit();
private:
WalletModel* walletModel;
QStringList columns;
QList<RecentRequestEntry> list;
int64_t nReceiveRequestsMaxId;
/** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */
void updateAmountColumnTitle();
/** Gets title for amount column including current display unit if optionsModel reference available. */
QString getAmountTitle();
};
#endif // BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
| [
"drandrewbullock@gmail.com"
] | drandrewbullock@gmail.com |
7ad9a69603a0f001d7d5405a5c2b07e24a6478f0 | 1419756bff091b50b99f1fac515c4f500d28b742 | /P43850.cpp | b1d963872d87d93803df6b5e06066486c301eef0 | [] | no_license | KremaktalanA/Jutge-Problems | c22c046556846445b50ed7886e0bfa3e77fa8ee2 | 9da6353b4d5d81f98bf65bf7035ab6ced1f020e9 | refs/heads/master | 2022-12-19T18:50:35.784055 | 2020-09-29T17:29:55 | 2020-09-29T17:29:55 | 298,081,834 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 191 | cpp | #include <iostream>
using namespace std;
int main() {
int x;
while (cin >> x) {
x = x / 5;
x = x - 9;
x = x / 4;
x = x - 6;
x = x / 5;
cout << x << endl;
}
}
| [
"davpetart@gmail.com"
] | davpetart@gmail.com |
b06a435f2948b513c184ca40dbf637d57fbacf73 | 16bdcd107c1ea77010c561a023e22020c403d54f | /Flyweight_variant2/gliffactory.cpp | 02a16610bbac1571309a0bb5397beb405d2496bf | [] | no_license | lzv/patterns | f38ef6aa456cd9005d530a37d125b4db1badb747 | 41ad24423afe46962c69826ed4b8474d85faf7c3 | refs/heads/master | 2020-04-02T07:10:25.932797 | 2014-03-05T06:51:16 | 2014-03-05T06:51:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | #include "gliffactory.h"
#include "glif.h"
glifFactory & glifFactory::I ()
{
static glifFactory obj;
return obj;
}
glifFactory::~glifFactory ()
{
for (auto i: symbols) delete i.second;
}
unsigned int glifFactory::count ()
{
return symbols.size();
}
symbol * glifFactory::create_symbol (char c)
{
auto iter = symbols.find(c);
if (iter == symbols.end())
{
symbol * obj = new symbol(c);
symbols[c] = obj;
return obj;
}
else {
return iter->second;
}
}
composite * glifFactory::create_composite ()
{
return new composite;
}
| [
"vic2_@mail.ru"
] | vic2_@mail.ru |
39d702640e6560b51712dcf19612dce9d52511d7 | 646f2d559c6739e282f2c0142fef56aa154d55b8 | /src/rpcrawtransaction.cpp | f6d3370b1cf7e7a6d7f1b08a56e41c35593a1f66 | [
"MIT"
] | permissive | Cyprella/suc | 72ed31971249e5dd688e664eff18c24eb0a42876 | 7c62b7f1c786dbbda3b93febefe8c818486d0e82 | refs/heads/master | 2021-04-27T18:26:08.619581 | 2018-02-23T06:03:29 | 2018-02-23T06:03:29 | 121,935,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,680 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The Suc Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "chain.h"
#include "coins.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "main.h"
#include "merkleblock.h"
#include "net.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpcserver.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include "txmempool.h"
#include "uint256.h"
#include "utilstrencodings.h"
#include "instantx.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", ScriptToAsmStr(scriptPubKey)));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
UniValue a(UniValue::VARR);
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
{
uint256 txid = tx.GetHash();
entry.push_back(Pair("txid", txid.GetHex()));
entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
UniValue vin(UniValue::VARR);
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else {
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (int64_t)txin.prevout.n));
UniValue o(UniValue::VOBJ);
o.push_back(Pair("asm", ScriptToAsmStr(txin.scriptSig, true)));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
// Add address and value info if spentindex enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n);
if (GetSpentIndex(spentKey, spentInfo)) {
in.push_back(Pair("value", ValueFromAmount(spentInfo.satoshis)));
in.push_back(Pair("valueSat", spentInfo.satoshis));
if (spentInfo.addressType == 1) {
in.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString()));
} else if (spentInfo.addressType == 2) {
in.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString()));
}
}
}
in.push_back(Pair("sequence", (int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("valueSat", txout.nValue));
out.push_back(Pair("n", (int64_t)i));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
// Add spent information if spentindex is enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txid, i);
if (GetSpentIndex(spentKey, spentInfo)) {
out.push_back(Pair("spentTxId", spentInfo.txid.GetHex()));
out.push_back(Pair("spentIndex", (int)spentInfo.inputIndex));
out.push_back(Pair("spentHeight", spentInfo.blockHeight));
}
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (!hashBlock.IsNull()) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("height", pindex->nHeight));
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
} else {
entry.push_back(Pair("height", -1));
entry.push_back(Pair("confirmations", 0));
}
}
}
}
UniValue getrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"sucaddress\" (string) suc address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
);
LOCK(cs_main);
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
string strHex = EncodeHexTx(tx);
if (!fVerbose)
return strHex;
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
UniValue gettxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 1 && params.size() != 2))
throw runtime_error(
"gettxoutproof [\"txid\",...] ( blockhash )\n"
"\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
"\nNOTE: By default this function only works sometimes. This is when there is an\n"
"unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option or\n"
"specify the block in which the transaction is included in manually (by blockhash).\n"
"\nReturn the raw transaction data.\n"
"\nArguments:\n"
"1. \"txids\" (string) A json array of txids to filter\n"
" [\n"
" \"txid\" (string) A transaction hash\n"
" ,...\n"
" ]\n"
"2. \"block hash\" (string, optional) If specified, looks for txid in the block with this hash\n"
"\nResult:\n"
"\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
);
set<uint256> setTxids;
uint256 oneTxid;
UniValue txids = params[0].get_array();
for (unsigned int idx = 0; idx < txids.size(); idx++) {
const UniValue& txid = txids[idx];
if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid txid ")+txid.get_str());
uint256 hash(uint256S(txid.get_str()));
if (setTxids.count(hash))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated txid: ")+txid.get_str());
setTxids.insert(hash);
oneTxid = hash;
}
LOCK(cs_main);
CBlockIndex* pblockindex = NULL;
uint256 hashBlock;
if (params.size() > 1)
{
hashBlock = uint256S(params[1].get_str());
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
pblockindex = mapBlockIndex[hashBlock];
} else {
CCoins coins;
if (pcoinsTip->GetCoins(oneTxid, coins) && coins.nHeight > 0 && coins.nHeight <= chainActive.Height())
pblockindex = chainActive[coins.nHeight];
}
if (pblockindex == NULL)
{
CTransaction tx;
if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
pblockindex = mapBlockIndex[hashBlock];
}
CBlock block;
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
unsigned int ntxFound = 0;
BOOST_FOREACH(const CTransaction&tx, block.vtx)
if (setTxids.count(tx.GetHash()))
ntxFound++;
if (ntxFound != setTxids.size())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block");
CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock mb(block, setTxids);
ssMB << mb;
std::string strHex = HexStr(ssMB.begin(), ssMB.end());
return strHex;
}
UniValue verifytxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"verifytxoutproof \"proof\"\n"
"\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
"and throwing an RPC error if the block is not in our best chain\n"
"\nArguments:\n"
"1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
"\nResult:\n"
"[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
);
CDataStream ssMB(ParseHexV(params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
UniValue res(UniValue::VARR);
vector<uint256> vMatch;
if (merkleBlock.txn.ExtractMatches(vMatch) != merkleBlock.header.hashMerkleRoot)
return res;
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
BOOST_FOREACH(const uint256& hash, vMatch)
res.push_back(hash.GetHex());
return res;
}
UniValue createrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime )\n"
"\nCreate a transaction spending the given inputs and creating new outputs.\n"
"Outputs can be addresses or data.\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"outputs\" (string, required) a json object with outputs\n"
" {\n"
" \"address\": x.xxx (numeric or string, required) The key is the suc address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
" \"data\": \"hex\", (string, required) The key is \"data\", the value is hex encoded data\n"
" ...\n"
" }\n"
"3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM), true);
if (params[0].isNull() || params[1].isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
UniValue inputs = params[0].get_array();
UniValue sendTo = params[1].get_obj();
CMutableTransaction rawTx;
if (params.size() > 2 && !params[2].isNull()) {
int64_t nLockTime = params[2].get_int64();
if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
rawTx.nLockTime = nLockTime;
}
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
vector<string> addrList = sendTo.getKeys();
BOOST_FOREACH(const string& name_, addrList) {
if (name_ == "data") {
std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
CTxOut out(0, CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
} else {
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Suc address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
return EncodeHexTx(rawTx);
}
UniValue decoderawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" (string) Suc address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decoderawtransaction", "\"hexstring\"")
+ HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
UniValue result(UniValue::VOBJ);
TxToJSON(tx, uint256(), result);
return result;
}
UniValue decodescript(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) suc address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) script address\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
UniValue r(UniValue::VOBJ);
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
return r;
}
/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
entry.push_back(Pair("error", strMessage));
vErrorsRet.push_back(entry);
}
UniValue signrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"The third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
" \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
" \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
" {\n"
" \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
" \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
" \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
" \"sequence\" : n, (numeric) Script sequence number\n"
" \"error\" : \"text\" (string) Verification or signing error related to the input\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else
LOCK(cs_main);
#endif
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (const std::exception&) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && !params[2].isNull()) {
fGivenKeys = true;
UniValue keys = params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwalletMain)
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && !params[1].isNull()) {
UniValue prevTxs = params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
CCoinsModifier coins = view.ModifyCoins(txid);
if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
if ((unsigned int)nOut >= coins->vout.size())
coins->vout.resize(nOut+1);
coins->vout[nOut].scriptPubKey = scriptPubKey;
coins->vout[nOut].nValue = 0; // we don't know the actual output value
}
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR));
UniValue v = find_value(prevOut, "redeemScript");
if (!v.isNull()) {
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && !params[3].isNull()) {
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Script verification errors
UniValue vErrors(UniValue::VARR);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const CCoins* coins = view.AccessCoins(txin.prevout.hash);
if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
continue;
}
const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CMutableTransaction& txv, txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
ScriptError serror = SCRIPT_ERR_OK;
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) {
TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
}
}
bool fComplete = vErrors.empty();
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
if (!vErrors.empty()) {
result.push_back(Pair("errors", vErrors));
}
return result;
}
UniValue sendrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees instantsend )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"3. instantsend (boolean, optional, default=false) Use InstantSend to send this transaction\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
bool fInstantSend = false;
if (params.size() > 2)
fInstantSend = params[2].get_bool();
CCoinsViewCache &view = *pcoinsTip;
const CCoins* existingCoins = view.AccessCoins(hashTx);
bool fHaveMempool = mempool.exists(hashTx);
bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
CValidationState state;
bool fMissingInputs;
if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, false, !fOverrideFees)) {
if (state.IsInvalid()) {
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else {
if (fMissingInputs) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
}
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
if (fInstantSend && !instantsend.ProcessTxLockRequest(tx)) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Not a valid InstantSend transaction, see debug.log for more info");
}
RelayTransaction(tx);
return hashTx.GetHex();
}
| [
"dharshan.rasiah@gmail.com"
] | dharshan.rasiah@gmail.com |
c82a899261132bf749590721dc8dd021b2e6dbf4 | d89f38086d84808de3a01e5502602dcbfc3254de | /digi/SceneConvert/ParticlePass.cpp | 9a0891c773841e6169a3a00dd88345f937b36651 | [] | no_license | Jochen0x90h/Digi | 1c9250b86d8b3a49724e62c2a624d25e141f5aff | 7cbb876ebaa5ef58417e9c6d99fdd44ebb041ad0 | refs/heads/master | 2021-01-20T08:44:05.229736 | 2017-06-27T21:29:46 | 2017-06-27T21:29:46 | 90,188,188 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,073 | cpp | #include <llvm/Instructions.h>
#include <llvm/Module.h>
#include <llvm/Analysis/PostDominators.h>
#include <llvm/Support/IRBuilder.h>
#include <digi/System/Log.h>
#include <digi/CodeGenerator/TypeInfo.h>
#include <digi/CodeGenerator/NameMangler.h>
#include "CopyWalker.h"
#include "ParticlePass.h"
#include "PrintHelper.h"
namespace digi {
// ParticlePass
ParticlePass::ParticlePass()
: llvm::FunctionPass(ID)
{
}
ParticlePass::~ParticlePass()
{
}
void ParticlePass::getAnalysisUsage(llvm::AnalysisUsage& analysisUsage) const
{
// tell llvm that we don't modify anything
analysisUsage.setPreservesAll();
// tell llvm that we don't add or remove basic blocks or modify terminator instructions
//analysisUsage.setPreservesCFG();
// tell llvm wich other passes we need
// analysisUsage.addRequired<llvm::TargetData>();
// analysisUsage.addRequired<llvm::LoopInfo>();
analysisUsage.addRequired<llvm::PostDominatorTree>();
}
bool ParticlePass::doInitialization(llvm::Module& module)
{
llvm::LLVMContext& c = module.getContext();
// create modules for copied functions
this->modules[UNIFORM].reset(new llvm::Module("particleU", c));
this->modules[PARTICLE].reset(new llvm::Module("particleP", c));
return false;
}
bool ParticlePass::runOnFunction(llvm::Function& function)
{
llvm::StringRef name = function.getName();
if (name == "create")
{
// create shader walker, creates the function in the modules. this object has ownership of modules
CopyWalker walker(&this->getAnalysis<llvm::PostDominatorTree>(), function, this->modules);
// set scopes of global inputs (get accessed by load instructions)
walker.setScope(function, "emitter", UNIFORM);
walker.setScope(function, "uniform", UNIFORM);
walker.setScope(function, "particle", PARTICLE);
walker.setScope(function, "index", PARTICLE);
walker.setScope(function, "id", PARTICLE);
walker.setScope(function, "seed", PARTICLE);
// classify instructions
// input/output
walker.classifyInstructions(function, "particle", PARTICLE, USED_BY_PARTICLE);
walker.classifyInstructions(function, "seed", PARTICLE, USED_BY_PARTICLE);
// start processing at entry block
walker.doBasicBlock(NULL, &function.getEntryBlock(), NULL);
walker.fixAndGetTransfer(UNIFORM, PARTICLE, this->create_u2p, "create_u2p", false);
}
else if (name == "update")
{
// create shader walker, creates the function in the modules. this object has ownership of modules
CopyWalker walker(&this->getAnalysis<llvm::PostDominatorTree>(), function, this->modules);
// set scopes of global inputs (get accessed by load instructions)
walker.setScope(function, "uniform", UNIFORM);
walker.setScope(function, "particle", PARTICLE);
walker.setScope(function, "index", PARTICLE);
walker.setScope(function, "id", PARTICLE);
walker.setScope(function, "seed", PARTICLE);
// classify instructions
// input/output
walker.classifyInstructions(function, "particle", PARTICLE, USED_BY_PARTICLE);
walker.classifyInstructions(function, "seed", PARTICLE, USED_BY_PARTICLE);
// output
walker.classifyInstructions(function, "alive", PARTICLE, USED_BY_PARTICLE);
// start processing at entry block
walker.doBasicBlock(NULL, &function.getEntryBlock(), NULL);
walker.fixAndGetTransfer(UNIFORM, PARTICLE, this->update_u2p, "update_u2p", false);
}
else
{
// error: unexprected function
dWarning("unexpected particle function '" << name << "' encountered");
}
return false;
}
char ParticlePass::ID = 0;
static llvm::RegisterPass<ParticlePass> registerParticlePass("digi-particle", "process particles");
// ShapeParticlePass
ShapeParticlePass::~ShapeParticlePass()
{
}
void ShapeParticlePass::getAnalysisUsage(llvm::AnalysisUsage& analysisUsage) const
{
// tell llvm that we don't modify anything
analysisUsage.setPreservesAll();
// tell llvm that we don't add or remove basic blocks or modify terminator instructions
//analysisUsage.setPreservesCFG();
// tell llvm wich other passes we need
// analysisUsage.addRequired<llvm::TargetData>();
// analysisUsage.addRequired<llvm::LoopInfo>();
analysisUsage.addRequired<llvm::PostDominatorTree>();
}
bool ShapeParticlePass::doInitialization(llvm::Module& module)
{
llvm::LLVMContext& c = module.getContext();
// create modules for copied functions
this->modules[UNIFORM].reset(new llvm::Module("shapeU", c));
this->modules[PARTICLE].reset(new llvm::Module("shapeP", c));
return false;
}
bool ShapeParticlePass::runOnFunction(llvm::Function& function)
{
llvm::StringRef name = function.getName();
if (name == "main")
{
// create shader walker, creates the function in the modules. this object has ownership of modules
CopyWalker walker(&this->getAnalysis<llvm::PostDominatorTree>(), function, this->modules);
// set scopes of global inputs (get accessed by load instructions)
walker.setScope(function, "transform", UNIFORM);
walker.setScope(function, "parentMatrix", UNIFORM);
walker.setScope(function, "uniform", UNIFORM);
walker.setScope(function, "particle", PARTICLE);
walker.setScope(function, "index", PARTICLE);
walker.setScope(function, "particleMatrix", PARTICLE);
// classify instructions
walker.classifyInstructions(function, "index", PARTICLE, USED_BY_PARTICLE);
walker.classifyInstructions(function, "particleMatrix", PARTICLE, USED_BY_PARTICLE);
// start processing at entry block
walker.doBasicBlock(NULL, &function.getEntryBlock(), NULL);
walker.fixAndGetTransfer(UNIFORM, PARTICLE, this->u2p, "u2p", false);
}
else
{
// error: unexprected function
dWarning("unexpected shape particle instancer function '" << name << "' encountered");
}
return false;
}
char ShapeParticlePass::ID = 0;
static llvm::RegisterPass<ShapeParticlePass> registerShapeParticlePass("digi-shapeParticle", "process shape particle instancers");
} // namespace digi
| [
"jochen.wilhelmy@medx.net"
] | jochen.wilhelmy@medx.net |
cebb1e78232453a40e6891f87b5a36405fd39af4 | 2d5cb388a34f1f143a998bfde0321c71411ada68 | /chrome/browser/ash/full_restore/full_restore_app_launch_handler_browsertest.cc | 38608ae141aa7fe5f0f21ba9b24aede0b22f6387 | [
"BSD-3-Clause"
] | permissive | sriramtechnolo/chromium | 9472ebed80454f9dc6fa6113c52a534b9536b7d5 | 5ff97c70f20c3f8677db9cbb193f253d47525d2e | refs/heads/master | 2023-07-02T03:49:04.580480 | 2021-09-06T06:52:59 | 2021-09-06T06:52:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105,394 | cc | // Copyright 2021 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/ash/full_restore/full_restore_app_launch_handler.h"
#include <cstdint>
#include <map>
#include <memory>
#include "ash/public/cpp/autotest_desks_api.h"
#include "ash/public/cpp/shell_window_ids.h"
#include "ash/public/cpp/split_view_test_api.h"
#include "ash/public/cpp/tablet_mode.h"
#include "ash/shell.h"
#include "ash/wm/window_state.h"
#include "ash/wm/wm_event.h"
#include "base/feature_list.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/timer/timer.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/apps/app_service/launch_utils.h"
#include "chrome/browser/apps/platform_apps/app_browsertest_util.h"
#include "chrome/browser/ash/arc/arc_util.h"
#include "chrome/browser/ash/arc/session/arc_session_manager.h"
#include "chrome/browser/ash/crosapi/browser_util.h"
#include "chrome/browser/ash/full_restore/arc_app_launch_handler.h"
#include "chrome/browser/ash/full_restore/full_restore_arc_task_handler.h"
#include "chrome/browser/ash/full_restore/full_restore_prefs.h"
#include "chrome/browser/ash/full_restore/full_restore_service.h"
#include "chrome/browser/ash/web_applications/system_web_app_integration_test.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/notifications/notification_display_service_tester.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include "chrome/browser/ui/ash/shelf/app_service/exo_app_type_resolver.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h"
#include "chrome/browser/web_applications/components/web_app_id.h"
#include "chrome/browser/web_applications/components/web_application_info.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/common/chrome_features.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "components/arc/arc_service_manager.h"
#include "components/arc/mojom/app.mojom.h"
#include "components/arc/session/arc_bridge_service.h"
#include "components/arc/test/arc_util_test_support.h"
#include "components/arc/test/fake_app_instance.h"
#include "components/exo/buffer.h"
#include "components/exo/shell_surface_util.h"
#include "components/exo/surface.h"
#include "components/exo/test/exo_test_helper.h"
#include "components/exo/wm_helper.h"
#include "components/exo/wm_helper_chromeos.h"
#include "components/full_restore/app_launch_info.h"
#include "components/full_restore/features.h"
#include "components/full_restore/full_restore_info.h"
#include "components/full_restore/full_restore_read_handler.h"
#include "components/full_restore/full_restore_save_handler.h"
#include "components/full_restore/full_restore_utils.h"
#include "components/full_restore/window_info.h"
#include "components/services/app_service/public/mojom/types.mojom.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/app_window/native_app_window.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#include "ui/base/window_open_disposition.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/display/types/display_constants.h"
#include "ui/message_center/public/cpp/notification.h"
#include "ui/wm/core/window_util.h"
namespace mojo {
template <>
struct TypeConverter<arc::mojom::ArcPackageInfoPtr,
arc::mojom::ArcPackageInfo> {
static arc::mojom::ArcPackageInfoPtr Convert(
const arc::mojom::ArcPackageInfo& package_info) {
return package_info.Clone();
}
};
} // namespace mojo
namespace ash {
namespace full_restore {
namespace {
constexpr char kAppId[] = "mldnpnnoiloahfhddhobgjeophloidmo";
constexpr int32_t kWindowId1 = 100;
constexpr int32_t kWindowId2 = 200;
constexpr char kTestAppName[] = "Test ARC App";
constexpr char kTestAppName2[] = "Test ARC App 2";
constexpr char kTestAppPackage[] = "test.arc.app.package";
constexpr char kTestAppActivity[] = "test.arc.app.package.activity";
constexpr char kTestAppActivity2[] = "test.arc.app.package.activity2";
// Test values for a test WindowInfo object.
constexpr int kActivationIndex = 2;
constexpr int kDeskId = 2;
constexpr gfx::Rect kCurrentBounds(500, 200);
constexpr chromeos::WindowStateType kWindowStateType =
chromeos::WindowStateType::kPrimarySnapped;
void RemoveInactiveDesks() {
// Removes all the inactive desks and waits for their async operations to
// complete.
while (true) {
base::RunLoop run_loop;
if (!ash::AutotestDesksApi().RemoveActiveDesk(run_loop.QuitClosure()))
break;
run_loop.Run();
}
}
class TestFullRestoreInfoObserver
: public ::full_restore::FullRestoreInfo::Observer {
public:
// ::full_restore::FullRestoreInfo::Observer:
void OnAppLaunched(aura::Window* window) override {
++launched_windows_[window];
}
void OnWindowInitialized(aura::Window* window) override {
++initialized_windows_[window];
}
void Reset() {
launched_windows_.clear();
initialized_windows_.clear();
}
std::map<aura::Window*, int>& launched_windows() { return launched_windows_; }
std::map<aura::Window*, int>& initialized_windows() {
return initialized_windows_;
}
private:
std::map<aura::Window*, int> launched_windows_;
std::map<aura::Window*, int> initialized_windows_;
};
// Creates a WindowInfo object and then saves it.
void CreateAndSaveWindowInfo(int desk_id,
const gfx::Rect& current_bounds,
chromeos::WindowStateType window_state_type,
ui::WindowShowState pre_minimized_show_state,
int32_t window_id) {
// A window is needed for SaveWindowInfo, but all it needs is a layer and
// kWindowIdKey to be set. `window` needs to be alive when save is called for
// SaveWindowInfo to work.
auto window = std::make_unique<aura::Window>(nullptr);
window->Init(ui::LAYER_NOT_DRAWN);
window->SetProperty(::full_restore::kWindowIdKey, window_id);
::full_restore::WindowInfo window_info;
window_info.window = window.get();
window_info.desk_id = desk_id;
window_info.current_bounds = current_bounds;
window_info.window_state_type = window_state_type;
if (pre_minimized_show_state != ui::SHOW_STATE_DEFAULT) {
DCHECK_EQ(chromeos::WindowStateType::kMinimized, window_state_type);
window_info.pre_minimized_show_state_type = pre_minimized_show_state;
}
::full_restore::SaveWindowInfo(window_info);
}
void CreateAndSaveWindowInfo(int desk_id,
const gfx::Rect& current_bounds,
chromeos::WindowStateType window_state_type) {
CreateAndSaveWindowInfo(desk_id, current_bounds, window_state_type,
ui::SHOW_STATE_DEFAULT, kWindowId1);
}
void SaveWindowInfo(aura::Window* window) {
::full_restore::WindowInfo window_info;
window_info.window = window;
window_info.activation_index = kActivationIndex;
window_info.desk_id = kDeskId;
window_info.current_bounds = kCurrentBounds;
window_info.window_state_type = ash::WindowState::Get(window)->GetStateType();
::full_restore::SaveWindowInfo(window_info);
}
void SaveWindowInfo(
aura::Window* window,
uint32_t activation_index,
chromeos::WindowStateType window_state_type = kWindowStateType) {
::full_restore::WindowInfo window_info;
window_info.window = window;
window_info.activation_index = activation_index;
window_info.desk_id = kDeskId;
window_info.current_bounds = kCurrentBounds;
window_info.window_state_type = window_state_type;
::full_restore::SaveWindowInfo(window_info);
}
std::string GetTestApp1Id(const std::string& package_name) {
return ArcAppListPrefs::GetAppId(package_name, kTestAppActivity);
}
std::string GetTestApp2Id(const std::string& package_name) {
return ArcAppListPrefs::GetAppId(package_name, kTestAppActivity2);
}
std::vector<arc::mojom::AppInfoPtr> GetTestAppsList(
const std::string& package_name,
bool multi_app) {
std::vector<arc::mojom::AppInfoPtr> apps;
arc::mojom::AppInfoPtr app(arc::mojom::AppInfo::New());
app->name = kTestAppName;
app->package_name = package_name;
app->activity = kTestAppActivity;
app->sticky = false;
apps.push_back(std::move(app));
if (multi_app) {
app = arc::mojom::AppInfo::New();
app->name = kTestAppName2;
app->package_name = package_name;
app->activity = kTestAppActivity2;
app->sticky = false;
apps.push_back(std::move(app));
}
return apps;
}
// Creates an exo app window, and sets `window_app_id` for its shell application
// id, `app_id` for the window property `::full_restore::kAppIdKey`.
views::Widget* CreateExoWindow(const std::string& window_app_id,
const std::string& app_id) {
views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(5, 5, 20, 20);
params.context = ash::Shell::GetPrimaryRootWindow();
exo::WMHelper::AppPropertyResolver::Params resolver_params;
resolver_params.app_id = window_app_id;
resolver_params.for_creation = true;
ExoAppTypeResolver().PopulateProperties(resolver_params,
params.init_properties_container);
if (!app_id.empty())
params.init_properties_container.SetProperty(::full_restore::kAppIdKey,
app_id);
views::Widget* widget = new views::Widget();
widget->Init(std::move(params));
// Make the window resizeable.
widget->GetNativeWindow()->SetProperty(
aura::client::kResizeBehaviorKey,
aura::client::kResizeBehaviorCanResize |
aura::client::kResizeBehaviorCanMaximize);
exo::SetShellApplicationId(widget->GetNativeWindow(), window_app_id);
widget->Show();
widget->Activate();
return widget;
}
// Calls the above function to create an exo app window, and sets
// `window_app_id` for its shell application id, with an empty app id.
views::Widget* CreateExoWindow(const std::string& window_app_id) {
return CreateExoWindow(window_app_id, std::string());
}
// Gets the browser whose restore window id is same as `window_id`.
Browser* GetBrowserForWindowId(int32_t window_id) {
for (Browser* browser : *BrowserList::GetInstance()) {
if (browser->window()->GetNativeWindow()->GetProperty(
::full_restore::kRestoreWindowIdKey) == window_id) {
return browser;
}
}
return nullptr;
}
} // namespace
class FullRestoreAppLaunchHandlerBrowserTest
: public extensions::PlatformAppBrowserTest {
public:
FullRestoreAppLaunchHandlerBrowserTest()
: faster_animations_(
ui::ScopedAnimationDurationScaleMode::ZERO_DURATION) {
scoped_feature_list_.InitAndEnableFeature(
::full_restore::features::kFullRestore);
scoped_restore_for_testing_ = std::make_unique<ScopedRestoreForTesting>();
set_launch_browser_for_testing(nullptr);
}
~FullRestoreAppLaunchHandlerBrowserTest() override = default;
void SetUpOnMainThread() override {
extensions::PlatformAppBrowserTest::SetUpOnMainThread();
display_service_ =
std::make_unique<NotificationDisplayServiceTester>(profile());
}
void SetShouldRestore(FullRestoreAppLaunchHandler* app_launch_handler) {
content::RunAllTasksUntilIdle();
app_launch_handler->SetShouldRestore();
content::RunAllTasksUntilIdle();
}
void CreateWebApp() {
auto web_application_info = std::make_unique<WebApplicationInfo>();
web_application_info->start_url = GURL("https://example.org");
web_app::AppId app_id = web_app::test::InstallWebApp(
profile(), std::move(web_application_info));
// Wait for app service to see the newly installed app.
auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile());
proxy->FlushMojoCallsForTesting();
}
aura::Window* FindWebAppWindow() {
for (auto* browser : *BrowserList::GetInstance()) {
aura::Window* window = browser->window()->GetNativeWindow();
if (window->GetProperty(::full_restore::kRestoreWindowIdKey) ==
kWindowId2) {
return window;
}
}
return nullptr;
}
void WaitForAppLaunchInfoSaved(bool allow_save = true) {
::full_restore::FullRestoreSaveHandler* save_handler =
::full_restore::FullRestoreSaveHandler::GetInstance();
if (allow_save)
save_handler->AllowSave();
base::OneShotTimer* timer = save_handler->GetTimerForTesting();
if (timer->IsRunning()) {
// Simulate timeout, and the launch info is saved.
timer->FireNow();
}
content::RunAllTasksUntilIdle();
::full_restore::FullRestoreReadHandler::GetInstance()
->profile_path_to_restore_data_.clear();
}
void SaveChromeAppLaunchInfo(const std::string& app_id) {
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(),
std::make_unique<::full_restore::AppLaunchInfo>(
app_id, apps::mojom::LaunchContainer::kLaunchContainerWindow,
WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId,
std::vector<base::FilePath>{}, nullptr));
}
std::unique_ptr<::full_restore::WindowInfo> GetWindowInfo(
int32_t restore_window_id) {
return ::full_restore::FullRestoreReadHandler::GetInstance()->GetWindowInfo(
restore_window_id);
}
bool HasNotificationFor(const std::string& notification_id) {
absl::optional<message_center::Notification> message_center_notification =
display_service()->GetNotification(notification_id);
return message_center_notification.has_value();
}
void SimulateClick(const std::string& notification_id,
RestoreNotificationButtonIndex action_index) {
FullRestoreService::GetForProfile(profile())->Click(
static_cast<int>(action_index), absl::nullopt);
}
NotificationDisplayServiceTester* display_service() const {
return display_service_.get();
}
void ResetRestoreForTesting() { scoped_restore_for_testing_.reset(); }
private:
base::test::ScopedFeatureList scoped_feature_list_;
ui::ScopedAnimationDurationScaleMode faster_animations_;
std::unique_ptr<ScopedRestoreForTesting> scoped_restore_for_testing_;
std::unique_ptr<NotificationDisplayServiceTester> display_service_;
};
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
NoBrowserOnLaunch) {
EXPECT_TRUE(BrowserList::GetInstance()->empty());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
NotLaunchBrowser) {
// Add app launch info.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
WaitForAppLaunchInfoSaved();
size_t count = BrowserList::GetInstance()->size();
// Create FullRestoreAppLaunchHandler, and set should restore.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
// Verify there is no new browser launched.
EXPECT_EQ(count, BrowserList::GetInstance()->size());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
RestoreAndAddApp) {
// Add app launch info.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(),
std::make_unique<::full_restore::AppLaunchInfo>(
kAppId, kWindowId2,
apps::mojom::LaunchContainer::kLaunchContainerWindow,
WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId,
std::vector<base::FilePath>{}, nullptr));
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler, and set should restore.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
CreateWebApp();
content::RunAllTasksUntilIdle();
aura::Window* web_app_window = FindWebAppWindow();
ASSERT_TRUE(web_app_window);
EXPECT_TRUE(web_app_window->GetProperty(::full_restore::kWindowInfoKey));
}
// Tests that restoring windows that are minimized will restore their
// pre-minimized window state when unminimizing.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
PreMinimizedState) {
// Add app launch info.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(),
std::make_unique<::full_restore::AppLaunchInfo>(
kAppId, kWindowId2,
apps::mojom::LaunchContainer::kLaunchContainerWindow,
WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId,
std::vector<base::FilePath>{}, nullptr));
CreateAndSaveWindowInfo(kDeskId, kCurrentBounds,
chromeos::WindowStateType::kMinimized,
ui::SHOW_STATE_MAXIMIZED, kWindowId2);
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler, and set should restore.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
// The web app window should be attainable.
CreateWebApp();
content::RunAllTasksUntilIdle();
aura::Window* app_window = FindWebAppWindow();
ASSERT_TRUE(app_window);
// The current window state should be minimized, and when we unminimize it
// should be maximized.
ash::WindowState* window_state = ash::WindowState::Get(app_window);
ASSERT_TRUE(window_state->IsMinimized());
window_state->Unminimize();
EXPECT_TRUE(window_state->IsMaximized());
window_state->Restore();
EXPECT_EQ(kCurrentBounds, app_window->GetBoundsInScreen());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
AddAppAndRestore) {
// Add app launch info.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(),
std::make_unique<::full_restore::AppLaunchInfo>(
kAppId, kWindowId2,
apps::mojom::LaunchContainer::kLaunchContainerWindow,
WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId,
std::vector<base::FilePath>{}, nullptr));
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
CreateWebApp();
SetShouldRestore(app_launch_handler.get());
EXPECT_TRUE(FindWebAppWindow());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
FirstRunFullRestore) {
// Add app launch infos.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
WaitForAppLaunchInfoSaved();
size_t count = BrowserList::GetInstance()->size();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
app_launch_handler->LaunchBrowserWhenReady(/*first_run_full_restore=*/true);
content::RunAllTasksUntilIdle();
// Verify there is a new browser launched.
EXPECT_EQ(count + 1, BrowserList::GetInstance()->size());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest, NotRestore) {
// Add app launch infos.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(),
std::make_unique<::full_restore::AppLaunchInfo>(
kAppId, kWindowId2,
apps::mojom::LaunchContainer::kLaunchContainerWindow,
WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId,
std::vector<base::FilePath>{}, nullptr));
WaitForAppLaunchInfoSaved();
size_t count = BrowserList::GetInstance()->size();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
app_launch_handler->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
CreateWebApp();
content::RunAllTasksUntilIdle();
// Verify there is no new browser launched.
EXPECT_EQ(count, BrowserList::GetInstance()->size());
EXPECT_FALSE(FindWebAppWindow());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
RestoreAndLaunchBrowser) {
size_t count = BrowserList::GetInstance()->size();
// Add the chrome browser launch info.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
auto app_launch_info = std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId2);
app_launch_info->app_type_browser = true;
::full_restore::SaveAppLaunchInfo(profile()->GetPath(),
std::move(app_launch_info));
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
app_launch_handler->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
content::RunAllTasksUntilIdle();
// Verify there is new browser launched.
EXPECT_EQ(count + 1, BrowserList::GetInstance()->size());
}
// Verify the restore data is saved when the restore setting is always and the
// restore finishes.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
RestoreAndLaunchBrowserWithAlwaysSetting) {
size_t count = BrowserList::GetInstance()->size();
// Add the chrome browser launch info.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
auto app_launch_info = std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId2);
app_launch_info->app_type_browser = true;
::full_restore::SaveAppLaunchInfo(profile()->GetPath(),
std::move(app_launch_info));
WaitForAppLaunchInfoSaved();
::full_restore::FullRestoreSaveHandler::GetInstance()->ClearForTesting();
// Set the restore pref setting as 'Always restore'.
profile()->GetPrefs()->SetInteger(kRestoreAppsAndPagesPrefName,
static_cast<int>(RestoreOption::kAlways));
// Create FullRestoreAppLaunchHandler to simulate the system startup.
auto* full_restore_service = FullRestoreService::GetForProfile(profile());
full_restore_service->SetAppLaunchHandlerForTesting(
std::make_unique<FullRestoreAppLaunchHandler>(
profile(), /*should_init_service=*/true));
auto* app_launch_handler1 = full_restore_service->app_launch_handler();
app_launch_handler1->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
content::RunAllTasksUntilIdle();
// Verify there is new browser launched.
EXPECT_EQ(count + 1, BrowserList::GetInstance()->size());
WaitForAppLaunchInfoSaved(/*allow_save*/ false);
::full_restore::FullRestoreSaveHandler::GetInstance()->ClearForTesting();
// Create FullRestoreAppLaunchHandler to simulate the system startup again.
full_restore_service->SetAppLaunchHandlerForTesting(
std::make_unique<FullRestoreAppLaunchHandler>(
profile(), /*should_init_service=*/true));
auto* app_launch_handler2 = full_restore_service->app_launch_handler();
app_launch_handler2->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
content::RunAllTasksUntilIdle();
// Verify there is a new browser launched again.
EXPECT_EQ(count + 2, BrowserList::GetInstance()->size());
}
// Verify the restore data is saved when the restore button is clicked and the
// restore finishes.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
RestoreAndLaunchBrowserWithClickRestore) {
size_t count = BrowserList::GetInstance()->size();
// Add the chrome browser launch info.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
auto app_launch_info = std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId2);
app_launch_info->app_type_browser = true;
::full_restore::SaveAppLaunchInfo(profile()->GetPath(),
std::move(app_launch_info));
WaitForAppLaunchInfoSaved();
::full_restore::FullRestoreSaveHandler::GetInstance()->ClearForTesting();
// Set the restore pref setting as 'Ask every time'.
profile()->GetPrefs()->SetInteger(
kRestoreAppsAndPagesPrefName,
static_cast<int>(RestoreOption::kAskEveryTime));
// Create FullRestoreAppLaunchHandler to simulate the system startup.
auto* full_restore_service = FullRestoreService::GetForProfile(profile());
full_restore_service->SetAppLaunchHandlerForTesting(
std::make_unique<FullRestoreAppLaunchHandler>(
profile(), /*should_init_service=*/true));
auto* app_launch_handler1 = full_restore_service->app_launch_handler();
app_launch_handler1->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
content::RunAllTasksUntilIdle();
EXPECT_TRUE(HasNotificationFor(kRestoreNotificationId));
SimulateClick(kRestoreForCrashNotificationId,
RestoreNotificationButtonIndex::kRestore);
content::RunAllTasksUntilIdle();
// Verify there is new browser launched.
EXPECT_EQ(count + 1, BrowserList::GetInstance()->size());
WaitForAppLaunchInfoSaved(/*allow_save*/ false);
::full_restore::FullRestoreSaveHandler::GetInstance()->ClearForTesting();
// Create FullRestoreAppLaunchHandler to simulate the system startup again.
auto app_launch_handler2 =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
app_launch_handler2->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
content::RunAllTasksUntilIdle();
SetShouldRestore(app_launch_handler2.get());
content::RunAllTasksUntilIdle();
content::RunAllTasksUntilIdle();
// Verify there is a new browser launched again.
EXPECT_EQ(count + 2, BrowserList::GetInstance()->size());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
RestoreAndNoBrowserLaunchInfo) {
size_t count = BrowserList::GetInstance()->size();
// Add app launch info, but no browser launch info.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(),
std::make_unique<::full_restore::AppLaunchInfo>(
kAppId, kWindowId2,
apps::mojom::LaunchContainer::kLaunchContainerWindow,
WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId,
std::vector<base::FilePath>{}, nullptr));
// Remove the browser app to mock no browser launch info.
::full_restore::FullRestoreSaveHandler::GetInstance()->RemoveApp(
profile()->GetPath(), extension_misc::kChromeAppId);
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
app_launch_handler->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
content::RunAllTasksUntilIdle();
// Verify there is no new browser launched.
EXPECT_EQ(count, BrowserList::GetInstance()->size());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
LaunchBrowserAndRestore) {
size_t count = BrowserList::GetInstance()->size();
// Add the chrome browser launch info.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
auto app_launch_info = std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId2);
app_launch_info->app_type_browser = true;
::full_restore::SaveAppLaunchInfo(profile()->GetPath(),
std::move(app_launch_info));
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
app_launch_handler->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
content::RunAllTasksUntilIdle();
// Verify there is no new browser launched.
EXPECT_EQ(count, BrowserList::GetInstance()->size());
// Set should restore.
app_launch_handler->SetShouldRestore();
content::RunAllTasksUntilIdle();
// Verify there is new browser launched.
EXPECT_EQ(count + 1, BrowserList::GetInstance()->size());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
RestoreAndLaunchBrowserAndAddApp) {
size_t count = BrowserList::GetInstance()->size();
// Add app launch infos.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(),
std::make_unique<::full_restore::AppLaunchInfo>(
kAppId, kWindowId2,
apps::mojom::LaunchContainer::kLaunchContainerWindow,
WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId,
std::vector<base::FilePath>{}, nullptr));
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler, and set should restore.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
app_launch_handler->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
CreateWebApp();
content::RunAllTasksUntilIdle();
// Verify there is new browser launched.
EXPECT_EQ(count + 2, BrowserList::GetInstance()->size());
EXPECT_TRUE(FindWebAppWindow());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
LaunchBrowserAndAddAppAndRestore) {
size_t count = BrowserList::GetInstance()->size();
// Add app launch infos.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(),
std::make_unique<::full_restore::AppLaunchInfo>(
kAppId, kWindowId2,
apps::mojom::LaunchContainer::kLaunchContainerWindow,
WindowOpenDisposition::NEW_WINDOW, display::kDefaultDisplayId,
std::vector<base::FilePath>{}, nullptr));
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
app_launch_handler->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
CreateWebApp();
SetShouldRestore(app_launch_handler.get());
// Verify there is new browser launched.
EXPECT_EQ(count + 2, BrowserList::GetInstance()->size());
EXPECT_TRUE(FindWebAppWindow());
}
// Tests that the window properties on the browser window match the ones we set
// in the window info.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
WindowProperties) {
size_t count = BrowserList::GetInstance()->size();
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kWindowId1));
CreateAndSaveWindowInfo(kDeskId, kCurrentBounds, kWindowStateType);
WaitForAppLaunchInfoSaved();
// Launch the browser.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
app_launch_handler->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
SetShouldRestore(app_launch_handler.get());
ASSERT_EQ(count + 1u, BrowserList::GetInstance()->size());
// TODO(sammiequon): Check the values from the actual browser window.
auto window = std::make_unique<aura::Window>(nullptr);
window->Init(ui::LAYER_NOT_DRAWN);
window->SetProperty(::full_restore::kRestoreWindowIdKey, kWindowId1);
auto stored_window_info = ::full_restore::GetWindowInfo(window.get());
EXPECT_EQ(kDeskId, *stored_window_info->desk_id);
EXPECT_EQ(kCurrentBounds, *stored_window_info->current_bounds);
EXPECT_EQ(kWindowStateType, *stored_window_info->window_state_type);
}
// The PRE phase of the FullRestoreOverridesSessionRestoreTest. Creates a
// browser and turns on session restore.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
PRE_FullRestoreOverridesSessionRestoreTest) {
// Create a browser and create a tab for it. Its bounds should not equal
// |kCurrentBounds|.
Browser* browser = Browser::Create(Browser::CreateParams(profile(), true));
AddBlankTabAndShow(browser);
aura::Window* window = browser->window()->GetNativeWindow();
ASSERT_NE(kCurrentBounds, window->bounds());
// Ensure that |browser| is in a normal show state.
auto* window_state = ash::WindowState::Get(window);
window_state->Restore();
ASSERT_TRUE(window_state->IsNormalStateType());
// Turn on session restore.
SessionStartupPref::SetStartupPref(
profile(), SessionStartupPref(SessionStartupPref::LAST));
}
// Tests that Full Restore data overrides the browser's session restore data.
// Session restore is turned on in the PRE phase of the test, simulating a user
// logging out and back in.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerBrowserTest,
FullRestoreOverridesSessionRestoreTest) {
constexpr int kRestoreId = 1;
auto* browser_list = BrowserList::GetInstance();
size_t count = browser_list->size();
ASSERT_EQ(0u, count);
// Create Full Restore launch data before launching any browser, simulating
// Full Restore data being saved prior to restart.
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
extension_misc::kChromeAppId, kRestoreId));
CreateAndSaveWindowInfo(kDeskId, kCurrentBounds,
chromeos::WindowStateType::kNormal,
ui::SHOW_STATE_DEFAULT, kRestoreId);
WaitForAppLaunchInfoSaved();
// Launch the browser.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
app_launch_handler->LaunchBrowserWhenReady(/*first_run_full_restore=*/false);
SetShouldRestore(app_launch_handler.get());
ASSERT_EQ(count + 1u, browser_list->size());
ASSERT_EQ(1u, browser_list->size());
// The restored browser's bounds should be the bounds saved by Full Restore,
// i.e. |kCurrentBounds|.
const gfx::Rect& browser_bounds =
browser_list->get(0u)->window()->GetNativeWindow()->bounds();
EXPECT_EQ(kCurrentBounds, browser_bounds);
}
class FullRestoreAppLaunchHandlerChromeAppBrowserTest
: public FullRestoreAppLaunchHandlerBrowserTest {
public:
FullRestoreAppLaunchHandlerChromeAppBrowserTest() {
ResetRestoreForTesting();
set_launch_browser_for_testing(
std::make_unique<ScopedLaunchBrowserForTesting>());
}
~FullRestoreAppLaunchHandlerChromeAppBrowserTest() override = default;
};
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerChromeAppBrowserTest,
RestoreChromeApp) {
// Have 4 desks total.
ash::AutotestDesksApi().CreateNewDesk();
ash::AutotestDesksApi().CreateNewDesk();
ash::AutotestDesksApi().CreateNewDesk();
::full_restore::SetActiveProfilePath(profile()->GetPath());
// Create the restore data.
const extensions::Extension* extension =
LoadAndLaunchPlatformApp("launch", "Launched");
ASSERT_TRUE(extension);
SaveChromeAppLaunchInfo(extension->id());
extensions::AppWindow* app_window = CreateAppWindow(profile(), extension);
ASSERT_TRUE(app_window);
auto* window = app_window->GetNativeWindow();
SaveWindowInfo(window);
WaitForAppLaunchInfoSaved();
// Simulate the system shutdown process, and the window is closed.
FullRestoreService::GetForProfile(profile())->Observe(
chrome::NOTIFICATION_APP_TERMINATING,
content::Source<extensions::AppWindow>(app_window),
content::NotificationDetails());
CloseAppWindow(app_window);
WaitForAppLaunchInfoSaved();
// Create a non-restored window in the restored window's desk container.
Browser::CreateParams non_restored_params(profile(), true);
non_restored_params.initial_workspace = "2";
Browser* non_restored_browser = Browser::Create(non_restored_params);
AddBlankTabAndShow(non_restored_browser);
aura::Window* non_restored_window =
non_restored_browser->window()->GetNativeWindow();
// Read from the restore data.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
// Verify the restore window id.
app_window = CreateAppWindow(browser()->profile(), extension);
ASSERT_TRUE(app_window);
window = app_window->GetNativeWindow();
ASSERT_TRUE(window);
int restore_window_id =
window->GetProperty(::full_restore::kRestoreWindowIdKey);
EXPECT_NE(0, restore_window_id);
auto* window_info = window->GetProperty(::full_restore::kWindowInfoKey);
ASSERT_TRUE(window_info);
EXPECT_TRUE(window_info->activation_index.has_value());
int32_t* index = window->GetProperty(::full_restore::kActivationIndexKey);
ASSERT_TRUE(index);
EXPECT_EQ(kActivationIndex, *index);
EXPECT_EQ(kDeskId, window->GetProperty(aura::client::kWindowWorkspaceKey));
// Non-topmost windows created from full restore are not activated. They will
// become activatable after a couple seconds. Verify that the
// `non_restored_window` is topmost and check that `window` is not
// activatable.
std::vector<aura::Window*> expected_stacking{window, non_restored_window};
EXPECT_EQ(non_restored_window->parent()->children(), expected_stacking);
EXPECT_FALSE(views::Widget::GetWidgetForNativeView(window)->IsActive());
EXPECT_FALSE(wm::CanActivateWindow(window));
// Wait a couple seconds and verify the window is now activatable.
base::RunLoop run_loop;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), base::TimeDelta::FromSeconds(3));
run_loop.Run();
EXPECT_TRUE(wm::CanActivateWindow(window));
EXPECT_EQ(0, ::full_restore::FetchRestoreWindowId(extension->id()));
// Close the window.
CloseAppWindow(app_window);
ASSERT_FALSE(GetWindowInfo(restore_window_id));
// Remove the added desks.
RemoveInactiveDesks();
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerChromeAppBrowserTest,
RestoreMinimizedChromeApp) {
::full_restore::SetActiveProfilePath(profile()->GetPath());
// Create the restore data.
const extensions::Extension* extension =
LoadAndLaunchPlatformApp("launch", "Launched");
ASSERT_TRUE(extension);
SaveChromeAppLaunchInfo(extension->id());
extensions::AppWindow* app_window = CreateAppWindow(profile(), extension);
ASSERT_TRUE(app_window);
// Save app window as minimized.
SaveWindowInfo(app_window->GetNativeWindow(), 1u,
chromeos::WindowStateType::kMinimized);
WaitForAppLaunchInfoSaved();
// Read from the restore data.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
// Tests that the created window is minimized.
app_window = CreateAppWindow(browser()->profile(), extension);
ASSERT_TRUE(app_window);
EXPECT_TRUE(app_window->GetBaseWindow()->IsMinimized());
}
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerChromeAppBrowserTest,
RestoreMultipleChromeAppWindows) {
::full_restore::SetActiveProfilePath(profile()->GetPath());
// Create the restore data, 2 windows for 1 chrome app.
const extensions::Extension* extension =
LoadAndLaunchPlatformApp("launch", "Launched");
ASSERT_TRUE(extension);
const std::string& app_id = extension->id();
SaveChromeAppLaunchInfo(app_id);
extensions::AppWindow* app_window1 = CreateAppWindow(profile(), extension);
ASSERT_TRUE(app_window1);
auto* window1 = app_window1->GetNativeWindow();
SaveWindowInfo(window1);
SaveChromeAppLaunchInfo(app_id);
extensions::AppWindow* app_window2 = CreateAppWindow(profile(), extension);
ASSERT_TRUE(app_window2);
auto* window2 = app_window2->GetNativeWindow();
SaveWindowInfo(window2);
WaitForAppLaunchInfoSaved();
// Read from the restore data.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
// Verify the restore window id;
app_window1 = CreateAppWindow(browser()->profile(), extension);
ASSERT_TRUE(app_window1);
window1 = app_window1->GetNativeWindow();
ASSERT_TRUE(window1);
EXPECT_NE(0, window1->GetProperty(::full_restore::kRestoreWindowIdKey));
auto window_info = ::full_restore::GetWindowInfo(window1);
ASSERT_TRUE(window_info);
EXPECT_TRUE(window_info->activation_index.has_value());
EXPECT_EQ(INT32_MIN, window_info->activation_index.value());
app_window2 = CreateAppWindow(browser()->profile(), extension);
ASSERT_TRUE(app_window2);
window2 = app_window2->GetNativeWindow();
ASSERT_TRUE(window2);
EXPECT_NE(0, window2->GetProperty(::full_restore::kRestoreWindowIdKey));
window_info = ::full_restore::GetWindowInfo(window2);
ASSERT_TRUE(window_info);
EXPECT_TRUE(window_info->activation_index.has_value());
EXPECT_EQ(INT32_MIN, window_info->activation_index.value());
// Create a new window, verity the restore window id is 0.
auto* app_window = CreateAppWindow(browser()->profile(), extension);
ASSERT_TRUE(app_window);
auto* window = app_window->GetNativeWindow();
ASSERT_TRUE(window);
EXPECT_EQ(0, window->GetProperty(::full_restore::kRestoreWindowIdKey));
// Close the window.
CloseAppWindow(app_window1);
CloseAppWindow(app_window2);
}
// Tests that fullscreened windows will not be restored as fullscreen, which is
// not supported for full restore. Regression test for
// https://crbug.com/1203010.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerChromeAppBrowserTest,
ImmersiveFullscreenApp) {
::full_restore::SetActiveProfilePath(profile()->GetPath());
// Create the restore data.
const extensions::Extension* extension =
LoadAndLaunchPlatformApp("launch", "Launched");
ASSERT_TRUE(extension);
SaveChromeAppLaunchInfo(extension->id());
extensions::AppWindow* app_window = CreateAppWindow(profile(), extension);
ASSERT_TRUE(app_window);
// Toggle immersive fullscreen by simulating what happens when F4 is pressed.
// FullRestoreController will save to file when the state changes.
const ash::WMEvent event(ash::WM_EVENT_TOGGLE_FULLSCREEN);
ash::WindowState::Get(app_window->GetNativeWindow())->OnWMEvent(&event);
WaitForAppLaunchInfoSaved();
// Read from the restore data.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
// Tests that the created window is not fullscreen.
app_window = CreateAppWindow(browser()->profile(), extension);
ASSERT_TRUE(app_window);
EXPECT_FALSE(app_window->GetBaseWindow()->IsFullscreenOrPending());
}
class FullRestoreAppLaunchHandlerArcAppBrowserTest
: public FullRestoreAppLaunchHandlerBrowserTest {
protected:
// FullRestoreAppLaunchHandlerBrowserTest:
void SetUpCommandLine(base::CommandLine* command_line) override {
FullRestoreAppLaunchHandlerBrowserTest::SetUpCommandLine(command_line);
arc::SetArcAvailableCommandLineForTesting(command_line);
}
void SetUpInProcessBrowserTestFixture() override {
FullRestoreAppLaunchHandlerBrowserTest::SetUpInProcessBrowserTestFixture();
arc::ArcSessionManager::SetUiEnabledForTesting(false);
}
void SetUpOnMainThread() override {
FullRestoreAppLaunchHandlerBrowserTest::SetUpOnMainThread();
arc::SetArcPlayStoreEnabledForProfile(profile(), true);
// This ensures app_prefs()->GetApp() below never returns nullptr.
base::RunLoop run_loop;
app_prefs()->SetDefaultAppsReadyCallback(run_loop.QuitClosure());
run_loop.Run();
}
void StartInstance() {
app_instance_ = std::make_unique<arc::FakeAppInstance>(app_host());
arc_brige_service()->app()->SetInstance(app_instance_.get());
}
void StopInstance() {
if (app_instance_)
arc_brige_service()->app()->CloseInstance(app_instance_.get());
arc_session_manager()->Shutdown();
}
void SendPackageAdded(const std::string& package_name) {
arc::mojom::ArcPackageInfo package_info;
package_info.package_name = package_name;
package_info.package_version = 1;
package_info.last_backup_android_id = 1;
package_info.last_backup_time = 1;
package_info.sync = false;
package_info.system = false;
app_host()->OnPackageAdded(arc::mojom::ArcPackageInfo::From(package_info));
base::RunLoop().RunUntilIdle();
}
void InstallTestApps(const std::string& package_name, bool multi_app) {
StartInstance();
app_host()->OnAppListRefreshed(GetTestAppsList(package_name, multi_app));
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
app_prefs()->GetApp(GetTestApp1Id(package_name));
ASSERT_TRUE(app_info);
EXPECT_TRUE(app_info->ready);
if (multi_app) {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info2 =
app_prefs()->GetApp(GetTestApp2Id(package_name));
ASSERT_TRUE(app_info2);
EXPECT_TRUE(app_info2->ready);
}
SendPackageAdded(package_name);
}
void CreateTask(const std::string& app_id,
int32_t task_id,
int32_t session_id) {
auto info = app_prefs()->GetApp(app_id);
app_host()->OnTaskCreated(task_id, info->package_name, info->activity,
info->name, info->intent_uri, session_id);
}
void UpdateThemeColor(int32_t task_id,
uint32_t primary_color,
uint32_t status_bar_color) {
auto empty_icon = arc::mojom::RawIconPngData::New();
app_host()->OnTaskDescriptionChanged(task_id, "", std::move(empty_icon),
primary_color, status_bar_color);
}
void SetProfile() {
::full_restore::FullRestoreSaveHandler::GetInstance()
->SetPrimaryProfilePath(profile()->GetPath());
::full_restore::SetActiveProfilePath(profile()->GetPath());
test_full_restore_info_observer_.Reset();
}
void SaveAppLaunchInfo(const std::string& app_id, int32_t session_id) {
::full_restore::SaveAppLaunchInfo(
profile()->GetPath(), std::make_unique<::full_restore::AppLaunchInfo>(
app_id, ui::EventFlags::EF_NONE, session_id,
display::kDefaultDisplayId));
}
void Restore() {
test_full_restore_info_observer_.Reset();
arc_app_launch_handler_ =
FullRestoreArcTaskHandler::GetForProfile(profile())
->arc_app_launch_handler();
arc_app_launch_handler_->is_app_connection_ready_ = false;
app_launch_handler_ =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler_.get());
}
void ForceLaunchApp(const std::string& app_id, int32_t window_id) {
if (arc_app_launch_handler_) {
arc_app_launch_handler_->LaunchApp(app_id, window_id);
content::RunAllTasksUntilIdle();
}
}
void VerifyGetArcAppLaunchInfo(const std::string& app_id,
int32_t session_id,
int32_t restore_window_id) {
auto app_launch_info =
::full_restore::GetArcAppLaunchInfo(app_id, session_id);
ASSERT_TRUE(app_launch_info);
EXPECT_EQ(app_id, app_launch_info->app_id);
EXPECT_TRUE(app_launch_info->window_id.has_value());
EXPECT_EQ(restore_window_id, app_launch_info->window_id.value());
EXPECT_TRUE(app_launch_info->event_flag.has_value());
EXPECT_EQ(ui::EventFlags::EF_NONE, app_launch_info->event_flag.value());
}
void VerifyWindowProperty(aura::Window* window,
int32_t window_id,
int32_t restore_window_id,
bool hidden) {
ASSERT_TRUE(window);
EXPECT_EQ(window_id, window->GetProperty(::full_restore::kWindowIdKey));
EXPECT_EQ(restore_window_id,
window->GetProperty(::full_restore::kRestoreWindowIdKey));
EXPECT_EQ(hidden,
window->GetProperty(::full_restore::kParentToHiddenContainerKey));
}
void VerifyWindowInfo(aura::Window* window,
int32_t activation_index,
chromeos::WindowStateType window_state_type =
chromeos::WindowStateType::kDefault) {
auto window_info = ::full_restore::GetWindowInfo(window);
ASSERT_TRUE(window_info);
EXPECT_TRUE(window_info->activation_index.has_value());
EXPECT_EQ(activation_index, window_info->activation_index.value());
EXPECT_FALSE(window_info->current_bounds.has_value());
// For ARC windows, Android can restore window minimized or maximized
// status, so the WindowStateType from the window info for the minimized and
// maximized state will be removed.
if (window_state_type == chromeos::WindowStateType::kMaximized ||
window_state_type == chromeos::WindowStateType::kMinimized) {
EXPECT_FALSE(window_info->window_state_type.has_value());
} else {
EXPECT_TRUE(window_info->window_state_type.has_value());
EXPECT_EQ(window_state_type, window_info->window_state_type.value());
}
}
void VerifyObserver(aura::Window* window, int launch_count, int init_count) {
auto& launched_windows =
test_full_restore_info_observer_.launched_windows();
if (launch_count == 0) {
EXPECT_TRUE(launched_windows.find(window) == launched_windows.end());
} else {
EXPECT_EQ(launch_count, launched_windows[window]);
}
auto& initialized_windows =
test_full_restore_info_observer_.initialized_windows();
if (init_count == 0) {
EXPECT_TRUE(initialized_windows.find(window) ==
initialized_windows.end());
} else {
EXPECT_EQ(init_count, initialized_windows[window]);
}
}
void VerifyThemeColor(const std::string& app_id,
int32_t task_id,
uint32_t primary_color,
uint32_t status_bar_color) {
const auto& app_id_to_launch_list =
app_launch_handler()->restore_data()->app_id_to_launch_list();
auto it = app_id_to_launch_list.find(app_id);
EXPECT_TRUE(it != app_id_to_launch_list.end());
auto data_it = it->second.find(task_id);
EXPECT_TRUE(data_it != it->second.end());
EXPECT_TRUE(data_it->second->primary_color.has_value());
EXPECT_EQ(primary_color, data_it->second->primary_color.value());
EXPECT_TRUE(data_it->second->status_bar_color.has_value());
EXPECT_EQ(status_bar_color, data_it->second->status_bar_color.value());
}
void VerifyRestoreData(const std::string& app_id, int32_t window_id) {
DCHECK(app_launch_handler());
const auto& app_id_to_launch_list =
app_launch_handler()->restore_data()->app_id_to_launch_list();
auto it = app_id_to_launch_list.find(app_id);
EXPECT_TRUE(it != app_id_to_launch_list.end());
auto data_it = it->second.find(window_id);
EXPECT_TRUE(data_it != it->second.end());
}
void VerifyNoRestoreData(const std::string& app_id) {
DCHECK(app_launch_handler());
const auto& app_id_to_launch_list =
app_launch_handler()->restore_data()->app_id_to_launch_list();
auto it = app_id_to_launch_list.find(app_id);
EXPECT_FALSE(it != app_id_to_launch_list.end());
}
ArcAppListPrefs* app_prefs() { return ArcAppListPrefs::Get(profile()); }
arc::mojom::AppHost* app_host() { return app_prefs(); }
FullRestoreAppLaunchHandler* app_launch_handler() {
if (!app_launch_handler_)
app_launch_handler_ =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
return app_launch_handler_.get();
}
TestFullRestoreInfoObserver* test_full_restore_info_observer() {
return &test_full_restore_info_observer_;
}
protected:
ArcAppLaunchHandler* arc_app_launch_handler_ = nullptr;
private:
arc::ArcSessionManager* arc_session_manager() {
return arc::ArcSessionManager::Get();
}
arc::ArcBridgeService* arc_brige_service() {
return arc::ArcServiceManager::Get()->arc_bridge_service();
}
std::unique_ptr<arc::FakeAppInstance> app_instance_;
std::unique_ptr<FullRestoreAppLaunchHandler> app_launch_handler_;
TestFullRestoreInfoObserver test_full_restore_info_observer_;
};
// Test the not restored ARC window is not added to the hidden container.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerArcAppBrowserTest,
NotHideArcWindow) {
SetProfile();
InstallTestApps(kTestAppPackage, false);
const std::string app_id = GetTestApp1Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
::full_restore::FullRestoreInfo::GetInstance()->AddObserver(
test_full_restore_info_observer());
SaveAppLaunchInfo(app_id, session_id1);
// Create the window for app1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
views::Widget* widget = CreateExoWindow("org.chromium.arc.100");
aura::Window* window = widget->GetNativeWindow();
VerifyObserver(window, /*launch_count=*/0, /*init_count=*/0);
VerifyWindowProperty(window, kTaskId1, /*restore_window_id=*/0,
/*hidden=*/false);
// Simulate creating the task.
CreateTask(app_id, kTaskId1, session_id1);
VerifyObserver(window, /*launch_count=*/1, /*init_count=*/0);
SaveWindowInfo(window);
WaitForAppLaunchInfoSaved();
Restore();
widget->CloseNow();
app_host()->OnTaskDestroyed(kTaskId1);
int32_t session_id2 = 1;
// Create the window to simulate launching the ARC app.
int32_t kTaskId2 = 200;
widget = CreateExoWindow("org.chromium.arc.200");
window = widget->GetNativeWindow();
// The task is not ready, so the window is currently in a hidden container.
EXPECT_EQ(ash::Shell::GetContainer(window->GetRootWindow(),
ash::kShellWindowId_UnparentedContainer),
window->parent());
VerifyObserver(window, /*launch_count=*/0, /*init_count=*/1);
VerifyWindowProperty(window, kTaskId2,
::full_restore::kParentToHiddenContainer,
/*hidden=*/true);
// Simulate creating the task for the ARC app window.
CreateTask(app_id, kTaskId2, session_id2);
VerifyObserver(window, /*launch_count=*/0, /*init_count=*/1);
VerifyWindowProperty(window, kTaskId2,
::full_restore::kParentToHiddenContainer,
/*hidden=*/false);
// Destroy the task and close the window.
app_host()->OnTaskDestroyed(kTaskId2);
widget->CloseNow();
int32_t session_id3 = 2;
int32_t kTaskId3 = 300;
// Simulate creating the task before the window is created.
CreateTask(app_id, kTaskId3, session_id3);
// Create the window to simulate launching the ARC app.
widget = CreateExoWindow("org.chromium.arc.300");
window = widget->GetNativeWindow();
VerifyObserver(window, /*launch_count=*/0, /*init_count=*/0);
// The window should not be hidden.
VerifyWindowProperty(window, kTaskId3,
/*restore_window_id=*/0,
/*hidden=*/false);
// Destroy the task and close the window.
app_host()->OnTaskDestroyed(kTaskId3);
widget->CloseNow();
::full_restore::FullRestoreInfo::GetInstance()->RemoveObserver(
test_full_restore_info_observer());
StopInstance();
}
// Test restoration when the ARC window is created before OnTaskCreated is
// called.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerArcAppBrowserTest,
RestoreArcApp) {
SetProfile();
InstallTestApps(kTestAppPackage, false);
const std::string app_id = GetTestApp1Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
::full_restore::FullRestoreInfo::GetInstance()->AddObserver(
test_full_restore_info_observer());
SaveAppLaunchInfo(app_id, session_id1);
// Create the window for app1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
views::Widget* widget = CreateExoWindow("org.chromium.arc.100");
aura::Window* window = widget->GetNativeWindow();
VerifyObserver(window, /*launch_count=*/0, /*init_count=*/0);
VerifyWindowProperty(window, kTaskId1, /*restore_window_id=*/0,
/*hidden=*/false);
// Simulate creating the task.
CreateTask(app_id, kTaskId1, session_id1);
VerifyObserver(window, /*launch_count=*/1, /*init_count=*/0);
SaveWindowInfo(window);
WaitForAppLaunchInfoSaved();
// Simulate the system shutdown process, and the window is closed.
FullRestoreService::GetForProfile(profile())->Observe(
chrome::NOTIFICATION_APP_TERMINATING,
content::Source<aura::Window>(window), content::NotificationDetails());
widget->CloseNow();
WaitForAppLaunchInfoSaved();
Restore();
app_host()->OnTaskDestroyed(kTaskId1);
int32_t session_id2 =
::full_restore::kArcSessionIdOffsetForRestoredLaunching + 1;
// Create some desks so we can test that the exo window is placed in the
// correct desk container after the task is created.
ash::AutotestDesksApi().CreateNewDesk();
ash::AutotestDesksApi().CreateNewDesk();
ash::AutotestDesksApi().CreateNewDesk();
ForceLaunchApp(app_id, kTaskId1);
// Create the window to simulate the restoration for the app. The task id
// needs to match the |window_app_id| arg of CreateExoWindow.
int32_t kTaskId2 = 200;
widget = CreateExoWindow("org.chromium.arc.200");
window = widget->GetNativeWindow();
// The task is not ready, so the window is currently in a hidden container.
EXPECT_EQ(ash::Shell::GetContainer(window->GetRootWindow(),
ash::kShellWindowId_UnparentedContainer),
window->parent());
VerifyObserver(window, /*launch_count=*/0, /*init_count=*/1);
VerifyWindowProperty(window, kTaskId2,
::full_restore::kParentToHiddenContainer,
/*hidden=*/true);
// Simulate creating the task for the restored window.
CreateTask(app_id, kTaskId2, session_id2);
// Tests that after the task is created, the window is placed in the container
// associated with `kDeskId` (2), which is desk C.
EXPECT_EQ(ash::Shell::GetContainer(window->GetRootWindow(),
ash::kShellWindowId_DeskContainerC),
window->parent());
VerifyObserver(window, /*launch_count=*/1, /*init_count=*/1);
VerifyWindowProperty(window, kTaskId2, kTaskId1, /*hidden=*/false);
VerifyWindowInfo(window, kActivationIndex);
// Destroy the task and close the window.
app_host()->OnTaskDestroyed(kTaskId2);
widget->CloseNow();
ASSERT_FALSE(GetWindowInfo(kTaskId1));
::full_restore::FullRestoreInfo::GetInstance()->RemoveObserver(
test_full_restore_info_observer());
StopInstance();
RemoveInactiveDesks();
}
// Test restoration when the ARC ghost window is created before OnTaskCreated is
// called.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerArcAppBrowserTest,
RestoreArcGhostWindow) {
SetProfile();
InstallTestApps(kTestAppPackage, false);
const std::string app_id = GetTestApp1Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
::full_restore::FullRestoreInfo::GetInstance()->AddObserver(
test_full_restore_info_observer());
SaveAppLaunchInfo(app_id, session_id1);
// Create the window for app1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
views::Widget* widget = CreateExoWindow("org.chromium.arc.100");
aura::Window* window = widget->GetNativeWindow();
VerifyObserver(window, /*launch_count=*/0, /*init_count=*/0);
VerifyWindowProperty(window, kTaskId1, /*restore_window_id=*/0,
/*hidden=*/false);
// Simulate creating the task.
CreateTask(app_id, kTaskId1, session_id1);
VerifyObserver(window, /*launch_count=*/1, /*init_count=*/0);
SaveWindowInfo(window);
WaitForAppLaunchInfoSaved();
Restore();
widget->CloseNow();
app_host()->OnTaskDestroyed(kTaskId1);
int32_t session_id2 =
::full_restore::FullRestoreReadHandler::GetInstance()->GetArcSessionId();
::full_restore::FullRestoreReadHandler::GetInstance()
->SetArcSessionIdForWindowId(session_id2, kTaskId1);
// Create the window with the ghost window session to simulate the ghost
// window restoration for the app.
widget = CreateExoWindow(
base::StringPrintf("org.chromium.arc.session.%d", session_id2), app_id);
window = widget->GetNativeWindow();
SaveAppLaunchInfo(app_id, session_id2);
// The ghost window should not be hidden.
VerifyWindowProperty(window, /*window_id*/ 0,
/*restore_window_id*/ kTaskId1,
/*hidden=*/false);
VerifyGetArcAppLaunchInfo(app_id, session_id2, kTaskId1);
// Call SaveAppLaunchInfo to simulate the ARC app is ready, and launch the app
// again.
SaveAppLaunchInfo(app_id, session_id2);
// Simulate creating the task for the restored window.
int32_t kTaskId2 = 200;
window->SetProperty(::full_restore::kWindowIdKey, kTaskId2);
CreateTask(app_id, kTaskId2, session_id2);
VerifyWindowProperty(window, kTaskId2, kTaskId1, /*hidden=*/false);
VerifyWindowInfo(window, kActivationIndex);
// Verify the ghost window session id has been removed from the restore data.
EXPECT_FALSE(::full_restore::GetArcAppLaunchInfo(app_id, session_id2));
// Destroy the task and close the window.
app_host()->OnTaskDestroyed(kTaskId2);
widget->CloseNow();
::full_restore::FullRestoreInfo::GetInstance()->RemoveObserver(
test_full_restore_info_observer());
StopInstance();
RemoveInactiveDesks();
}
// Test the ARC ghost window is saved if the task is not created.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerArcAppBrowserTest,
SaveArcGhostWindow) {
SetProfile();
InstallTestApps(kTestAppPackage, false);
const std::string app_id = GetTestApp1Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
::full_restore::FullRestoreInfo::GetInstance()->AddObserver(
test_full_restore_info_observer());
SaveAppLaunchInfo(app_id, session_id1);
// Create the window for app1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
views::Widget* widget = CreateExoWindow("org.chromium.arc.100");
aura::Window* window = widget->GetNativeWindow();
VerifyObserver(window, /*launch_count=*/0, /*init_count=*/0);
VerifyWindowProperty(window, kTaskId1, /*restore_window_id=*/0,
/*hidden=*/false);
// Simulate creating the task.
CreateTask(app_id, kTaskId1, session_id1);
VerifyObserver(window, /*launch_count=*/1, /*init_count=*/0);
SaveWindowInfo(window);
WaitForAppLaunchInfoSaved();
// Simulate the system reboot.
Restore();
widget->CloseNow();
app_host()->OnTaskDestroyed(kTaskId1);
int32_t session_id2 =
::full_restore::FullRestoreReadHandler::GetInstance()->GetArcSessionId();
::full_restore::FullRestoreReadHandler::GetInstance()
->SetArcSessionIdForWindowId(session_id2, kTaskId1);
// Create the window with the ghost window session to simulate the ghost
// window restoration for the app.
widget = CreateExoWindow(
base::StringPrintf("org.chromium.arc.session.%d", session_id2), app_id);
window = widget->GetNativeWindow();
SaveAppLaunchInfo(app_id, session_id2);
SaveWindowInfo(window);
// The ghost window should not be hidden.
VerifyWindowProperty(window, /*window_id*/ 0,
/*restore_window_id*/ kTaskId1,
/*hidden=*/false);
VerifyGetArcAppLaunchInfo(app_id, session_id2, kTaskId1);
WaitForAppLaunchInfoSaved();
// Simulate the system reboot before the task id is created.
Restore();
widget->CloseNow();
int32_t session_id3 =
::full_restore::FullRestoreReadHandler::GetInstance()->GetArcSessionId();
::full_restore::FullRestoreReadHandler::GetInstance()
->SetArcSessionIdForWindowId(session_id3, session_id2);
// Create the window with the ghost window session to simulate the ghost
// window restoration for the app.
widget = CreateExoWindow(
base::StringPrintf("org.chromium.arc.session.%d", session_id3), app_id);
window = widget->GetNativeWindow();
SaveAppLaunchInfo(app_id, session_id3);
SaveWindowInfo(window);
// Call SaveAppLaunchInfo to simulate the ARC app is ready, and launch the app
// again.
SaveAppLaunchInfo(app_id, session_id3);
// Simulate creating the task for the restored window.
int32_t kTaskId2 = 200;
CreateTask(app_id, kTaskId2, session_id3);
window->SetProperty(::full_restore::kWindowIdKey, kTaskId2);
VerifyWindowProperty(window, kTaskId2, session_id2, /*hidden=*/false);
VerifyWindowInfo(window, kActivationIndex);
// Verify the ghost window session id has been removed from the restore data.
EXPECT_FALSE(::full_restore::GetArcAppLaunchInfo(app_id, session_id3));
// Destroy the task and close the window.
app_host()->OnTaskDestroyed(kTaskId2);
widget->CloseNow();
::full_restore::FullRestoreInfo::GetInstance()->RemoveObserver(
test_full_restore_info_observer());
StopInstance();
RemoveInactiveDesks();
}
// Test restoration with multiple ARC apps, when the ARC windows are created
// before and after OnTaskCreated is called.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerArcAppBrowserTest,
RestoreMultipleArcApps) {
SetProfile();
InstallTestApps(kTestAppPackage, true);
const std::string app_id1 = GetTestApp1Id(kTestAppPackage);
const std::string app_id2 = GetTestApp2Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
int32_t session_id2 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
::full_restore::FullRestoreInfo::GetInstance()->AddObserver(
test_full_restore_info_observer());
SaveAppLaunchInfo(app_id1, session_id1);
SaveAppLaunchInfo(app_id2, session_id2);
// Simulate creating kTaskId1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
CreateTask(app_id1, kTaskId1, session_id1);
// Create the window for the app1 and store its bounds.
views::Widget* widget1 = CreateExoWindow("org.chromium.arc.100");
aura::Window* window1 = widget1->GetNativeWindow();
gfx::Rect pre_restore_bounds_1 = window1->GetBoundsInScreen();
// Create the window for the app2 and store its bounds. The task id needs to
// match the |window_app_id| arg of CreateExoWindow.
int32_t kTaskId2 = 101;
views::Widget* widget2 = CreateExoWindow("org.chromium.arc.101");
aura::Window* window2 = widget2->GetNativeWindow();
gfx::Rect pre_restore_bounds_2 = window2->GetBoundsInScreen();
// Simulate creating kTaskId2.
CreateTask(app_id2, kTaskId2, session_id2);
VerifyObserver(window1, /*launch_count=*/1, /*init_count=*/0);
VerifyObserver(window2, /*launch_count=*/1, /*init_count=*/0);
VerifyWindowProperty(window1, kTaskId1, /*restore_window_id*/ 0,
/*hidden=*/false);
VerifyWindowProperty(window2, kTaskId2, /*restore_window_id*/ 0,
/*hidden=*/false);
WaitForAppLaunchInfoSaved();
int32_t activation_index1 = 11;
int32_t activation_index2 = 12;
SaveWindowInfo(window1, activation_index1,
chromeos::WindowStateType::kMaximized);
SaveWindowInfo(window2, activation_index2,
chromeos::WindowStateType::kMinimized);
WaitForAppLaunchInfoSaved();
Restore();
widget1->CloseNow();
widget2->CloseNow();
app_host()->OnTaskDestroyed(kTaskId1);
app_host()->OnTaskDestroyed(kTaskId2);
ForceLaunchApp(app_id1, kTaskId1);
ForceLaunchApp(app_id2, kTaskId2);
int32_t session_id3 =
::full_restore::kArcSessionIdOffsetForRestoredLaunching + 1;
int32_t session_id4 =
::full_restore::kArcSessionIdOffsetForRestoredLaunching + 2;
// Create the window to simulate the restoration for the app1. The task id
// needs to match the |window_app_id| arg of CreateExoWindow.
int32_t kTaskId3 = 201;
widget1 = CreateExoWindow("org.chromium.arc.201");
window1 = widget1->GetNativeWindow();
VerifyWindowProperty(window1, kTaskId3,
::full_restore::kParentToHiddenContainer,
/*hidden=*/true);
EXPECT_EQ(pre_restore_bounds_1, window1->GetBoundsInScreen());
// Simulate creating tasks for apps.
CreateTask(app_id1, kTaskId3, session_id3);
int32_t kTaskId4 = 202;
CreateTask(app_id2, kTaskId4, session_id4);
// Create the window to simulate the restoration for the app2.
widget2 = CreateExoWindow("org.chromium.arc.202");
window2 = widget2->GetNativeWindow();
EXPECT_EQ(pre_restore_bounds_2, window2->GetBoundsInScreen());
VerifyObserver(window1, /*launch_count=*/1, /*init_count=*/1);
VerifyObserver(window2, /*launch_count=*/1, /*init_count=*/1);
VerifyWindowProperty(window1, kTaskId3, kTaskId1, /*hidden=*/false);
VerifyWindowProperty(window2, kTaskId4, kTaskId2, /*hidden=*/false);
VerifyWindowInfo(window1, activation_index1,
chromeos::WindowStateType::kMaximized);
VerifyWindowInfo(window2, activation_index2,
chromeos::WindowStateType::kMinimized);
// destroy tasks and close windows.
widget1->CloseNow();
app_host()->OnTaskDestroyed(kTaskId3);
app_host()->OnTaskDestroyed(kTaskId4);
widget2->CloseNow();
ASSERT_FALSE(GetWindowInfo(kTaskId1));
ASSERT_FALSE(GetWindowInfo(kTaskId2));
StopInstance();
}
// Test restoration when the ARC window is created before OnTaskCreated is
// called.
IN_PROC_BROWSER_TEST_F(FullRestoreAppLaunchHandlerArcAppBrowserTest,
ArcAppThemeColorUpdate) {
SetProfile();
InstallTestApps(kTestAppPackage, false);
const std::string app_id = GetTestApp1Id(kTestAppPackage);
int32_t session_id =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
::full_restore::FullRestoreInfo::GetInstance()->AddObserver(
test_full_restore_info_observer());
SaveAppLaunchInfo(app_id, session_id);
// Create the window for app1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId = 100;
uint32_t kPrimaryColor = 0xFFFFFFFF;
uint32_t kStatusBarColor = 0xFF000000;
views::Widget* widget = CreateExoWindow("org.chromium.arc.100");
aura::Window* window = widget->GetNativeWindow();
VerifyObserver(window, /*launch_count=*/0, /*init_count=*/0);
VerifyWindowProperty(window, kTaskId, /*restore_window_id=*/0,
/*hidden=*/false);
// Simulate creating the task.
CreateTask(app_id, kTaskId, session_id);
UpdateThemeColor(kTaskId, kPrimaryColor, kStatusBarColor);
VerifyObserver(window, /*launch_count=*/1, /*init_count=*/0);
SaveWindowInfo(window);
WaitForAppLaunchInfoSaved();
ASSERT_TRUE(app_launch_handler());
content::RunAllTasksUntilIdle();
VerifyThemeColor(app_id, kTaskId, kPrimaryColor, kStatusBarColor);
widget->CloseNow();
app_host()->OnTaskDestroyed(kTaskId);
::full_restore::FullRestoreInfo::GetInstance()->RemoveObserver(
test_full_restore_info_observer());
StopInstance();
}
class ArcAppLaunchHandlerArcAppBrowserTest
: public FullRestoreAppLaunchHandlerArcAppBrowserTest {
protected:
void UpdateApp(const std::string& app_id, apps::mojom::Readiness readiness) {
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_id = app_id;
app->app_type = apps::mojom::AppType::kArc;
app->readiness = readiness;
std::vector<apps::mojom::AppPtr> deltas;
deltas.push_back(std::move(app));
auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile());
proxy->AppRegistryCache().OnApps(std::move(deltas),
apps::mojom::AppType::kArc,
false /* should_notify_initialized */);
}
void RemoveApp(const std::string& app_id) {
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_id = app_id;
app->app_type = apps::mojom::AppType::kArc;
app->readiness = apps::mojom::Readiness::kUninstalledByUser;
std::vector<apps::mojom::AppPtr> deltas;
deltas.push_back(std::move(app));
auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile());
proxy->AppRegistryCache().OnApps(std::move(deltas),
apps::mojom::AppType::kArc,
false /* should_notify_initialized */);
}
bool HasRestoreData() {
DCHECK(arc_app_launch_handler_);
return arc_app_launch_handler_->HasRestoreData();
}
bool HasRestoreData(const std::string& app_id) {
DCHECK(arc_app_launch_handler_);
for (auto it : arc_app_launch_handler_->windows_) {
if (it.second.app_id == app_id)
return true;
}
for (auto it : arc_app_launch_handler_->no_stack_windows_) {
if (it.app_id == app_id)
return true;
}
return false;
}
std::set<std::string> GetAppIds() {
DCHECK(arc_app_launch_handler_);
return arc_app_launch_handler_->app_ids_;
}
void OnAppConnectionReady() {
if (!arc_app_launch_handler_) {
arc_app_launch_handler_ =
FullRestoreArcTaskHandler::GetForProfile(profile())
->arc_app_launch_handler();
}
arc_app_launch_handler_->OnAppConnectionReady();
}
void VerifyWindows(int32_t index,
const std::string& app_id,
int32_t window_id) {
DCHECK(arc_app_launch_handler_);
auto it = arc_app_launch_handler_->windows_.find(index);
ASSERT_TRUE(it != arc_app_launch_handler_->windows_.end());
EXPECT_EQ(app_id, it->second.app_id);
EXPECT_EQ(window_id, it->second.window_id);
}
void VerifyNoStackWindows(const std::string& app_id, int32_t window_id) {
DCHECK(arc_app_launch_handler_);
bool found = false;
for (auto it : arc_app_launch_handler_->no_stack_windows_) {
if (it.app_id == app_id && it.window_id == window_id) {
found = true;
break;
}
}
EXPECT_TRUE(found);
}
};
// Verify the saved windows in ArcAppLaunchHandler when apps are removed.
IN_PROC_BROWSER_TEST_F(ArcAppLaunchHandlerArcAppBrowserTest, RemoveApps) {
SetProfile();
InstallTestApps(kTestAppPackage, true);
const std::string app_id1 = GetTestApp1Id(kTestAppPackage);
const std::string app_id2 = GetTestApp2Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
int32_t session_id2 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
SaveAppLaunchInfo(app_id1, session_id1);
SaveAppLaunchInfo(app_id2, session_id2);
// Simulate creating kTaskId1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
CreateTask(app_id1, kTaskId1, session_id1);
// Create the window for the app1.
views::Widget* widget1 = CreateExoWindow("org.chromium.arc.100");
aura::Window* window1 = widget1->GetNativeWindow();
// Simulate creating kTaskId2 for the app2.
int32_t kTaskId2 = 101;
CreateTask(app_id2, kTaskId2, session_id2);
WaitForAppLaunchInfoSaved();
int32_t activation_index1 = 11;
SaveWindowInfo(window1, activation_index1,
chromeos::WindowStateType::kNormal);
WaitForAppLaunchInfoSaved();
base::HistogramTester histogram_tester;
Restore();
widget1->CloseNow();
app_host()->OnTaskDestroyed(kTaskId1);
app_host()->OnTaskDestroyed(kTaskId2);
EXPECT_TRUE(HasRestoreData());
VerifyWindows(activation_index1, app_id1, kTaskId1);
VerifyNoStackWindows(app_id2, kTaskId2);
VerifyRestoreData(app_id1, kTaskId1);
VerifyRestoreData(app_id2, kTaskId2);
// Remove `app_id2`, and verify windows and restore data for `app_id2` have
// been removed.
RemoveApp(app_id2);
VerifyWindows(activation_index1, app_id1, kTaskId1);
EXPECT_FALSE(HasRestoreData(app_id2));
VerifyRestoreData(app_id1, kTaskId1);
VerifyNoRestoreData(app_id2);
OnAppConnectionReady();
EXPECT_EQ(
1, histogram_tester.GetBucketCount(kRestoredAppWindowCountHistogram, 1));
// Remove app_id1, and verify windows and restore data for `app_id1` have been
// removed.
RemoveApp(app_id1);
EXPECT_FALSE(HasRestoreData(app_id1));
VerifyNoRestoreData(app_id1);
VerifyNoRestoreData(app_id2);
// Modify `app_id1` status to be ready to simulate `app_id1` is installed.
UpdateApp(app_id1, apps::mojom::Readiness::kReady);
EXPECT_FALSE(HasRestoreData(app_id1));
EXPECT_TRUE(GetAppIds().empty());
VerifyNoRestoreData(app_id1);
StopInstance();
}
// Verify the saved windows in ArcAppLaunchHandler when apps status are
// modified.
IN_PROC_BROWSER_TEST_F(ArcAppLaunchHandlerArcAppBrowserTest, UpdateApps) {
SetProfile();
InstallTestApps(kTestAppPackage, true);
const std::string app_id1 = GetTestApp1Id(kTestAppPackage);
const std::string app_id2 = GetTestApp2Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
int32_t session_id2 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
SaveAppLaunchInfo(app_id1, session_id1);
SaveAppLaunchInfo(app_id2, session_id2);
// Simulate creating kTaskId1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
CreateTask(app_id1, kTaskId1, session_id1);
// Create the window for the app1.
views::Widget* widget1 = CreateExoWindow("org.chromium.arc.100");
aura::Window* window1 = widget1->GetNativeWindow();
// Simulate creating kTaskId2 for the app2.
int32_t kTaskId2 = 101;
CreateTask(app_id2, kTaskId2, session_id2);
WaitForAppLaunchInfoSaved();
int32_t activation_index1 = 11;
SaveWindowInfo(window1, activation_index1,
chromeos::WindowStateType::kNormal);
WaitForAppLaunchInfoSaved();
// Modify apps status before restoring, so that apps can't be restored.
UpdateApp(app_id1, apps::mojom::Readiness::kDisabledByPolicy);
UpdateApp(app_id2, apps::mojom::Readiness::kDisabledByPolicy);
base::HistogramTester histogram_tester;
Restore();
widget1->CloseNow();
app_host()->OnTaskDestroyed(kTaskId1);
app_host()->OnTaskDestroyed(kTaskId2);
std::set<std::string> app_ids = GetAppIds();
EXPECT_EQ(2u, app_ids.size());
EXPECT_TRUE(base::Contains(app_ids, app_id1));
EXPECT_TRUE(base::Contains(app_ids, app_id2));
EXPECT_FALSE(HasRestoreData());
// Modify `app_id1` status to be ready to prepare launching `app_id1`.
UpdateApp(app_id1, apps::mojom::Readiness::kReady);
app_ids = GetAppIds();
EXPECT_FALSE(base::Contains(app_ids, app_id1));
EXPECT_TRUE(base::Contains(app_ids, app_id2));
VerifyWindows(activation_index1, app_id1, kTaskId1);
// Modify `app_id2` status to be ready to prepare launching `app_id2`.
UpdateApp(app_id2, apps::mojom::Readiness::kReady);
app_ids = GetAppIds();
EXPECT_FALSE(base::Contains(app_ids, app_id1));
EXPECT_FALSE(base::Contains(app_ids, app_id2));
VerifyNoStackWindows(app_id2, kTaskId2);
// Verify the restore data and windows for `app_id1` and `app_id2` are not
// removed.
VerifyRestoreData(app_id1, kTaskId1);
VerifyRestoreData(app_id2, kTaskId2);
OnAppConnectionReady();
EXPECT_EQ(
1, histogram_tester.GetBucketCount(kRestoredAppWindowCountHistogram, 2));
StopInstance();
}
// Verify the saved windows in ArcAppLaunchHandler when only restore one of the
// apps.
IN_PROC_BROWSER_TEST_F(ArcAppLaunchHandlerArcAppBrowserTest, RestoreOneApp) {
SetProfile();
InstallTestApps(kTestAppPackage, true);
const std::string app_id1 = GetTestApp1Id(kTestAppPackage);
const std::string app_id2 = GetTestApp2Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
SaveAppLaunchInfo(app_id1, session_id1);
// Simulate creating kTaskId1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
CreateTask(app_id1, kTaskId1, session_id1);
// Create the window for the app1.
views::Widget* widget1 = CreateExoWindow("org.chromium.arc.100");
aura::Window* window1 = widget1->GetNativeWindow();
WaitForAppLaunchInfoSaved();
int32_t activation_index1 = 11;
SaveWindowInfo(window1, activation_index1,
chromeos::WindowStateType::kNormal);
WaitForAppLaunchInfoSaved();
base::HistogramTester histogram_tester;
Restore();
widget1->CloseNow();
app_host()->OnTaskDestroyed(kTaskId1);
EXPECT_TRUE(GetAppIds().empty());
EXPECT_TRUE(HasRestoreData());
VerifyWindows(activation_index1, app_id1, kTaskId1);
// Verify the restore data and windows for `app_id1` are not removed.
VerifyRestoreData(app_id1, kTaskId1);
VerifyNoRestoreData(app_id2);
OnAppConnectionReady();
EXPECT_EQ(
1, histogram_tester.GetBucketCount(kRestoredAppWindowCountHistogram, 1));
StopInstance();
}
// Verify the saved windows in ArcAppLaunchHandler when one of apps is ready
// late.
IN_PROC_BROWSER_TEST_F(ArcAppLaunchHandlerArcAppBrowserTest, AppIsReadyLate) {
SetProfile();
InstallTestApps(kTestAppPackage, true);
const std::string app_id1 = GetTestApp1Id(kTestAppPackage);
const std::string app_id2 = GetTestApp2Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
int32_t session_id2 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
SaveAppLaunchInfo(app_id1, session_id1);
SaveAppLaunchInfo(app_id2, session_id2);
// Simulate creating kTaskId1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
CreateTask(app_id1, kTaskId1, session_id1);
// Create the window for the app1.
views::Widget* widget1 = CreateExoWindow("org.chromium.arc.100");
aura::Window* window1 = widget1->GetNativeWindow();
// Simulate creating kTaskId2 for the app2.
int32_t kTaskId2 = 101;
CreateTask(app_id2, kTaskId2, session_id2);
WaitForAppLaunchInfoSaved();
int32_t activation_index1 = 11;
SaveWindowInfo(window1, activation_index1,
chromeos::WindowStateType::kNormal);
WaitForAppLaunchInfoSaved();
// Remove `app_id2` before restoring, so that `app_id2` can't be restored.
RemoveApp(app_id2);
base::HistogramTester histogram_tester;
Restore();
widget1->CloseNow();
app_host()->OnTaskDestroyed(kTaskId1);
app_host()->OnTaskDestroyed(kTaskId2);
std::set<std::string> app_ids = GetAppIds();
EXPECT_EQ(1u, app_ids.size());
EXPECT_TRUE(base::Contains(app_ids, app_id2));
EXPECT_TRUE(HasRestoreData());
VerifyWindows(activation_index1, app_id1, kTaskId1);
OnAppConnectionReady();
EXPECT_EQ(
1, histogram_tester.GetBucketCount(kRestoredAppWindowCountHistogram, 1));
// Modify `app_id2` status to be ready to prepare launching `app_id2`.
UpdateApp(app_id2, apps::mojom::Readiness::kReady);
EXPECT_TRUE(GetAppIds().empty());
EXPECT_TRUE(HasRestoreData());
VerifyWindows(activation_index1, app_id1, kTaskId1);
VerifyNoStackWindows(app_id2, kTaskId2);
// Verify the restore data and windows for `app_id1` and `app_id2` are not
// removed.
VerifyRestoreData(app_id1, kTaskId1);
VerifyRestoreData(app_id2, kTaskId2);
StopInstance();
}
// Verify the restore process when the user clicks the `restore` button very
// late after the OnAppConnectionReady is called.
IN_PROC_BROWSER_TEST_F(ArcAppLaunchHandlerArcAppBrowserTest, RestoreLate) {
SetProfile();
InstallTestApps(kTestAppPackage, true);
const std::string app_id1 = GetTestApp1Id(kTestAppPackage);
const std::string app_id2 = GetTestApp2Id(kTestAppPackage);
int32_t session_id1 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
int32_t session_id2 =
::full_restore::FullRestoreSaveHandler::GetInstance()->GetArcSessionId();
SaveAppLaunchInfo(app_id1, session_id1);
SaveAppLaunchInfo(app_id2, session_id2);
// Simulate creating kTaskId1. The task id needs to match the |window_app_id|
// arg of CreateExoWindow.
int32_t kTaskId1 = 100;
CreateTask(app_id1, kTaskId1, session_id1);
// Create the window for the app1.
views::Widget* widget1 = CreateExoWindow("org.chromium.arc.100");
aura::Window* window1 = widget1->GetNativeWindow();
// Simulate creating kTaskId2 for the app2.
int32_t kTaskId2 = 101;
CreateTask(app_id2, kTaskId2, session_id2);
int32_t activation_index1 = 11;
SaveWindowInfo(window1, activation_index1,
chromeos::WindowStateType::kNormal);
WaitForAppLaunchInfoSaved();
// Call OnAppConnectionReady to simulate the app connection is ready.
base::HistogramTester histogram_tester;
OnAppConnectionReady();
// Simulate the user clicks the `restore` button.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
widget1->CloseNow();
app_host()->OnTaskDestroyed(kTaskId1);
app_host()->OnTaskDestroyed(kTaskId2);
EXPECT_TRUE(HasRestoreData());
VerifyWindows(activation_index1, app_id1, kTaskId1);
VerifyNoStackWindows(app_id2, kTaskId2);
EXPECT_EQ(
1, histogram_tester.GetBucketCount(kRestoredAppWindowCountHistogram, 2));
StopInstance();
}
class FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest
: public SystemWebAppIntegrationTest {
public:
FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest() {
scoped_feature_list_.InitAndEnableFeature(
::full_restore::features::kFullRestore);
}
~FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest() override = default;
Browser* LaunchSystemWebApp(
const GURL& gurl,
web_app::SystemAppType system_app_type,
apps::mojom::LaunchSource launch_source =
apps::mojom::LaunchSource::kFromChromeInternal) {
WaitForTestSystemAppInstall();
auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile());
content::TestNavigationObserver navigation_observer(gurl);
navigation_observer.StartWatchingNewWebContents();
proxy->Launch(*GetManager().GetAppIdForSystemApp(system_app_type),
ui::EventFlags::EF_NONE, launch_source,
apps::MakeWindowInfo(display::kDefaultDisplayId));
navigation_observer.Wait();
return BrowserList::GetInstance()->GetLastActive();
}
Browser* LaunchSystemWebApp(
apps::mojom::LaunchSource launch_source =
apps::mojom::LaunchSource::kFromChromeInternal) {
return LaunchSystemWebApp(GURL("chrome://help-app/"),
web_app::SystemAppType::HELP, launch_source);
}
// Launches the media system web app. Used when a test needs to use a
// different system web app.
Browser* LaunchMediaSystemWebApp(
apps::mojom::LaunchSource launch_source =
apps::mojom::LaunchSource::kFromChromeInternal) {
return LaunchSystemWebApp(GURL("chrome://media-app/"),
web_app::SystemAppType::MEDIA, launch_source);
}
void WaitForAppLaunchInfoSaved(bool allow_save = true) {
::full_restore::FullRestoreSaveHandler* save_handler =
::full_restore::FullRestoreSaveHandler::GetInstance();
if (allow_save)
save_handler->AllowSave();
base::OneShotTimer* timer = save_handler->GetTimerForTesting();
if (timer->IsRunning()) {
// Simulate timeout, and the launch info is saved.
timer->FireNow();
}
content::RunAllTasksUntilIdle();
::full_restore::FullRestoreReadHandler::GetInstance()
->profile_path_to_restore_data_.clear();
}
void ModifyAppReadiness(apps::mojom::Readiness readiness) {
apps::mojom::AppType app_type = apps::mojom::AppType::kWeb;
if (crosapi::browser_util::IsLacrosEnabled() &&
base::FeatureList::IsEnabled(features::kWebAppsCrosapi)) {
app_type = apps::mojom::AppType::kSystemWeb;
}
auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile());
std::vector<apps::mojom::AppPtr> deltas;
apps::AppRegistryCache& cache = proxy->AppRegistryCache();
apps::mojom::AppPtr app = apps::mojom::App::New();
app->app_id =
*GetManager().GetAppIdForSystemApp(web_app::SystemAppType::HELP);
app->app_type = app_type;
app->readiness = readiness;
deltas.push_back(std::move(app));
cache.OnApps(std::move(deltas), app_type,
false /* should_notify_initialized */);
}
void SetShouldRestore(FullRestoreAppLaunchHandler* app_launch_handler) {
content::RunAllTasksUntilIdle();
app_launch_handler->SetShouldRestore();
content::RunAllTasksUntilIdle();
}
bool HasWindowInfo(int32_t restore_window_id) {
return ::full_restore::FullRestoreReadHandler::GetInstance()->HasWindowInfo(
restore_window_id);
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_P(FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest,
LaunchSWA) {
Browser* app_browser = LaunchSystemWebApp();
ASSERT_TRUE(app_browser);
ASSERT_NE(browser(), app_browser);
// Get the window id.
aura::Window* window = app_browser->window()->GetNativeWindow();
int32_t window_id = window->GetProperty(::full_restore::kWindowIdKey);
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
// Close app_browser so that the SWA can be relaunched.
web_app::CloseAndWait(app_browser);
ASSERT_FALSE(HasWindowInfo(window_id));
SetShouldRestore(app_launch_handler.get());
ASSERT_TRUE(HasWindowInfo(window_id));
// Get the restored browser for the system web app.
Browser* restore_app_browser = GetBrowserForWindowId(window_id);
ASSERT_TRUE(restore_app_browser);
ASSERT_NE(browser(), restore_app_browser);
// Get the restore window id.
window = restore_app_browser->window()->GetNativeWindow();
int32_t restore_window_id =
window->GetProperty(::full_restore::kRestoreWindowIdKey);
EXPECT_EQ(window_id, restore_window_id);
}
// Verify that when the full restore doesn't start, the browser window of the
// SWA doesn't have the restore info.
IN_PROC_BROWSER_TEST_P(FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest,
LaunchSWAWithoutRestore) {
Browser* app_browser = LaunchSystemWebApp();
ASSERT_TRUE(app_browser);
ASSERT_NE(browser(), app_browser);
// Get the window id.
aura::Window* window = app_browser->window()->GetNativeWindow();
int32_t window_id = window->GetProperty(::full_restore::kWindowIdKey);
SaveWindowInfo(window);
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
// Close app_browser so that the SWA can be relaunched.
web_app::CloseAndWait(app_browser);
content::RunAllTasksUntilIdle();
ASSERT_FALSE(HasWindowInfo(window_id));
Browser* new_app_browser = LaunchSystemWebApp();
ASSERT_TRUE(new_app_browser);
ASSERT_NE(browser(), new_app_browser);
window = new_app_browser->window()->GetNativeWindow();
auto* window_state = ash::WindowState::Get(window);
EXPECT_FALSE(window_state->HasRestoreBounds());
}
// Verify the restoration if the SWA is not available when set
// restore, and the restoration can work if the SWA is added later.
IN_PROC_BROWSER_TEST_P(FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest,
NoSWAWhenRestore) {
Browser* app_browser = LaunchSystemWebApp();
ASSERT_TRUE(app_browser);
ASSERT_NE(browser(), app_browser);
// Get the window id.
aura::Window* window = app_browser->window()->GetNativeWindow();
int32_t window_id = window->GetProperty(::full_restore::kWindowIdKey);
WaitForAppLaunchInfoSaved();
// Close app_browser so that the SWA can be relaunched.
web_app::CloseAndWait(app_browser);
// Modify the app readiness to uninstall to simulate the app is not installed
// during the system startup phase.
ModifyAppReadiness(apps::mojom::Readiness::kUninstalledByUser);
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
SetShouldRestore(app_launch_handler.get());
// Verify the app is not restored because the app is not installed.
Browser* restore_app_browser = GetBrowserForWindowId(window_id);
ASSERT_FALSE(restore_app_browser);
// Modify the app readiness to kReady to simulate the app is installed.
ModifyAppReadiness(apps::mojom::Readiness::kReady);
// Wait for the restoration.
content::RunAllTasksUntilIdle();
// Get the restored browser for the system web app to verify the app is
// restored.
restore_app_browser = GetBrowserForWindowId(window_id);
ASSERT_TRUE(restore_app_browser);
ASSERT_NE(browser(), restore_app_browser);
// Get the restore window id.
window = restore_app_browser->window()->GetNativeWindow();
int32_t restore_window_id =
window->GetProperty(::full_restore::kRestoreWindowIdKey);
EXPECT_EQ(window_id, restore_window_id);
}
// Launch the help app. Reboot, no restore. Launch the media app by the system.
// Reboot, verify the help app can be restored.
IN_PROC_BROWSER_TEST_P(FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest,
RestartMutiTimesWithLaunchBySystem) {
Browser* app_browser1 = LaunchSystemWebApp();
ASSERT_TRUE(app_browser1);
ASSERT_NE(browser(), app_browser1);
// Get the window id.
aura::Window* window1 = app_browser1->window()->GetNativeWindow();
int32_t window_id1 = window1->GetProperty(::full_restore::kWindowIdKey);
WaitForAppLaunchInfoSaved();
::full_restore::FullRestoreSaveHandler::GetInstance()->ClearForTesting();
// Close app_browser so that the SWA can be relaunched.
web_app::CloseAndWait(app_browser1);
// Modify the app readiness to uninstall to simulate the app is not installed
// during the system startup phase.
ModifyAppReadiness(apps::mojom::Readiness::kUninstalledByUser);
// Create FullRestoreAppLaunchHandler to simulate the system reboot.
auto app_launch_handler1 =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
content::RunAllTasksUntilIdle();
// Verify the app is not restored because the app is not installed.
ASSERT_FALSE(GetBrowserForWindowId(window_id1));
// Launch another app from kFromChromeInternal, so not start the save timer,
// to prevent overwriting the full restore file.
Browser* app_browser2 = LaunchMediaSystemWebApp();
ASSERT_TRUE(app_browser2);
aura::Window* window2 = app_browser2->window()->GetNativeWindow();
int32_t window_id2 = window2->GetProperty(::full_restore::kWindowIdKey);
WaitForAppLaunchInfoSaved(/*allow_save=*/false);
::full_restore::FullRestoreSaveHandler::GetInstance()->ClearForTesting();
app_launch_handler1.reset();
// Modify the app readiness to kReady to simulate the app is installed.
ModifyAppReadiness(apps::mojom::Readiness::kReady);
// Create FullRestoreAppLaunchHandler to simulate the system reboot again.
auto app_launch_handler2 =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
content::RunAllTasksUntilIdle();
SetShouldRestore(app_launch_handler2.get());
// Wait for the restoration.
content::RunAllTasksUntilIdle();
ASSERT_FALSE(GetBrowserForWindowId(window_id2));
// Get the restored browser for the system web app to verify the app is
// restored.
auto* restore_app_browser = GetBrowserForWindowId(window_id1);
ASSERT_TRUE(restore_app_browser);
// Get the restore window id.
window1 = restore_app_browser->window()->GetNativeWindow();
int32_t restore_window_id =
window1->GetProperty(::full_restore::kRestoreWindowIdKey);
EXPECT_EQ(window_id1, restore_window_id);
}
// Launch the help app. Reboot, no restore. Launch the media app by the user.
// Reboot, verify the media app can be restored.
IN_PROC_BROWSER_TEST_P(FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest,
RestartMutiTimesWithLaunchByUser) {
Browser* app_browser1 = LaunchSystemWebApp();
ASSERT_TRUE(app_browser1);
ASSERT_NE(browser(), app_browser1);
// Get the window id.
aura::Window* window1 = app_browser1->window()->GetNativeWindow();
int32_t window_id1 = window1->GetProperty(::full_restore::kWindowIdKey);
WaitForAppLaunchInfoSaved();
::full_restore::FullRestoreSaveHandler::GetInstance()->ClearForTesting();
// Close app_browser so that the SWA can be relaunched.
web_app::CloseAndWait(app_browser1);
// Modify the app readiness to uninstall to simulate the app is not installed
// during the system startup phase.
ModifyAppReadiness(apps::mojom::Readiness::kUninstalledByUser);
// Create FullRestoreAppLaunchHandler to simulate the system reboot.
auto app_launch_handler1 =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
content::RunAllTasksUntilIdle();
// Verify the app is not restored because the app is not installed.
ASSERT_FALSE(GetBrowserForWindowId(window_id1));
// Launch another app from kFromShelf, so start the save timer,
Browser* app_browser2 =
LaunchMediaSystemWebApp(apps::mojom::LaunchSource::kFromShelf);
ASSERT_TRUE(app_browser2);
aura::Window* window2 = app_browser2->window()->GetNativeWindow();
int32_t window_id2 = window2->GetProperty(::full_restore::kWindowIdKey);
WaitForAppLaunchInfoSaved(/*allow_save=*/false);
::full_restore::FullRestoreSaveHandler::GetInstance()->ClearForTesting();
web_app::CloseAndWait(app_browser2);
app_launch_handler1.reset();
// Modify the app readiness to kReady to simulate the app is installed.
ModifyAppReadiness(apps::mojom::Readiness::kReady);
// Create FullRestoreAppLaunchHandler to simulate the system reboot again.
auto app_launch_handler2 =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
content::RunAllTasksUntilIdle();
SetShouldRestore(app_launch_handler2.get());
// Wait for the restoration.
content::RunAllTasksUntilIdle();
ASSERT_FALSE(GetBrowserForWindowId(window_id1));
// Get the restored browser for the system web app to verify the app is
// restored.
auto* restore_app_browser = GetBrowserForWindowId(window_id2);
ASSERT_TRUE(restore_app_browser);
// Get the restore window id.
window2 = restore_app_browser->window()->GetNativeWindow();
int32_t restore_window_id =
window2->GetProperty(::full_restore::kRestoreWindowIdKey);
EXPECT_EQ(window_id2, restore_window_id);
}
IN_PROC_BROWSER_TEST_P(FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest,
WindowProperties) {
Browser* app_browser = LaunchSystemWebApp();
ASSERT_TRUE(app_browser);
ASSERT_NE(browser(), app_browser);
// Get the window id.
aura::Window* window = app_browser->window()->GetNativeWindow();
int32_t window_id = window->GetProperty(::full_restore::kWindowIdKey);
// Snap |window| to the left and store its window properties.
// TODO(sammiequon): Store and check desk id and restore bounds.
auto* window_state = ash::WindowState::Get(window);
const ash::WMEvent left_snap_event(ash::WM_EVENT_SNAP_PRIMARY);
window_state->OnWMEvent(&left_snap_event);
const chromeos::WindowStateType pre_save_state_type =
window_state->GetStateType();
EXPECT_EQ(chromeos::WindowStateType::kPrimarySnapped, pre_save_state_type);
const gfx::Rect pre_save_bounds = window->GetBoundsInScreen();
SaveWindowInfo(window);
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
// Close |app_browser| so that the SWA can be relaunched.
web_app::CloseAndWait(app_browser);
SetShouldRestore(app_launch_handler.get());
// Get the restored browser for the system web app.
Browser* restore_app_browser = GetBrowserForWindowId(window_id);
ASSERT_TRUE(restore_app_browser);
ASSERT_NE(browser(), restore_app_browser);
// Get the restored browser's window.
window = restore_app_browser->window()->GetNativeWindow();
ASSERT_EQ(window_id,
window->GetProperty(::full_restore::kRestoreWindowIdKey));
// Check that |window|'s properties match the one's we stored.
EXPECT_EQ(pre_save_bounds, window->GetBoundsInScreen());
window_state = ash::WindowState::Get(window);
EXPECT_EQ(pre_save_state_type, window_state->GetStateType());
// Verify that |window_state| has viable restore bounds for when the user
// wants to return to normal window show state. Regression test for
// https://crbug.com/1188986.
EXPECT_TRUE(window_state->HasRestoreBounds());
}
// Tests that apps maintain splitview snap status after being relaunched with
// full restore.
IN_PROC_BROWSER_TEST_P(FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest,
TabletSplitView) {
ash::TabletMode::Get()->SetEnabledForTest(true);
Browser* app1_browser = LaunchSystemWebApp();
Browser* app2_browser = LaunchMediaSystemWebApp();
aura::Window* app1_window = app1_browser->window()->GetNativeWindow();
aura::Window* app2_window = app2_browser->window()->GetNativeWindow();
ash::SplitViewTestApi split_view_test_api;
split_view_test_api.SnapWindow(app1_window,
ash::SplitViewTestApi::SnapPosition::LEFT);
split_view_test_api.SnapWindow(app2_window,
ash::SplitViewTestApi::SnapPosition::RIGHT);
ASSERT_EQ(app1_window, split_view_test_api.GetLeftWindow());
ASSERT_EQ(app2_window, split_view_test_api.GetRightWindow());
const int32_t app1_id =
app1_window->GetProperty(::full_restore::kWindowIdKey);
const int32_t app2_id =
app2_window->GetProperty(::full_restore::kWindowIdKey);
SaveWindowInfo(app1_window);
SaveWindowInfo(app2_window);
WaitForAppLaunchInfoSaved();
// Create FullRestoreAppLaunchHandler.
auto app_launch_handler =
std::make_unique<FullRestoreAppLaunchHandler>(profile());
// Close `app1_browser` and `app2_browser` so that the SWA can be relaunched.
web_app::CloseAndWait(app1_browser);
web_app::CloseAndWait(app2_browser);
SetShouldRestore(app_launch_handler.get());
aura::Window* restore_app1_window = nullptr;
aura::Window* restore_app2_window = nullptr;
// Find the restored app windows in the browser list.
for (Browser* browser : *BrowserList::GetInstance()) {
aura::Window* native_window = browser->window()->GetNativeWindow();
if (native_window->GetProperty(::full_restore::kRestoreWindowIdKey) ==
app1_id) {
restore_app1_window = native_window;
}
if (native_window->GetProperty(::full_restore::kRestoreWindowIdKey) ==
app2_id) {
restore_app2_window = native_window;
}
}
ASSERT_TRUE(restore_app1_window);
ASSERT_TRUE(restore_app2_window);
EXPECT_EQ(restore_app1_window, split_view_test_api.GetLeftWindow());
EXPECT_EQ(restore_app2_window, split_view_test_api.GetRightWindow());
}
INSTANTIATE_SYSTEM_WEB_APP_MANAGER_TEST_SUITE_REGULAR_PROFILE_P(
FullRestoreAppLaunchHandlerSystemWebAppsBrowserTest);
} // namespace full_restore
} // namespace ash
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
edb18193aac74e2d3e1877b3e9359569a512f5a3 | a98f0e636ef12af1916b9c6bf98007dcf2d51693 | /src/mainwindow.cpp | 12f8b9772aa8079152e077c4d8a4cc5d9e57a9af | [] | no_license | nttlman23/apdu_exchange | 64fbb3c27894c1ad97eaaa97537333ce0c9a66f9 | 4b200e542deda12f44920d59d1fed957e205b6d0 | refs/heads/main | 2023-04-21T04:28:51.508625 | 2021-05-14T13:24:52 | 2021-05-14T13:24:52 | 367,365,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 87,468 | cpp | #include <QtGui>
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QShortcut>
#include <QScrollBar>
#include <QHeaderView>
#include <QPixmap>
#include <iostream>
#include <cstdlib>
#include <sys/stat.h>
#include <algorithm>
#include <functional>
#if _WIN32 || _WIN64
#include <direct.h>
#endif
#if __GNUC__
#include <unistd.h>
#endif
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "commands.h"
#include "dialogsettestitem.h"
#include "dialognewseqpreset.h"
#include "dialogshowgraph.h"
#include "dialogshowdevattrib.h"
#include "commonfuncs.h"
#include <smartcard.h>
#include "logger.h"
using namespace std;
using namespace conf;
using namespace smcard;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
_pConfig(nullptr),
_deviceInfoShow(true),
_test_running(false),
indexSeqPresUpdateInfo(-1),
indexSeqCMDUpdateInfo(-1),
_needReselect(false),
_curr_win_width(0),
_curr_win_height(0),
_customPlot(nullptr),
_failCheckInfo(false),
_exclusiveConnect(false)
{
ui->setupUi(this);
popUp = new PopUp();
this->setMinimumSize(this->size());
this->showMaximized();
int ret = -1;
std::string log_path = QDir::currentPath().toStdString();// QDir::homePath().toStdString();
#if _WIN32 || _WIN64
log_path += "/log_testex";
ret = _mkdir(log_path.c_str());
if (!ret || errno == EEXIST)
{
log_path += "/testex";
DEBUG_CONF( log_path.c_str(),
Logger::file_on|
Logger::screen_on,
DBG_DEBUG,
DBG_DEBUG);
QString logPath = Logger::getInstance().getLogFilename();
// log file name: full_log_path/log_2020_00_00-00-00.log
int log_name_index = logPath.lastIndexOf("/");
// remove full_log_path. Use only log name: log_2020_00_00-00-00.log
logPath.remove(0,log_name_index + 1);
// create link
ui->labelFileLog->setText(QString("<a href=") +
Logger::getInstance().getLogFilename() +
QString(">") +
QString("Show log") +
// logPath +
QString("</a>"));
DEBUG(DBG_DEBUG, "Program started");
}
#else
log_path += "/log_testex";
ret = mkdir(log_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH );
if (!ret || errno == EEXIST)
{
log_path += "/testex";
DEBUG_CONF( log_path.c_str(),
Logger::file_on|
Logger::screen_on,
DBG_DEBUG,
DBG_DEBUG);
ui->labelFileLog->setText(Logger::getInstance().getLogFilename());
}
#endif
// plot
_customPlot = ui->widgetPlot;
_customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
_customPlot->xAxis->setAutoTicks(false);
_customPlot->xAxis->setRange(0, 1);
_customPlot->yAxis->setRange(0, 1);
//_customPlot->hide();
//ui->pushButtonShowGraph->hide();
// Config Menu
loadPresetConf = new QAction(tr("&Load config (Ctrl + O)"), this);
editPresetConf = new QAction(tr("&Edit current command (Ctrl + E)"), this);
addPresetConf = new QAction(tr("&Add (Ctrl + N)"), this);
delItemConf = new QAction(tr("&Delete current command (Ctrl + D)"), this);
delPresetConf = new QAction(tr("&Del current preset"), this);
reloadPresetConf = new QAction(tr("&Reload config (Ctrl + R)"), this);
configMenu = menuBar()->addMenu(tr("&Config"));
configMenu->addAction(loadPresetConf);
configMenu->addAction(editPresetConf);
configMenu->addAction(addPresetConf);
configMenu->addAction(delItemConf);
configMenu->addAction(delPresetConf);
configMenu->addAction(reloadPresetConf);
// Seq Menu
startSeqTestConf = new QAction(tr("&Start test (Space)"), this);
addSeqTestPreset = new QAction(tr("&New sequence"), this);
delSeqTestPreset = new QAction(tr("&Del current sequence"), this);
addCmd2SeqTestConf = new QAction(tr("&Add command (+)"), this);
saveSeqTestConf = new QAction(tr("&Save (Ctrl + P)"), this);
clearSeqTestConf = new QAction(tr("&Clear sequence"), this);
seqTestMenu = menuBar()->addMenu(tr("&Test"));
seqTestMenu->addAction(startSeqTestConf);
seqTestMenu->addAction(addCmd2SeqTestConf);
seqTestMenu->addAction(addSeqTestPreset);
seqTestMenu->addAction(saveSeqTestConf);
seqTestMenu->addAction(delSeqTestPreset);
seqTestMenu->addAction(clearSeqTestConf);
partitionTest = new QAction(tr("&Partition"), this);
showDeviceAttributes = new QAction(tr("&Reader attributes (Ctrl+I)"), this);
// About Menu
aboutAct = new QAction(tr("&About"), this);
aboutQtAct = new QAction(tr("About &Qt"), this);
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct);
// Sets
ui->lineEditData->setEnabled(false);
ui->textEdit->setReadOnly(true);
ui->lineEditProto->setReadOnly(true);
ui->progressBarTest->hide();
ui->checkBoxExclusive->setChecked(false);
// table commands
ui->tableWidget->setColumnCount(3);
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableWidget->setShowGrid(true);
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
ui->tableWidget->setHorizontalHeaderLabels(QStringList()
<< "Cmd name" << "Result" << "APDU");
ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
// ui->groupBoxDevice->setStyleSheet("QGroupBox { border: 2px solid gray; border-radius: 3px; }");
// Key Shortcut
ui->pushButtonSendAPDU->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Enter));
QKeySequence ksO(Qt::CTRL + Qt::Key_O);
QShortcut* shortcutO = new QShortcut(ksO, this);
QObject::connect(shortcutO, SIGNAL(activated()),
this, SLOT(LoadCfg_clicked()));
QKeySequence ksN(Qt::CTRL + Qt::Key_N);
QShortcut* shortcutN = new QShortcut(ksN, this);
QObject::connect(shortcutN, SIGNAL(activated()),
this, SLOT(AddItem_clicked()));
QKeySequence ksE(Qt::CTRL + Qt::Key_E);
QShortcut* shortcutE = new QShortcut(ksE, this);
QObject::connect(shortcutE, SIGNAL(activated()),
this, SLOT(EditCfg_clicked()));
QKeySequence ksR(Qt::CTRL + Qt::Key_R);
QShortcut* shortcutR = new QShortcut(ksR, this);
QObject::connect(shortcutR, SIGNAL(activated()),
this, SLOT(reloadConfiguration_triggered()));
QKeySequence ksD(Qt::CTRL + Qt::Key_D);
QShortcut* shortcutD = new QShortcut(ksD, this);
QObject::connect(shortcutD, SIGNAL(activated()),
this, SLOT(DelItem_clicked()));
QKeySequence ksSpace(/*Qt::CTRL + */Qt::Key_Space);
QShortcut* shortcutSpace = new QShortcut(ksSpace, this);
QObject::connect(shortcutSpace, SIGNAL(activated()),
this, SLOT(on_pushButtonStartTest_clicked()));
QKeySequence ksCSpace(Qt::CTRL + Qt::Key_Space);
QShortcut* shortcutCSpace = new QShortcut(ksCSpace, this);
QObject::connect(shortcutCSpace, SIGNAL(activated()),
this, SLOT(StartTest_Selected_activated()));
QKeySequence ksP(Qt::CTRL + Qt::Key_S);
QShortcut* shortcutP = new QShortcut(ksP, this);
QObject::connect(shortcutP, SIGNAL(activated()),
this, SLOT(saveSeqConfiguration_triggered()));
QKeySequence ksPlus(/*Qt::CTRL + */Qt::Key_Plus);
QShortcut* shortcutPlus = new QShortcut(ksPlus, this);
QObject::connect(shortcutPlus, SIGNAL(activated()),
this, SLOT(on_pushButtonAddTotable_clicked()));
QKeySequence ksDel(/*Qt::CTRL + */Qt::Key_Delete);
QShortcut* shortcutDel = new QShortcut(ksDel, this);
QObject::connect(shortcutDel, SIGNAL(activated()),
this, SLOT(deleteSelectedRows_pressed()));
QKeySequence ksC(Qt::CTRL + Qt::Key_C);
QShortcut* shortcutC = new QShortcut(ksC, this);
QObject::connect(shortcutC, SIGNAL(activated()),
this, SLOT(copySelectedRows_pressed()));
QKeySequence ksV(Qt::CTRL + Qt::Key_V);
QShortcut* shortcutV = new QShortcut(ksV, this);
QObject::connect(shortcutV, SIGNAL(activated()),
this, SLOT(pasteSelectedRows_pressed()));
QKeySequence ksI(Qt::CTRL + Qt::Key_I);
QShortcut* shortcutI = new QShortcut(ksI, this);
QObject::connect(shortcutI, SIGNAL(activated()),
this, SLOT(showDeviceAttrib_triggered()));
// Connect Slots
// Config Menu
connect(addPresetConf, SIGNAL(triggered()),
this, SLOT(AddItem_clicked()));
connect(loadPresetConf, SIGNAL(triggered()),
this, SLOT(LoadCfg_clicked()));
connect(editPresetConf, SIGNAL(triggered()),
this, SLOT(EditCfg_clicked()));
connect(delItemConf, SIGNAL(triggered()),
this, SLOT(DelItem_clicked()));
connect(delPresetConf, SIGNAL(triggered()),
this, SLOT(DelPreset_clicked()));
connect(reloadPresetConf, SIGNAL(triggered()),
this, SLOT(reloadConfiguration_triggered()));
// Tools Menu
connect(showDeviceAttributes, SIGNAL(triggered()),
this, SLOT(showDeviceAttrib_triggered()));
// Seq Menu
connect(startSeqTestConf, SIGNAL(triggered()),
this, SLOT(on_pushButtonStartTest_clicked()));
connect(addSeqTestPreset, SIGNAL(triggered()),
this, SLOT(AddSeqTestItem_clicked()));
connect(delSeqTestPreset, SIGNAL(triggered()),
this, SLOT(DelSeqPreset_clicked()));
connect(addCmd2SeqTestConf, SIGNAL(triggered()),
this, SLOT(on_pushButtonAddTotable_clicked()));
connect(saveSeqTestConf, SIGNAL(triggered()),
this, SLOT(saveSeqConfiguration_triggered()));
connect(clearSeqTestConf, SIGNAL(triggered()),
this, SLOT(clearSeqConfiguration_triggered()));
// Table Menu
connect(ui->tableWidget, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(customMenuRequested(QPoint)));
connect(ui->tableWidget, SIGNAL(cellDoubleClicked(int,int)),
this, SLOT(tableItemClicked(int,int)));
// About Menu
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(this, SIGNAL(findDevices_signal()),
this, SLOT(on_pushButtonFindDevs_clicked()));
ui->textEdit->installEventFilter(this);
emit findDevices_signal();
memset(&ansBuffer,0,sizeof(answerBuffer_t));
this->showMaximized();
}
MainWindow::~MainWindow()
{
_test_running = false;
if (this->_pConfig)
{
if (QFile::exists(QString(_pConfig->getConfFilePath()) + QString(".bck")))
{
QFile::remove(QString(_pConfig->getConfFilePath()) + QString(".bck"));
}
QFile::copy(_pConfig->getConfFilePath(),
QString(_pConfig->getConfFilePath()) + QString(".bck"));
}
this->_SCard.disconnect();
if (_pConfig)
{
delete _pConfig;
}
delete _customPlot;
delete popUp;
DEBUG(DBG_DEBUG, "Program stopped");
delete ui;
}
void MainWindow::about()
{
QMessageBox::about(this, tr("About Menu"),
tr("The <b>Menu</b> About "
"About menu"));
}
void MainWindow::on_pushButtonFindDevs_clicked()
{
if (!this->findDevices())
{
DEBUG(DBG_WARN, "No Devices" );
}
}
void MainWindow::LoadCfg_clicked()
{
if (_test_running)
{
return;
}
QString fileName = QFileDialog::getOpenFileName(this,
tr("Load Config"),
QDir::currentPath(),//homePath(),
tr("Config Files (*.xml)"));
if (!_pConfig)
{
_pConfig = new Configuration();
}
if (fileName.isEmpty())
{
return;
}
else
{
QFile::copy(fileName, QString(fileName + ".bck"));
_pConfig->setConfFilePath(fileName.toStdString().c_str());
if (QFile::exists(QString(_pConfig->getConfFilePath()) + QString(".bck")))
{
QFile::remove(QString(_pConfig->getConfFilePath()) + QString(".bck"));
}
QFile::copy(_pConfig->getConfFilePath(),
QString(_pConfig->getConfFilePath()) + QString(".bck"));
}
updateLocalConfig();
}
void MainWindow::EditCfg_clicked()
{
if (_test_running)
{
return;
}
DialogAddItem d;
if(!_pConfig )
{
return;
}
if(!_pConfig->isConfigured())
{
return;
}
if (ui->comboBoxPreset->currentIndex() < 0 ||
ui->comboBoxAPDUSelect->currentIndex() < 0)
{
return;
}
if (!d.setCurrentPreset(_pConfig,
&_common_conf,
ui->comboBoxPreset->currentIndex(),
ui->comboBoxAPDUSelect->currentIndex(),
true))
{
return;
}
d.show();
d.exec();
this->savePresetsToConf();
}
void MainWindow::AddItem_clicked()
{
if (_test_running)
{
return;
}
DialogAddItem d;
if(!_pConfig )
{
return;
}
if(!_pConfig->isConfigured())
{
return;
}
conf_item_t item;
if (ui->comboBoxPreset->currentIndex() < 0)
{
return;
}
if (!d.setCurrentPreset(_pConfig,
&_common_conf,
ui->comboBoxPreset->currentIndex(),
-1,
false))
{
return;
}
d.show();
d.exec();
_common_conf.presetCommandsV[ui->comboBoxPreset->currentIndex()].commandConf.push_back(item);
this->savePresetsToConf();
}
bool MainWindow::updateLocalConfig()
{
if (!_pConfig)
{
QMessageBox messageBox;
messageBox.critical(this,"Error","Config file missing");
messageBox.setFixedSize(500,200);
return false;
}
if(!_pConfig->fillPresetsConf(this->_common_conf))
{
QMessageBox messageBox;
messageBox.critical(this,"Error","Read conffile failded");
messageBox.setFixedSize(500,200);
return false;
}
int preset_index_1 = ui->comboBoxPreset->currentIndex();
int seq_preset_index = ui->comboBoxSeqPreset->currentIndex();
ui->comboBoxPreset->clear();
for (int i = 0;i < _common_conf.presetCommandsV.size();i++)
{
ui->comboBoxPreset->addItem(_common_conf.presetCommandsV[i].preset_name.c_str());
}
ui->comboBoxSeqPreset->clear();
for (auto i = 0;i < _common_conf.presetSequenceV.size();i++)
{
ui->comboBoxSeqPreset->addItem(QString::number(i + 1) +
QString(") ") +
QString(_common_conf.presetSequenceV[i].seqPresetName.c_str()));
}
if (preset_index_1 >= 0 &&
preset_index_1 < _common_conf.presetSequenceV.size())
{
ui->comboBoxPreset->setCurrentIndex(preset_index_1);
}
if (seq_preset_index >= 0 &&
seq_preset_index < _common_conf.presetSequenceV.size())
{
ui->comboBoxSeqPreset->setCurrentIndex(seq_preset_index);
}
if (ui->tableWidget->rowCount() > 0)
{
QString text = "Total: ";
text += QString::number(ui->tableWidget->rowCount());
ui->label_33->setText(text);
}
ui->label_34->setText("---");
return true;
}
bool MainWindow::findDevices()
{
ui->comboBoxDevice->clear();
uint8_t ReadersCnt = 0;
#if __GNUC__
LPTSTR Readers[MAX_READERS_AVAILABLE];
SCARDCONTEXT tmpCardCtx;
char ReadersList[READER_LIST_SIZE];
DWORD size = READER_LIST_SIZE;
LONG res = SCardEstablishContext(SCARD_SCOPE_USER, nullptr, nullptr, &tmpCardCtx);
if (SCARD_S_SUCCESS != res)
{
qDebug() << __FUNCTION__ <<
"Failed to establish context: ";
/*<<
pcsc_stringify_error(res);*/
return false;
}
res = SCardListReaders(tmpCardCtx, NULL, (LPTSTR)ReadersList, &size);
if (tmpCardCtx)
{
SCardReleaseContext(tmpCardCtx);
}
if (SCARD_S_SUCCESS != res)
{
qDebug() << "WARNING: Reader not available";
ui->textEdit->append("No device");
}
else
{
char *pReader = ReadersList;
while ('\0' != *pReader)
{
Readers[ReadersCnt++] = pReader;
pReader = pReader + strlen((const char *)pReader) + 1;
if (ReadersCnt >= MAX_READERS_AVAILABLE)
{
qDebug() << __FUNCTION__ <<
"ERROR: Too much Reader, MAX = " <<
MAX_READERS_AVAILABLE <<
", available: " <<
ReadersCnt;
return false;
}
}
}
for (uint8_t i = 0; i < ReadersCnt; i++)
{
ui->comboBoxDevice->addItem((char *)Readers[i]);
}
if (ReadersCnt > 1)
{
ui->comboBoxDevice->setCurrentIndex(0);
}
#else
SCARDCONTEXT hSC;
LONG lReturn;
char * Readers[MAX_READERS_AVAILABLE];
lReturn = SCardEstablishContext(SCARD_SCOPE_USER,
NULL,
NULL,
&hSC);
if (lReturn != SCARD_S_SUCCESS)
{
DEBUG(DBG_ERROR, "Failed Establish Context");
return false;
}
LPTSTR pmszReaders = NULL;
LPTSTR pReader;
DWORD cch = SCARD_AUTOALLOCATE;
// Retrieve the list the readers.
// hSC was set by a previous call to SCardEstablishContext.
lReturn = SCardListReaders(hSC,
NULL,
(LPTSTR)&pmszReaders,
&cch );
switch( lReturn )
{
case SCARD_E_NO_READERS_AVAILABLE:
// "Reader is not in groups";
return false;
case SCARD_S_SUCCESS:
pReader = pmszReaders;
while ( '\0' != *pReader )
{
Readers[ReadersCnt++] = encode(pReader, CP_UTF8);
pReader = pReader + wcslen((wchar_t *)pReader) + 1;
}
SCardFreeMemory( hSC, pmszReaders );
break;
default:
return false;
}
if (hSC)
SCardReleaseContext(hSC);
#endif // __GNUC__
// int JaCartaReaders = 0;
for (uint8_t i = 0; i < ReadersCnt; i++)
{
ui->comboBoxDevice->addItem((char *)Readers[i]);
}
if (ReadersCnt > 1)
{
ui->comboBoxDevice->setCurrentIndex(0);
}
return true;
}
void MainWindow::on_comboBoxPreset_currentIndexChanged(int index)
{
if(index < 0)
{
return;
}
ui->lineEditCLA->clear();
ui->lineEditINS->clear();
ui->lineEditP1->clear();
ui->lineEditP2->clear();
ui->lineEditLEN->clear();
ui->lineEditData->clear();
ui->comboBoxAPDUSelect->clear();
int num = 0;
for (std::vector<conf_item_t>::iterator it = _common_conf.presetCommandsV[index].commandConf.begin();
it != _common_conf.presetCommandsV[index].commandConf.end() ; it++)
{
QString desc = QString::number(num);
desc += " ";
desc += it->commandDesc.c_str();
desc += " [";
desc += QString("%1").arg(it->cla, 2, 16, QChar('0')).toUpper();
desc += " ";
desc += QString("%1").arg(it->ins, 2, 16, QChar('0')).toUpper();
desc += " ";
desc += QString("%1").arg(it->p1, 2, 16, QChar('0')).toUpper();
desc += " ";
desc += QString("%1").arg(it->p2, 2, 16, QChar('0')).toUpper();
desc += " ";
desc += QString("%1").arg(it->len, 2, 16, QChar('0')).toUpper();
desc += "]";
ui->comboBoxAPDUSelect->addItem(desc);
num++;
}
if (_common_conf.presetCommandsV[index].commandConf.empty())
{
ui->lineEditCLA->setEnabled(false);
ui->lineEditINS->setEnabled(false);
ui->lineEditP1->setEnabled(false);
ui->lineEditP2->setEnabled(false);
ui->lineEditLEN->setEnabled(false);
ui->lineEditCLA->clear();
ui->lineEditINS->clear();
ui->lineEditP1->clear();
ui->lineEditP2->clear();
ui->lineEditLEN->clear();
ui->lineEditData->clear();
}
else
{
ui->lineEditCLA->setEnabled(true);
ui->lineEditINS->setEnabled(true);
ui->lineEditP1->setEnabled(true);
ui->lineEditP2->setEnabled(true);
ui->lineEditLEN->setEnabled(true);
}
}
void MainWindow::on_comboBoxAPDUSelect_currentIndexChanged(int index)
{
if (index < 0)
{
ui->comboBoxAPDUSelect->clear();
return;
}
ui->lineEditCLA->clear();
ui->lineEditINS->clear();
ui->lineEditP1->clear();
ui->lineEditP2->clear();
ui->lineEditLEN->clear();
ui->lineEditData->clear();
int preset_index = ui->comboBoxPreset->currentIndex();
if (preset_index < 0)
{
return;
}
QString text = "";
std::string result = this->n2hexstr(_common_conf.presetCommandsV[preset_index].commandConf[index].cla,
sizeof(_common_conf.presetCommandsV[preset_index].commandConf[index].cla));
text += _common_conf.presetCommandsV[preset_index].commandConf[index].commandDesc.c_str();
text += ": ";
result.erase(result.begin(),result.end() - 2);
result += " ";
text += result.c_str();
result = this->n2hexstr(_common_conf.presetCommandsV[preset_index].commandConf[index].ins,
sizeof(_common_conf.presetCommandsV[preset_index].commandConf[index].ins));
result.erase(result.begin(),result.end() - 2);
result += " ";
text += result.c_str();
result = this->n2hexstr(_common_conf.presetCommandsV[preset_index].commandConf[index].p1,
sizeof(_common_conf.presetCommandsV[preset_index].commandConf[index].p1));
result.erase(result.begin(),result.end() - 2);
result += " ";
text += result.c_str();
result = this->n2hexstr(_common_conf.presetCommandsV[preset_index].commandConf[index].p2,
sizeof(_common_conf.presetCommandsV[preset_index].commandConf[index].p2));
result.erase(result.begin(),result.end() - 2);
result += " ";
text += result.c_str();
result = this->n2hexstr(_common_conf.presetCommandsV[preset_index].commandConf[index].len,
sizeof(_common_conf.presetCommandsV[preset_index].commandConf[index].len));
result.erase(result.begin(),result.end() - 2);
result += " ";
text += result.c_str();
ui->lineEditCLA->setText(QString("%1").arg(_common_conf.presetCommandsV[preset_index].commandConf[index].cla, 2, 16, QChar('0')).toUpper());
ui->lineEditINS->setText(QString("%1").arg(_common_conf.presetCommandsV[preset_index].commandConf[index].ins, 2, 16, QChar('0')).toUpper());
ui->lineEditP1->setText(QString("%1").arg(_common_conf.presetCommandsV[preset_index].commandConf[index].p1, 2, 16, QChar('0')).toUpper());
ui->lineEditP2->setText(QString("%1").arg(_common_conf.presetCommandsV[preset_index].commandConf[index].p2, 2, 16, QChar('0')).toUpper());
ui->lineEditLEN->setText(QString("%1").arg(_common_conf.presetCommandsV[preset_index].commandConf[index].len, 2, 16, QChar('0')).toUpper());
ui->lineEditData->setText(_common_conf.presetCommandsV[preset_index].commandConf[index].data_field.c_str());
if (_common_conf.presetCommandsV[preset_index].commandConf[index].len > 0)
{
ui->lineEditData->setEnabled(true);
}
else
{
ui->lineEditData->setEnabled(false);
}
qApp->processEvents();
}
void MainWindow::DelPreset_clicked()
{
std::string msg_text;
msg_text = "Remove preset Config: ";
msg_text += ui->comboBoxPreset->currentText().toStdString();
msg_text += "?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,
"Warning",
msg_text.c_str(),
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
{
this->_pConfig->removePreset(this->_common_conf, ui->comboBoxPreset->currentIndex());
this->savePresetsToConf();
}
}
void MainWindow::DelSeqPreset_clicked()
{
if (_test_running)
{
return;
}
std::string msg_text;
msg_text = "Remove Seq preset: ";
msg_text += ui->comboBoxSeqPreset->currentText().toStdString();
msg_text += "?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,
"Warning",
msg_text.c_str(),
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
{
this->_pConfig->removeSequence(this->_common_conf,
ui->comboBoxSeqPreset->currentIndex());
while (ui->tableWidget->rowCount() > 0)
{
ui->tableWidget->removeRow(0);
}
this->savePresetsToConf();
}
}
void MainWindow::DelItem_clicked()
{
if (_test_running)
{
return;
}
std::string msg_text;
msg_text = "Remove APDU: ";
msg_text += ui->comboBoxAPDUSelect->currentText().toStdString();
msg_text += "?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Warning", msg_text.c_str(),
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
{
if (ui->comboBoxPreset->currentIndex() < 0 ||
ui->comboBoxAPDUSelect->currentIndex() < 0)
{
return;
}
this->_pConfig->removePresetItem(this->_common_conf,
ui->comboBoxPreset->currentIndex(),
ui->comboBoxAPDUSelect->currentIndex());
this->savePresetsToConf();
}
}
void MainWindow::on_comboBoxDevice_currentIndexChanged(int index)
{
if (index < 0)
{
return;
}
}
void MainWindow::showDeviceAttrib_triggered()
{
DialogShowDevAttrib dialDevAttr(0,
&this->_SCard);
dialDevAttr.show();
dialDevAttr.exec();
}
void MainWindow::on_pushButtonConnect_clicked()
{
if (ui->comboBoxDevice->currentIndex() < 0)
{
return;
}
std::string str;
if (!this->_SCard.isActive() && ui->pushButtonConnect->text().compare("Disconnect"))
{
this->_SCard.setDeviceName(ui->comboBoxDevice->currentText().toStdString());
if (this->_SCard.connect(ui->checkBoxExclusive->isChecked()))
{
ui->pushButtonFindDevs->setEnabled(false);
ui->pushButtonConnect->setText(tr("Disconnect"));
ui->comboBoxDevice->setEnabled(false);
str = "Reader (";
str += std::to_string(INDEX_DEVICE_1);
str += "): \"";
str += this->_SCard.getDeviceName();
str += "\" Connected";
ui->textEdit->append(str.c_str());
DEBUG(DBG_DEBUG, str);
ui->lineEditProto->setText(QString("T=" + QString::number(this->_SCard.getProto())));
}
else
{
str = "Reader 1:";
str += this->_SCard.getSCardErrorDescription(this->_SCard.getLastSCardErrror());
ui->textEdit->append(str.c_str());
DEBUG(DBG_DEBUG, str);
}
}
else
{
if (this->_SCard.disconnect())
{
std::string str = "Reader: ";
str += "\"";
str += this->_SCard.getDeviceName();
str += "\" disconnected (Device 1)";
ui->textEdit->append(str.c_str());
DEBUG(DBG_DEBUG, str);
ui->pushButtonFindDevs->setEnabled(true);
ui->pushButtonConnect->setText(tr("Connect"));
ui->comboBoxDevice->setEnabled(true);
ui->lineEditProto->clear();
}
ui->pushButtonFindDevs->setEnabled(true);
ui->pushButtonConnect->setText(tr("Connect"));
ui->comboBoxDevice->setEnabled(true);
}
this->showCurExecCommand();
}
void MainWindow::on_pushButtonSendAPDU_clicked()
{
if (!this->_SCard.isActive())
{
ui->textEdit->append("Reader 1 Not Connected");
return;
}
if (!_pConfig ||
!_pConfig->isConfigured() ||
ui->comboBoxPreset->currentIndex() < 0 ||
ui->comboBoxAPDUSelect->currentIndex() < 0)
{
if (ui->lineEditCLA->text().isEmpty() ||
ui->lineEditINS->text().isEmpty() ||
ui->lineEditP1->text().isEmpty() ||
ui->lineEditP2->text().isEmpty())
{
return;
}
}
uint8_t apduBuf[APDU_BUFFER_SIZE] = {0};
uint32_t apduLength = 0;
uint8_t rpl[APDU_BUFFER_SIZE];
uint32_t rLength;
long rVal = 0;
ui->lineEditData->setStyleSheet("QLineEdit { background: white;}");
int base = 16;
bool ok = false;
if (ui->lineEditLEN->text().isEmpty())
{
ui->lineEditLEN->setText("0");
}
apduBuf[CLA_INDEX] = (0xff & ui->lineEditCLA->text().toInt(&ok,base));
apduBuf[INS_INDEX] = (0xff & ui->lineEditINS->text().toInt(&ok,base));
apduBuf[P1_INDEX] = (0xff & ui->lineEditP1->text().toInt(&ok,base));
apduBuf[P2_INDEX] = (0xff & ui->lineEditP2->text().toInt(&ok,base));
apduBuf[LEN_INDEX] = (0xff & ui->lineEditLEN->text().toInt(&ok,base));
std::string data = ui->lineEditData->text().toStdString();
if (apduBuf[LEN_INDEX] != 0x00 && !ui->lineEditData->text().isEmpty())
{
for (unsigned int j = 0,index = 5;j < data.size() - 1;j+=2,index++)
{
apduBuf[index] = (0xff & ((char2bin(data[j]) << 4) | char2bin(data[j+1])));
}
apduLength = APDU_HEAD_LEN + apduBuf[LEN_INDEX];
}
else
{
apduLength = APDU_HEAD_LEN;
}
DEBUG(DBG_DEBUG, "---------------------------------------------");
ui->textEdit->append("---------------------------------------------");
QString text;
text += " ";
text += ui->comboBoxAPDUSelect->currentText();
text += " [";
text += data.c_str();
text += "]";
ui->textEdit->append(QString("Single command: " + text));
DEBUG(DBG_DEBUG, "Single command: " + text.toStdString());
rVal = this->scardExchange((const char*)apduBuf, apduLength, (char*)rpl, (int*)&rLength);
if (rVal)
{
ui->textEdit->append("APDU Fail");
DEBUG(DBG_DEBUG,"APDU Fail");
}
DEBUG(DBG_DEBUG, "---------------------------------------------");
ui->textEdit->append("---------------------------------------------");
}
void MainWindow::on_pushButtonClearLog_clicked()
{
ui->textEdit->clear();
}
bool MainWindow::addItemToTableByIndex(int index)
{
int indexPres = ui->comboBoxPreset->currentIndex();
if ( indexPres < 0)
{
return false;
}
int row = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(row);
QString command;
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[index].cla, 2, 16, QChar('0')).toUpper();
command += ":";
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[index].ins, 2, 16, QChar('0')).toUpper();
command += ":";
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[index].p1, 2, 16, QChar('0')).toUpper();
command += ":";
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[index].p2, 2, 16, QChar('0')).toUpper();
command += " | ";
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[index].len, 2, 16, QChar('0')).toUpper();
command += " | ";
if (_common_conf.presetCommandsV[indexPres].commandConf[index].len > 0)
{
for (unsigned i = 0;i < _common_conf.presetCommandsV[indexPres].commandConf[index].data_field.size()-1;i+=2)
{
command += _common_conf.presetCommandsV[indexPres].commandConf[index].data_field.substr(i,2).c_str();
if (i != _common_conf.presetCommandsV[indexPres].commandConf[index].data_field.size()-2)
{
command += ":";
}
}
}
ui->tableWidget->setItem(row, TABLE_COL_CMD_NAME, new QTableWidgetItem(_common_conf.presetCommandsV[indexPres].commandConf[index].commandDesc.c_str()));
ui->tableWidget->setItem(row, TABLE_COL_APDU, new QTableWidgetItem(command));
this->showCurExecCommand();
return true;
}
void MainWindow::confSendUpdateInfo(int index_seq_pres, int index_seq_command)
{
indexSeqPresUpdateInfo = index_seq_pres;
indexSeqCMDUpdateInfo = index_seq_command;
emit updateInfo();
}
void MainWindow::showCurExecCommand()
{
if (!_pConfig)
{
return;
}
if (!_pConfig->isConfigured())
{
return;
}
if (ui->comboBoxSeqPreset->currentIndex() < 0)
{
return;
}
if (this->_SCard.isActive())
{
for (unsigned i = 0;i < _common_conf.presetSequenceV[ui->comboBoxSeqPreset->currentIndex()].seqTest.size();i++)
{
ui->tableWidget->setItem(i, TABLE_COL_DEVICE, new QTableWidgetItem("---"));
}
}
}
void MainWindow::setWidgetProperties(bool flag)
{
ui->pushButtonConnect->setEnabled(flag);
ui->pushButtonAddTotable->setEnabled(flag);
ui->pushButtonFindDevs->setEnabled(flag);
ui->pushButtonSendAPDU->setEnabled(flag);
}
void MainWindow::on_lineEditLEN_editingFinished()
{
if (ui->lineEditLEN->text().compare("00"))
{
ui->lineEditData->setEnabled(true);
}
else
{
ui->lineEditData->setEnabled(false);
}
}
void MainWindow::on_pushButtonAddTotable_clicked()
{
if (_test_running)
{
return;
}
if (_common_conf.presetSequenceV.size() == 0)
{
ui->textEdit->append("Seq preset is missing. Create New Sequnce Preset");
return;
}
int indexCMD = ui->comboBoxAPDUSelect->currentIndex();
int indexPres = ui->comboBoxPreset->currentIndex();
int indexSeqPreset = ui->comboBoxSeqPreset->currentIndex();
if (indexCMD < 0 ||
indexPres < 0 ||
indexSeqPreset < 0)
{
return;
}
test_conf_t test_conf;
this->_pConfig->setDefaultTestConf(&test_conf);
test_conf.commandDesc = _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].commandDesc;
test_conf.cla = _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].cla;
test_conf.ins = _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].ins;
test_conf.p1 = _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].p1;
test_conf.p2 = _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].p2;
test_conf.len = _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].len;
test_conf.data_field = _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].data_field;
QString command;
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].cla, 2, 16, QChar('0')).toUpper();
command += ":";
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].ins, 2, 16, QChar('0')).toUpper();
command += ":";
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].p1, 2, 16, QChar('0')).toUpper();
command += ":";
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].p2, 2, 16, QChar('0')).toUpper();
command += " | ";
command += QString("%1").arg(_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].len, 2, 16, QChar('0')).toUpper();
command += " | ";
if (_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].len > 0)
{
if (_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].data_field.empty())
{
DEBUG(DBG_ERROR, "No Data In command: '" <<
_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].commandDesc <<
"', but len > 0");
ui->textEdit->append(QString("No Data In command: '") +
QString(_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].commandDesc.c_str()) +
QString("', but len > 0"));
return;
}
for (unsigned i = 0;i < _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].data_field.size()-1;i+=2)
{
command += _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].data_field.substr(i,2).c_str();
if (i != _common_conf.presetCommandsV[indexPres].commandConf[indexCMD].data_field.size()-2)
{
command += ":";
}
}
}
int row = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(row);
ui->tableWidget->setItem(row, TABLE_COL_CMD_NAME,
new QTableWidgetItem(_common_conf.presetCommandsV[indexPres].commandConf[indexCMD].commandDesc.c_str()));
ui->tableWidget->setItem(row, TABLE_COL_APDU, new QTableWidgetItem(command));
this->showCurExecCommand();
_common_conf.presetSequenceV[indexSeqPreset].seqTest.push_back(test_conf);
if (ui->tableWidget->rowCount() > 0)
{
QString text = "Total: ";
text += QString::number(ui->tableWidget->rowCount());
ui->label_33->setText(text);
}
ui->label_34->setText("---");
this->savePresetsToConf();
}
void MainWindow::on_pushButtonStartTest_clicked()
{
if (_test_running)
{
DEBUG(DBG_DEBUG,"Stop test.");
_test_running = false;
this->setWidgetProperties(!_test_running);
return;
}
int column = -1;
bool both_device = false;
if (ui->comboBoxDevice->currentIndex() < 0)
{
return;
}
int indexSeqPres = ui->comboBoxSeqPreset->currentIndex();
if (indexSeqPres < 0)
{
return;
}
DEBUG(DBG_DEBUG, "START NEW TEST");
DEBUG(DBG_DEBUG, _common_conf.presetSequenceV[indexSeqPres].seqPresetName.c_str());
ui->textEdit->append("START NEW TEST");
ui->textEdit->append(_common_conf.presetSequenceV[indexSeqPres].seqPresetName.c_str());
if (this->_SCard.isActive())
{
DEBUG(DBG_DEBUG, "Device: " <<
this->_SCard.getDeviceName());
column = TABLE_COL_DEVICE;
}
else
{
DEBUG(DBG_WARN,"No connected readers. Stop test...");
ui->textEdit->append("No connected readers");
return;
}
this->showCurExecCommand();
int row = ui->tableWidget->rowCount();
if(row <= 0)
{
return;
}
_test_running = true;
int repeat_cnt = 1;
this->setWidgetProperties(!_test_running);
ui->pushButtonStartTest->setText(tr("Stop Test"));
startSeqTestConf->setText(tr("Stop Test (Space)"));
qApp->processEvents();
ui->tableWidget->verticalScrollBar()->setSliderPosition(0);
double success = 0;
unsigned i = 0;
unsigned startTimeTest = getTimeMs();
QVector<double> testNum(1), timeEx(1);
testNum[0] = 0;
timeEx[0] = 0;
unsigned maxTimeEx = 0;
unsigned exchange_tm = 0;
if (_customPlot->graphCount() > 0)
{
_customPlot->removeGraph(0);
}
_customPlot->show();
ui->progressBarTest->show();
ui->progressBarTest->setTextVisible(true);
ui->comboBoxSeqPreset->setEnabled(false);
do
{
this->showCurExecCommand();
for (i = 0; _test_running && i < _common_conf.presetSequenceV[indexSeqPres].seqTest.size(); i++)
{
ui->label_33->setText(QString("Test # ") +
QString::number(i + 1) +
QString(" of ") +
QString::number(ui->tableWidget->rowCount()));
DEBUG(DBG_DEBUG, "---------------------------------------------");
ui->textEdit->append("---------------------------------------------");
ui->textEdit->append(QString("Test # " +
QString::number(i + 1) +
":" +
_common_conf.presetSequenceV[indexSeqPres].seqTest[i].commandDesc.c_str()));
DEBUG(DBG_DEBUG, "Test # " <<
(i + 1)
<< ":"
<< _common_conf.presetSequenceV[indexSeqPres].seqTest[i].commandDesc);
qApp->processEvents();
this->_failCheckInfo = false;
if (!both_device)
{
// ui->tableWidget->item( i, 0)->setBackgroundColor(Qt::lightGray);
// ui->tableWidget->item( i, 2)->setBackgroundColor(Qt::lightGray);
qApp->processEvents();
uint8_t apduBuf[APDU_BUFFER_SIZE] = {0};
uint32_t apduLength = 0;
uint8_t rpl[APDU_BUFFER_SIZE];
uint32_t rLength;
long rVal = 0;
apduBuf[CLA_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[i].cla);
apduBuf[INS_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[i].ins);
apduBuf[P1_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[i].p1);
apduBuf[P2_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[i].p2);
apduBuf[LEN_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[i].len);
apduLength = APDU_HEAD_LEN;
if (!_common_conf.presetSequenceV[indexSeqPres].seqTest[i].data_field.empty())
{
std::string data = _common_conf.presetSequenceV[indexSeqPres].seqTest[i].data_field;
for (unsigned int j = 0,index = 5;j < data.size() - 1;j+=2,index++)
{
apduBuf[index] = (0xff & ((char2bin(data[j]) << 4) | char2bin(data[j+1])));
}
apduBuf[LEN_INDEX] = 0xff & (data.size()/2); // String "FF" means 2 character
}
apduLength += apduBuf[LEN_INDEX];
bool cmdOK = true;
QString text = "OK";
unsigned start_tm = getTimeMs();
rVal = this->scardExchange((const char*)apduBuf,
apduLength,
(char*)rpl,
(int*)&rLength,
exchange_tm);
unsigned stop_tm = getTimeMs();
qApp->processEvents();
testNum.append(i+1);
timeEx.append(stop_tm - start_tm);
if (maxTimeEx < (stop_tm - start_tm))
{
maxTimeEx = (stop_tm - start_tm);
}
if (!rVal)
{
if ((uint32_t)_common_conf.presetSequenceV[indexSeqPres].seqTest[i].ansLen != rLength)
{
if (rLength > (uint32_t)_common_conf.presetSequenceV[indexSeqPres].seqTest[i].ansLenMax)
{
cmdOK = false;
DEBUG(DBG_ERROR, "WRONG LEN. LEN > MAX" << "(" << rLength << " >" <<
_common_conf.presetSequenceV[indexSeqPres].seqTest[i].ansLenMax << ")");
text = "FAIL";
QString desc = "WRONG LEN. LEN > MAX";
desc += "(";
desc += QString::number(rLength);
desc += " > ";
desc += QString::number(_common_conf.presetSequenceV[indexSeqPres].seqTest[i].ansLenMax);
desc += ")";
ui->textEdit->append(desc);
}
else if (rLength < (uint32_t)_common_conf.presetSequenceV[indexSeqPres].seqTest[i].ansLenMin)
{
cmdOK = false;
DEBUG(DBG_ERROR, "WRONG LEN. LEN > MIN" << "(" << rLength << " >" <<
_common_conf.presetSequenceV[indexSeqPres].seqTest[i].ansLenMin << ")");
text = "FAIL";
QString desc = "WRONG LEN. LEN < MIN";
desc += "(";
desc += QString::number(rLength);
desc += " < ";
desc += QString::number(_common_conf.presetSequenceV[indexSeqPres].seqTest[i].ansLenMin);
desc += ")";
ui->textEdit->append(desc);
}
else
{
DEBUG(DBG_WARN, "WRONG LEN in test. conf: " <<
_common_conf.presetSequenceV[indexSeqPres].seqTest[i].ansLen << ", answer: " << rLength);
QString desc = "WRONG LEN in test";
desc += "( test:";
desc += QString::number(rLength);
desc += ", answer: ";
desc += QString::number(_common_conf.presetSequenceV[indexSeqPres].seqTest[i].ansLen);
desc += " )";
ui->textEdit->append(desc);
}
}
if (rpl[rLength - 2] != _common_conf.presetSequenceV[indexSeqPres].seqTest[i].SW1)
{
cmdOK = false;
DEBUG(DBG_ERROR, "WRONG SW1");
text = "FAIL";
ui->textEdit->append("WRONG SW1");
}
if (rpl[rLength - 1] != _common_conf.presetSequenceV[indexSeqPres].seqTest[i].SW2)
{
cmdOK = false;
DEBUG(DBG_ERROR, "WRONG SW2");
text = "FAIL";
ui->textEdit->append("WRONG SW2");
}
ui->tableWidget->setItem(i, column, new QTableWidgetItem(text));
ui->textEdit->append(text);
if (cmdOK)
{
ui->tableWidget->item( i, column)->setBackground(Qt::darkGreen);
success++;
}
else
{
ui->tableWidget->item( i, column)->setBackground(Qt::darkRed);
this->_test_running = false;
break;
}
if (_common_conf.presetSequenceV[indexSeqPres].seqTest[i].resetUSB)
{
DEBUG(DBG_WARN, "Try reconnect after reset USB");
ui->textEdit->append("Try reconnect after reset USB");
qApp->processEvents();
this->_SCard.reconnect(DEFAULT_RECON_TIMEOUT_MS,
ui->checkBoxExclusive->isChecked());
}
}
else if (SCARD_E_INVALID_HANDLE != rVal || SCARD_W_RESET_CARD == rVal)
{
if (_common_conf.presetSequenceV[indexSeqPres].seqTest[i].resetUSB)
{
ui->tableWidget->setItem(i, column, new QTableWidgetItem(text));
ui->textEdit->append(text);
ui->tableWidget->item( i, column)->setBackground(Qt::darkGreen);
success++;
DEBUG(DBG_WARN, "Try reconnect after reset USB");
ui->textEdit->append("Try reconnect after reset USB");
qApp->processEvents();
this->_SCard.reconnect(DEFAULT_RECON_TIMEOUT_MS,
ui->checkBoxExclusive->isChecked());
}
else
{
ui->tableWidget->setItem(i, column, new QTableWidgetItem("FAIL (TRANS)"));
DEBUG(DBG_ERROR, "FAIL (TRANS). Error: " << this->_SCard.getSCardErrorDescription(rVal));
ui->textEdit->append(QString("FAIL (TRANS). Error: ") + QString(this->_SCard.getSCardErrorDescription(rVal)));
qApp->processEvents();
this->_test_running = false;
break;
}
}
else
{
ui->tableWidget->setItem(i, column, new QTableWidgetItem("FAIL (HANDLE)"));
DEBUG(DBG_ERROR, "FAIL (HANDLE). Error: " << this->_SCard.getSCardErrorDescription(rVal));
ui->textEdit->append(QString("FAIL (HANDLE). Error: ") + QString(this->_SCard.getSCardErrorDescription(rVal)));
ui->tableWidget->item( i, column)->setBackground(Qt::darkRed);
qApp->processEvents();
this->_test_running = false;
break;
}
if (!(i % 20))
{
ui->tableWidget->verticalScrollBar()->setSliderPosition(i);
}
// ui->tableWidget->item( i, 0)->setBackgroundColor(Qt::white);
// ui->tableWidget->item( i, 2)->setBackgroundColor(Qt::white);
DEBUG(DBG_DEBUG, "---------------------------------------------");
ui->textEdit->append("---------------------------------------------");
qApp->processEvents();
}
ui->label_34->setText(QString("Success: ") +
QString::number(success) +
QString(" | Test Count: ") +
QString::number(repeat_cnt));
if (this->_failCheckInfo)
{
this->_test_running = false;
break;
}
ui->progressBarTest->setValue(((float)(i + 1)/(float)ui->tableWidget->rowCount()) * 100);
}
if (ui->checkBoxInfinite->isChecked() && this->_test_running)
{
DEBUG(DBG_DEBUG, "\n\nRepeat\n\n");
ui->textEdit->append("\n\nRepeat\n\n");
repeat_cnt++;
}
} while(ui->checkBoxInfinite->isChecked() && this->_test_running);
unsigned stopTimeTest = getTimeMs();
ui->comboBoxSeqPreset->setEnabled(true);
ui->checkBoxInfinite->setChecked(false);
_customPlot->addGraph();
_customPlot->graph(0)->setData(testNum, timeEx);
_customPlot->xAxis->setLabel("test num");
_customPlot->yAxis->setLabel("time, ms");
_customPlot->xAxis->setRange(0, ui->tableWidget->rowCount() + 2);
_customPlot->yAxis->setRange(0, maxTimeEx + (maxTimeEx/100 * 5)); // + 5%
_customPlot->xAxis->setTickVector(testNum);
_customPlot->graph(0)->rescaleAxes();
_customPlot->replot();
QString txt = "Test Done. Total: ";
txt += QString::number(ui->tableWidget->rowCount());
txt += " | Count: ";
txt += QString::number(repeat_cnt);
txt += " | OK: ";
txt += QString::number(success);
txt += " | Fail: ";
txt += QString::number(ui->tableWidget->rowCount() * repeat_cnt - success);
unsigned difftime = stopTimeTest - startTimeTest;
txt += " | Time: ";
txt += QString("%1").arg((difftime/3600000), 2, 10, QChar('0')).toUpper();
txt += ":";
difftime %= 3600000;
txt += QString("%1").arg((difftime/60000), 2, 10, QChar('0')).toUpper();
txt += ":";
difftime %= 60000;
txt += QString("%1").arg((difftime/1000), 2, 10, QChar('0')).toUpper();
txt += ".";
difftime %= 1000;
txt += QString::number(difftime);
ui->textEdit->append(txt + "\n\n\n");
DEBUG(DBG_DEBUG, txt.toStdString() << "\n\n\n");
if (i != _common_conf.presetSequenceV[indexSeqPres].seqTest.size())
{
ui->tableWidget->item( i, column)->setBackground(Qt::darkRed);
if (this->_failCheckInfo)
{
ui->tableWidget->item( i, column)->setBackground(Qt::darkRed);
}
}
ui->label_34->setText(txt.remove("Test Done. "));
_test_running = false;
this->setWidgetProperties(!_test_running);
ui->pushButtonStartTest->setText(tr("Start Test"));
startSeqTestConf->setText(tr("Start Test (Space)"));
}
void MainWindow::StartTest_Selected_activated()
{
if (_test_running)
{
DEBUG(DBG_DEBUG,"Stop test.");
_test_running = false;
this->setWidgetProperties(!_test_running);
return;
}
int column = -1;
bool both_device = false;
if (ui->comboBoxDevice->currentIndex() < 0)
{
return;
}
int indexSeqPres = ui->comboBoxSeqPreset->currentIndex();
if (indexSeqPres < 0)
{
return;
}
QList<QTableWidgetItem *> itemList = ui->tableWidget->selectedItems();
if (itemList.empty())
{
return;
}
std::vector<int> vectIndex;
for (int i = (itemList.size() - 1); i > 0; i -= ui->tableWidget->columnCount())
{
vectIndex.push_back(itemList[i]->row());
}
// lambdas not working Hz
std::sort(vectIndex.begin(), vectIndex.end());
DEBUG(DBG_DEBUG, "START NEW TEST");
DEBUG(DBG_DEBUG, _common_conf.presetSequenceV[indexSeqPres].seqPresetName.c_str());
ui->textEdit->append("START NEW TEST");
ui->textEdit->append(_common_conf.presetSequenceV[indexSeqPres].seqPresetName.c_str());
if (this->_SCard.isActive())
{
DEBUG(DBG_DEBUG, "Device 1: " <<
this->_SCard.getDeviceName());
column = TABLE_COL_DEVICE;
}
else
{
DEBUG(DBG_WARN,"No connected readers. Stop test...");
ui->textEdit->append("No connected readers");
return;
}
this->showCurExecCommand();
int row = ui->tableWidget->rowCount();
if(row <= 0)
{
return;
}
_test_running = true;
this->setWidgetProperties(!_test_running);
ui->pushButtonStartTest->setText(tr("Stop Test"));
startSeqTestConf->setText(tr("Stop Test (Space)"));
qApp->processEvents();
ui->tableWidget->verticalScrollBar()->setSliderPosition(0);
double success = 0;
unsigned i = 0;
int repeat_cnt = 1;
unsigned startTimeTest = getTimeMs();
QVector<double> testNum(1), timeEx(1);
testNum[0] = 0;
timeEx[0] = 0;
unsigned maxTimeEx = 0;
unsigned exchange_tm = 0;
if (_customPlot->graphCount() > 0)
{
_customPlot->removeGraph(0);
}
_customPlot->show();
//ui->pushButtonShowGraph->show();
ui->progressBarTest->show();
ui->progressBarTest->setTextVisible(true);
ui->comboBoxSeqPreset->setEnabled(false);
do
{
this->showCurExecCommand();
for (i = 0; _test_running && i < vectIndex.size(); i++)
{
ui->label_33->setText(QString("Test # ") +
QString::number(vectIndex[i] + 1) +
QString(" of ") +
QString::number(ui->tableWidget->rowCount()));
DEBUG(DBG_DEBUG, "---------------------------------------------");
ui->textEdit->append("---------------------------------------------");
ui->textEdit->append(QString("Test # " +
QString::number(vectIndex[i] + 1) +
":" +
_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].commandDesc.c_str()));
DEBUG(DBG_DEBUG, "Test # " <<
(vectIndex[i] + 1)
<< ":"
<< _common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].commandDesc);
qApp->processEvents();
this->_failCheckInfo = false;
if (!both_device)
{
// ui->tableWidget->item( vectIndex[i], 0)->setBackgroundColor(Qt::lightGray);
// ui->tableWidget->item( vectIndex[i], 2)->setBackgroundColor(Qt::lightGray);
qApp->processEvents();
uint8_t apduBuf[APDU_BUFFER_SIZE] = {0};
uint32_t apduLength = 0;
uint8_t rpl[APDU_BUFFER_SIZE];
uint32_t rLength;
long rVal = 0;
apduBuf[CLA_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].cla);
apduBuf[INS_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ins);
apduBuf[P1_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].p1);
apduBuf[P2_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].p2);
apduBuf[LEN_INDEX] = (0xff & _common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].len);
apduLength = APDU_HEAD_LEN;
if (!_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].data_field.empty())
{
std::string data = _common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].data_field;
for (unsigned int j = 0,index = 5;j < data.size() - 1;j+=2,index++)
{
apduBuf[index] = (0xff & ((char2bin(data[j]) << 4) | char2bin(data[j+1])));
}
apduBuf[LEN_INDEX] = 0xff & (data.size()/2); // String "FF" means 2 character
}
apduLength += apduBuf[LEN_INDEX];
bool cmdOK = true;
QString text = "OK";
rVal = this->scardExchange((const char*)apduBuf,
apduLength,
(char*)rpl,
(int*)&rLength,
exchange_tm);
testNum.append(vectIndex[i]+1);
timeEx.append(exchange_tm);
if (maxTimeEx < (exchange_tm))
{
maxTimeEx = (exchange_tm);
}
if (!rVal)
{
if ((uint32_t)_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ansLen != rLength)
{
if (rLength > (uint32_t)_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ansLenMax)
{
cmdOK = false;
DEBUG(DBG_ERROR, "WRONG LEN. LEN > MAX" << "(" << rLength << " >" <<
_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ansLenMax << ")");
text = "FAIL";
QString desc = "WRONG LEN. LEN > MAX";
desc += "(";
desc += QString::number(rLength);
desc += " > ";
desc += QString::number(_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ansLenMax);
desc += ")";
ui->textEdit->append(desc);
}
else if (rLength < (uint32_t)_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ansLenMin)
{
cmdOK = false;
DEBUG(DBG_ERROR, "WRONG LEN. LEN > MIN" << "(" << rLength << " >" <<
_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ansLenMin << ")");
text = "FAIL";
QString desc = "WRONG LEN. LEN < MIN";
desc += "(";
desc += QString::number(rLength);
desc += " < ";
desc += QString::number(_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ansLenMin);
desc += ")";
ui->textEdit->append(desc);
}
else
{
DEBUG(DBG_WARN, "WRONG LEN in test. conf: " <<
_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ansLen << ", answer: " << rLength);
QString desc = "WRONG LEN in test";
desc += "( test:";
desc += QString::number(rLength);
desc += ", answer: ";
desc += QString::number(_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].ansLen);
desc += " )";
ui->textEdit->append(desc);
}
}
if (rpl[rLength - 2] != _common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].SW1)
{
cmdOK = false;
DEBUG(DBG_ERROR, "WRONG SW1");
text = "FAIL";
ui->textEdit->append("WRONG SW1");
}
if (rpl[rLength - 1] != _common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].SW2)
{
cmdOK = false;
DEBUG(DBG_ERROR, "WRONG SW2");
text = "FAIL";
ui->textEdit->append("WRONG SW2");
}
ui->tableWidget->setItem(vectIndex[i], column, new QTableWidgetItem(text));
ui->textEdit->append(text);
if (cmdOK)
{
ui->tableWidget->item( vectIndex[i], column)->setBackground(Qt::darkGreen);
success++;
}
else
{
ui->tableWidget->item( vectIndex[i], column)->setBackground(Qt::darkRed);
this->_test_running = false;
break;
}
if (_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].resetUSB)
{
DEBUG(DBG_WARN, "Try reconnect after reset USB");
ui->textEdit->append("Try reconnect after reset USB");
qApp->processEvents();
this->_SCard.reconnect(DEFAULT_RECON_TIMEOUT_MS,
ui->checkBoxExclusive->isChecked());
}
}
else if (SCARD_E_INVALID_HANDLE != rVal || SCARD_W_RESET_CARD == rVal)
{
if (_common_conf.presetSequenceV[indexSeqPres].seqTest[vectIndex[i]].resetUSB)
{
ui->tableWidget->setItem(vectIndex[i], column, new QTableWidgetItem(text));
ui->textEdit->append(text);
ui->tableWidget->item( vectIndex[i], column)->setBackground(Qt::darkGreen);
success++;
DEBUG(DBG_WARN, "Try reconnect after reset USB");
ui->textEdit->append("Try reconnect after reset USB");
qApp->processEvents();
this->_SCard.reconnect(DEFAULT_RECON_TIMEOUT_MS,
ui->checkBoxExclusive->isChecked());
}
else
{
ui->tableWidget->setItem(vectIndex[i], column, new QTableWidgetItem("FAIL (TRANS)"));
DEBUG(DBG_ERROR, "FAIL (TRANS). Error: " << this->_SCard.getSCardErrorDescription(rVal));
ui->textEdit->append(QString("FAIL (TRANS). Error: ") + QString(this->_SCard.getSCardErrorDescription(rVal)));
qApp->processEvents();
this->_test_running = false;
break;
}
}
else
{
ui->tableWidget->setItem(vectIndex[i], column, new QTableWidgetItem("FAIL (HANDLE)"));
DEBUG(DBG_ERROR, "FAIL (HANDLE). Error: " << this->_SCard.getSCardErrorDescription(rVal));
ui->textEdit->append(QString("FAIL (HANDLE). Error: ") + QString(this->_SCard.getSCardErrorDescription(rVal)));
ui->tableWidget->item( vectIndex[i], column)->setBackground(Qt::darkRed);
qApp->processEvents();
this->_test_running = false;
break;
}
if (!(i % 20))
{
ui->tableWidget->verticalScrollBar()->setSliderPosition(i);
}
DEBUG(DBG_DEBUG, "---------------------------------------------");
ui->textEdit->append("---------------------------------------------");
// ui->tableWidget->item( vectIndex[i], 0)->setBackgroundColor(Qt::white);
// ui->tableWidget->item( vectIndex[i], 2)->setBackgroundColor(Qt::white);
qApp->processEvents();
}
ui->label_34->setText(QString("Success: ") +
QString::number(success) +
QString(" | Test Count: ") +
QString::number(repeat_cnt));
if (this->_failCheckInfo)
{
this->_test_running = false;
break;
}
ui->progressBarTest->setValue(((float)(i + 1)/(float)vectIndex.size()) * 100);
}
if (ui->checkBoxInfinite->isChecked() && this->_test_running)
{
DEBUG(DBG_DEBUG, "\n\nRepeat\n\n" + QString::number(repeat_cnt).toStdString());
ui->textEdit->append(QString("\n\nRepeat\n\n") + QString::number(repeat_cnt));
repeat_cnt++;
}
} while(ui->checkBoxInfinite->isChecked() && this->_test_running);
unsigned stopTimeTest = getTimeMs();
ui->comboBoxSeqPreset->setEnabled(true);
ui->checkBoxInfinite->setChecked(false);
_customPlot->addGraph();
_customPlot->graph(0)->setData(testNum, timeEx);
_customPlot->xAxis->setLabel("test num");
_customPlot->yAxis->setLabel("time, ms");
_customPlot->xAxis->setRange(0, ui->tableWidget->rowCount() + 2);
_customPlot->yAxis->setRange(0, maxTimeEx + (maxTimeEx/100 * 5)); // + 5%
_customPlot->xAxis->setTickVector(testNum);
_customPlot->graph(0)->rescaleAxes();
_customPlot->replot();
QString txt = "Test Done. Total: ";
txt += QString::number(vectIndex.size());
txt += " | Count: ";
txt += QString::number(repeat_cnt);
txt += " | OK: ";
txt += QString::number(success);
txt += " | Fail: ";
txt += QString::number(vectIndex.size() * repeat_cnt - success);
unsigned difftime = stopTimeTest - startTimeTest;
txt += " | Time: ";
txt += QString("%1").arg((difftime/3600000), 2, 10, QChar('0')).toUpper();
txt += ":";
difftime %= 3600000;
txt += QString("%1").arg((difftime/60000), 2, 10, QChar('0')).toUpper();
txt += ":";
difftime %= 60000;
txt += QString("%1").arg((difftime/1000), 2, 10, QChar('0')).toUpper();
txt += ".";
difftime %= 1000;
txt += QString::number(difftime);
ui->textEdit->append(txt + "\n\n\n");
DEBUG(DBG_DEBUG, txt.toStdString() << "\n\n\n");
if (i != vectIndex.size())
{
ui->tableWidget->item( vectIndex[i], column)->setBackground(Qt::darkRed);
if (this->_failCheckInfo)
{
ui->tableWidget->item( vectIndex[i], column)->setBackground(Qt::darkRed);
}
}
ui->label_34->setText(txt.remove("Test Done. "));
_test_running = false;
this->setWidgetProperties(!_test_running);
ui->pushButtonStartTest->setText(tr("Start Test"));
startSeqTestConf->setText(tr("Start Test (Space)"));
}
void MainWindow::customMenuRequested(QPoint pos)
{
if (!_pConfig || !_pConfig->isConfigured())
{
return;
}
int indexSeqPres = ui->comboBoxSeqPreset->currentIndex();
if (indexSeqPres < 0)
{
return;
}
QModelIndex index = ui->tableWidget->indexAt(pos);
if (ui->tableWidget->rowCount() < index.row() || index.row() < 0)
{
return;
}
QMenu *menu = new QMenu(this);
QAction *setItem = menu->addAction("Set Item");
QAction *delItem = menu->addAction("Del Item");
QAction *sel = menu->exec(ui->tableWidget->viewport()->mapToGlobal(pos));
if (sel == setItem)
{
DialogSetTestItem dialogTestItem;
if(!_pConfig )
{
return;
}
if(!_pConfig->isConfigured())
{
return;
}
if (!dialogTestItem.setCurrentPreset(this->_pConfig,
&this->_common_conf,
indexSeqPres,
index.row()))
{
return;
}
int position = ui->tableWidget->verticalScrollBar()->sliderPosition();
dialogTestItem.show();
int dialogCode = dialogTestItem.exec();
if (dialogCode == QDialog::Accepted)
{
this->savePresetsToConf();
}
ui->tableWidget->verticalScrollBar()->setSliderPosition(position);
ui->tableWidget->selectRow(index.row());
}
if (sel == delItem)
{
std::string msg_text;
msg_text = "Delete Item #";
msg_text += std::to_string(index.row());
msg_text += " '";
msg_text += _common_conf.presetSequenceV[indexSeqPres].seqTest[index.row()].commandDesc.c_str();
msg_text += "'?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Warning", msg_text.c_str(),
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
{
ui->tableWidget->removeRow(index.row());
_pConfig->removeSeqPresetItem(this->_common_conf, indexSeqPres, index.row());
this->savePresetsToConf();
}
}
}
void MainWindow::tableItemClicked(int row, int column)
{
Q_UNUSED(column)
if (!_pConfig || !_pConfig->isConfigured())
{
return;
}
int indexSeqPres = ui->comboBoxSeqPreset->currentIndex();
if (row < 0 || indexSeqPres < 0)
{
return;
}
DialogSetTestItem dialogTestItem;
if(!_pConfig )
{
return;
}
if(!_pConfig->isConfigured())
{
return;
}
if (!dialogTestItem.setCurrentPreset(this->_pConfig,
&this->_common_conf,
indexSeqPres,
row))
{
return;
}
int position = ui->tableWidget->verticalScrollBar()->sliderPosition();
dialogTestItem.show();
int dialogCode = dialogTestItem.exec();
if (dialogCode == QDialog::Accepted)
{
this->savePresetsToConf();
}
ui->tableWidget->verticalScrollBar()->setSliderPosition(position);
ui->tableWidget->selectRow(row);
}
void MainWindow::AddSeqTestItem_clicked()
{
if (_test_running)
{
return;
}
DialogNewSeqPreset dial;
if(!_pConfig )
{
return;
}
if(!_pConfig->isConfigured())
{
return;
}
if (!dial.setCurrentConfig(_pConfig, &this->_common_conf))
{
return;
}
dial.show();
dial.exec();
this->savePresetsToConf();
}
void MainWindow::saveSeqConfiguration_triggered()
{
if (_test_running)
{
return;
}
if (!_pConfig || !_pConfig->isConfigured())
{
return;
}
this->savePresetsToConf();
}
void MainWindow::clearSeqConfiguration_triggered()
{
if (_test_running)
{
return;
}
if (!_pConfig || !_pConfig->isConfigured())
{
return;
}
std::string msg_text;
msg_text = "Clear Test Sequence?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Warning", msg_text.c_str(),
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
{
while (ui->tableWidget->rowCount() > 0)
{
ui->tableWidget->removeRow(0);
}
this->_pConfig->clearSequenceList(this->_common_conf,
ui->comboBoxSeqPreset->currentIndex());
this->savePresetsToConf();
}
}
void MainWindow::reloadConfiguration_triggered()
{
if (_test_running)
{
return;
}
updateLocalConfig();
}
bool MainWindow::savePresetsToConf()
{
if (!_pConfig->savePresetsConf(this->_common_conf))
{
ui->textEdit->append("Sequece not saved");
return false;
}
updateLocalConfig();
return true;
}
void MainWindow::printExchageBuffers(const char *cmd, const int cLength,
const char *rpl, const int rLength, unsigned time_ms)
{
QString text = "C-APDU (";
text += "Dev ";
text += "): ";
for (int i = 0;i < cLength;i++)
{
text += QString("%1").arg((0xff & cmd[i]), 2, 16, QChar('0')).toUpper();
text += " ";
}
ui->textEdit->append(text);
DEBUG(DBG_DEBUG, text.toStdString());
text = "R-APDU (";
text += "Dev ";
text += "): ";
for (int i = 0;i < rLength;i++)
{
text += QString("%1").arg((0xff & rpl[i]), 2, 16, QChar('0')).toUpper();
text += " ";
}
ui->textEdit->append(text);
DEBUG(DBG_DEBUG, text.toStdString());
text = "Time exchange: ";
text += QString::number(time_ms);
text += " ms";
ui->textEdit->append(text);
DEBUG(DBG_DEBUG, text.toStdString());
}
long MainWindow::scardExchange(const char *cmd,
int cLength, char *rpl, int *rLength)
{
long res;
#ifdef DEBUG_EXCHANGE_BUFFERS
unsigned start_tm = getTimeMs();
#endif // DEBUG_EXCHANGE_BUFFERS
res = this->_SCard.transmit(cmd,
cLength,
rpl,
rLength);
#ifdef DEBUG_EXCHANGE_BUFFERS
unsigned stop_tm = getTimeMs();
this->printExchageBuffers(cmd,
cLength, rpl, *rLength,
stop_tm - start_tm);
#endif // DEBUG_EXCHANGE_BUFFERS
qApp->processEvents();
return res;
}
long MainWindow::scardExchange(const char *cmd,
int cLength, char *rpl, int *rLength,
unsigned &ex_time)
{
long res;
unsigned start_tm = getTimeMs();
res = this->_SCard.transmit(cmd,
cLength,
rpl,
rLength);
unsigned stop_tm = getTimeMs();
ex_time = stop_tm - start_tm;
this->printExchageBuffers(cmd,
cLength, rpl, *rLength,
ex_time);
qApp->processEvents();
return res;
}
void MainWindow::on_pushButtonCopyToClipboard_clicked()
{
QClipboard *clipboard = QApplication::clipboard();
QString logPath = ui->labelFileLog->text();
logPath.replace("<a href=", "");
logPath.replace("</a>", "");
int last_index = logPath.lastIndexOf(">");
logPath.remove(last_index, logPath.size() - last_index);
clipboard->setText(logPath);
}
void MainWindow::on_comboBoxSeqPreset_currentIndexChanged(int index)
{
if (index < 0)
{
return;
}
while (ui->tableWidget->rowCount() > 0)
{
ui->tableWidget->removeRow(0);
}
for (unsigned i = 0;i < _common_conf.presetSequenceV[index].seqTest.size();i++)
{
int row = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(row);
QString command;
command += QString("%1").arg(_common_conf.presetSequenceV[index].seqTest[i].cla, 2, 16, QChar('0')).toUpper();
command += ":";
command += QString("%1").arg(_common_conf.presetSequenceV[index].seqTest[i].ins, 2, 16, QChar('0')).toUpper();
command += ":";
command += QString("%1").arg(_common_conf.presetSequenceV[index].seqTest[i].p1, 2, 16, QChar('0')).toUpper();
command += ":";
command += QString("%1").arg(_common_conf.presetSequenceV[index].seqTest[i].p2, 2, 16, QChar('0')).toUpper();
command += " | ";
command += QString("%1").arg(_common_conf.presetSequenceV[index].seqTest[i].len, 2, 16, QChar('0')).toUpper();
command += " | ";
if (!_common_conf.presetSequenceV[index].seqTest[i].data_field.empty())
{
if (_common_conf.presetSequenceV[index].seqTest[i].len > 0)
{
for (unsigned j = 0;j < _common_conf.presetSequenceV[index].seqTest[i].data_field.size()-1;j+=2)
{
command += _common_conf.presetSequenceV[index].seqTest[i].data_field.substr(j,2).c_str();
if (j != _common_conf.presetSequenceV[index].seqTest[i].data_field.size()-2)
{
command += ":";
}
}
}
}
ui->tableWidget->setItem(row, TABLE_COL_CMD_NAME, new QTableWidgetItem(_common_conf.presetSequenceV[index].seqTest[i].commandDesc.c_str()));
ui->tableWidget->setItem(row, TABLE_COL_APDU, new QTableWidgetItem(command));
this->showCurExecCommand();
}
if (ui->tableWidget->rowCount() > 0)
{
QString text = tr("Total: ");
text += QString::number(ui->tableWidget->rowCount());
ui->label_33->setText(text);
}
ui->label_34->setText("---");
}
void MainWindow::on_tableWidget_clicked(const QModelIndex &index)
{
test_conf_t temp_seq_item;
temp_seq_item = this->_common_conf.presetSequenceV[ui->comboBoxSeqPreset->currentIndex()].seqTest[index.row()];
QString txt = "Item configuration\n";
txt += "Command:\t";
txt += temp_seq_item.commandDesc.c_str();
txt += "\n";
txt += "CLA:\t\t";
txt += QString("%1").arg(temp_seq_item.cla, 2, 16, QChar('0')).toUpper();
txt += "\n";
txt += "INS:\t\t";
txt += QString("%1").arg(temp_seq_item.ins, 2, 16, QChar('0')).toUpper();
txt += "\n";
txt += "P1:\t\t";
txt += QString("%1").arg(temp_seq_item.p1, 2, 16, QChar('0')).toUpper();
txt += "\n";
txt += "P2:\t\t";
txt += QString("%1").arg(temp_seq_item.p2, 2, 16, QChar('0')).toUpper();
txt += "\n";
txt += "LC:\t\t";
txt += QString("%1").arg(temp_seq_item.len, 2, 16, QChar('0')).toUpper();
txt += "\n";
txt += "Data:\t\t";
if (temp_seq_item.data_field.size() > 11)
{
txt += "...";
txt += temp_seq_item.data_field.substr(temp_seq_item.data_field.size() - 11).c_str();
}
else
{
txt += temp_seq_item.data_field.c_str();
}
txt += "\n";
txt += "Resp len:\t\t";
txt += QString::number(temp_seq_item.ansLen - 2); // without SW's
txt += "\n";
txt += "Min resp len:\t";
txt += QString::number(temp_seq_item.ansLenMin - 2); // without SW's
txt += "\n";
txt += "Max resp len:\t";
txt += QString::number(temp_seq_item.ansLenMax - 2); // without SW's
txt += "\n";
txt += "SW1:\t\t";
txt += QString("%1").arg(temp_seq_item.SW1, 2, 16, QChar('0')).toUpper();
txt += "\n";
txt += "SW2:\t\t";
txt += QString("%1").arg(temp_seq_item.SW2, 2, 16, QChar('0')).toUpper();
txt += "\n";
txt += "Save2Buf1:\t";
txt += temp_seq_item.save2Buf1?"TRUE":"FALSE";
txt += "\n";
txt += "Save2Buf2:\t";
txt += temp_seq_item.save2Buf2?"TRUE":"FALSE";
txt += "\n";
txt += "LoadFromBuf1:\t";
txt += temp_seq_item.loadFromBuf1?"TRUE":"FALSE";
txt += "\n";
txt += "LoadFromBuf2:\t";
txt += temp_seq_item.loadFromBuf2?"TRUE":"FALSE";
txt += "\n";
txt += "USB Reset:\t";
txt += temp_seq_item.resetUSB?"TRUE":"FALSE";
txt += "\n";
popUp->setPopupText(txt);
popUp->show();
}
void MainWindow::on_pushButtonShowGraph_clicked()
{
if(!ui->widgetPlot->graphCount())
{
QMessageBox messageBox;
messageBox.warning(this,"Show graph","No data");
messageBox.setFixedSize(500,200);
return;
}
DialogShowGraph dialGraph;
dialGraph.setParentPlot(_customPlot);
dialGraph.show();
dialGraph.exec();
}
void MainWindow::deleteSelectedRows_pressed()
{
QList<QTableWidgetItem *> itemList = ui->tableWidget->selectedItems();
int indexSeqPreset = ui->comboBoxSeqPreset->currentIndex();
std::vector<int> vectIndex;
for (int i = (itemList.size() - 1); i > 0; i -= ui->tableWidget->columnCount())
{
vectIndex.push_back(itemList[i]->row());
}
// lambdas not working Hz
std::sort(vectIndex.begin(), vectIndex.end());
std::string msg_text;
msg_text = "Delete item(s):";
for (int i = 0;i < itemList.size();i += ui->tableWidget->columnCount())
{
msg_text += "\n";
msg_text += "#";
msg_text += std::to_string(itemList[i]->row() + 1);
msg_text += " '";
msg_text += (_common_conf.presetSequenceV[indexSeqPreset].seqTest.begin() +
itemList[i]->row())->commandDesc;
msg_text += "'";
}
msg_text += " ?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this,
"Warning",
msg_text.c_str(),
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes)
{
for (int i = (int)vectIndex.size() - 1; i >= 0; i--)
{
this->_pConfig->removeSeqPresetItem(this->_common_conf,indexSeqPreset,vectIndex[i]);
}
this->savePresetsToConf();
}
}
void MainWindow::copySelectedRows_pressed()
{
_copyVectIndex.resize(0);
QList<QTableWidgetItem *> itemList = ui->tableWidget->selectedItems();
for (int i = (itemList.size() - 1); i > 0; i -= ui->tableWidget->columnCount())
{
_copyVectIndex.push_back(itemList[i]->row());
}
// lambdas not working Hz
std::sort(_copyVectIndex.begin(), _copyVectIndex.end());
this->_copySeqPreset = ui->comboBoxSeqPreset->currentIndex();
}
void MainWindow::pasteSelectedRows_pressed()
{
QList<QTableWidgetItem *> itemList = ui->tableWidget->selectedItems();
int indexSeqPreset = ui->comboBoxSeqPreset->currentIndex();
for (unsigned int i = 0; i < _copyVectIndex.size(); i++)
{
_common_conf.presetSequenceV[indexSeqPreset].seqTest.push_back(_common_conf.presetSequenceV[this->_copySeqPreset].seqTest[_copyVectIndex[i]]);
}
this->savePresetsToConf();
}
//void MainWindow::closeEvent(QCloseEvent *event)
//{
//#if _WIN32 || _WIN64
// if (_test_running)
// {
// QMessageBox::information(this, tr("test_ex"),
// tr("The program will keep running in the "
// "system tray. To terminate the program, "
// "choose <b>Restore</b> or <b>Maximize</b> in the context menu "
// "of the system tray entry and stop the current test."));
// }
//#else
// this->_test_running = false;
//#endif
//}
void MainWindow::on_tableWidget_cellEntered(int row, int column)
{
Q_UNUSED(column)
if (ui->checkBoxMultiSelect->isChecked())
{
ui->tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
return;
}
int colCount =ui->tableWidget->columnCount();
int rowsel;
if(ui->tableWidget->currentIndex().row() < row)
rowsel = row - 1; //down
else if(ui->tableWidget->currentIndex().row() > row)
rowsel = row + 1; //up
else
return;
test_conf_t temp_seq_conf = this->_common_conf.presetSequenceV[ui->comboBoxSeqPreset->currentIndex()].seqTest[row];
this->_common_conf.presetSequenceV[ui->comboBoxSeqPreset->currentIndex()].seqTest[row] =
this->_common_conf.presetSequenceV[ui->comboBoxSeqPreset->currentIndex()].seqTest[rowsel];
this->_common_conf.presetSequenceV[ui->comboBoxSeqPreset->currentIndex()].seqTest[rowsel] = temp_seq_conf;
QList<QTableWidgetItem*> rowItems, rowItems1;
for (int col = 0; col < colCount; ++col)
{
rowItems << ui->tableWidget->takeItem(row, col);
rowItems1 << ui->tableWidget->takeItem(rowsel, col);
}
for (int cola = 0; cola < colCount; ++cola)
{
ui->tableWidget->setItem(rowsel, cola, rowItems.at(cola));
ui->tableWidget->setItem(row, cola, rowItems1.at(cola));
}
}
void MainWindow::on_checkBoxMultiSelect_toggled(bool checked)
{
if (checked)
{
ui->tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
else
{
ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
}
}
void MainWindow::keyPressEvent(QKeyEvent * event)
{
switch(event->key())
{
case Qt::Key_Shift:
ui->checkBoxMultiSelect->setChecked(false);
break;
default:
QWidget::keyPressEvent(event);
}
}
void MainWindow::keyReleaseEvent(QKeyEvent * event)
{
switch(event->key())
{
case Qt::Key_Shift:
ui->checkBoxMultiSelect->setChecked(true);
this->savePresetsToConf();
break;
default:
QWidget::keyPressEvent(event);
}
}
| [
"mrnettleman88@gmail.com"
] | mrnettleman88@gmail.com |
6d615d546b13c81f8ae07181304f176115e8bd09 | d43b69d5ef9c9624832c346ce7aa9637b1655a10 | /Lab4/src/DynamicMethod.h | 1ddf7c4935dad7929adf8fbba83b983828b7d89b | [] | no_license | XuanZhai/CS3353_Algorithm | 818cd2581de12c9a3e74ff239fcd49fb1c5da618 | f355fae72508952b4307da7697ed3486f0189943 | refs/heads/master | 2022-04-14T08:15:18.291784 | 2020-04-16T15:35:48 | 2020-04-16T15:35:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | h | #ifndef DYNAMICMETHOD_H
#define DYNAMICMETHOD_H
#include "FindPathBase.h"
#include "TSPTable.h"
class DynamicMethod: public FindPathBase {
public:
void Implement() override;
};
#endif | [
"xzhai@smu.edu"
] | xzhai@smu.edu |
fb9f844698abcef3fdb39a9e326a0e272aa17e43 | cf440e299f576604880d201c480ccd641e3ccf0b | /cpp/test/unit/image/OrientationTest.cpp | 0e7ac48c009ec7d6dfd6e92b3aad91cf45e66bc7 | [
"MIT"
] | permissive | facebookincubator/spectrum | 03c22fa0dad157d35e084ec500aebeb456f50f27 | f955ddbc5f992915a60f4ee35f8a336a08f7781a | refs/heads/main | 2023-08-25T19:57:05.211461 | 2023-08-23T22:34:45 | 2023-08-23T22:34:45 | 151,472,642 | 1,938 | 177 | MIT | 2023-07-11T00:57:02 | 2018-10-03T19:58:50 | C++ | UTF-8 | C++ | false | false | 7,550 | cpp | // 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 <spectrum/image/Orientation.h>
#include <spectrum/core/SpectrumEnforce.h>
#include <gtest/gtest.h>
using namespace facebook::spectrum::image;
namespace facebook {
namespace spectrum {
namespace image {
namespace test {
TEST(image_image_Orientation, whenCreatedFromWrongValue_thenThrows) {
ASSERT_THROW(orientationFromValue(9), SpectrumException);
ASSERT_THROW(orientationFromValue(0), SpectrumException);
}
TEST(image_image_Orientation, whenCreatedFromValidValue_thenReturned) {
ASSERT_EQ(Orientation::Up, orientationFromValue(1));
ASSERT_EQ(Orientation::Left, orientationFromValue(8));
}
TEST(
image_Orientation,
whenCreatingWithAnAngleNotBetween0And360_thenItIsSanitized) {
ASSERT_EQ(
Orientation::Bottom,
orientationRotatedWithDegrees(Orientation::Bottom, -360));
ASSERT_EQ(
Orientation::Up, orientationRotatedWithDegrees(Orientation::Bottom, 540));
ASSERT_EQ(
Orientation::Left, orientationRotatedWithDegrees(Orientation::Up, 630));
ASSERT_EQ(
Orientation::Right,
orientationRotatedWithDegrees(Orientation::Bottom, -90));
}
TEST(image_Orientation, whenCreatingWithValuesMatchingUp_thenUpIsReturned) {
ASSERT_EQ(Orientation::Up, orientationRotatedWithDegrees(Orientation::Up, 0));
ASSERT_EQ(
Orientation::Up, orientationRotatedWithDegrees(Orientation::Left, 90));
ASSERT_EQ(
Orientation::Up, orientationRotatedWithDegrees(Orientation::Right, -90));
}
TEST(
image_Orientation,
whenCreatingWithValuesMatchingRight_thenRightIsReturned) {
ASSERT_EQ(
Orientation::Right, orientationRotatedWithDegrees(Orientation::Up, 90));
ASSERT_EQ(
Orientation::Right, orientationRotatedWithDegrees(Orientation::Right, 0));
ASSERT_EQ(
Orientation::Right, orientationRotatedWithDegrees(Orientation::Up, 90));
ASSERT_EQ(
Orientation::Right,
orientationRotatedWithDegrees(Orientation::Bottom, -90));
}
TEST(
image_Orientation,
whenCreatingWithValuesMatchingBottom_thenBottomIsReturned) {
ASSERT_EQ(
Orientation::Bottom, orientationRotatedWithDegrees(Orientation::Up, 180));
ASSERT_EQ(
Orientation::Bottom,
orientationRotatedWithDegrees(Orientation::Bottom, 0));
ASSERT_EQ(
Orientation::Bottom,
orientationRotatedWithDegrees(Orientation::Right, 90));
ASSERT_EQ(
Orientation::Bottom,
orientationRotatedWithDegrees(Orientation::Left, -90));
}
TEST(image_Orientation, whenCreatingWithValuesMatchingLeft_thenLeftIsReturned) {
ASSERT_EQ(
Orientation::Left, orientationRotatedWithDegrees(Orientation::Up, 270));
ASSERT_EQ(
Orientation::Left, orientationRotatedWithDegrees(Orientation::Left, 0));
ASSERT_EQ(
Orientation::Left,
orientationRotatedWithDegrees(Orientation::Bottom, 90));
ASSERT_EQ(
Orientation::Left, orientationRotatedWithDegrees(Orientation::Up, -90));
}
TEST(
image_Orientation,
whenCreatingWithValuesMatchingUpMirrored_thenUpMirroredIsReturned) {
ASSERT_EQ(
Orientation::UpMirrored,
orientationRotatedWithDegrees(Orientation::UpMirrored, 0));
ASSERT_EQ(
Orientation::UpMirrored,
orientationRotatedWithDegrees(Orientation::LeftMirrored, 90));
ASSERT_EQ(
Orientation::UpMirrored,
orientationRotatedWithDegrees(Orientation::RightMirrored, -90));
}
TEST(
image_Orientation,
whenCreatingWithValuesMatchingRightMirrored_thenRightMirroredIsReturned) {
ASSERT_EQ(
Orientation::RightMirrored,
orientationRotatedWithDegrees(Orientation::RightMirrored, 0));
ASSERT_EQ(
Orientation::RightMirrored,
orientationRotatedWithDegrees(Orientation::UpMirrored, 90));
ASSERT_EQ(
Orientation::RightMirrored,
orientationRotatedWithDegrees(Orientation::BottomMirrored, -90));
}
TEST(
image_Orientation,
whenCreatingWithValuesMatchingBottomMirrored_thenBottomMirroredIsReturned) {
ASSERT_EQ(
Orientation::BottomMirrored,
orientationRotatedWithDegrees(Orientation::BottomMirrored, 0));
ASSERT_EQ(
Orientation::BottomMirrored,
orientationRotatedWithDegrees(Orientation::RightMirrored, 90));
ASSERT_EQ(
Orientation::BottomMirrored,
orientationRotatedWithDegrees(Orientation::LeftMirrored, -90));
}
TEST(
image_Orientation,
whenCreatingWithValuesMatchingLeftMirrored_thenLeftMirroredIsReturned) {
ASSERT_EQ(
Orientation::LeftMirrored,
orientationRotatedWithDegrees(Orientation::LeftMirrored, 0));
ASSERT_EQ(
Orientation::LeftMirrored,
orientationRotatedWithDegrees(Orientation::BottomMirrored, 90));
ASSERT_EQ(
Orientation::LeftMirrored,
orientationRotatedWithDegrees(Orientation::UpMirrored, -90));
}
TEST(
image_Orientation,
whenMergeFunctionNotMirroring_thenSameEffectAsJustRotationFunction) {
ASSERT_EQ(
orientationRotatedWithDegrees(Orientation::BottomMirrored, 90),
orientationRotatedAndFlipped(
Orientation::BottomMirrored, 90, false, false));
ASSERT_EQ(
orientationRotatedWithDegrees(Orientation::Up, 0),
orientationRotatedAndFlipped(Orientation::Up, 0, false, false));
}
TEST(image_Orientation, whenMergeFunctionMirroring_thenUpResultsInUpMirrored) {
ASSERT_EQ(
Orientation::UpMirrored,
orientationRotatedAndFlipped(Orientation::Up, 0, true, false));
}
TEST(image_Orientation, whenMergeFunctionRotatingAndMirroring_thenCorrect) {
ASSERT_EQ(
Orientation::LeftMirrored,
orientationRotatedAndFlipped(Orientation::Up, 270, true, false));
}
TEST(image_Orientation, whenMirrored_thenMirroredValueReturned) {
// non-mirror to mirrored
ASSERT_EQ(
Orientation::UpMirrored, orientationFlippedHorizontally(Orientation::Up));
ASSERT_EQ(
Orientation::RightMirrored,
orientationFlippedHorizontally(Orientation::Right));
ASSERT_EQ(
Orientation::BottomMirrored,
orientationFlippedHorizontally(Orientation::Bottom));
ASSERT_EQ(
Orientation::LeftMirrored,
orientationFlippedHorizontally(Orientation::Left));
// mirrored to non-mirrored
ASSERT_EQ(
Orientation::Up, orientationFlippedHorizontally(Orientation::UpMirrored));
ASSERT_EQ(
Orientation::Right,
orientationFlippedHorizontally(Orientation::RightMirrored));
ASSERT_EQ(
Orientation::Bottom,
orientationFlippedHorizontally(Orientation::BottomMirrored));
ASSERT_EQ(
Orientation::Left,
orientationFlippedHorizontally(Orientation::LeftMirrored));
}
TEST(image_Orientation, whenConvertedToString_thenCorrect) {
ASSERT_EQ("up", orientationStringFromValue(Orientation::Up));
ASSERT_EQ("up_mirrored", orientationStringFromValue(Orientation::UpMirrored));
ASSERT_EQ("right", orientationStringFromValue(Orientation::Right));
ASSERT_EQ(
"right_mirrored", orientationStringFromValue(Orientation::RightMirrored));
ASSERT_EQ("bottom", orientationStringFromValue(Orientation::Bottom));
ASSERT_EQ(
"bottom_mirrored",
orientationStringFromValue(Orientation::BottomMirrored));
ASSERT_EQ("left", orientationStringFromValue(Orientation::Left));
ASSERT_EQ(
"left_mirrored", orientationStringFromValue(Orientation::LeftMirrored));
ASSERT_EQ(
"unknown (9)", orientationStringFromValue(static_cast<Orientation>(9)));
}
} // namespace test
} // namespace image
} // namespace spectrum
} // namespace facebook
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
9b72c92a1ccde72ac42c8f9649a88ce72138ce79 | bfacbf029c6c76fbff700b1dd8858fb4627f6d28 | /src/asio/src/tests/unit/execution/scheduler.cpp | 7611b98864847fe744ee26089b686d6d0fa4ef20 | [
"BSL-1.0"
] | permissive | hbwangjinwu/dragonfly | 1924e50e8eddc21134ca4b34b0e0c34b317a057e | b918fa267aebef854ab85c280414fbae6d888d1e | refs/heads/master | 2022-12-03T08:47:07.377236 | 2020-08-20T16:02:03 | 2020-08-20T16:02:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,926 | cpp | //
// scheduler.cpp
// ~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include "asio/execution/scheduler.hpp"
#include "../unit_test.hpp"
namespace exec = asio::execution;
struct not_a_scheduler
{
};
struct executor
{
executor()
{
}
executor(const executor&) ASIO_NOEXCEPT
{
}
#if defined(ASIO_HAS_MOVE)
executor(executor&&) ASIO_NOEXCEPT
{
}
#endif // defined(ASIO_HAS_MOVE)
template <typename F>
void execute(ASIO_MOVE_ARG(F) f) const ASIO_NOEXCEPT
{
(void)f;
}
bool operator==(const executor&) const ASIO_NOEXCEPT
{
return true;
}
bool operator!=(const executor&) const ASIO_NOEXCEPT
{
return false;
}
};
namespace asio {
namespace traits {
#if !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT)
template <typename F>
struct execute_member<executor, F>
{
ASIO_STATIC_CONSTEXPR(bool, is_valid = true);
ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true);
typedef void result_type;
};
#endif // !defined(ASIO_HAS_DEDUCED_SET_ERROR_MEMBER_TRAIT)
#if !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT)
template <>
struct equality_comparable<executor>
{
ASIO_STATIC_CONSTEXPR(bool, is_valid = true);
ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true);
};
#endif // !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT)
} // namespace traits
} // namespace asio
void test_is_scheduler()
{
ASIO_CHECK(!exec::is_scheduler<not_a_scheduler>::value);
ASIO_CHECK(exec::is_scheduler<executor>::value);
}
ASIO_TEST_SUITE
(
"scheduler",
ASIO_TEST_CASE(test_is_scheduler)
)
| [
"allen@allen-18.04"
] | allen@allen-18.04 |
88f28390571a241cf9ecd8bad6397b9f8685b025 | c8c668836de8c64e0d087a7f247ab29a4ea48427 | /thinglang/runtime/errors/RuntimeError.cpp | 8cdc13e7036988c41ea4e5e6c4774bf16f66a14a | [
"MIT"
] | permissive | ytanay/thinglang | 138a2b04816c6ad9ca173bdc4d3f5ff2a8891d79 | 18557db95ead629e1cda2da65a22b942bcc8077c | refs/heads/master | 2021-01-17T04:32:49.387017 | 2018-02-17T11:56:43 | 2018-02-17T11:56:43 | 82,967,133 | 5 | 1 | MIT | 2018-01-04T19:49:30 | 2017-02-23T20:13:03 | Python | UTF-8 | C++ | false | false | 107 | cpp | #include "RuntimeError.h"
const char *RuntimeError::what() const noexcept {
return message.c_str();
}
| [
"yotam.tanay@gmail.com"
] | yotam.tanay@gmail.com |
8e9cb14e2e85970e30d3fdfaf1c896ddf6632598 | cfee198c3ec5225249fa2cdc66d1639c631c2b3f | /src/core/visual/win32/DrawDevice.h | 55acd57c12f6fa10f3341ca6c03e1c5e07b8282d | [
"FTL",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"Libpng",
"Zlib",
"Apache-2.0",
"BSD-2-Clause-Views",
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | unlimit999/krkrz | adb1948797f668f2d225c4c66c39ac86292ac9df | 627bd42b67943071874a5fe1a9645b021bd6bc99 | refs/heads/master | 2021-01-15T14:24:40.775799 | 2016-04-26T13:39:08 | 2016-04-26T13:39:08 | 57,589,538 | 1 | 0 | null | 2016-05-01T07:47:12 | 2016-05-01T07:47:11 | null | SHIFT_JIS | C++ | false | false | 33,431 | h | //---------------------------------------------------------------------------
/*
TVP2 ( T Visual Presenter 2 ) A script authoring tool
Copyright (C) 2000 W.Dee <dee@kikyou.info> and contributors
See details of license at "license.txt"
*/
//---------------------------------------------------------------------------
//!@file æç»ããã€ã¹ç®¡ç
//---------------------------------------------------------------------------
#ifndef DRAWDEVICE_H
#define DRAWDEVICE_H
#include "LayerIntf.h"
#include "LayerManager.h"
#include "ComplexRect.h"
class iTVPWindow;
class tTJSNI_BaseLayer;
/*[*/
//---------------------------------------------------------------------------
//! @brief æç»ããã€ã¹ã€ã³ã¿ãŒãã§ãŒã¹
//---------------------------------------------------------------------------
class iTVPDrawDevice
{
public:
//---- ãªããžã§ã¯ãçåæéå¶åŸ¡
//! @brief (WindowâDrawDevice) æç»ããã€ã¹ãç Žæ£ãã
//! @note ãŠã£ã³ããŠãç Žæ£ããããšãããããã¯ã»ãã®æç»ããã€ã¹ã
//! èšå®ãããããã«ãã®æç»ããã€ã¹ãå¿
èŠãªããªã£ãéã«åŒã°ããã
//! éåžžãããã§ã¯ delete this ãå®è¡ããæç»ããã€ã¹ãç Žæ£ãããããã®åã«
//! AddLayerManager() ã§ãã®æç»ããã€ã¹ã®ç®¡çäžã«å
¥ã£ãŠãã
//! ã¬ã€ã€ãããŒãžã£ããã¹ãŠ Release ããã
//! ã¬ã€ã€ãããŒãžã£ã® Release äžã« RemoveLayerManager() ãåŒã°ãã
//! å¯èœæ§ãããããšã«æ³šæããããšã
virtual void TJS_INTF_METHOD Destruct() = 0;
//---- window interface é¢é£
//! @brief (WindowâDrawDevice) ãŠã£ã³ããŠã€ã³ã¿ãŒãã§ãŒã¹ãèšå®ãã
//! @param window ãŠã£ã³ããŠã€ã³ã¿ãŒãã§ãŒã¹
//! @note (TJSãã) Window.drawDevice ããããã£ãèšå®ããçŽåŸã«åŒã°ããã
virtual void TJS_INTF_METHOD SetWindowInterface(iTVPWindow * window) = 0;
//---- LayerManager ã®ç®¡çé¢é£
//! @brief (WindowâDrawDevice) ã¬ã€ã€ãããŒãžã£ã远å ãã
//! @note ãã©ã€ããªã¬ã€ã€ããŠã£ã³ããŠã«è¿œå ããããšãèªåçã«ã¬ã€ã€ãããŒãžã£ã
//! äœæããããããæç»ããã€ã¹ã«ããã®ã¡ãœããã®åŒã³åºãã«ãŠéç¥ãããã
//! æç»ããã€ã¹ã§ã¯ iTVPLayerManager::AddRef() ãåŒã³åºããŠã远å ããã
//! ã¬ã€ã€ãããŒãžã£ãããã¯ããããšã
virtual void TJS_INTF_METHOD AddLayerManager(iTVPLayerManager * manager) = 0;
//! @brief (WindowâDrawDevice) ã¬ã€ã€ãããŒãžã£ãåé€ãã
//! @note ãã©ã€ããªã¬ã€ã€ã invalidate ãããéã«åŒã³åºãããã
//TODO: ãã©ã€ããªã¬ã€ã€ç¡å¹åããããã¯ãŠã£ã³ããŠç Žæ£æã®çµäºåŠçãæ£ãããïŒ
virtual void TJS_INTF_METHOD RemoveLayerManager(iTVPLayerManager * manager) = 0;
//---- æç»äœçœ®ã»ãµã€ãºé¢é£
//! @brief (WindowâDrawDevice) æç»å
ãŠã£ã³ããŠã®èšå®
//! @param wnd ãŠã£ã³ããŠãã³ãã«
//! @param is_main ã¡ã€ã³ãŠã£ã³ããŠã®å Žåã«ç
//! @note ãŠã£ã³ããŠããæç»å
ãšãªããŠã£ã³ããŠãã³ãã«ãæå®ããããã«åŒã°ããã
//! ãã°ãã°ãWindow.borderStyle ããããã£ã倿Žããããããã«ã¹ã¯ãªãŒã³ã«
//! ç§»è¡ãããšãããã«ã¹ã¯ãªãŒã³ããæ»ãæãªã©ããŠã£ã³ããŠãåäœæããã
//! ããšããããããã®ãããªå Žåã«ã¯ããŠã£ã³ããŠããã£ããç Žæ£ãããçŽåã«
//! wnd = NULL ã®ç¶æ
ã§ãã®ã¡ãœãããåŒã°ããããšã«æ³šæããŠã£ã³ããŠãäœæ
//! ãããããšãåã³æå¹ãªãŠã£ã³ããŠãã³ãã«ã䌎ã£ãŠãã®ã¡ãœãããåŒã°ããã
//! ãã®ã¡ãœããã¯ããŠã£ã³ããŠãäœæãããçŽåŸã«åŒã°ããä¿èšŒã¯ãªãã
//! ãããŠããäžçªæåã«ãŠã£ã³ããŠã衚瀺ãããçŽåŸã«åŒã°ããã
virtual void TJS_INTF_METHOD SetTargetWindow(HWND wnd, bool is_main) = 0;
//! @brief (Window->DrawDevice) æç»ç©åœ¢ã®èšå®
//! @note ãŠã£ã³ããŠãããæç»å
ãšãªãç©åœ¢ãèšå®ããããã«åŒã°ããã
//! æç»ããã€ã¹ã¯ãSetTargetWindow() ã§æå®ããããŠã£ã³ããŠã®ã¯ã©ã€ã¢ã³ãé åã®ã
//! ãã®ã¡ãœããã§æå®ãããç©åœ¢ã«è¡šç€ºãè¡ãå¿
èŠãããã
//! ãã®ç©åœ¢ã¯ãGetSrcSize ã§è¿ããå€ã«å¯ŸããWindow.zoomNumer ã Window.zoomDenum
//! ããããã£ã«ããæ¡å€§çããWindow.layerLeft ã Window.layerTop ãå å³ããã
//! ç©åœ¢ã§ããã
//! ãã®ã¡ãœããã«ãã£ãŠæç»ç©åœ¢ãå€ãã£ããšããŠãããã®ã¿ã€ãã³ã°ã§
//! æç»ããã€ã¹åŽã§åæç»ãè¡ãå¿
èŠã¯ãªã(å¿
èŠãããã°å¥ã¡ãœããã«ãã
//! åæç»ã®å¿
èŠæ§ãéç¥ããããã)ã
virtual void TJS_INTF_METHOD SetDestRectangle(const tTVPRect & rect) = 0;
//! @brief (Window->DrawDevice) ã¯ãªããã³ã°ç©åœ¢ã®èšå®
//! @note ãŠã£ã³ããŠãããæç»å
ãã¯ãªããã³ã°ããããã®ç©åœ¢ãèšå®ããããã«åŒã°ããã
//! æç»ããã€ã¹ã¯ãSetDestRectangleã§æå®ãããé åãããã®ã¡ãœããã§æå®ãããç©åœ¢
//! ã§ã¯ãªããã³ã°ãè¡ã衚瀺ãè¡ãå¿
èŠãããã
//! ãã®ã¡ãœããã«ãã£ãŠæç»é åãå€ãã£ããšããŠãããã®ã¿ã€ãã³ã°ã§
//! æç»ããã€ã¹åŽã§åæç»ãè¡ãå¿
èŠã¯ãªã(å¿
èŠãããã°å¥ã¡ãœããã«ãã
//! åæç»ã®å¿
èŠæ§ãéç¥ããããã)ã
virtual void TJS_INTF_METHOD SetClipRectangle(const tTVPRect & rect) = 0;
//! @brief (Window->DrawDevice) å
ç»åã®ãµã€ãºãåŸã
//! @note ãŠã£ã³ããŠãããæç»ç©åœ¢ã®ãµã€ãºã決å®ããããã«å
ç»åã®ãµã€ãºã
//! å¿
èŠã«ãªã£ãéã«åŒã°ããããŠã£ã³ããŠã¯ãããããšã« SetDestRectangle()
//! ã¡ãœããã§æç»ç©åœ¢ãéç¥ããŠããã ããªã®ã§ã
//! ãªãããã®æå³ã®ãããµã€ãºã§ããå¿
èŠã¯å¿
ããããªãã
virtual void TJS_INTF_METHOD GetSrcSize(tjs_int &w, tjs_int &h) = 0;
//! @brief (LayerManagerâDrawDevice) ã¬ã€ã€ãµã€ãºå€æŽã®éç¥
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @note ã¬ã€ã€ãããŒãžã£ã«ã¢ã¿ãããããŠãããã©ã€ããªã¬ã€ã€ã®ãµã€ãºãå€ãã£ã
//! éã«åŒã³åºããã
virtual void TJS_INTF_METHOD NotifyLayerResize(iTVPLayerManager * manager) = 0;
//! @brief (LayerManagerâDrawDevice) ã¬ã€ã€ã®ç»åã®å€æŽã®éç¥
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @note ã¬ã€ã€ã®ç»åã«å€åããã£ãéã«åŒã³åºãããã
//! ãã®éç¥ãåãåã£ãåŸã« iTVPLayerManager::UpdateToDrawDevice()
//! ãåŒã³åºãã°ã該åœéšåãæç»ããã€ã¹ã«å¯ŸããŠæç»ãããããšãã§ããã
//! ãã®éç¥ãåãåã£ãŠãç¡èŠããããšã¯å¯èœããã®å Žåã¯ã
//! 次㫠iTVPLayerManager::UpdateToDrawDevice() ãåŒãã éã«ã
//! ãããŸã§ã®å€æŽåããã¹ãŠæç»ãããã
virtual void TJS_INTF_METHOD NotifyLayerImageChange(iTVPLayerManager * manager) = 0;
//---- ãŠãŒã¶ãŒã€ã³ã¿ãŒãã§ãŒã¹é¢é£
//! @brief (WindowâDrawDevice) ã¯ãªãã¯ããã
//! @param x æç»ç©åœ¢å
ã«ããã x äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param y æç»ç©åœ¢å
ã«ããã y äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
virtual void TJS_INTF_METHOD OnClick(tjs_int x, tjs_int y) = 0;
//! @brief (WindowâDrawDevice) ããã«ã¯ãªãã¯ããã
//! @param x æç»ç©åœ¢å
ã«ããã x äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param y æç»ç©åœ¢å
ã«ããã y äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
virtual void TJS_INTF_METHOD OnDoubleClick(tjs_int x, tjs_int y) = 0;
//! @brief (WindowâDrawDevice) ããŠã¹ãã¿ã³ãæŒäžããã
//! @param x æç»ç©åœ¢å
ã«ããã x äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param y æç»ç©åœ¢å
ã«ããã y äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param mb ã©ã®ããŠã¹ãã¿ã³ã
//! @param flags ãã©ã°(TVP_SS_*宿°ã®çµã¿åãã)
virtual void TJS_INTF_METHOD OnMouseDown(tjs_int x, tjs_int y, tTVPMouseButton mb, tjs_uint32 flags) = 0;
//! @brief (WindowâDrawDevice) ããŠã¹ãã¿ã³ãé¢ããã
//! @param x æç»ç©åœ¢å
ã«ããã x äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param y æç»ç©åœ¢å
ã«ããã y äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param mb ã©ã®ããŠã¹ãã¿ã³ã
//! @param flags ãã©ã°(TVP_SS_*宿°ã®çµã¿åãã)
virtual void TJS_INTF_METHOD OnMouseUp(tjs_int x, tjs_int y, tTVPMouseButton mb, tjs_uint32 flags) = 0;
//! @brief (WindowâDrawDevice) ããŠã¹ãç§»åãã
//! @param x æç»ç©åœ¢å
ã«ããã x äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param y æç»ç©åœ¢å
ã«ããã y äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param flags ãã©ã°(TVP_SS_*宿°ã®çµã¿åãã)
virtual void TJS_INTF_METHOD OnMouseMove(tjs_int x, tjs_int y, tjs_uint32 flags) = 0;
//! @brief (WindowâDrawDevice) ã¬ã€ã€ã®ããŠã¹ãã£ããã£ãè§£æŸãã
//! @note ã¬ã€ã€ã®ããŠã¹ãã£ããã£ãè§£æŸãã¹ãå Žåã«ãŠã£ã³ããŠããåŒã°ããã
//! @note WindowReleaseCapture() ãšæ··åããªãããšã
virtual void TJS_INTF_METHOD OnReleaseCapture() = 0;
//! @brief (WindowâDrawDevice) ããŠã¹ãæç»ç©åœ¢å€ã«ç§»åãã
virtual void TJS_INTF_METHOD OnMouseOutOfWindow() = 0;
//! @brief (WindowâDrawDevice) ããŒãæŒããã
//! @param key ä»®æ³ããŒã³ãŒã
//! @param shift ã·ããããŒã®ç¶æ
virtual void TJS_INTF_METHOD OnKeyDown(tjs_uint key, tjs_uint32 shift) = 0;
//! @brief (WindowâDrawDevice) ããŒãé¢ããã
//! @param key ä»®æ³ããŒã³ãŒã
//! @param shift ã·ããããŒã®ç¶æ
virtual void TJS_INTF_METHOD OnKeyUp(tjs_uint key, tjs_uint32 shift) = 0;
//! @brief (WindowâDrawDevice) ããŒã«ããå
¥å
//! @param key æåã³ãŒã
virtual void TJS_INTF_METHOD OnKeyPress(tjs_char key) = 0;
//! @brief (WindowâDrawDevice) ããŠã¹ãã€ãŒã«ãå転ãã
//! @param shift ã·ããããŒã®ç¶æ
//! @param delta å転è§
//! @param x æç»ç©åœ¢å
ã«ããã x äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param y æç»ç©åœ¢å
ã«ããã y äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
virtual void TJS_INTF_METHOD OnMouseWheel(tjs_uint32 shift, tjs_int delta, tjs_int x, tjs_int y) = 0;
//! @brief (WindowâDrawDevice) ç»é¢ãã¿ããããã
//! @param x æç»ç©åœ¢å
ã«ããã x äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param y æç»ç©åœ¢å
ã«ããã y äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param cx è§ŠããŠããå¹
//! @param cy è§ŠããŠããé«ã
//! @param id ã¿ããèå¥çšID
virtual void TJS_INTF_METHOD OnTouchDown( tjs_real x, tjs_real y, tjs_real cx, tjs_real cy, tjs_uint32 id ) = 0;
//! @brief (WindowâDrawDevice) ã¿ãããé¢ããã
//! @param x æç»ç©åœ¢å
ã«ããã x äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param y æç»ç©åœ¢å
ã«ããã y äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param cx è§ŠããŠããå¹
//! @param cy è§ŠããŠããé«ã
//! @param id ã¿ããèå¥çšID
virtual void TJS_INTF_METHOD OnTouchUp( tjs_real x, tjs_real y, tjs_real cx, tjs_real cy, tjs_uint32 id ) = 0;
//! @brief (WindowâDrawDevice) ã¿ãããç§»åãã
//! @param x æç»ç©åœ¢å
ã«ããã x äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param y æç»ç©åœ¢å
ã«ããã y äœçœ®(æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @param cx è§ŠããŠããå¹
//! @param cy è§ŠããŠããé«ã
//! @param id ã¿ããèå¥çšID
virtual void TJS_INTF_METHOD OnTouchMove( tjs_real x, tjs_real y, tjs_real cx, tjs_real cy, tjs_uint32 id ) = 0;
//! @brief (WindowâDrawDevice) æ¡å€§ã¿ããæäœãè¡ããã
//! @param startdist éå§æã®2ç¹éã®å¹
//! @param curdist çŸåšã®2ç¹éã®å¹
//! @param cx è§ŠããŠããå¹
//! @param cy è§ŠããŠããé«ã
//! @param flag ã¿ããç¶æ
ãã©ã°
virtual void TJS_INTF_METHOD OnTouchScaling( tjs_real startdist, tjs_real curdist, tjs_real cx, tjs_real cy, tjs_int flag ) = 0;
//! @brief (WindowâDrawDevice) å転ã¿ããæäœãè¡ããã
//! @param startangle éå§æã®è§åºŠ
//! @param curangle çŸåšã®è§åºŠ
//! @param dist çŸåšã®2ç¹éã®å¹
//! @param cx è§ŠããŠããå¹
//! @param cy è§ŠããŠããé«ã
//! @param flag ã¿ããç¶æ
ãã©ã°
virtual void TJS_INTF_METHOD OnTouchRotate( tjs_real startangle, tjs_real curangle, tjs_real dist, tjs_real cx, tjs_real cy, tjs_int flag ) = 0;
//! @brief (WindowâDrawDevice) ãã«ãã¿ããç¶æ
ãæŽæ°ããã
virtual void TJS_INTF_METHOD OnMultiTouch() = 0;
//! @brief (Window->DrawDevice) ç»é¢ã®å転ãè¡ããã
//! @param orientation ç»é¢ã®åã ( 暪åãã瞊åããäžæ )
//! @param rotate å転è§åºŠãDegreeãè² ã®å€ã®æäžæ
//! @param bpp Bits per pixel
//! @param width ç»é¢å¹
//! @param height ç»é¢é«ã
virtual void TJS_INTF_METHOD OnDisplayRotate( tjs_int orientation, tjs_int rotate, tjs_int bpp, tjs_int width, tjs_int height ) = 0;
//! @brief (Window->DrawDevice) å
¥åç¶æ
ã®ãã§ãã¯
//! @note ãŠã£ã³ããŠããçŽ1ç§ããã«ãã¬ã€ã€ãããŒãžã£ããŠãŒã¶ããã®å
¥åã®ç¶æ
ã
//! åãã§ãã¯ããããã«åŒã°ãããã¬ã€ã€ç¶æ
ã®å€åããŠãŒã¶ã®å
¥åãšã¯
//! éåæã«è¡ãããå Žåãããšãã°ããŠã¹ã«ãŒãœã«ã®äžã«ã¬ã€ã€ãåºçŸãã
//! ã®ã«ãããããããããŠã¹ã«ãŒãœã«ããã®ã¬ã€ã€ã®æå®ãã圢ç¶ã«å€æŽãããªã
//! ãšãã£ãç¶æ³ãçºçãããããã®ãããªç¶æ³ã«å¯ŸåŠããããããŠã£ã³ããŠãã
//! ãã®ã¡ãœãããçŽ1ç§ããã«åŒã°ããã
virtual void TJS_INTF_METHOD RecheckInputState() = 0;
//! @brief (LayerManagerâDrawDevice) ããŠã¹ã«ãŒãœã«ã®åœ¢ç¶ãããã©ã«ãã«æ»ã
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @note ããŠã¹ã«ãŒãœã«ã®åœ¢ç¶ãããã©ã«ãã®ç©ã«æ»ãããå Žåã«åŒã°ãã
virtual void TJS_INTF_METHOD SetDefaultMouseCursor(iTVPLayerManager * manager) = 0;
//! @brief (LayerManagerâDrawDevice) ããŠã¹ã«ãŒãœã«ã®åœ¢ç¶ãèšå®ãã
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @param cursor ããŠã¹ã«ãŒãœã«åœ¢ç¶çªå·
virtual void TJS_INTF_METHOD SetMouseCursor(iTVPLayerManager * manager, tjs_int cursor) = 0;
//! @brief (LayerManagerâDrawDevice) ããŠã¹ã«ãŒãœã«ã®äœçœ®ãååŸãã
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @param x ãã©ã€ããªã¬ã€ã€äžã®åº§æšã«ãããããŠã¹ã«ãŒãœã«ã®xäœçœ®
//! @param y ãã©ã€ããªã¬ã€ã€äžã®åº§æšã«ãããããŠã¹ã«ãŒãœã«ã®yäœçœ®
//! @note 座æšã¯ãã©ã€ããªã¬ã€ã€äžã®åº§æšãªã®ã§ãå¿
èŠãªãã°å€æãè¡ã
virtual void TJS_INTF_METHOD GetCursorPos(iTVPLayerManager * manager, tjs_int &x, tjs_int &y) = 0;
//! @brief (LayerManagerâDrawDevice) ããŠã¹ã«ãŒãœã«ã®äœçœ®ãèšå®ãã
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @param x ãã©ã€ããªã¬ã€ã€äžã®åº§æšã«ãããããŠã¹ã«ãŒãœã«ã®xäœçœ®
//! @param y ãã©ã€ããªã¬ã€ã€äžã®åº§æšã«ãããããŠã¹ã«ãŒãœã«ã®yäœçœ®
//! @note 座æšã¯ãã©ã€ããªã¬ã€ã€äžã®åº§æšãªã®ã§ãå¿
èŠãªãã°å€æãè¡ã
virtual void TJS_INTF_METHOD SetCursorPos(iTVPLayerManager * manager, tjs_int x, tjs_int y) = 0;
//! @brief (LayerManagerâDrawDevice) ãŠã£ã³ããŠã®ããŠã¹ãã£ããã£ãè§£æŸãã
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @note ãŠã£ã³ããŠã®ããŠã¹ãã£ããã£ãè§£æŸãã¹ãå Žåã«ã¬ã€ã€ãããŒãžã£ããåŒã°ããã
//! @note ãŠã£ã³ããŠã®ããŠã¹ãã£ããã£ã¯ OnReleaseCapture() ã§éæŸã§ããã¬ã€ã€ã®ããŠã¹ãã£ããã£
//! ãšç°ãªãããšã«æ³šæããŠã£ã³ããŠã®ããŠã¹ãã£ããã£ã¯äž»ã«OSã®ãŠã£ã³ããŠã·ã¹ãã ã®
//! æ©èœã§ããããã¬ã€ã€ã®ããŠã¹ãã£ããã£ã¯åéåéãã¬ã€ã€ãããŒãžã£ããšã«
//! ç¬èªã«ç®¡çããŠããç©ã§ããããã®ã¡ãœããã§ã¯åºæ¬çã«ã¯ ::ReleaseCapture() ãªã©ã§
//! ããŠã¹ã®ãã£ããã£ãéæŸããã
virtual void TJS_INTF_METHOD WindowReleaseCapture(iTVPLayerManager * manager) = 0;
//! @brief (LayerManagerâDrawDevice) ããŒã«ããããã³ããèšå®ãã
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @param text ãã³ãããã¹ã(空æååã®å Žåã¯ãã³ãã®è¡šç€ºããã£ã³ã»ã«ãã)
virtual void TJS_INTF_METHOD SetHintText(iTVPLayerManager * manager, iTJSDispatch2* sender, const ttstr & text) = 0;
//! @brief (LayerManagerâDrawDevice) 泚èŠãã€ã³ãã®èšå®
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @param layer ãã©ã³ãæ
å ±ã®å«ãŸããã¬ã€ã€
//! @param x ãã©ã€ããªã¬ã€ã€äžã®åº§æšã«ãããæ³šèŠãã€ã³ãã®xäœçœ®
//! @param y ãã©ã€ããªã¬ã€ã€äžã®åº§æšã«ãããæ³šèŠãã€ã³ãã®yäœçœ®
//! @note 泚èŠãã€ã³ãã¯éåžžãã£ã¬ããäœçœ®ã®ããšã§ãããã«IMEã®ã³ã³ããžããã»ãŠã£ã³ããŠã
//! 衚瀺ããããããŠãŒã¶è£å©ã®æ¡å€§é¡ããããæ¡å€§ããããããIMEãã³ã³ããžãããŠã£ã³ããŠã
//! 衚瀺ããããæªç¢ºå®ã®æåãããã«è¡šç€ºãããããéã®ãã©ã³ã㯠layer ãã©ã¡ãŒã¿
//! ã§ç€ºãããã¬ã€ã€ãæã€æ
å ±ã«ãããããã©ã°ã€ã³ãããã®æ
å ±ãåŸããèšå®ããã
//! ããã€ã³ã¿ãŒãã§ãŒã¹ã¯ä»ã®ãšãããªãã
//! @note 座æšã¯ãã©ã€ããªã¬ã€ã€äžã®åº§æšãªã®ã§ãå¿
èŠãªãã°å€æãè¡ãã
virtual void TJS_INTF_METHOD SetAttentionPoint(iTVPLayerManager * manager, tTJSNI_BaseLayer *layer,
tjs_int l, tjs_int t) = 0;
//! @brief (LayerManagerâDrawDevice) 泚èŠãã€ã³ãã®è§£é€
//! @param manager ã¬ã€ã€ãããŒãžã£
virtual void TJS_INTF_METHOD DisableAttentionPoint(iTVPLayerManager * manager) = 0;
//! @brief (LayerManagerâDrawDevice) IMEã¢ãŒãã®èšå®
//! @param manager ã¬ã€ã€ãããŒãžã£
//! @param mode IMEã¢ãŒã
virtual void TJS_INTF_METHOD SetImeMode(iTVPLayerManager * manager, tTVPImeMode mode) = 0;
//! @brief (LayerManagerâDrawDevice) IMEã¢ãŒãã®ãªã»ãã
//! @param manager ã¬ã€ã€ãããŒãžã£
virtual void TJS_INTF_METHOD ResetImeMode(iTVPLayerManager * manager) = 0;
//---- ãã©ã€ããªã¬ã€ã€é¢é£
//! @brief (WindowâDrawDevice) ãã©ã€ããªã¬ã€ã€ã®ååŸ
//! @return ãã©ã€ããªã¬ã€ã€
//! @note Window.primaryLayer ãèªã¿åºãããéã«ãã®ã¡ãœãããåŒã°ããã
//! ãã以å€ã«åŒã°ããããšã¯ãªãã
virtual tTJSNI_BaseLayer * TJS_INTF_METHOD GetPrimaryLayer() = 0;
//! @brief (WindowâDrawDevice) ãã©ãŒã«ã¹ã®ããã¬ã€ã€ã®ååŸ
//! @return ãã©ãŒã«ã¹ã®ããã¬ã€ã€(NULL=ãã©ãŒã«ã¹ã®ããã¬ã€ã€ããªãå Žå)
//! @note Window.focusedLayer ãèªã¿åºãããéã«ãã®ã¡ãœãããåŒã°ããã
//! ãã以å€ã«åŒã°ããããšã¯ãªãã
virtual tTJSNI_BaseLayer * TJS_INTF_METHOD GetFocusedLayer() = 0;
//! @brief (WindowâDrawDevice) ãã©ãŒã«ã¹ã®ããã¬ã€ã€ã®èšå®
//! @param layer ãã©ãŒã«ã¹ã®ããã¬ã€ã€(NULL=ãã©ãŒã«ã¹ã®ããã¬ã€ã€ããªãç¶æ
ã«ãããå Žå)
//! @note Window.focusedLayer ãæžã蟌ãŸããéã«ãã®ã¡ãœãããåŒã°ããã
//! ãã以å€ã«åŒã°ããããšã¯ãªãã
virtual void TJS_INTF_METHOD SetFocusedLayer(tTJSNI_BaseLayer * layer) = 0;
//---- åæç»é¢é£
//! @brief (WindowâDrawDevice) æç»ç©åœ¢ã®ç¡å¹åã®éç¥
//! @param rect æç»ç©åœ¢å
ã®åº§æšã«ããããç¡å¹ã«ãªã£ãé å
//! (æç»ç©åœ¢ã®å·Šäžãåç¹)
//! @note æç»ç©åœ¢ã®äžéšãããã¯å
šéšãç¡å¹ã«ãªã£ãéã«ãŠã£ã³ããŠããéç¥ãããã
//! æç»ããã€ã¹ã¯ããªãã¹ãæ©ãææã«ç¡å¹ã«ãªã£ãéšåãåæç»ãã¹ãã§ããã
virtual void TJS_INTF_METHOD RequestInvalidation(const tTVPRect & rect) = 0;
//! @brief (WindowâDrawDevice) æŽæ°ã®èŠæ±
//! @note æç»ç©åœ¢ã®å
å®¹ãææ°ã®ç¶æ
ã«æŽæ°ãã¹ãã¿ã€ãã³ã°ã§ããŠã£ã³ããŠããåŒã°ããã
//! iTVPWindow::RequestUpdate() ãåŒãã åŸãã·ã¹ãã ãæç»ã¿ã€ãã³ã°ã«å
¥ã£ãéã«
//! åŒã°ãããéåžžãæç»ããã€ã¹ã¯ãã®ã¿ã€ãã³ã°ãå©çšããŠãªãã¹ã¯ãªãŒã³
//! ãµãŒãã§ãŒã¹ã«ç»åãæç»ããã
virtual void TJS_INTF_METHOD Update() = 0;
//! @brief (Window->DrawDevice) ç»åã®è¡šç€º
//! @note ãªãã¹ã¯ãªãŒã³ãµãŒãã§ãŒã¹ã«æç»ãããç»åãããªã³ã¹ã¯ãªãŒã³ã«è¡šç€ºãã
//! (ãããã¯ããªãããã) ã¿ã€ãã³ã°ã§åŒã°ãããé垞㯠Update ã®çŽåŸã«
//! åŒã°ããããVSync åŸ
ã¡ãæå¹ã«ãªã£ãŠããå Žå㯠Update çŽåŸã§ã¯ãªãã
//! VBlank äžã«åŒã°ããå¯èœæ§ãããããªãã¹ã¯ãªãŒã³ãµãŒãã§ãŒã¹ã
//! 䜿ããªãå Žåã¯ç¡èŠããŠããŸããªãã
virtual void TJS_INTF_METHOD Show() = 0;
//---- LayerManager ããã®ç»ååãæž¡ãé¢é£
//! @brief (LayerManager->DrawDevice) ããããããã®æç»ãéå§ãã
//! @param manager æç»ãéå§ããã¬ã€ã€ãããŒãžã£
//! @note ã¬ã€ã€ãããŒãžã£ããæç»ããã€ã¹ãžç»åã転éãããåã«åŒã°ããã
//! ãã®ããšãNotifyBitmapCompleted() ãä»»æã®åæ°åŒã°ããæåŸã«
//! EndBitmapCompletion() ãåŒã°ããã
//! å¿
èŠãªãã°ããã®ã¿ã€ãã³ã°ã§æç»ããã€ã¹åŽã§ãµãŒãã§ãŒã¹ã®ããã¯ãªã©ã
//! è¡ãããšã
virtual void TJS_INTF_METHOD StartBitmapCompletion(iTVPLayerManager * manager) = 0;
//! @brief (LayerManager->DrawDevice) ããããããã®æç»ãéç¥ãã
//! @param manager ç»åã®æäŸå
ã®ã¬ã€ã€ãããŒãžã£
//! @param x ãã©ã€ããªã¬ã€ã€äžã®åº§æšã«ãããç»åã®å·Šç«¯äœçœ®
//! @param y ãã©ã€ããªã¬ã€ã€äžã®åº§æšã«ãããç»åã®äžç«¯äœçœ®
//! @param bits ããããããããŒã¿
//! @param bitmapinfo ããããããã®åœ¢åŒæ
å ±
//! @param cliprect bits ã®ãã¡ãã©ã®éšåã䜿ã£ãŠæ¬²ãããã®æ
å ±
//! @param type æäŸãããç»åãæ³å®ããåæã¢ãŒã
//! @param opacity æäŸãããç»åãæ³å®ããäžéæåºŠ(0ã255)
//! @note ã¬ã€ã€ãããŒãžã£ãåæãå®äºããçµæãæç»ããã€ã¹ã«æç»ããŠãããããéã«
//! åŒã°ãããäžã€ã®æŽæ°ãè€æ°ã®ç©åœ¢ã§æ§æãããå Žåãããããããã®ã¡ãœããã¯
//! StartBitmapCompletion() ãš EndBitmapCompletion() ã®éã«è€æ°ååŒã°ããå¯èœæ§ãããã
//! åºæ¬çã«ã¯ãbits ãš bitmapinfo ã§è¡šãããããããããã®ãã¡ãcliprect ã§
//! 瀺ãããç©åœ¢ã x, y äœçœ®ã«è»¢éããã°ããããæç»ç©åœ¢ã®å€§ããã«åããã
//! æ¡å€§ãçž®å°ãªã©ã¯æç»ããã€ã¹åŽã§é¢åãèŠãå¿
èŠãããã
virtual void TJS_INTF_METHOD NotifyBitmapCompleted(iTVPLayerManager * manager,
tjs_int x, tjs_int y, const void * bits, const BITMAPINFO * bitmapinfo,
const tTVPRect &cliprect, tTVPLayerType type, tjs_int opacity) = 0;
//! @brief (LayerManager->DrawDevice) ããããããã®æç»ãçµäºãã
//! @param manager æç»ãçµäºããã¬ã€ã€ãããŒãžã£
virtual void TJS_INTF_METHOD EndBitmapCompletion(iTVPLayerManager * manager) = 0;
//---- ãããã°æ¯æŽ
//! @brief (Window->DrawDevice) ã¬ã€ã€æ§é ãã³ã³ãœãŒã«ã«ãã³ããã
virtual void TJS_INTF_METHOD DumpLayerStructure() = 0;
//! @brief (Window->DrawDevice) æŽæ°ç©åœ¢ã®è¡šç€ºãè¡ããã©ãããèšå®ãã
//! @param b 衚瀺ãè¡ããã©ãã
//! @note ã¬ã€ã€è¡šç€ºæ©æ§ãå·®åæŽæ°ãè¡ãéã®ç©åœ¢ã衚瀺ãã
//! å·®åæŽæ°ã®æé©åã«åœ¹ç«ãŠãããã®æ¯æŽæ©èœã
//! å®è£
ããå¿
èŠã¯ãªãããå®è£
ããããšãæãŸããã
virtual void TJS_INTF_METHOD SetShowUpdateRect(bool b) = 0;
//! @brief (Window->DrawDevice) ãã«ã¹ã¯ãªãŒã³åãã
//! @param window ãŠã£ã³ããŠãã³ãã«
//! @param w èŠæ±ããå¹
//! @param h èŠæ±ããé«ã
//! @param bpp Bit per pixels
//! @param color 16bpp ã®æ 565 ã 555ãæå®
//! @param changeresolution è§£ååºŠå€æŽãè¡ããã©ãã
virtual bool TJS_INTF_METHOD SwitchToFullScreen( HWND window, tjs_uint w, tjs_uint h, tjs_uint bpp, tjs_uint color, bool changeresolution ) = 0;
//! @brief (Window->DrawDevice) ãã«ã¹ã¯ãªãŒã³ãè§£é€ãã
//! @param window ãŠã£ã³ããŠãã³ãã«
//! @param w èŠæ±ããå¹
//! @param h èŠæ±ããé«ã
//! @param bpp å
ã
ã®Bit per pixels
//! @param color 16bpp ã®æ 565 ã 555ãæå®
virtual void TJS_INTF_METHOD RevertFromFullScreen( HWND window, tjs_uint w, tjs_uint h, tjs_uint bpp, tjs_uint color ) = 0;
//! @brief (Window->DrawDevice) VBlankåŸ
ã¡ãè¡ã
//! @param in_vblank åŸ
ããªããŠãVBlankå
ã ã£ããã©ãããè¿ã( !0 : å
ã0: å€ )
//! @param delayed 1ãã¬ãŒã é
å»¶ãçºçãããã©ãããè¿ã( !0 : çºçã0: çºçãã )
//! @return Waitå¯äžå¯ true : å¯èœãfalse : äžå¯
virtual bool TJS_INTF_METHOD WaitForVBlank( tjs_int* in_vblank, tjs_int* delayed ) = 0;
};
//---------------------------------------------------------------------------
/*]*/
//---------------------------------------------------------------------------
//! @brief æç»ããã€ã¹ã€ã³ã¿ãŒãã§ãŒã¹ã®åºæ¬çãªå®è£
//---------------------------------------------------------------------------
class tTVPDrawDevice : public iTVPDrawDevice
{
protected:
iTVPWindow * Window;
size_t PrimaryLayerManagerIndex; //!< ãã©ã€ããªã¬ã€ã€ãããŒãžã£
std::vector<iTVPLayerManager *> Managers; //!< ã¬ã€ã€ãããŒãžã£ã®é
å
tTVPRect DestRect; //!< æç»å
äœçœ®
tTVPRect ClipRect; //!< ã¯ãªããã³ã°ç©åœ¢
protected:
tTVPDrawDevice(); //!< ã³ã³ã¹ãã©ã¯ã¿
protected:
virtual ~tTVPDrawDevice(); //!< ãã¹ãã©ã¯ã¿
public:
//! @brief æå®äœçœ®ã«ããã¬ã€ã€ãããŒãžã£ãåŸã
//! @param index ã€ã³ããã¯ã¹(0ã)
//! @return æå®äœçœ®ã«ããã¬ã€ã€ãããŒãžã£(AddRefãããªãã®ã§æ³šæ)ã
//! æå®äœçœ®ã«ã¬ã€ã€ãããŒãžã£ããªããã°NULLãè¿ã
iTVPLayerManager * GetLayerManagerAt(size_t index)
{
if(Managers.size() <= index) return NULL;
return Managers[index];
}
//! @brief DeviceâLayerManageræ¹åã®åº§æšã®å€æãè¡ã
//! @param x Xäœçœ®
//! @param y Yäœçœ®
//! @return å€æã«æåããã°çããããªããã°åœãPrimaryLayerManagerIndexã«è©²åœãã
//! ã¬ã€ã€ãããŒãžã£ããªããã°åœãè¿ã
//! @note x, y 㯠DestRectã® (0,0) ãåç¹ãšãã座æšãšããŠæž¡ããããšèŠãªã
bool TransformToPrimaryLayerManager(tjs_int &x, tjs_int &y);
bool TransformToPrimaryLayerManager(tjs_real &x, tjs_real &y);
//! @brief LayerManagerâDeviceæ¹åã®åº§æšã®å€æãè¡ã
//! @param x Xäœçœ®
//! @param y Yäœçœ®
//! @return å€æã«æåããã°çããããªããã°åœãPrimaryLayerManagerIndexã«è©²åœãã
//! ã¬ã€ã€ãããŒãžã£ããªããã°åœãè¿ã
//! @note x, y 㯠ã¬ã€ã€ã® (0,0) ãåç¹ãšãã座æšãšããŠæž¡ããããšèŠãªã
bool TransformFromPrimaryLayerManager(tjs_int &x, tjs_int &y);
//---- ãªããžã§ã¯ãçåæéå¶åŸ¡
virtual void TJS_INTF_METHOD Destruct();
//---- window interface é¢é£
virtual void TJS_INTF_METHOD SetWindowInterface(iTVPWindow * window);
//---- LayerManager ã®ç®¡çé¢é£
virtual void TJS_INTF_METHOD AddLayerManager(iTVPLayerManager * manager);
virtual void TJS_INTF_METHOD RemoveLayerManager(iTVPLayerManager * manager);
//---- æç»äœçœ®ã»ãµã€ãºé¢é£
virtual void TJS_INTF_METHOD SetDestRectangle(const tTVPRect & rect);
virtual void TJS_INTF_METHOD SetClipRectangle(const tTVPRect & rect);
virtual void TJS_INTF_METHOD GetSrcSize(tjs_int &w, tjs_int &h);
virtual void TJS_INTF_METHOD NotifyLayerResize(iTVPLayerManager * manager);
virtual void TJS_INTF_METHOD NotifyLayerImageChange(iTVPLayerManager * manager);
//---- ãŠãŒã¶ãŒã€ã³ã¿ãŒãã§ãŒã¹é¢é£
// window â drawdevice
virtual void TJS_INTF_METHOD OnClick(tjs_int x, tjs_int y);
virtual void TJS_INTF_METHOD OnDoubleClick(tjs_int x, tjs_int y);
virtual void TJS_INTF_METHOD OnMouseDown(tjs_int x, tjs_int y, tTVPMouseButton mb, tjs_uint32 flags);
virtual void TJS_INTF_METHOD OnMouseUp(tjs_int x, tjs_int y, tTVPMouseButton mb, tjs_uint32 flags);
virtual void TJS_INTF_METHOD OnMouseMove(tjs_int x, tjs_int y, tjs_uint32 flags);
virtual void TJS_INTF_METHOD OnReleaseCapture();
virtual void TJS_INTF_METHOD OnMouseOutOfWindow();
virtual void TJS_INTF_METHOD OnKeyDown(tjs_uint key, tjs_uint32 shift);
virtual void TJS_INTF_METHOD OnKeyUp(tjs_uint key, tjs_uint32 shift);
virtual void TJS_INTF_METHOD OnKeyPress(tjs_char key);
virtual void TJS_INTF_METHOD OnMouseWheel(tjs_uint32 shift, tjs_int delta, tjs_int x, tjs_int y);
virtual void TJS_INTF_METHOD OnTouchDown( tjs_real x, tjs_real y, tjs_real cx, tjs_real cy, tjs_uint32 id );
virtual void TJS_INTF_METHOD OnTouchUp( tjs_real x, tjs_real y, tjs_real cx, tjs_real cy, tjs_uint32 id );
virtual void TJS_INTF_METHOD OnTouchMove( tjs_real x, tjs_real y, tjs_real cx, tjs_real cy, tjs_uint32 id );
virtual void TJS_INTF_METHOD OnTouchScaling( tjs_real startdist, tjs_real curdist, tjs_real cx, tjs_real cy, tjs_int flag );
virtual void TJS_INTF_METHOD OnTouchRotate( tjs_real startangle, tjs_real curangle, tjs_real dist, tjs_real cx, tjs_real cy, tjs_int flag );
virtual void TJS_INTF_METHOD OnMultiTouch();
virtual void TJS_INTF_METHOD OnDisplayRotate( tjs_int orientation, tjs_int rotate, tjs_int bpp, tjs_int width, tjs_int height );
virtual void TJS_INTF_METHOD RecheckInputState();
// layer manager â drawdevice
virtual void TJS_INTF_METHOD SetDefaultMouseCursor(iTVPLayerManager * manager);
virtual void TJS_INTF_METHOD SetMouseCursor(iTVPLayerManager * manager, tjs_int cursor);
virtual void TJS_INTF_METHOD GetCursorPos(iTVPLayerManager * manager, tjs_int &x, tjs_int &y);
virtual void TJS_INTF_METHOD SetCursorPos(iTVPLayerManager * manager, tjs_int x, tjs_int y);
virtual void TJS_INTF_METHOD SetHintText(iTVPLayerManager * manager, iTJSDispatch2* sender, const ttstr & text);
virtual void TJS_INTF_METHOD WindowReleaseCapture(iTVPLayerManager * manager);
virtual void TJS_INTF_METHOD SetAttentionPoint(iTVPLayerManager * manager, tTJSNI_BaseLayer *layer,
tjs_int l, tjs_int t);
virtual void TJS_INTF_METHOD DisableAttentionPoint(iTVPLayerManager * manager);
virtual void TJS_INTF_METHOD SetImeMode(iTVPLayerManager * manager, tTVPImeMode mode);
virtual void TJS_INTF_METHOD ResetImeMode(iTVPLayerManager * manager);
//---- ãã©ã€ããªã¬ã€ã€é¢é£
virtual tTJSNI_BaseLayer * TJS_INTF_METHOD GetPrimaryLayer();
virtual tTJSNI_BaseLayer * TJS_INTF_METHOD GetFocusedLayer();
virtual void TJS_INTF_METHOD SetFocusedLayer(tTJSNI_BaseLayer * layer);
//---- åæç»é¢é£
virtual void TJS_INTF_METHOD RequestInvalidation(const tTVPRect & rect);
virtual void TJS_INTF_METHOD Update();
virtual void TJS_INTF_METHOD Show() = 0;
virtual bool TJS_INTF_METHOD WaitForVBlank( tjs_int* in_vblank, tjs_int* delayed );
//---- ãããã°æ¯æŽ
virtual void TJS_INTF_METHOD DumpLayerStructure();
virtual void TJS_INTF_METHOD SetShowUpdateRect(bool b);
//---- ãã«ã¹ã¯ãªãŒã³
virtual bool TJS_INTF_METHOD SwitchToFullScreen( HWND window, tjs_uint w, tjs_uint h, tjs_uint bpp, tjs_uint color, bool changeresolution );
virtual void TJS_INTF_METHOD RevertFromFullScreen( HWND window, tjs_uint w, tjs_uint h, tjs_uint bpp, tjs_uint color );
// ã»ãã®ã¡ãœããã«ã€ããŠã¯å®è£
ããªã
};
//---------------------------------------------------------------------------
#endif
| [
"info@kaede-software.com"
] | info@kaede-software.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.